Reputation: 67
I am working in app with cakephp 3, in this app the admin users can register pays made for other users, what i am trying to do is allow the users to create multiple pays at once in the same view, one pay per user. what i have done is first create one form repeating the fields for each user.
The problem is when i click the submit button(i want only one), the data that i recive in my controller is always the data of the last fields. I don't know how to handle this in the rigth way.
Here is the code of mi view:
addMulti.ctp
<div class="pagos form col-lg-offset-2 col-lg-7">
<?= $this->Form->create(false) ?>
<?php foreach ($users as $user):
echo '<br><strong>'.$user->full_name.'</strong>';
echo $this->Form->checkbox('selected',['id'=>'select-'.$user->id,'onclick'=>'display_add_form('.$user->id.')']).'<br>';
echo '<div style="display: none;" id= form-'.$user->id.'>';
echo $this->Form->input('user_id', array(
'type' => 'hidden',
'value' => $user->id,
'id'=>'user-'.$user->id
));
echo $this->Form->input('mes', ['type' => 'month','selected'=>'0','id'=>'month-'.$user->id]);
echo $this->Form->input('monto',['default' => $user->monto_paga,'id'=>'monto-'.$user->id]);
echo $this->Form->input('año', ['type' => 'year', [
'minYear' => date('Y')-2,
'maxYear' => date('Y')+2
],'value'=> date('Y'),'id'=>'year-'.$user->id]);
echo $this->Form->input('forma_pago', ['options'=>['Efectivo'=>'Efectivo','Transferencia'=>'Transferencia','Cheque'=>'Cheque'],'id'=>'pago-'.$user->id]);
echo $this->Form->button('Cancelar',['type'=>'button','onclick'=>'hide_add_form('.$user->id.')','class'=>'btn btn-danger','id'=>'cancel-'.$user->id]);
echo '</div>';
endforeach;
echo $this->Form->button(__('Agregar Pagos'),['class'=>'btn btn-primary']);
echo $this->Form->end(); ?>
<script>
function display_add_form(id){
$("#form-"+ id).show('fast');
$("#select-"+ id).hide();
}
function hide_add_form(id) {
$("#form-"+ id).hide('fast');
$("#select-"+ id).show();
}
Upvotes: 0
Views: 983
Reputation: 891
To continue the answer from @Asif, it would be easier if you save each user separately.
...
echo $this->Form->input('users['.$user->id.'][mes]', ['type' => 'month','selected'=>'0','id'=>'month-'.$user->id]);
echo $this->Form->input('users['.$user->id.'][monto]',['default' => $user->monto_paga,'id'=>'monto-'.$user->id]);
...
In this way you could use an easy loop in the backend, like:
<?php
foreach($input['users'] as $userId => $user){
echo $user['mes'];
}
Upvotes: 2
Reputation: 409
you can put the filed name as array so you can get all your form POST value in array cause you are posting multiple value under a single variable. I just give a simple html input field example below. Wish you know how to add in cakephp.
<input type="text" name="year[]" id="your-id">
Upvotes: 1