Reputation: 3
There is Payments that belongsTo Salaries (Payments.salary_id).
In Salaries/view.php I have "Add new payment" link:
<?= $this->Html->link(__('Add new payment'), ['controller'=>'Payments','action' => 'add', $salary->id], ['class' => 'side-nav-item']) ?>
In PaymentsController.php:
public function add($salary_id = null)
{
$payment = $this->Payments->newEmptyEntity();
if ($this->request->is('post')) {
$payment = $this->Payments->patchEntity($payment, $this->request->getData());
if ($this->Payments->save($payment)) {
$this->Flash->success(__('The payment has been saved.'));
return $this->redirect(['controller'=>'Salaries','action' => 'view', $payment->salary_id]);
}
$this->Flash->error(__('The payment could not be saved. Please, try again.'));
}
if ($salary_id) {
$salaries = $this->Payments->Salaries->find('list')
->where(['Salaries.id LIKE' => $salary_id])
->contain(['Employees'])
->all();
} else {
$salaries = $this->Payments->Salaries->find('list', ['contain' => ['Employees']])->all();
}
$this->set(compact('payment', 'salaries'));
}
When the salary_id is passed to the Payments/add.php, only this Salary is shown in the select menu. If there is no salary_id, then all the Salaries are shown in the select menu. The Salaries needs to have Employees as there is displayField that will get data from Employee.
This part in the Payments/add.php:
echo $this->Form->control('salary_id');
Seems to get the displayField from $salaries (array) by magic.
The questions are:
I am new to CakePHP so please bear with me.
Upvotes: 0
Views: 21
Reputation: 60463
What you probably should do is to:
Always pass all salaries to the view, ie do not take the ID into account in the controller.
Pass the $salary_id
variable to the view, and use it for the control's default
option, it will then use this as the value for selection unless there's a value for it in the current request (for example in the POST data).
// ...
$salaries = $this->Payments->Salaries->find('list')->contain('Employees')->all();
$this->set(compact('payment', 'salaries', 'salary_id'));
echo $this->Form->control('salary_id', ['default' => $salary_id]);
On a side note, containing data when using a list
finder will not add any of the contained data to the results, so unless the contain causes an INNER
join that you'd want to use for filtering data, there should be no need for it (consider using innerJoinWith()
instead if you want to filter things).
See also
Upvotes: 1