last night I saw a video on YouTube: CakeFest 2024 HtmxHelper The revival of JsHelper by Juan Diaz Gonzalez
After installing the plugin from Github and playing around with it, I have a question regarding the response from the controller.
I have three tables:
Worldcuisines with fields “id” and “name”
Nationalcuisines with fields “id”, “name” and “worldcuisine_id”
(Regionalcuisines with fields “id”, “name” and “nationalcuisine_id”)
Nationalcuisines is associated to Worldcuisines via (regionalcuisines is associated in the same way to nationalcuisines)
$this->belongsTo('Worldcuisines', [
'foreignKey' => 'worldcuisine_id',
'joinType' => 'INNER',
]);
The form looks like this:
<?= $this->Form->control('worldcuisine_id', [
'options' => $worldcuisines,
'empty' => true,
'hx-trigger'=> "change",
'hx-get' => $this->Url->build(['controller' => 'Nationalcuisines', 'action' => 'fetchNationalcuisines']),
'hx-target'=> '#nationalcuisine-id',
])
?>
<?= $this->Form->control('nationalcuisine_id', [
'hx-trigger'=> "change",
'hx-get' => $this->Url->build(['controller' => 'Regionalcuisines', 'action' => 'fetchRegionalcuisines']),
'hx-target'=> '#regionalcuisine-id',
'empty' => false,
'options'=>[__('Please select a worldcuisine')],
])
?>
<?= $this->Form->control('regionalcuisine_id', [
'empty' => false,
'options'=>[__('Please select a nationalcuisine')],
])
?>
The method in NationalcuisinesController:
public function fetchNationalcuisines()
{
$this->autoRender=false;
if (!$this->request->is('htmx')) {
//do something, if it is no htmx request
}
$worldcuisine_id = $this->request->getQuery('worldcuisine_id');
$nationalcuisines = $this->Nationalcuisines
->find()
->select(['id','name'])
->where(['worldcuisine_id'=>$worldcuisine_id])
->all();
$options="<option>".__('No nationalcuisines to select')."</option>";
if (count($nationalcuisines)>0) {
$options="<option>".__('Please select a nationalcuisine')."</option>";
foreach ($nationalcuisines AS $nationalcuisine) {
$options.= '<option value="'.$nationalcuisine->id.'">'.$nationalcuisine->name.'</option>';
}
}
echo $options;
exit();
}
This works for me, but I´m wondering if there is any other way to return the “$options” to the form. Maybe as json?
I did not find anything in the documents (maybe I did not enough research?).
Any hint or link to the documents would be helpful.