symfony vich uploader image_name不能为空

时间:2017-12-02 13:57:10

标签: php symfony doctrine vichuploaderbundle

我试图关注VichUploaderBundle的文档,但事情似乎没有按预期工作。 我收到了错误

  

SQLSTATE [23000]:完整性约束违规:1048列   'image_name'不能为空

当然,有关它的问题被多次询问,但我没有找到任何合适的答案。

所以我的config.yml看起来像这样:

vich_uploader:
    db_driver: orm
    mappings:
        image:
            uri_prefix:         /images
            upload_destination: '%kernel.project_dir%/web/images'
            inject_on_load:     true
            namer:              vich_uploader.namer_uniqid

我有制片人实体:

/**
 * Products table
 *
 * @author gallareton
 *
 * @ORM\Table(name="producer")
 * @ORM\Entity(repositoryClass="ShopBundle\Repository\ProducerRepository")
 */
class Producer
{
    /**
     * Constructor
     */
    public function __construct() {
        $this->products = new ArrayCollection();
    }

    /**
     * @ORM\Column(type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    private $id;

    /**
     * @ORM\Column(type="string", length=25, unique=true)
     */
    private $name;

    /**
     * One Producer has Many Products
     * @ORM\OneToMany(targetEntity="Product", mappedBy="producer")
     */
    private $products;

    /**
     * One Producer has One Image
     * @ORM\OneToOne(targetEntity="\AppBundle\Entity\Image", cascade={"persist"})
     */
    private $image;

图像实体(几乎从文档中复制):

/**
 * @ORM\Entity
 * @Vich\Uploadable
 * @ORM\HasLifecycleCallbacks
 */
class Image
{
    /**
     * @ORM\Id
     * @ORM\Column(type="integer")
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    private $id;

    /**
     * NOTE: This is not a mapped field of entity metadata, just a simple property.
     *
     * @Vich\UploadableField(mapping="image", fileNameProperty="imageName", size="imageSize")
     *
     * @var File
     */
    private $imageFile;

    /**
     * @ORM\Column(type="string", length=255)
     *
     * @var string
     */
    private $imageName;

    /**
     * @ORM\Column(type="integer")
     *
     * @var integer
     */
    private $imageSize;

    /**
     * @ORM\Column(type="datetime")
     *
     * @var \DateTime
     */
    private $updatedAt;

    /**
     * If manually uploading a file (i.e. not using Symfony Form) ensure an instance
     * of 'UploadedFile' is injected into this setter to trigger the  update. If this
     * bundle's configuration parameter 'inject_on_load' is set to 'true' this setter
     * must be able to accept an instance of 'File' as the bundle will inject one here
     * during Doctrine hydration.
     *
     * @param File|\Symfony\Component\HttpFoundation\File\UploadedFile $image
     *
     * @return Image
     */
    public function setImageFile(File $image = null)
    {
        $this->imageFile = $image;

        if ($image) {
            // It is required that at least one field changes if you are using doctrine
            // otherwise the event listeners won't be called and the file is lost
            $this->updatedAt = new \DateTimeImmutable();
        }

        return $this;
    }

    /**
     * @return File|null
     */
    public function getImageFile()
    {
        return $this->imageFile;
    }

    /**
     * @param string $imageName
     *
     * @return Image
     */
    public function setImageName($imageName)
    {
        $this->imageName = $imageName;

        return $this;
    }

    /**
     * @return string|null
     */
    public function getImageName()
    {
        return $this->imageName;
    }

    /**
     * @param integer $imageSize
     *
     * @return Image
     */
    public function setImageSize($imageSize)
    {
        $this->imageSize = $imageSize;

        return $this;
    }

    /**
     * @return integer|null
     */
    public function getImageSize()
    {
        return $this->imageSize;
    }
}

还有2个Form类,一个嵌入另一个: ProducerImageType:

/**
 * Created by PhpStorm.
 * User: gallareton
 * Date: 16.11.2017
 * Time: 17:55
 */
class ProducerImageType extends AbstractForm
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder->add('imageFile', VichImageType::class, [
            'required' => false,
            'allow_delete' => true,
            'label' => false,
        ]);
    }

    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults(array(
            'data_class' => Image::class,
        ));
    }
}

ProducerForm:

/**
 * Created by PhpStorm.
 * User: gallareton
 * Date: 16.11.2017
 * Time: 17:55
 */
class ProducerForm extends AbstractForm
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder->add(
            'id',
            HiddenType::class
        );

        $builder->add(
            'name',
            TextType::class,
            array(
                'label' => 'app.name',
                'constraints' => array(
                    new Length(
                        array(
                            'max' => 25,
                        )
                    ),
                ),
            )
        );

        $builder->add(
            'image',
            ProducerImageType::class,
            array(
                'label' => 'app.image',
            )
        );

        $builder->add(
            'save',
            SubmitType::class,
            array('label' => 'app.save')
        );
    }//end BuildForm()

    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults(array(
            'data_class'      => Producer::class,
            'crsf_protection' => true,
            'crsf_field_name' => '_token',
            'crsf_token_id'   => 'producer'
        ));
    }//end configureOptions()
}

我尝试启动沙盒,但是我犯了很多错误,我在1小时后放弃了。查看文件,看起来我已经做好了一切。可能我错过了一些小细节。我考虑过在setImageFile方法中手动设置文件名和文件大小,但这只是一种解决方法,我试图避免像每个人都应该这样的解决方案。

提交表单的行为也很重要,所以这是行动: 注意:$this->db()是我$this->getDoctrine()->getManager()的快捷方式,$this->getRepo()$this->getDoctrine()->getManager()->getRepository()的快捷方式

/**
 * @Route("/edit/{id}", name="producerAdminEdit")
 * @param Request $request
 * @param int $id
 * @return \Symfony\Component\HttpFoundation\JsonResponse|\Symfony\Component\HttpFoundation\Response
 */
public function editAction(Request $request, $id = null)
{
    $this->setMenuTab('cars', 'admin');

    if (!empty($id)) {
        $producer = $this->getRepo(Producer::class)->find($id);
        if (empty($producer)) {
            throw $this->createNotFoundException();
        }

        $this->setTitle('admin.cars.producers.edit');
    } else {
        $producer = new Producer();
        $this->setTitle('admin.cars.producers.new');
    }

    $form = $this->createForm(ProducerForm::class, $producer);
    $form->handleRequest($request);

    if ($form->isSubmitted() && $form->isValid()) {
        $producer = $form->getData();
        dump($producer);

        $this->db()->persist($producer);
        $this->db()->flush();

        return $this->redirectToRoute('carAdmin', array('tab' => 'producers'));
    }

    $this->setVariables(
        array(
            'form'     => $form->createView(),
            'producer' => $producer,
        )
    );

    return $this->response();

}//end editAction()

0 个答案:

没有答案