<?php

declare(strict_types=1);

/*
 * Chill is a software for social workers
 *
 * For the full copyright and license information, please view
 * the LICENSE file that was distributed with this source code.
 */

namespace Chill\CustomFieldsBundle\Form\Type;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\Extension\Core\Type\ChoiceType;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;

/**
 * Return a choice widget with an "other" option.
 */
class ChoiceWithOtherType extends AbstractType
{
    private string $otherValueLabel = 'Other value';

    /** (non-PHPdoc).
     * @see \Symfony\Component\Form\AbstractType::buildForm()
     */
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        // add an 'other' entry in choices array
        $options['choices'][$this->otherValueLabel] = '_other';
        // ChoiceWithOther must always be expanded
        $options['expanded'] = true;
        // adding a default value for choice
        $options['empty_data'] = null;

        $builder
            ->add('_other', TextType::class, ['required' => false])
            ->add('_choices', ChoiceType::class, $options);
    }

    /** (non-PHPdoc).
     * @see \Symfony\Component\Form\AbstractType::configureOptions()
     */
    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver
            ->setRequired(['choices'])
            ->setAllowedTypes('choices', ['array'])
            ->setDefaults([
                'multiple' => false,
            ]);
    }
}
