I have a symfony form with database tables in a choice field. The second field is a choice field which should display the columns in the previous selected database table field.
I got it to work without using symfony forms by using a form markup with plain javascript. Now I want to achieve the same with symfony forms but can't get it to work.
My code this far:
class SearchReplaceType extends AbstractType
{
private $_tableColumns = [];
public function __construct(TwigEnvironment $twig, Connection $connection)
{
$this->twig = $twig;
$this->connection = $connection;
}
public function buildForm(FormBuilderInterface $builder, array $options): void
{
$schemaManager = $this->connection->getSchemaManager();
$tables = $schemaManager->listTables();
$tableNames = [];
foreach($tables as $table) {
$tableNames[$table->getName()] = $table->getName();
foreach($table->getColumns() as $column) {
$this->_tableColumns[$table->getName()][] = $column->getName();
}
}
$builder
->add('table', ChoiceType::class, [
'placeholder' => 'Test',
'choices' => $tableNames
])
->addEventListener(FormEvents::PRE_SET_DATA, function (FormEvent $event) {
// check which value/option is selected in table choice field
// display the columns in the selected table as choices
})
->add('column', ChoiceType::class, [
'placeholder' => 'Please select a column',
'choices' => [] // callback function to get the columns
])
->add('search', TextType::class)
->add('replace', TextType::class)
->add('submit', SubmitType::class)
;
}
}
I tried reading the docs regarding symfony form events but still could not find a solution. My questions:
- Which would be the right event to use? I want it to update the column choice field as soon as the table choice field is changed. I don't want to wait till the form is submitted by the user. https://symfony.com/doc/4.4/form/dynamic_form_modification.html#form-events-submitted-data
Based on my little knowledge this far I'd tend to use the post_submit event, but I could be wrong here. This event also does not seem to fire for some reason :/
- How could I change the options for my column field dynamically via such an event? In the symfony example ajax was used, would this be the right way?
Maybe someone can help me here. Would be very appreciated. I read a lot of stackoverflow questions regarding this issue but couldn't get it to work yet.
Thank you!
