我正在使用像这样的表单类型配置运行Symfony 3.3。
class UserFinancialTransactionType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('billingAddresses', AddressType::class, array(
))
;
}
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults(array(
'data_class' => User::class,
'translation_domain' => 'forms',
));
}
}
class AddressType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$countryChoices = $options['country_choices'];
$builder
->add('firstName', TextType::class, array(
'label' => 'address.first_name',
'required' => false,
))
->add('lastName', TextType::class, array(
'label' => 'address.last_name',
'required' => false,
))
->add('line1', TextType::class, array(
'label' => 'address.line1',
))
->add('line2', TextType::class, array(
'label' => 'address.line2'
))
->add('city', TextType::class, array(
'label' => 'address.city'
))
->add('postalCode', TextType::class, array(
'label' => 'address.postal_code'
))
->add('country', EntityType::class, array(
'label' => 'address.country',
'class' => 'AppBundle:Country',
'choices' => $countryChoices,
'choice_label' => 'shortDe',
'query_builder' => function (EntityRepository $entityRepository) {
return $entityRepository->createQueryBuilder('c')
->orderBy('c.shortDe', 'ASC');
},
))
;
}
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults(array(
'data_class' => Address::class,
'translation_domain' => 'forms',
'country_choices' => null,
));
}
}
BillingAddresses是用户的子节点(多对多关系)。在我的表单中,我想只有一个BillingAddress,并希望没有javascript,这就是我没有使用CollectionType的原因。
为了实现这一点,我为“billingAddresses”添加了一个setter Method to Entity \ User:
/**
* Set billingAddresses
*
* @param \AppBundle\Entity\Address $billingAddress
*
* @return User
*
*/
public function setBillingAddresses(\AppBundle\Entity\Address $billingAddress)
{
if($this->billingAddresses !== NULL and $this->billingAddresses->contains($billingAddress)){
return false;
}
$this->addBillingAddress($billingAddress);
return $this;
}
在树枝上我渲染这样的字段:
{{ form_row(form.payment.user.billingAddresses) }}
当我提交表单时,我在symfony探查器中的所有地址表单字段(例如user.billingAddresses [0] .line1)和{{ form_errors(form) }}
中也有错误,但我的billingAddress表单字段不是标记为有错误(通常每个字段的错误消息由表单字段直接返回,而不是{{ form_errors(form) }}
并且在树枝形式字段模板form.vars.valid
中未设置为“false”)。
那么我如何使用自定义表单类型(AddressType)获得具有多对多属性的正确表单处理?
谢谢你,最好!