表单 – 使用相同的Symfony 2表单进行编辑和删除(字段差异)

目前我有一张表格
class Project extends AbstractType {
    public function buildForm(FormBuilder $builder,array $options) {
        $builder->add('name');
        $builder->add('description','textarea');
        $builder->add('iconFile','file',array('label' => 'Icon','required' => false));
    }
    // ...
}

我用于编辑&到目前为止删除罚款.但现在,在编辑“模式”中,我想允许用户清除项目的图标.我想我可以添加一个单选按钮,但我需要它在添加模式下“不活动”.现在我正在我的模型中处理图像上传,我希望在那里(除非有更好的地方去做)

/**
 * If isDirty && iconFile is null: deletes old icon (if any). 
 * Else,replace/upload icon
 * 
 * @ORM\PrePersist 
 * @ORM\PreUpdate
 */
public function updateIcon() {

    $oldIcon = $this->iconUrl;

    if ($this->isDirty && $this->iconFile == null) {

        if (!empty($oldIcon) && file_exists(APP_ROOT . '/uploads/' . $oldIcon)) 
            unlink($oldIcon);

    } else {

        // exit if not dirty | not valid
        if (!$this->isDirty || !$this->iconFile->isValid())
            return;

        // guess the extension
        $ext = $this->iconFile->guessExtension();
        if (!$ext) 
            $ext = 'png';

        // upload the icon (new name will be "proj_{id}_{time}.{ext}")
        $newIcon = sprintf('proj_%d_%d.%s',$this->id,time(),$ext);
        $this->iconFile->move(APP_ROOT . '/uploads/',$newIcon);

        // set icon with path to icon (relative to app root)
        $this->iconUrl = $newIcon;

        // delete the old file if any
        if (file_exists(APP_ROOT . '/uploads/' . $oldIcon) 
            && is_file(APP_ROOT . '/uploads/' . $oldIcon)) 
            unlink($oldIcon);

        // cleanup
        unset($this->iconFile);
        $this->isDirty = false;
    }

}

解决方法

您可以使用数据在表单构建期间放置条件:
class Project extends AbstractType {
    public function buildForm(FormBuilder $builder,'required' => false));

        if ($builder->getData()->isNew()) { // or !getId()
            $builder->add('delete','checkBox'); // or whatever
        }
    }
    // ...
}

相关文章

vue阻止冒泡事件 阻止点击事件的执行 <div @click=&a...
尝试过使用网友说的API接口获取 找到的都是失效了 暂时就使用...
后台我拿的数据是这样的格式: [ {id:1 , parentId: 0, name:...
JAVA下载文件防重复点击,防止多次下载请求,Cookie方式快速简...
Mip是什么意思以及作用有哪些