【问题标题】:Country field type get Null in Symfony2国家/地区字段类型在 Symfony2 中获取 Null
【发布时间】:2013-06-19 09:44:57
【问题描述】:

我创建了一个 FormType,它添加了这样的国家/地区字段类型

public function buildForm(FormBuilderInterface $builder, array $options)
{
    $builder
        ->add('address', 'text', array(
            'required' => false,
        ))
        ->add('country', 'country', array(
            'required' => false,
        ));
}

public function setDefaultOptions(OptionsResolverInterface $resolver)
{
    $resolver->setDefaults(array(
        'data_class' => $this->dataClass,
    ));
}

public function getName()
{
    return 'form_contact';
}

我将此表单的 data_class 选项设置为具有 addresscountry 这两个字段的实体都是 string 输入

重新编辑表单并提交就可以了,POST参数包括

form_contact['address'] = 'Some value'
form_contact['country'] = 'US'

但是当我从提交的表单中保留实体时,国家字段为 NULL。转储 $form->getData() 我得到了这个:

object(Namspace\Entity\MyEntity)#3501 (3) {
  ["id":protected]=>
  NULL
  ["address1":protected]=>
  string(12) "Some value"
  ["country":protected]=>
  NULL
  ["US"]=>
  string(2) "US"
}

我希望这个国家是美国而不是关键和价值美国的新元素。你能帮助我吗?非常感谢

【问题讨论】:

  • 我发现这是我的错误。在我的实体国家设置器中。应该是 $this->country = $country 而不是 $this->$country = $country 会导致问题。感谢您的帮助 nifr
  • 如果您认为这对将来的某人有帮助,请在您的解决方案中发布答案并接受它。

标签: symfony


【解决方案1】:

您可能忘记将实体绑定到控制器中的表单。

因此,当调用$form->bind($request) 时,提交的表单数据(尽管存在)不会填充到您的实体中。

public function submitAction(Request $request)
{

    $entity = new YourEntity();
    $form = $this->createForm(new YourFormType, $entity); // <- see here
    $form->bind($request);

    if ($form->isValid) {
       $em = $this->get('doctrine')->getManager();
       $em->persist($entity);
       $em->flush;

【讨论】:

  • 不走运,这个问题仍然存在
猜你喜欢
  • 2012-12-17
  • 1970-01-01
  • 2022-11-14
  • 2011-12-20
  • 1970-01-01
  • 1970-01-01
  • 2012-11-21
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多