I have this tables:
customers[id, name, surname, phone, text, balance, created]
service_types[id, title, price, length, is_subscription, created]
customer_service_types[id, customer_id, service_type_id, price, created]
In add.ctp
of CustomerServiceTypes I have a dropdown containing the Service Types and a field containing the price. What I want is when the user selects a Service Type from the dropdown, then update the price field with the price
of selected Service Type.
Here is the existing code:
add.ctp
<fieldset>
<legend><?= __('Add Customer Service Type') ?></legend>
<?php
echo $this->Form->control('customer_id', ['options' => $customers]);
echo $this->Form->control('service_type_id', ['options' => $serviceTypes]);
echo $this->Form->control('price');
?>
</fieldset>
<?= $this->Form->button(__('Submit')) ?>
<?= $this->Form->end() ?>
CustomerServiceTypesController.php
(add function)
public function add()
{
$customerServiceType = $this->CustomerServiceTypes->newEntity();
if ($this->request->is('post')) {
$customerServiceType = $this->CustomerServiceTypes->patchEntity($customerServiceType, $this->request->getData());
if ($this->CustomerServiceTypes->save($customerServiceType)) {
$this->Flash->success(__('The customer service type has been saved.'));
return $this->redirect(['action' => 'index']);
}
$this->Flash->error(__('The customer service type could not be saved. Please, try again.'));
}
$customers = $this->CustomerServiceTypes->Customers->find('list', ['limit' => 200]);
$serviceTypes = $this->CustomerServiceTypes->ServiceTypes->find('list', ['limit' => 200]);
$this->set(compact('customerServiceType', 'customers', 'serviceTypes'));
}
You can create a js function which is called using the onchange property for the select box and then as soon as you got the result you can change the input field value.
For reference you can take a look at this Changing the value of Input field when user select option from select box