6

目前我有一个表格

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项目。我想我可以添加一个单选按钮,但我需要它在添加模式下处于“非活动状态”。现在我正在处理我的模型中的图像上传,我希望有它(除非有更好的地方来做)

/**
 * 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;
    }

}
4

2 回答 2

12

您可以在表单构建期间使用数据设置条件:

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
        }
    }
    // ...
}
于 2012-05-21T12:02:10.907 回答
4

您可以使用表单事件,有一个类似的方法:

http://symfony.com/doc/current/cookbook/form/dynamic_form_generation.html

于 2012-05-23T23:15:31.900 回答