How to include in entity form type some fields from another entity?

后端 未结 1 1083
孤独总比滥情好
孤独总比滥情好 2021-01-14 04:10

I want to use fields from few entities in one form, can I do it? For example, I want to add to one form surname field from ProfileType type and

相关标签:
1条回答
  • 2021-01-14 04:32

    To include fields from related entities in a form you embed a custom form type for each related entity. Theoretically it is possible to display and update all the data for a complex entity with many relationships in a single form. In practice, doing this for toMany relationships can get complicated but it is straightforward for toOne relationships. See Embedded Forms: Embedding a single object in the Symfony Forms documentation.

    For example, in the form type for your main entity:

    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        ...
        $builder->add('profile', new ProfileType());
        $builder->add('country', new CountryType());
        ...
    }
    
    public function setDefaultOptions(OptionsResolverInterface $resolver)
    {
        $resolver->setDefaults(array(
            ...,
            'cascade_validation' => true,
        ));
    }
    

    Then in your twig you can add the fields you require like this:

    {{ form_widget(form.profile.surname) }}
    {{ form_widget(form.country.name) }}
    

    Assuming your ProfileType and CountryType add other fields to their forms then if you use "form_rest(form)" in your twig you will get the other fields that you don't want, or if you don't use form_rest then depending which symfony version you are using you might get errors. There is more than one way to handle this.

    I sometimes use 'form_widget(_token)' in place of 'form_rest(form)' to get round this issue. However I don't know if you can rely on this continuing to work in the future. You could wrap "form_rest(form)" in a hidden div as it is usually only used to add the hidden '_token' field and in this case you don't want to see the other Profile and Country fields. In this case the hidden entity values are still mapped to the form and back, with any corresponding overhead, but the values cannot be changed.

    Alternatively, you can have multiple form types for your Profile and Country entities and use the appropriate one for the context. I don't know what your form is for but, for example, you might have EditThingProfileType and EditThingCountryType for use in the buildForm() method above, each adding only the single field you require on your form.

    0 讨论(0)
提交回复
热议问题