简体   繁体   English

Symfony2表单处理

[英]Symfony2 Form Handling

I am using forms to process my entity data via ajax to an api-method. 我正在使用表单通过ajax将我的实体数据处理为api方法。

My Type Class: 我的类型班:

/**
 * @param FormBuilderInterface $builder
 * @param array $options
 */
public function buildForm(FormBuilderInterface $builder, array $options)
{
    $builder->add(
        $builder->create('basicdata', 'form', array('virtual' => true))
        ->add('firstname', null, array('required' => true))
        ->add('lastname', null, array('required' => true))
    );        
    $builder->add('contactdetails', new ContactdetailsType());
    $builder->add('medialinks', new MedialinksType());
}

As u can see i seperate my form in 3 sections, one with basedata and 2 additional entities to keep contactdetails and medialinks. 如您所见,我将表单分为3个部分,其中一个包含baseata和2个其他实体以保留contactdetails和medialinks。

In my JavaScript i have the following listener on the create button: 在我的JavaScript中,创建按钮上具有以下侦听器:

$('#player_form_create').on('click', function(e){
    e.preventDefault();
    $.ajax({
        type: "POST",
        url: remotePathPlayerCreate,
        data: $('.form').serialize()
    });
});

According to chromes developer tool the POST data look like following: 根据chromes开发人员工具,POST数据如下所示:

player_form[basicdata][firstname]:Harvey
player_form[basicdata][lastname]:Specter
player_form[contactdetails][email]:h.specter@pearson.com
player_form[medialinks][website]: http://

In my API action i wanna handle the request and save a new player record: 在我的API操作中,我要处理请求并保存新的玩家记录:

public function cpostAction()
{
  $player = new Player();
  $form = $this->createForm(new PlayersType(), $player);
  $form->handleRequest($this->getRequest());
  if($form->isValid()){
    $em = $this->getDoctrine()->getManager();
    $em->persist($player);
    $em->persist($player->getContactdetails());
    $em->persist($player->getMedialinks());
    $em->flush();

    return $this->redirectView(
      $this->generateUrl(
        'get_player',
        array('id' => $player->getId())
      ),
      Codes::HTTP_CREATED
    );
  }

  return array(
    'processedForm' => $form
  );
}    

As u might allready know, the problem happens while i want to handle the request. 正如您可能已经知道的那样,问题是在我想处理请求时发生的。 I guess $this->getRequest() does not contain the POST data information in the format needed by the request handler. 我猜$this->getRequest()不包含请求处理程序所需格式的POST数据信息。

When i post data like this, i get a 500 with Expected argument of type \\"Symfony\\\\Component\\\\HttpFoundation\\\\Request\\", \\"array\\" given . 当我这样发布数据时,我得到500,其Expected argument of type \\"Symfony\\\\Component\\\\HttpFoundation\\\\Request\\", \\"array\\" given

How can i achieve that my POST data is submited as an request object? 我如何实现我的POST数据作为请求对象提交?

I ran into the same problem when building an app with Symfony on server side and AngularJS on client side. 使用服务器端的Symfony和客户端的AngularJS构建应用程序时,我遇到了相同的问题。 Handling the form this way worked: 以这种方式处理表单有效:

$content = $this->get('request')->getContent();
if (!empty($content)) { $params = json_decode($content, true); }
else { // return an error or whatever }

$defaultOptions = array('csrf_protection' => false);
$form = $this->createFormBuilder(null, $defaultOptions)
    ->add('email', 'email', array(
        'constraints' => new Constraints\Email(array('message' => 'emailError'))
    ))
    ->getForm();

$form->submit($params);

if ($form->isValid()) {
    ...
}

Of course here I'm not using a type to create the form like you but the result is the same. 当然,这里我没有使用类型来创建像您一样的表单,但是结果是相同的。 This assumes that the request payload is something like this: 假设请求有效负载是这样的:

{email: 'test@example.com'}

好的,我找到了解决方案:根据页面如何使用Submit()函数处理表单提交,我现在使用$form->submit将我的数组数据$form->submit给表单:

  $form->submit($this->getRequest()->request->get($form->getName()));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM