gpt4 book ai didi

Symfony2 : do not update a form field if not provided

转载 作者:行者123 更新时间:2023-12-04 02:58:49 28 4
gpt4 key购买 nike

我有我的“团队”实体的表格。该实体有一个“图像”字段。此字段在创建过程中是必需的,但在编辑过程中不是必需的。但是现在,在编辑过程中,如果我在文件输入中不提供任何图像,则空输入仍然存在,因此在此过程中我的数据库字段被清空。
如果表单文件输入中未提供任何内容,我该如何避免此字段的持久性?因此,实体保留该字段的旧值。当然,如果提供了文件,我希望他删除旧的。

我的 Controller 看起来像这样:

if ($request->getMethod() == 'POST') {

$form->bind($request);

if ($form->isValid()) {

$em->persist($team);
$em->flush();
...
}
}

和我的实体的一部分,处理图像(我很确定我必须在这里做一些事情,但不知道究竟是什么):
/**
* @ORM\PrePersist()
* @ORM\PreUpdate()
*/
public function uploadImage() {
// the file property can be empty if the field is not required
if (null === $this->image) {
return;
}
if(!$this->id){
$this->image->move($this->getTmpUploadRootDir(), $this->image->getClientOriginalName());
}else{
$this->image->move($this->getUploadRootDir(), $this->image->getClientOriginalName());
}
$this->setImage($this->image->getClientOriginalName());
}

编辑

好的,我对 this answer's code 做了一些更改代码,因为显然事件监听器要求 FormEvent在他的回调中的实例,而不是 FormInterface实例。
$builder->addEventListener(FormEvents::POST_SUBMIT, function (FormEvent $event) {
// Retrieve submitted data
$form = $event->getForm();
$item = $event->getData();

// Test if upload image is null (maybe adapt it to work with your code)
if (null !== $form->get('image')->getData()) {
var_dump($form->get('image')->getData());
die('image provided');
$item->setImage($form->get('image')->getData());
}

});

当我提供图像时,脚本进入测试, die() ,正如预期的那样。当我不提供任何文件时,脚本不会进入测试 if() ,但我在数据库中的字段仍然被空值删除。任何的想法?

正如下面所问的,这是表格
// src/Van/TeamsBundle/Form/TeamEditType.php

namespace Van\TeamsBundle\Form;

use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;
use Symfony\Component\Form\FormEvent;
use Symfony\Component\Form\FormEvents;

class TeamEditType extends TeamType // Ici, on hérite de ArticleType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
// On fait appel à la méthode buildForm du parent, qui va ajouter tous les champs à $builder
parent::buildForm($builder, $options);
// On supprime celui qu'on ne veut pas dans le formulaire de modification
$builder->remove('image')
->add('image', 'file', array(
'data_class' => null,
'required' => false
))
;


$builder->addEventListener(FormEvents::POST_SUBMIT, function (FormEvent $event) {
// Retrieve submitted data
$form = $event->getForm();
$item = $event->getData();

// Test if upload image is null (maybe adapt it to work with your code)
if (null !== $form->get('image')->getData()) {
var_dump($form->get('image')->getData());
die('image provided');
$item->setImage($form->get('image')->getData());
}
});


}

// On modifie cette méthode car les deux formulaires doivent avoir un nom différent
public function getName()
{
return 'van_teamsbundle_teamedittype';
}
}

和整个团队实体:
<?php

namespace Van\TeamsBundle\Entity;

use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;

/**
* Team
*
* @ORM\Table()
* @ORM\HasLifecycleCallbacks
* @ORM\Entity
* @ORM\Entity(repositoryClass="Van\TeamsBundle\Entity\TeamRepository") @ORM\Table(name="van_teams")
*/
class Team
{
/**
* @var integer
*
* @ORM\Column(name="id", type="integer")
* @ORM\Id
* @ORM\GeneratedValue(strategy="AUTO")
*/
private $id;

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

/**
* @var string
*
* @ORM\Column(name="countryCode", type="string", length=2)
*/
private $countryCode;

/**
* @ORM\ManyToOne(targetEntity="Van\TeamsBundle\Entity\Game")
* @ORM\JoinColumn(nullable=false)
*/
private $game;

/**
* @ORM\ManyToOne(targetEntity="Van\TeamsBundle\Entity\Statut")
* @ORM\JoinColumn(nullable=false)
*/
private $statut;

/**
* @var string $image
* @Assert\File( maxSize = "1024k", mimeTypesMessage = "Please upload a valid Image")
* @ORM\Column(name="image", type="string", length=255)
*/
private $image;



/**
* Get id
*
* @return integer
*/
public function getId()
{
return $this->id;
}

/**
* Set name
*
* @param string $name
* @return Team
*/
public function setName($name)
{
$this->name = $name;

return $this;
}

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

/**
* Set countryCode
*
* @param string $countryCode
* @return Team
*/
public function setCountryCode($countryCode)
{
$this->countryCode = $countryCode;

return $this;
}

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

/**
* Set image
*
* @param string $image
* @return Team
*/
public function setImage($image)
{
$this->image = $image;

return $this;
}

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

/**
* Set game
*
* @param \Van\TeamsBundle\Entity\Game $game
* @return Team
*/
public function setGame(\Van\TeamsBundle\Entity\Game $game)
{
$this->game = $game;

return $this;
}

/**
* Get game
*
* @return \Van\TeamsBundle\Entity\Game
*/
public function getGame()
{
return $this->game;
}

/**
* Set statut
*
* @param \Van\TeamsBundle\Entity\Statut $statut
* @return Team
*/
public function setStatut(\Van\TeamsBundle\Entity\Statut $statut)
{
$this->statut = $statut;

return $this;
}

/**
* Get statut
*
* @return \Van\TeamsBundle\Entity\Statut
*/
public function getStatut()
{
return $this->statut;
}






public function getFullImagePath() {
return null === $this->image ? null : $this->getUploadRootDir(). $this->image;
}

protected function getUploadRootDir() {
// the absolute directory path where uploaded documents should be saved
// return $this->getTmpUploadRootDir();
return __DIR__ . '/../../../../web/uploads/';
}

protected function getTmpUploadRootDir() {
// the absolute directory path where uploaded documents should be saved
return __DIR__ . '/../../../../web/uploads_tmp/';
}

/**
* @ORM\PrePersist()
* @ORM\PreUpdate()
*/
public function uploadImage() {
// the file property can be empty if the field is not required
if (null === $this->image) {
return;
}
if(!$this->id){
$this->image->move($this->getTmpUploadRootDir(), $this->image->getClientOriginalName());
}else{
$this->image->move($this->getUploadRootDir(), $this->image->getClientOriginalName());
}
$this->setImage($this->image->getClientOriginalName());
}

/**
* @ORM\PostPersist()
*/
public function moveImage()
{
if (null === $this->image) {
return;
}
if(!is_dir($this->getUploadRootDir())){
mkdir($this->getUploadRootDir());
}
copy($this->getTmpUploadRootDir().$this->image, $this->getFullImagePath());
unlink($this->getTmpUploadRootDir().$this->image);
}

/**
* @ORM\PreRemove()
*/
public function removeImage()
{
unlink($this->getFullImagePath());
rmdir($this->getUploadRootDir());
}
}

编辑 2

我就是这么做的。当我提供图像时,它会保存在数据库的图像字段中并重定向到我的索引页面。当我不提供任何图像时,不会发生重定向,并且在我的表单中的文件输入上方显示以下消息:“找不到文件。”在我的 TeamEditType类,我做了以下,所以图像不应该是必需的。
$builder->remove('image')
->add('image', 'file', array(
'data_class' => null,
'required' => false
))
;

最佳答案

从 Symfony 2.3 开始,您可以简单地使用 补丁 http 方法,如文档所示 here .

    $form = $this->createForm(FooType::class, $foo, array(
'action' => $this->generateUrl('foo_update', array('id' => $foo->getId())),
'method' => 'PATCH',
));

这是使用主表单对实体进行部分更新的简单方法,无需渲染所有字段。

关于Symfony2 : do not update a form field if not provided,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22557340/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com