php - 表单中的 Symfony2 FileType 输入总是返回 null

标签 php symfony twig symfony-forms

我正在研究一种在我的网站上上传 .pdf 文件的方法。

我创建了一个实体,其中包含字符串中的文件名。 有实体映射:

<field name="pdf" type="string" column="pdf" length="200" nullable="true"/>

我输入文件的形式:

$builder
        ->add('pdf', FileType::class, array('label' => 'Fiche de paie'))
        /* other input */
    ;

我的表单 View :

{{ form_start(form) }}
    {{ form_row(form._token) }}
    <div class="modal-body row">
        <div class="col-md-6 col-sm-8">
            /* other input */
            {{ form_row(form.pdf) }}}
        </div>
        <div class="col-md-6 col-sm-8">
            /* other input */
        </div>
    </div>

    <div class="modal-footer">
        <button type="button" class="btn btn-info" id="save">{% trans %}Save{% endtrans %}</button>
    </div>
    {{ form_end(form, { 'render_rest': false } ) }}

还有 Controller :

if ($form->isSubmitted() && $form->isValid()) {
        $pdf = $salaire->getPdf();

        if ($pdf == null) { /* Always true */
            $salaire->setPdf('test');
        }

        /* operations to extract the file name and set it to the pdf variable in salaire */

        $em->persist($salaire);
        $em->flush();

        return $this->redirectToRoute('salaires_index', array("id" => $remuneration->getId()));
    }

问题是,即使我输入了一个文件,当我用

获取输入的值时
->salaire->getPdf()

结果总是空的。

首先我认为这是因为我在我的实体中的一个字符串上设置了表单输入 FileType,但我试图在我的实体中的一个 UploadedFile 变量上设置它,结果仍然为空。

感谢您的帮助。

最佳答案

一定要设置正确的表单元素的enctype(在表单标签中的值enctype="multipart/form-data")。

引用documentation你可以这样做:

{{ form_start(form, {'multipart': true}) }}

希望对你有帮助

关于php - 表单中的 Symfony2 FileType 输入总是返回 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39533313/

相关文章:

javascript - jQuery 脚本仅适用于产品目录上的一个按钮

php - 在 Symfony2 twig express 中添加 CSS

php - 使用 twig 和 Slim 框架上传文件(版本 2)- PHP

php - 重定向到主页(索引)

php - GMaps api 地理编码奇怪的行为

php - .htaccess 在 ubuntu 服务器上无法正常工作

symfony - Twig 空日期过滤器显示当前日期

php - 如何在 Symfony2 中使用 jquery/Ajax 从 PHP 文件中获取数组字段值?

php - Setlocale 将小数点设置为点而不是逗号

php - 替换 sylius 中的身份验证层和用户实体