如何将表单类型与请求匹配?

时间:2013-11-27 16:04:39

标签: symfony fosrestbundle

请求JSON:

{"vpnusers": {"expire_account": "2017-11-27 16:28:15", "status_id": 1}}

打印结果(在控制器中):

print_r($request->get('vpnusers'));
Array
(
    [expire_account] => 2017-11-27 16:28:15
    [status_id] => 1
)

VpnUsersType:

namespace Hoax\PartnerBundle\Form\Type;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;

class VpnUsersType extends AbstractType
{
    /**
     * @param FormBuilderInterface $builder
     * @param array $options
     */
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('status_id')
            ->add('expire_account')
        ;
    }

    /**
     * @param OptionsResolverInterface $resolver
     */
    public function setDefaultOptions(OptionsResolverInterface $resolver)
    {
        $resolver->setDefaults(array(
            'data_class' => 'Hoax\PartnerBundle\Entity\VpnUsers'
            , 'csrf_protection' => false
        ));
    }

    /**
     * @return string
     */
    public function getName()
    {
        return 'vpnusers';
    }
}

我刚刚遵循了这个指南,可以看到我没有这样的问题:http://williamdurand.fr/2012/08/02/rest-apis-with-symfony2-the-right-way/

1 个答案:

答案 0 :(得分:2)

您无法设置data_class选项`Hoax \ PartnerBundle \ Entity \ VpnUsers',因为您提交的内容不是对象。

将其设置为NULL或从请求数据创建对象并将其传递给您。

如果NULL你非常接近:

  1. data_class设为null
  2. 在控制器中执行以下操作:

    $form = $this->createForm(new VpnUsersType(), $request->get('vpnusers'));
    
  3. 如果您选择对象类型:

    1. 离开data_class
    2. 在控制器中:

      $req_data = $request->get('vpnusers');
      
      // either fetch from database **or** creare new instance here, your call...
      $vpnUser = $this->getDoctrine()->getRepository('HoaxPartnerBundle:VpnUsers')->find($req_data['status_id']); // IS THIS OK? Not sure really...
      $form = $this->createForm(new VpnUsersType(), $vpnUser);