当前位置: 动力学知识库 > 问答 > 编程问答 >

Symfony3 Forms–obtain Form with choices, default data etc. as JSON

问题描述:

I have a Symfony3 Application setup and would like to rebuild the frontend based on React now.

One of the Entities is User and each of them can have one or more Groups so in the HTML form a list of Checkboxes appears, so the admin can select the groups attached to a User.

In UserType.php this looks like that:

public function buildForm(FormBuilderInterface $builder, array $options)

{

$builder

->add('username', TextType::class)

->add('password', TextType::class)

->add('email', EmailType::class)

->add('groups', EntityType::class, [

'class' => Group::class,

'choice_label' => 'name',

'expanded' => true,

'multiple' => true//,

//'data' => $builder->getData()->getGroups()

]);

}

To render the Form using React, it would be extremely handy to get a JSON response which could look like that:

{

"user": {

"groups": [<gid 1>, …]

"groups_available": [

{

"id": <gid 1>,

"name": …

},

]

}

}

So that the groups array contains all the ids of the groups, the user is attached to and groups_available a list of all available groups.

Right now I am using FOSRestBundle and in the Controller it looks like that:

public function getUserformAction($id=null)

{

//if the id is null, create a new user

//else get the existing one

$form = $this->createForm(UserType::class, $user);

$view = $form->createView();

return $this->handleView($view);

}

How can I do that?

网友答案:

you should try the following code:

 ->add('groups', EntityType::class, array(
    //if Group is in AppBundle or use the required Bundle name
                    'class' => 'AppBundle:Group',
                    'query_builder' => function (EntityRepository $er) {
                        return $er->createQueryBuilder('u')
                                     ->orderBy('u.name', 'ASC')
                             },
                    'choice_label' => 'name',
                    'multiple' => true,
                    'expanded' => true,
                ));

You can also get a reference from here

网友答案:

After digging in the source and with the help of the debugger I could manage to do it in a more less robust and generic way like so:

protected function getFormStructure(Form $form)
{
  return $this->iterateFormview($form->createView(), []);
}

private function iterateFormview(FormView $view, array $result)
{
  foreach($view as $child) {
    $vars = $child->vars;
    $data = ['value' => $vars['value']];

    if(isset($vars['choices'])) {
      $data['choices'] = [];

      foreach ($vars['choices'] as $choice) {
        array_push($data['choices'], [
          'label' => $choice->label,
          'value' => $choice->value]);
      }
    }

    $result[$vars['full_name']] = $data;

    if(count($child) > 0) {
      $result = $this->iterateFormview($child, $result);
    }
  }
  return $result;
}

Result (as json):

{
  …
  "user[groups]":
  {
    "value": "",
    "choices":  [
      {
        "value": 100,
        "label": "the name"
      },
      …
    ] 
  }
}

I guess this routine needs to be extended if I need to support more types… But for now this will do it.

分享给朋友:
您可能感兴趣的文章:
随机阅读: