Custom Choice type with parameters

Viewed 20

I make my custom ChoiceType

class CountryType extends ChoiceType
{

    public function configureOptions(OptionsResolver $resolver): void
    {
        parent::configureOptions($resolver);
        $resolver->setDefaults([
            'choices'      => $this->locationService->getCountries(),
        ]);
    }
}

class StateType extends ChoiceType
{

    public function configureOptions(OptionsResolver $resolver): void
    {
        parent::configureOptions($resolver);
        $choices = isset($countryId)? $this->locationService->getStatesByCountryId($countryId):[]; <---

        $resolver->setDefaults([
            'choices' => $choices,
        ]);
    }
}

class FormType extends AbstractType
{

    public function buildForm(FormBuilderInterface $builder, array $options): void
    {
        $builder->add('country', CountryType::class, [
                'label'    => 'Country',
                'required' => false,
            ])->add('state', StateType::class, [
                'label'    => 'State',
                'required' => false,
            ]);
    }

    public function configureOptions(OptionsResolver $resolver): void
    {
        $resolver->setDefaults([
            'data_class'        => FormRequest::class,
            'validation_groups' => [],
        ]);
    }
}

But for StateType optionally (when I edit entity) I need $countryId how I can put it? Maybe with options or choice_loader?

I also tried to crank out such an idea, but as I understand it, this is not possible

                         {{ form_widget(form.state, {
                            'countryId': form.country.vars.value,
                         }) }}    

           
0 Answers
Related