Symfony2表单字段未更新

Symfony2表单字段未更新

本文介绍了发生验证错误时,Symfony2表单字段未更新的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的表单类型:

class TestFormType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {

        $builder->add('thumbnail', 'hidden', array(
            'label' => 'Thumbnail',
            'label_attr' => array(
                'class' => 'col-xs-2 control-label'
            ),
            'required' => false,
            'error_bubbling' => true,
            'required' => false
        ));

        $builder->add('thumbnail_data', 'file', array(
            'error_bubbling' => true,
            'required' => false
        ));
    }

    public function setDefaultOptions(\Symfony\Component\OptionsResolver\OptionsResolverInterface $resolver)
    {
        $resolver->setDefaults(array(
            'data_class' => 'X\LibraryBundle\Entity\Test',
            'cascade_validation' => true,
            'error_bubbling' => true,
        ));

    }

    public function getName()
    {
        return 'test';
    }
}

这里是实体,重要的是setThumbnailData($ file)方法,该方法存储缩略图文件并通过setThumbnail(string)方法设置缩略图路径.

Here is the entity, important part is the setThumbnailData($file) method, which stores the thumbnail file and sets the thumbnail path via the setThumbnail(string) method.

<?php

namespace X\LibraryBundle\Entity;

use Doctrine\ORM\Mapping as ORM;

/**
 * Test
 *
 * @ORM\Table(name="test")
 * @ORM\Entity(repositoryClass="X\LibraryBundle\Repository\TestRepository")
 */
class Test
{
    /**
     * @ORM\Column(name="id", type="integer", nullable=false)
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    protected $id;

    /**
     * @ORM\Column(type="text", nullable=true)
     */
    protected $thumbnail;

    /**
     * Set thumbnail
     *
     * @param string $thumbnail
     * @return Test
     */
    public function setThumbnail($thumbnail)
    {
        $this->thumbnail = $thumbnail;

        return $this;
    }

    /**
     * Get thumbnail
     *
     * @return string
     */
    public function getThumbnail()
    {
        return $this->thumbnail;
    }

    /**
     * This will save file to disk
     * @param $file
     */
    public function setThumbnailData($file) {
        if($file !== null && $file !== false)
        {
            $fileName = $file->getClientOriginalName();
            $baseDir = __DIR__ . '/../../../../../../../web/uploads/promotional_material/';
            $dir =  sha1(microtime());
            while (is_dir($baseDir . $dir)) {
                $dir = sha1(microtime());
            }
            mkdir($baseDir . $dir);
            $this->setThumbnail('/uploads/promotional_material/' . $dir . '/' . $fileName);
            $file->move($baseDir . $dir, $fileName);
        }
    }

    public function getThumbnailData() {
        return '';
    }
}

现在的问题是,如果表单遇到验证错误,则以下细枝行将产生不同的输出,第二行输出正确的值,另一行产生原始的缩略图路径.因此,如果我使用{{form_widget(form.thumbnail)}}输出缩略图输入,则会得到原始的缩略图路径,而不是应该通过setThumbnailData()方法更改的缩略图路径.

Now the issue is, if the form runs into a validation error, the following twig lines produce different output, the correct value outputted from the second line, the other produces the original thumbnail path. So if I output the thumbnail input using {{ form_widget(form.thumbnail) }}, I get the original thumbnail path, not the one that should have changed via the setThumbnailData() method.

{{ dump(form.thumbnail.vars.data) }}
{{ dump(form.vars.data.thumbnail) }}

问题是由使用setThumbnailData()方法设置缩略图引起的吗?除了像这样对枝中的输入进行硬编码之外,不确定如何解决此问题:

Is the issue caused by setting the thumbnail using the setThumbnailData() method? Not sure how to fix this other than hard coding the input in twig like so:

<input type="hidden" name="test[thumbnail]" value="{{ form.vars.value.thumbnail }}"/>

推荐答案

我无法完全解决您的问题,因为我认为您的做法是错误的.数据类实际上只是负责保存数据,因此您的方法set/getThumbnailData应该看起来像这样

I cannot exactly solve your problem, because in my opinion you're doing it the wrong way. A data class is actually only responsibly for keeping your data, so your method set/getThumbnailData should look like this

<?php
// ...
private $thumbnailData;

public function setThumbnailData(UploadedFile $thumbnailData) {
    $this->thumbnailData = $thumbnailData;
}

public function getThumbnailData() {
    return $this->thumbnailData;
}

在您的控制器中,您将看到以下内容:

In your controller you have something like this:

<?php
// ...
public function formAction() {

    $form = // ...
    $form->handleRequest($request);
    if($form->isValid()) {
        $test = $form->getData();
        /* @var $test Test */
        $thumbnailUploader = $this->get('thumbnail_uploader');
        /* @var $thumbnailUploader ThumbnailUploadService */

        $file = $test->getThumbnailData();
        $filename = $file->getClientOriginalName();
        $thumbnailUploader->upload($filename, $file);

        // ...
    }
}

我建议将与表单或请求无关的所有逻辑都移到服务中.在这种情况下,您的服务可以更通用地处理具有给定文件名的任何symfony文件.

I recommend to move all logic which has nothing to do with forms or requests into services. Your service in this case can be more generic handle any symfony files with a given filename.

<?php
class ThumbnailUploadService {
    /**
     * @param $file Symfony\Component\HttpFoundation\File\File
     *
     */
    public function upload($filename, File $file) {
        // ...
    }
}

这篇关于发生验证错误时,Symfony2表单字段未更新的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-02 02:14