I have defined couple of fields inside my custom entity basefielddefinitions() like so...
$fields['product_line'] = BaseFieldDefinition::create('entity_reference')...
$fields['product'] = BaseFieldDefinition::create('entity_reference')...
.
Then in entity form class (ProductLineForm.php), I try to attach an ajax callback to my product_line select
list such that it populates the product select list
, like this
$form['product_line']['#group'] = 'details';
$form['product_line']['#ajax'] = [
'callback' => '::populateProducts',
'event' => 'change',
'wrapper' => 'edit-products'
];
Then my product select list looks like this...
$form['product']['#group'] = 'details';
$form['product']['#attributes'] = [
'id' => 'edit-products',
];
and then my populateProducts() function...
public function populateProducts(array $form, FormStateInterface $form_state) {
$form['product']['#options'] = ['1' => 'One', '2' => 'Two'];
$form_state->setRebuild(TRUE);
$response = new AjaxResponse();
$option = "<option value='45'>Just testing</option>";
$response->addCommand(
new \Drupal\Core\Ajax\ReplaceCommand(
'#edit-products',
($form['product'])
)
);
return $response;
}
The problem is that nothing whatsoever happens, no signs of any ajax call, and the product select list stays empty as it always been.
(1)Is the the entityform class the right place for me to attach an #ajax call to a field defined in a custom entity? Or do I need a hook? Meanwhile I've done a lot of other modifications on the custom fields here in this entity form edit class (like grouping into fieldsets, vertical tabs and even modifying weight (eg $form['product_line']['#weight'] = 3
- and they all work, why not $form['product_line']['#ajax']
....?
(2) Is there a way of attaching the ajax callback directly inside my custom entity's basefielddefinitions
where I define the fields, I would prefer that...
Really stuck on this one, folks, please could someone help me? Appreciate all your input, Thank you all.
product_line
andproduct
?'#type' => 'select'
?product_line
andproduct
are select.\module\src\Form\ProductLine Form
which is theadd_form
for myProductLine
entity...