Using the same Symfony 2 form for editing and deletion (field differences)

I currently have a form

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

I use to edit and delete so far. But now, in edit mode, I want to allow the user to clear the icon for the project. I think I can add a switch, but I need it to be "inactive" in add mode. At the moment I am processing image upload in my model and I hope that it will be there (if this is not the best place for this)

 /** * 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; } } 
+6
source share
2 answers

You can set conditions during the assembly of the form using the data:

 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 } } // ... } 
+12
source

You can use form events, there is a recipe for just something like this:

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

+4
source

Source: https://habr.com/ru/post/915195/


All Articles