Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rmsint/ad4d8804e3ae6fae2160 to your computer and use it in GitHub Desktop.
Save rmsint/ad4d8804e3ae6fae2160 to your computer and use it in GitHub Desktop.
remove option for file upload field
<?php
namespace Acme\DemoBundle\Form\EventListener;
use Symfony\Component\Form\Event\DataEvent;
use Symfony\Component\Form\FormFactoryInterface;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\Form\FormEvents;
class AddRemoveImageFieldSubscriber implements EventSubscriberInterface
{
private $factory;
public function __construct(FormFactoryInterface $factory)
{
$this->factory = $factory;
}
public static function getSubscribedEvents()
{
// Tells the dispatcher that we want to listen on the form.pre_set_data
// event and that the preSetData method should be called.
return array(FormEvents::PRE_SET_DATA => 'preSetData');
}
public function preSetData(DataEvent $event)
{
$data = $event->getData();
$form = $event->getForm();
// During form creation setData() is called with null as an argument
// by the FormBuilder constructor. We're only concerned with when
// setData is called with an actual Entity object in it (whether new,
// or fetched with Doctrine). This if statement let's us skip right
// over the null condition.
if (null === $data) {
return;
}
// check if the data object has an image
if ($data->getImage()) {
$form->add($this->factory->createNamed('checkbox', 'removeFile', null, array('required' => false)));
}
}
}
{{ form_label(form.file,'form.label_file'|trans({}, admin.translationDomain)) }}
<div class="input">
<ul class="inputs-list">
{% if form.vars.data.image %}
<li><img src="{{ asset(form.vars.data.webPath) }}" /></li>
<li>
<label for="{{ form.removeFile.get('id') }}">
{{ form_widget(form.removeFile) }}
<span>{{ 'form.label_remove_file'|trans({}, admin.translationDomain) }}</span>
</label>
</li>
{% endif %}
<li>
{{ form_widget(form.file) }}
{{ form_errors(form.file) }}
</li>
</ul>
</div>
// ...
public function buildForm(FormBuilder $builder, array $options)
{
$builder
// ...
->add('file', null, array('required' => false))
;
// only add a remove file checkbock when the document has an image
$subscriber = new AddRemoveFileFieldSubscriber($builder->getFormFactory());
$builder->addEventSubscriber($subscriber);
}
// ...
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment