我正在尝试做一个简单的表格。控制器和视图之间的绑定已完成。但是当用户提交时我无法收到表单数据。
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:
答案 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 %}