Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Allow to add a new value in a choice Field Type

I use Form Component and have a choice Field Type on a form which is rendered to a select field. On a client-side I use select2 plugin which initializes the select with the setting tags: true which allows to add a new value in it. But if I add a new value then a validation on a server will fail with error

This value is not valid.

because the new value isn't in a choice list.

Is there a way to allow adding of a new value to choice a Field Type?

like image 458
Vasily Avatar asked Sep 17 '15 10:09

Vasily


People also ask

How do you add a Choice column in PowerApps?

Sign into powerapps.com, select Solutions, and then open the solution you want. Open the table where you want to create the choice, and then on the command bar, select New > Choice. In the New column panel, enter properties for the choice column.

How do I add a blank field to a choice field in SharePoint?

At the first entry on the list do a return to create a blank space. Inside that blank space place your cursor and press and hold down the ALT key while typing 0129 on the NUMERIC KEYPAD. ... In the Default Entry setting do the same. Save and you are done.


2 Answers

The problem is in a choice transformer, which erases values that don't exist in a choice list.
The workaround with disabling the transformer helped me:

public function buildForm(FormBuilderInterface $builder, array $options)
{
    $builder->add('choiceField', 'choice', ['choices' => $someList]);

    // more fields...

    $builder->get('choiceField')->resetViewTransformers();
}
like image 146
Vasily Avatar answered Sep 28 '22 20:09

Vasily


Here's an example code in case someone needs this for EntityType instead of the ChoiceType. Add this to your FormType:

use AppBundle\Entity\Category;
use Symfony\Component\Form\FormEvent;
use Symfony\Component\Form\FormEvents;

$builder->addEventListener(FormEvents::PRE_SUBMIT, function (FormEvent $event) {
    $data = $event->getData();

    if (!$data) {
        return;
    }

    $categoryId = $data['category'];

    // Do nothing if the category with the given ID exists
    if ($this->em->getRepository(Category::class)->find($categoryId)) {
        return;
    }

    // Create the new category
    $category = new Category();
    $category->setName($categoryId);
    $this->em->persist($category);
    $this->em->flush();

    $data['category'] = $category->getId();
    $event->setData($data);
});
like image 25
Taylan Avatar answered Sep 28 '22 19:09

Taylan