Created
February 16, 2018 06:12
-
-
Save blackandred/f0a4df26ec3cb618203a0863d21ee6d8 to your computer and use it in GitHub Desktop.
Symfony 4: In context of edit (not creation) allow the fields to be partialy modified (single fields could be submitted, the rest ignored)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php declare(strict_types = 1); | |
namespace App\Core\Form\Type; | |
use App\Core\Service\Content\TextUtils; | |
use Symfony\Component\Form\AbstractType; | |
use Symfony\Component\Form\FormBuilderInterface; | |
use Symfony\Component\Form\Extension\Core\Type\{TextType, LanguageType, SubmitType, CheckboxType}; | |
use Symfony\Component\Form\FormEvent; | |
use Symfony\Component\Form\FormEvents; | |
use Symfony\Component\OptionsResolver\OptionsResolver; | |
use App\Core\Entity\Page; | |
/** | |
* Form for static pages edit | |
* ========================== | |
* | |
* @see Page | |
*/ | |
class PageType extends AbstractType | |
{ | |
/** | |
* @see Page | |
* | |
* @param FormBuilderInterface $builder | |
* @param array $options | |
*/ | |
public function buildForm(FormBuilderInterface $builder, array $options) | |
{ | |
$builder | |
->add('title', TextType::class) | |
->add('language', LanguageType::class) | |
->add('submitted', SubmitType::class) | |
->add('is_published', CheckboxType::class) | |
->add('url_name', TextType::class); | |
if ($options['isEditMode'] === true) { | |
$this->allowFieldsToBeOptionalInEditMode($builder); | |
} | |
} | |
/** | |
* @param OptionsResolver $resolver | |
*/ | |
public function configureOptions(OptionsResolver $resolver) | |
{ | |
$resolver->setDefaults([ | |
'data_class' => Page::class, | |
'allow_extra_fields' => false, | |
'isEditMode' => false, | |
]); | |
} | |
private function allowFieldsToBeOptionalInEditMode(FormBuilderInterface $builder) | |
{ | |
$builder->addEventListener(FormEvents::PRE_SUBMIT, function (FormEvent $event) { | |
$data = $event->getData(); | |
$form = $event->getForm(); | |
foreach ($form->all() as $field) { | |
$fieldName = TextUtils::dashesToCamelCase($field->getName()); | |
if (!isset($data[$fieldName]) || !$data[$fieldName]) { | |
$form->remove($field->getName()); | |
} | |
} | |
}); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment