[英]Symfony2, How to edit fields in a form and avoid empty password field
[英]Symfony file field empty on edit
我正在閱讀有關此內容的一段時間,但沒有發現對我有用的內容。 這是實體
/**
* @ORM\Column(type="string")
*
* @Assert\NotBlank(message="Molimo unesite PDF ili Word fajl.")
* @Assert\File(mimeTypes={ "application/vnd.openxmlformats-officedocument.presentationml.presentation", "application/vnd.ms-powerpoint", "application/pdf", "application/msword", "application/vnd.openxmlformats-officedocument.wordprocessingml.document"})
*/
private $body;
這是表格
// Problem with empty field on edit persist! Form expect FileType but db sends string!!!
->add('body', FileType::class, [
//'data_class' => null,// <-- If I change it nothing happened.
'label' => 'Word ili pdf dokument',
'invalid_message' =>'Id posta nije validan',
'attr' => [
'class' => 'form-group',
]])
一切都非常簡單,並根據文檔制作。 我有一個實體,其中包含很少的屬性,其中一個屬性用於文件($ body)。 文件設置為保存在web / uploads / post /中。 當我進入編輯頁面時,出現此錯誤:
“該表單的視圖數據應該是Symfony \\ Component \\ HttpFoundation \\ File \\ File類的實例,但是是一個(n)字符串。您可以通過將“ data_class”選項設置為null或添加一個視圖轉換器來避免這種情況。將字符串轉換為Symfony \\ Component \\ HttpFoundation \\ File \\ File的實例”。
如果我設置data_status => null字段為空。
我需要的是與此示例相關的一些鏈接,也許是Data Transformer?
我在編輯操作中遇到了同樣的問題,並通過將clearMissing參數設置為false而不是使用$form->handleRequest($request);
手動提交表單來解決了該問題$form->handleRequest($request);
,如https://symfony.com/doc/current/form/direct_submit.html所述 :
if ($request->isMethod('POST'))
{
$form->submit($request->request->get($form->getName()),false);
if ($form->isSubmitted() && $form->isValid())
{
這樣,如果您不提交新文件,則file的原始值將不會設置為null。
您可以通過在editAction中創建一個新的File()來解決此問題。 像這樣:
/**
* @Route("/edit/{yourEntity}", name="entity_edit")
*
* @return Response
*/
public function editAction(Request $request, YourEntity yourEntity)
{
$body = new File($this->getParameter('your_files_directory') . '/' . $yourEntity->getBody());
$yourEntity->setBody($body);
// rest of your editAction
}
好,解決了 @ASOlivieri的答案只有一個小的修改就很好。 他的答案中的代碼將記住帶有文件名的路徑。 因此,如果要再次編輯它,它將拋出未找到的樣本。 您必須再次-> setBody,以與原始文件名相同。 在flush()之前設置它
public function editAction(Request $request, Post $post) {
$fileName = $post->getBody();
$file = new File($this->getParameter('post_directory') . '/' . $post->getBody());
$post->setBody($file);
$deleteForm = $this->createDeleteForm($post);
$editForm = $this->createForm('AppBundle\Form\PostEditType', $post);
$editForm->handleRequest($request);
if ($editForm->isSubmitted() && $editForm->isValid()) {
$post->setBody($fileName);
$this->getDoctrine()->getManager()->flush();
希望這可以幫助!
就我而言,有幫助的是:
if ($request->isMethod('POST')) {
$form->submit($request->request->get($form->getName()));
if ($form->isValid()) {...
至
$form->handleRequest($request);
if ($form->isSubmitted()) {
if ($form->isValid()) { ...
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.