我正在使用一个名为FilePond的插件,以便在通过VichUploaderBundle上传图像时具有更好的外观。因此,为避免使用捆绑包的默认form_row模板,我做了一个自定义模板:
//template/forms/upload_image.html.twig
{% block _image_file_row %}
<input type="file" class="filepond-initialise" name="image[file][file]" required="required" accept=".gif, .jpg, .png">
{% endblock %}
然后我在页面中呈现模板:
{% form_theme form 'forms/upload_image.html.twig' %}
{{ form_start(form) }}
{{ form_row(form.file) }}
<h3>Tags</h3>
<ul class="tags list-inline" data-prototype="{{ form_widget(form.tags.vars.prototype.name)|e('html_attr') }}">
{% for tag in form.tags %}
<li>{{ form_row(tag.name) }}</li>
{% endfor %}
</ul>
<button class="btn btn-success btn-block" type="submit">Upload</button>
<input type="hidden" name="token" value="{{ csrf_token('image-upload') }}">
{{ form_end(form, {'render_rest': false}) }}
这是控制器中的操作:
public function upload(Request $request):Response
{
$image = new Image();
$form = $this->createForm(ImageType::class, $image);
$token = $request->request->get('token');
$form->handleRequest($request);
if ($form->isSubmitted() && $this->isCsrfTokenValid('image-upload', $token)) {
dump($image);
dump($form->getData());
$this->em->persist($image);
$this->em->flush();
return $this->redirectToRoute('admin_image_index');
}
return $this->render('admin/image/upload.html.twig', array(
'form' => $form->createView()
));
}
文件输入的内容似乎未在表单提交中发送的问题。我收到名称属性为null的错误:
An exception occurred while executing 'INSERT INTO image (name, updated_at) VALUES (?, ?)' with params [null, "2019-05-14 22:42:18"]:
SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'name' cannot be null
以及$ image变量和$ form-getData()的转储,如下所示:
Image {#496 ▼
-id: null
-file: null
-name: null
-updatedAt: DateTime @1557873995 {#497 ▼
date: 2019-05-14 22:46:35.496026 UTC (+00:00)
}
-tags: ArrayCollection {#498 ▼
-elements: array:3 [▼
0 => Tag {#901 ▼
-id: null
-name: "sport"
-images: ArrayCollection {#902 ▶}
}
1 => Tag {#878 ▼
-id: null
-name: "nature"
-images: ArrayCollection {#905 ▶}
}
2 => Tag {#906 ▼
-id: null
-name: "fashion"
-images: ArrayCollection {#908 ▶}
}
]
}
}
虽然标签输入工作正常,但这意味着问题出在文件输入上。
这是ImageType.php中的生成器,其余默认为:
$builder
->add('file', VichImageType::class)
->add('tags', CollectionType::class, [
'entry_type' => TagType::class,
'entry_options' => ['label' => false],
'allow_add' => true,
'allow_delete' => true,
'by_reference' => false,
])
;