CakePHP 3.x update multiple rows - cakephp-3.0

I have a table AssetsAssignations, with hundreds of rows. In some cases, the user needs to select many rows with a checkbox, and change the "status" for all of them together.
In my controller, I have this function
public function editMultiple()
{
$assetStatuses = $this->AssetsAssignations->AssetStatuses->find('list');
$this->paginate = [
'contain' => ['Assets', 'AssetStatuses', 'Clients', 'Rooms'],
'sortWhitelist' => [
'Assets.model_number',
'Assets.serial_number',
'AssetStatuses.name',
'Clients.last_name',
'Rooms.name',
]
];
$assetsAssignations = $this->request->data;
$assetsAssignations_ids = array();
foreach($assetsAssignations as $a){
$assetsAssignations_ids[$a['id']] = $a['id'];
$this->AssetsAssignations->updateAll(
array('AssetAssignation.id' => $assetsAssignations_ids)
);
$this->Session->setFlash(__('Statsus is updated for the selcted entries!'));
}
debug($assetsAssignations);
$query = $this->AssetsAssignations->find()
->contain(['Assets', 'AssetStatuses', 'Clients', 'Rooms']);
$filter = $this->Filter->prg($query);
$assetsAssignations = $this->paginate($filter, ['maxLimit' => 10000, 'limit' => 10000]);
$this->set(compact('assetsAssignations', 'assetStatuses'));
$this->set('_serialize', ['assetsAssignations']);
}
In my edit_multiple.ctp, I use a javascript to filter the data. And I put this code:
<table class="hoverTable dataTable">
<thead>
<tr>
<th>Select</th><th>Model Number</th><th>Serial Number</th><th>Room</th><th>Client</th><th>Status</th>
</tr>
</thead>
</thead>
<?php foreach ($assetsAssignations as $assetsAssignation): ?>
<tr>
<td><input name="data[AssetsAssignations][id][]" value="<?= $assetsAssignation->id ?>" id="AssetsAssignationsId1" type="checkbox"></td>
<td><?= $assetsAssignation->has('asset') ? $assetsAssignation->asset->model_number : '' ?></td>
<td><?= $assetsAssignation->has('asset') ? $assetsAssignation->asset->serial_number : '' ?></td>
<td><?= $assetsAssignation->has('room') ? $assetsAssignation->room->name : '' ?></td>
<td><?= $assetsAssignation->has('client') ? $assetsAssignation->client->last_name . ', ' . $assetsAssignation->client->first_name: '' ?></td>
<td><?= $assetsAssignation->has('asset_status') ? $assetsAssignation->asset_status->name : '' ?></td>
</tr>
<?php endforeach; ?>
</table>
<legend><?= __('') ?></legend>
</div>
<?= $this->Form->create($assetsAssignation) ?>
<fieldset>
<div class="row">
<div class="col-xs-3"><?= $this->Form->input('asset_status_id', ['options' => $assetStatuses, 'empty' => true, 'label' => __('Change Status To')]) ?></div>
</div>
</fieldset>
<?= $this->Form->button(__('Submit')) ?>
<?= $this->Form->end() ?>
When I debug the result, checking 3 entries, I get this:
[
'data' => [
'AssetsAssignations' => [
'id' => [
(int) 0 => '411',
(int) 1 => '413',
(int) 2 => '415'
]
]
],
'asset_status_id' => '3'
]
My question is: How to pass the selected row IDs to the "Submit" button after selecting the checkboxes ?
Thanks in advance.

I think that what you want to do is something like
if($this->request->is('post')
{
$ids = $this->request->data('data.AssetsAssignations.id');
$asset_status_id = $this->request->data('asset_status_id');
$this->AssetsAssignations->updateAll(
['asset_status_id ' => $asset_status_id ]
['id IN' => $ids]
);
}

Based on what #Arilia suggested, tis worked for me. In my controller, function, I put this:
$this->request->data;
$data = $this->request->data;
debug($data);
if($this->request->is(['patch', 'post', 'put']))
{
$ids = $this->request->data('data.AssetsAssignations.id');
$asset_status_id = $this->request->data('asset_status_id');
$this->AssetsAssignations->updateAll(
['asset_status_id ' => $asset_status_id ],
['id IN' => $ids]
);
}
In my view, I put this:
<td><input type="checkbox" name="data[AssetsAssignations][id][]" value="<?= $assetsAssignation->id ?>" id="ApplicationId1" ></td>

Related

Yii2 - Key Value Not Working

I want to relate to a model from another model, but I got this error:
This is the other model I am pointing to from the View
CourseMaster Model
public function attributeLabels()
{
return [
'id' => Yii::t('course', 'ID'),
'course_code' => Yii::t('course', 'Course Code'),
'course_type' => Yii::t('course', 'Course Type'),
'course_title' => Yii::t('course', 'Course Title'),
'course_unit' => Yii::t('course', 'Course Unit'),
];
}
function getCourseCodes()
{
return ($this->course_code);
}
function getCourseTitles()
{
return ($this->course_title);
}
function getCourseTypes()
{
return ($this->course_type);
}
function getCourseUnits()
{
return ($this->course_unit);
}
This is the Main Model that I want to display in the view
CourseRegistrationDetail Model
public function attributeLabels()
{
return [
'id' => Yii::t('course', 'ID'),
'course_registration_id' => Yii::t('course', 'Course Registration'),
'course_id' => Yii::t('course', 'Course Title'),
'student_id' => Yii::t('course', 'Student'),
'remark' => Yii::t('course', 'Remark'),
];
}
public function getCourseMaster()
{
return $this->hasOne(CourseMaster::className(), ['id' => 'course_id']);
}
I want to be able to use array index as $key
View
<tr>
<td colspan=3 class="padding-left padding-right">
<?php $totalUnit = 0;
$courseRegistrationDetails = \app\modules\course\models\CourseRegistrationDetail::find()->where(['course_registration_id' => $model->id])->asArray()->all(); ?>
<table border="1" class="table table-border" style="width:100%;">
<tr class="header">
<th><?php echo Yii::t('report', 'SI.No'); ?></th>
<th><?php echo Yii::t('report', 'Course Code'); ?></th>
<th><?php echo Yii::t('report', 'Course Title'); ?></th>
<th><?php echo Yii::t('report', 'Course Type'); ?></th>
<th><?php echo Yii::t('report', 'Unit'); ?></th>
<th><?php echo Yii::t('report', 'Remark'); ?></th>
</tr>
<?php
foreach($courseRegistrationDetails as $key=>$value) {
echo '<tr>';
echo '<td class="text-center">'.($key+1).'</td>';
echo '<td class="text-center">'.$value->courseMasters->courseCodes.'</td>';
echo '<td class="text-center">'.$value->courseMasters->courseTitles.'</td>';
echo '<td class="text-center">'.$value->courseMasters->courseTypes.'</td>';
echo '<td class="text-center">'.$value->courseMasters->courseUnits.'</td>';
echo '<td class="text-center">'.$value['remark'].'</td>';
echo '</tr>';
$totalUnit+=$value['course_unit'];
}
?>
<tr>
<th class="text-right border-hide padding-right" colspan=4><?php echo Yii::t('report', 'Total Unit'); ?></th>
<th><?php echo $totalUnit; ?></th>
</tr>
</table>
</td>
</tr>
How do I resolve the error and use array index as $key
Query
$courseRegistrationDetails = \app\modules\course\models\CourseRegistrationDetail::find()
->with('courseMaster')
->where(['course_registration_id' => $model->id])
->all();
View
<?php foreach ($courseRegistrationDetails as $key => $value) : ?>
<tr>
<td class="text-center"> <?= ($key + 1) ?> </td>
<td class="text-center"> <?= $value->courseMaster->courseCodes ?> </td>
<td class="text-center"> <?= $value->courseMaster->courseTitles ?> </td>
<td class="text-center"> <?= $value->courseMaster->courseTypes ?> </td>
<td class="text-center"> <?= $value->courseMaster->courseUnits ?> </td>
<td class="text-center"> <?= $value->remark ?> </td>
</tr>
<?php $totalUnit += $value->course_unit; ?>
<?php endforeach; ?>
Using asArray()
Query
$courseRegistrationDetails = \app\modules\course\models\CourseRegistrationDetail::find()
->with('courseMaster')
->where(['course_registration_id' => $model->id])
->asArray()
->all();
View
<?php foreach ($courseRegistrationDetails as $key => $value) : ?>
<tr>
<td class="text-center"> <?= ($key + 1) ?> </td>
<td class="text-center"> <?= $value['courseMaster']['course_code'] ?> </td>
<td class="text-center"> <?= $value['courseMaster']['course_title'] ?> </td>
<td class="text-center"> <?= $value['courseMaster']['course_type'] ?> </td>
<td class="text-center"> <?= $value['courseMaster']['course_unit'] ?> </td>
<td class="text-center"> <?= $value['remark'] ?> </td>
</tr>
<?php $totalUnit += $value['course_unit']; ?>
<?php endforeach; ?>

How to show data in the following format from database?

Database Table Structure
Data need to show
Please note: The city_from and city_to not fixed. It comes from city table. But single_or_group_id is fixed 1 = Single and 2 = Group.
Should try this. Think it will work according to your condition
select a.Trans_rent as Single, b.Trans_rent as Group
from table as a
inner join table as b on a.city_from = b.city_from and a.city_to = b.city_to
and b.single_or_group_id = 2
where a.single_or_group_id = 1
You can see this. Hope it will help you.
<?php
$map_city = ['2'=>'Madina','3'=>'Makkah'];
$single_group = ['1'=>'Single','2'=>'Group'];
$data = [
[
'city_form' => 2,
'city_to' => 3,
'single_or_group_id' => 1,
'rent' => 1000
],
[
'city_form' => 2,
'city_to' => 3,
'single_or_group_id' => 2,
'rent' => 4000
],
];
?>
<table style="width:25%" border=1>
<?php $is_first = true; ?>
<?php foreach($data as $single){ ?>
<?php if($is_first) { ?>
<tr>
<th colspan=2><?php echo $map_city[$single['city_form']] .'-'. $map_city[$single['city_to']];?></th>
</tr>
<tr>
<?php foreach($data as $single){ ?>
<td><?php echo $single_group[$single['single_or_group_id']];?></td>
<?php } ?>
</tr>
<tr>
<?php foreach($data as $single){ ?>
<td><?php echo 'S.R '.$single['rent'];?></td>
<?php } ?>
</tr>
<?php $is_first = false; } ?>
<?php } ?>
</table>

How to Add Select2 to row Dynamically in Yii2

I'm using Yii2 for my developments and I'm trying to Add Rows to table using plus button.
I'm able To add new row from that. And i need to append Krajee Select2 to my appending row. is that possible? how Can I Do that?
Following is my code use for append.
$('#main_tbl_body').append(
'<tr class='+row_class+' id="tbl_rw_appent_'+new_count+'">\n\
<td><a onclick ="removeMoreCommentField(this.id)" id="a_link_remove_'+new_count+'"><img id="image_remove_'+new_count+'" src="images/minus.png" style="width: 20px;height: 20px;cursor: pointer;" ></a></td>\n\
<td><div class="col-lg-12 col-md-12 col-sm-12 col-xs-12">'+' <?php
//echo '<label class="control-label">Part Code</label>';
$data = ArrayHelper::map(Mproduct::find()
// where(['P_model' => $model->relatedToVehicle->V_model])
->all(), 'idProduct', 'P_description');
//$items = DealerHelper::getRemainItems();
echo Select2::widget([
'name' => 'part_description_1',
'data' => $data,
'options' => [
// 'class'=>'textBox mobviewmargin',
'placeholder' => 'Select Product',
// 'multiple' => true
],
'pluginOptions' => [
'closeOnSelect' => true,
'tags' => false,
'multiple' => false,
'allowClear' => false,
],
]);
?>'+'</div></td>\n\
<td></td>\n\ \n\\n\
<td></td>\n\ \n\\n\
<td></td>\n\ \n\
<td></td>\n\ \n\
<td><a onclick ="addMoreCommentField()" id="a_link_add_'+new_count+'"><img id="image_add_'+new_count+'" src="images/plus.png" style="width: 20px;height: 20px;cursor: pointer;" ></a></td>\n\
</tr>'
);
Please Help me

Only single return value($data) will display codeigniter View page

I have a result.php page in view/result.php
<body>
<table border="1">
<tr>
<th>name1</th>
<th>name2</th>
<th>name3</th>
</tr>
<?php foreach($result as $row): ?>
<tr>
<td><?php echo $row->name1; ?></td>
<td><?php echo $row->name2; ?></td>
<td><?php echo $row->name3; ?></td>
</tr>
<?php endforeach; ?>
</table>
<?php echo 'Your new value is '.$name1;?>
<?php echo 'Your new value is '.$name2;?>
<?php echo 'Your new value is '.$name3;?>
</body>
html table is currently working. It retrives data from my table testing and display it. The problem is echo part in below code, it doesn't work.
<?php echo 'Your new value is '.$name1;?>
<?php echo 'Your new value is '.$name2;?>
<?php echo 'Your new value is '.$name3;?>
From the same table testing. It shows an error in the error page it shows Undefined variable name1,name2,name3
controller/example.php
<?php
class Example extends CI_Controller {
function __construct()
{
parent::__construct();
$this->load->helper('form');
$this->load->helper('url');
}
function index() {
$this->load->view('example_view');
$this->getvalue();
$this->edit_content();
}
function getvalue()
{
if ($this->input->post('submit')==true) {
$data1['name1']=$this->input->post('name1');
$data1['name2']=$this->input->post('name2');
$data1['name3']=$this->input->post('name3');
$this->load->view('result',$data1);
$this->load->model('Insert_model');
$this->Insert_model->uploaddata($data);
}
}
function edit_content()
{
$data = array();
$this->load->model('Selected_model');
$this->load->helper('url');
$data['result'] = $this->Selected_model->get_contents();
$this->load->view('result',$data);
}
}
?>
<body>
<table border="1">
<tr>
<th>name1</th>
<th>name2</th>
<th>name3</th>
</tr>
<?php if(is_array($result)){ foreach($result as $row): ?>
<tr>
<td><?php echo $row->name1; ?></td>
<td><?php echo $row->name2; ?></td>
<td><?php echo $row->name3; ?></td>
</tr>
<?php endforeach; } ?>
</table>
<?php echo 'Your new value is '.$row->name1;?>
<?php echo 'Your new value is '.$row->name2;?>
<?php echo 'Your new value is '.$row->name3;?>
If your array is like in the following format.
$info = array
(
[0] => Array
(
[name1] => a
[name2] => b
[name3] => c
)
[1] => Array
(
[name1] => aa
[name2] => bb
[name3] => cc
)
[2] => Array
(
[name1] => aaa
[name2] => bbb
[name3] => ccc
)
[3] => Array
(
[name1] => aaaa
[name2] => bbbb
[name3] => cccc
)
);
Then
<body>
<table border="1">
<tr>
<th>name1</th>
<th>name2</th>
<th>name3</th>
</tr>
<?php foreach($info as $row): ?>
<tr>
<td><?php echo $row->name1; ?></td>
<td><?php echo $row->name2; ?></td>
<td><?php echo $row->name3; ?></td>
</tr>
<?php endforeach; ?>
</table>
The above loop will give you accurate result like.
name1 name2 name3
a b c
aa bb cc
aaa bbb ccc
aaaa bbbb cccc
Now the following code will generate an error because it does not know the following
$row->name1
$row->name1
$row->name1
The reason is that these are defined in the scope of foreach loop thats why its generate error.

SQL error on pagination

Hey guys we have a perfectly working web page (index_admin) of the Relationships controller, but after adding pagination its all crashing.
Coming up with:
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'Relationship.sender_id' in 'where clause'
Customers and businesses build 'relationships' so they can exchange invoices over our website. Here is the DB schema:
id, sender_id, receiver_id, active, requested, expiry_date
Sender_id and receiver_id are both foreign keys to the Account Table. So in other words tells the db which accounts are linked to each other.
Relationship model 'BELONGSTO' 'RECEIVER AND SENDER ACCOUNT MODELS':
public $belongsTo = array(
'ReceiverAccount' =>array(
'className' => 'Account',
'foreignKey' =>'receiver_id',
'associationForeignKey' => 'accounts_id',
),
'SenderAccount' =>array(
'className' => 'Account',
'foreignKey' =>'sender_id',
'associationForeignKey' => 'accounts_id',)
);
Index_admin:
public function index_admin(){
$this->set('title_for_layout', 'Relationships');
$this->set('stylesheet_used', 'homestyle');
$this->set('image_used', 'eBOXLogoHome.png');
$this->layout='home_layout';
//retrieve Account Id of current User
$accountid=$this->Auth->user('account_id');
//Conditions
$conditions=array(
"OR"=> array(
'Relationship.sender_id' => $accountid,
'Relationship.receiver_id' => $accountid)
);
//Find all Invoices where receiver_id = accountid
$relationships=$this->Relationship->find('all', array(
'conditions' => $conditions));
debug($conditions);
$compName = $this->Account->field('account_name', array('id' => 'Relationship.id'));
$this->paginate = array(
'limit' => 10,
'conditions'=> $conditions
);
$this->set('accountid', $accountid);
$this->set('relationship', $this->paginate());
$this->set('compName', $compName);
}
Index_admin view (partial):
<table id="data">
<tr>
<td colspan=7 align='right'>
<?php
echo $this->Paginator->prev('<' . __('previous'), array(), null, array('class'=>'prev disabled'));
echo ' ';
echo $this->Paginator->numbers(array('seperator'=>''));
echo ' ';
echo $this->Paginator->next(__('next') . '>', array(), null, array('class'=>'next disabled'));
?>
</td>
</tr>
<tr>
<th><?php echo $this->Paginator->sort('id'); ?></th>
<th><?php echo $this->Paginator->sort('sender_id'); ?></th>
<th><?php echo $this->Paginator->sort('receiver_id'); ?></th>
<th><?php echo $this->Paginator->sort('expiry_date'); ?></th>
<th>Status</th>
<th>Actions</th>
</tr>
<?php foreach($relationship as $relationships):?>
<?php
if($relationships['Relationship']['requested']==1)
{
$status = 'Requested';
$bgcol = '#F8FAC0';
}
else if($relationships['Relationship']['active']==1)
{
$status = 'Active';
$bgcol = '#CFDAE8';
}
else if($relationships['Relationship']['active']==0)
{
$status = 'Expired';
$bgcol = '#FAB9B9';
}
if($relationships['Relationship']['active']==0 && $relationships['Relationship']['requested']==0)
{
$action = 'Reactivate';
}
else
{
$action = 'Edit Expiry';
}
if($relationships['Relationship']['sender_id']==$accountid)
{
$start = '<font color="#191970">';
$end = '</font>';
}
else
{
$start = NULL;
$end = NULL;
}
if($relationships['Relationship']['receiver_id']==$accountid)
{
$startr = '<font color="#191970">';
$endr = '</font>';
}
else
{
$startr = NULL;
$endr = NULL;
}
if($relationships['Relationship']['sender_id']==$accountid)
{
$acctname = $relationships['ReceiverAccount']['account_name'];
}
else if($relationships['Relationship']['receiver_id']==$accountid)
{
$acctname = $relationships['SenderAccount']['account_name'];
}
?>
<tr>
<td align='center'><?php echo $relationships['Relationship']['id']; ?></td>
<td align='center'><?php echo $start?><?php echo $relationships['SenderAccount']['account_name']; ?><?php echo $end ?></td>
<td align='center'><?php echo $startr?><?php echo $relationships['ReceiverAccount']['account_name']; ?><?php echo $endr ?></td>
<td align='center'><?php echo date('d.m.Y', strtotime($relationships['Relationship']['expiry_date'])); ?></td>
<td align='center' bgcolor='<?php echo $bgcol ?>'><?php echo $status ?></td>
<td align='center'>
<?php echo $this->Form->Html->link('Delete', array('controller' => 'Relationships','action'=>'delete',$relationships['Relationship']['id']), NULL, 'Are you sure you want to delete '. $acctname);
?> | <?php echo $action ?> </td>
</tr>
<?php endforeach; ?>
<tr>
<td colspan=7 align='right'>
<?php
echo $this->Paginator->prev('<' . __('previous'), array(), null, array('class'=>'prev disabled'));
echo ' ';
echo $this->Paginator->numbers(array('seperator'=>''));
echo ' ';
echo $this->Paginator->next(__('next') . '>', array(), null, array('class'=>'next disabled'));
?>
</td>
</tr>
</table>
Like I said it was all working before hand, now it isn't, but I can't see why.
It is always wise to set the debug mode on to see all possible errors in detail. You've just shared the sql error part from which it is clear that the intended table doesn't have the "sender_id" field. I'm assuming you've debug mode on. So first have a look at the generated query. Then you'll find which table the query is trying to dig in.
If your query is referencing the correct table, you can try this:
public function index_admin(){
$this->set('title_for_layout', 'Relationships');
$this->set('stylesheet_used', 'homestyle');
$this->set('image_used', 'eBOXLogoHome.png');
$this->layout='home_layout';
//retrieve Account Id of current User
$accountid=$this->Auth->user('account_id');
//Conditions
$conditions=array(
"OR"=> array(
'Relationship.sender_id' => $accountid,
'Relationship.receiver_id' => $accountid)
);
App::import('Model', 'Relationship');
$objRelationship = new Relationship();
$this->paginate = array( "conditions" => $conditions, 'limit' => 10 );
$relationships = $this->paginate( $objRelationship );
$compName = $this->Account->field('account_name', array('id' => 'Relationship.id'));
$this->set('accountid', $accountid);
$this->set('relationship', $this->paginate());
$this->set('compName', $compName);
}