无法从我的控制器接收表单请求

时间:2014-11-02 14:20:30

标签: php forms symfony

我正在尝试做一个简单的表格。控制器和视图之间的绑定已完成。但是当用户提交时我无法收到表单数据。

public function addAction()
{
    $router = $this->get('router');
    $request = $this->get('request');

    $ret = 'not set';
    $title = 'not set';

    if ($request->getMethod() == 'POST') {

    $pictures = $request->files->get('pictures');
    $title = $request->request->get('title');

    $ret = $this->get('my_project_blog.post_service')
                ->create($title, $subtitle, $description, $pictures);

    }

    return $this->render('MyProjectBlogBundle:Default:add.html.twig', array('err' => $ret, 'title' => $title));
}

现在是add.twig.html

<form enctype="multipart/form-data" action="{{ path('my_project_blog_add') }}" method="POST" id="contactform">

  <fieldset id="contact_form">
    <label for="title">
      <input type="text" name="title" id="name" placeholder="Enter A Title">
    </label>
    <label for="file">
      <input name="pictures[]" type='file' multiple='multiple' ></input>
    </label>

    <input type="submit" class="submit btn btn-default btn-black" id="submit" value="Submit">
  </fieldset>

</form>

提交前的结果:

Pictures: not set.
Title: not set

提交后:

Pictures: Error pictures count == 0.
Title:

1 个答案:

答案 0 :(得分:2)

有什么特别的原因,为什么你不使用Symfony表单组件?

不确定它是如何可能的,但也许你从容器中得到错误的request服务。您应该使用Request Stack服务或添加$request作为您的操作参数。刚刚测试了以下代码,一切正常。

public function addAction(Request $request)
{
    if ($request->getMethod() == 'POST') {
        $title = $request->request->get('title');
        $files = $request->files->all();
    }
}

正如xurshid29在评论中提到的那样,symfony让您有机会更轻松地定义表单并更轻松地处理响应。

// In controller
public function addAction(Request $request)
{
   $form = $this->createFormBuilder()
        ->add('title')
        ->add('pictures', 'file', [
            'multiple' => true, // Since symfony 2.5
        ])
        ->add('Submit', 'submit')
        ->getForm();

    $form->handleRequest($request);
    if ($form->isValid()) {
        // Process data from $form->getData()
    }

    return $this->render('MyProjectBlogBundle:Default:add.html.twig', [
        'form' => $form->createView()
    ]);
}

// In view 
{% block content %}
    {{ form(form) }}
{% endblock %}