Alexis_D
Alexis_D

Reputation: 1948

How can I get the structure of $form->getData()

I have difficulties to get the structure of the array / object form->getData(). also I wanted to know there is a way to get it easily.

I have tried the following but there are to many information therefore it isn't readable

$data = $form->getData();
$for_twig_data = var_dump($data);

I also tried the following, but $data_value_value is an object, therefore I cannot fetch throught it:

  $liste_key = '';
  foreach($data as $data_key => $data_value)
  {
      $liste_key = $liste_key."[".$data_key."]";
      if(is_array($data[$data_key]))
      {
        foreach($data_value as $data_value_key => $data_value_value)
        {
          $liste_key = $liste_key."(".$data_value_key.")".$data_value_value;
          if(is_array($data[$data_key][$data_value_key]))  
          {
            foreach($data_value_value as $data_value_value_key => $data_value_value_value)
            {
              $liste_key = $liste_key."{".$data_value_value_key."}";
            }
          }
        }
      }
  }

Upvotes: 0

Views: 174

Answers (1)

Nickolaus
Nickolaus

Reputation: 4835

I dont think you have another possibility than iterating through the dataset, but I would advice you to write a recursive function to do that so you don't have to nest the for-loops and elements can have infinite child layers.

Something like this should work:

$liste_key = '';
$this->parseFormData($liste_key, $data);
...

function parseFormData(&$liste_key, $data){
    foreach($data as $data_key => $data_value)
    {
        $liste_key = $liste_key."[".$data_key."]";
        if(is_array($data[$data_key]))
        {
            $this->parseFormData($liste_key, $data_value)
        }
    }
}

(I have not tested the function so I can not garantee the syntax is correct, but the approach should be right)

...

For an output dump do this:

function yourformAction() {
   if ($form->isValid()) {
       echo '<pre>';
       print_r($form->getData());
       $liste_key = '';
       $this->parseFormData($liste_key, $form->getData());
       print_r($liste_key); // you could also use echo $liste_key;
       die; // this is optional and will stop further processing
   }
}

Upvotes: 1

Related Questions