目前我有一个表格

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));
    }
    // ...
}

到目前为止,我使用的是编辑和删除功能。但是现在,在编辑“模式”下,我希望允许用户清除项目的icon。我想我可以添加一个单选按钮,但是在添加模式下,我需要使其处于“非 Activity 状态”。目前,我正在模型中处理图片上传,希望在那里保存(除非有更好的放置位置)
/**
 * 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, array $options) {
        $builder->add('name');
        $builder->add('description', 'textarea');
        $builder->add('iconFile', 'file', array('label' => 'Icon', 'required' => false));

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

关于forms - 使用相同的Symfony2表单进行编辑和删除(字段中的差异),我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/10498807/

10-09 20:40
查看更多