2012-05-08 10 views
6

Actualmente tengo una formaUtilizando la misma forma Symfony 2 para editar y eliminar (las diferencias en los campos)

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

estoy usando para editar & eliminar bien hasta ahora. Pero ahora, en el "modo" de edición, quiero permitir que el usuario borre el icon para el proyecto. Creo que puedo agregar un botón de opción, pero necesitaré que esté "inactivo" en el modo de agregar. Por ahora yo estoy manejando la carga de imágenes en mi modelo, y me espero tenerlo allí (a menos theres un mejor lugar para hacerlo)

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

} 

Respuesta

12

Usted puede poner condiciones durante la forma de la estructura a partir de datos:

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 
     } 
    } 
    // ... 
} 
Cuestiones relacionadas