Skip to content
Grav 2.0 is officially stable. Read the announcement →

Community guidelines

Please keep discussions civil and on-topic. Repeated violations may lead to a temporary ban.

Forms & Blueprints

Help with form data, invalid json

Solved by pamtbaau View solution

Started by yehuda 5 years ago · 2 replies · 756 views
5 years ago

I'm having trouble getting data from my simple custom function in which I want to input form data. the

$form = $event['form'];

is getting invalid json

5 years ago

i managed to get the data i want using this

PHP
$data = json_decode( json_encode($form["data"]), true);
foreach($data as $val){
    if(!is_array($val)){
      $x=0;
      $myfields[$x]=$val;
    }
}
5 years ago Solution

@yehudac, Every time when code looks clunky, a little voice in the back of your head should say, "Hm I can't imagine this is really meant to be"

In the case of Grav, one could then lookup the API of Data in the docs and find for example:

public toArray() : array
Convert object into an array.

or

public get( string $name , mixed $default=null , string $separator=null ) : mixed Value.
Get value by using dot notation for nested arrays/objects.

Or use code IntelliSense which will reveal:
Untitled|690x189

To summarise the options:

PHP
public function onFormProcessed(Event $event) {
  /** @var Form */
  $form = $event['form'];

  // Using Data::toArray()
  $data = $form->data->toArray();

  // Using Data::get($name, $default = null, $separator = null)
  $message = $form->data->get('message', 'some default value');
  $nestedFieldname = $form->data->get('a.nested.fieldname', 'some default value');

  // Using associative array access
  $name = $form->data['name'];
}
last edited 11/18/21 by pamtbaau

Suggested topics

Topic Participants Replies Views Activity
Forms & Blueprints · by Ton Haarmans, 5 years ago
13 1139 4 months ago
Forms & Blueprints · by Hugo Oliveira, 5 months ago
0 63 5 months ago
Forms & Blueprints · by Flachy Joe, 6 months ago
9 137 6 months ago
Forms & Blueprints · by Augustus, 7 months ago
7 112 7 months ago
Forms & Blueprints · by Julien, 7 months ago
10 131 7 months ago