Cake php Multiple model validation - cakephp-2.0

I have two tables :
senderinfos :
id | Name | email_add | Address |
============================================
1 | Amit | 1#1.com | park Street|
receiverinfos:
id | Name | email_add| Address |
=======================================
1 | SOS | 2#2.com | park1
I am giving the model,view,And Controller Code :
Model
Senderinfo :
<?php
App::uses('AppModel', 'Model');
/**
* Admin Login Model
*
*/
class Senderinfo extends AppModel
{
public $name='Senderinfo';
public $usetables='senderinfos';
public $validate = array(
'contact' =>
array(
'rule' => 'notEmpty', // or: array('ruleName', 'param1', 'param2' ...)
'allowEmpty' => false,
'message' => 'Please Enter Contact.'
),
'name' =>
array(
'rule' => 'notEmpty', // or: array('ruleName', 'param1', 'param2' ...)
'allowEmpty' => false,
'message' => 'Please Enter Sender Name.'
),
'email_add' => array(
'email_add' => array(
'rule' => 'email',
'allowEmpty' => true,
'message' => 'Please Enter Valid Email',
'last' => true
)),
);
}
?>
Receiveinfo :
<?php
App::uses('AppModel', 'Model');
/**
* Admin Login Model
*
*/
class Receiverinfo extends AppModel
{
public $name='Receiverinfo';
public $usetables='receiverinfos';
public $validate = array(
'contact' =>
array(
'rule' => 'notEmpty', // or: array('ruleName', 'param1', 'param2' ...)
'allowEmpty' => false,
'message' => 'Please Enter Contact.'
),
'name' =>
array(
'rule' => 'notEmpty', // or: array('ruleName', 'param1', 'param2' ...)
'allowEmpty' => false,
'message' => 'Please Enter Sender Name.'
),
'email_add' => array(
'email_add' => array(
'rule' => 'email',
'allowEmpty' => true,
'message' => 'Please Enter Valid Email',
'last' => true
)),
);
}
?>
View
send_money.ctp
<content>
<div class="pg_title txtLeft">Send Money</div>
<?php echo $this->Form->create('Agents', array('action' => 'send_money'));?>
<div style="display:none;"><input type="hidden" value="POST" name="_method"></div>
<fieldset title="SENDER'S INFORMATION"><legend>SENDER'S INFORMATION</legend>
<table>
<tbody>
<tr>
<td><label>Contact No.<span class="red">*</span></label></td>
<td><?php echo $this->Form->input('Senderinfo.contact',array('label'=>false,'div'=>false,'size'=>50,'style'=>'width:330px')); ?></td>
</tr>
<tr>
<td><label>Sender's Name<span class="red">*</span></label></td>
<td><?php echo $this->Form->input('Senderinfo.name',array('label'=>false,'div'=>false,'size'=>50,'style'=>'width:330px')); ?></td>
</tr>
<tr>
<td><label>Email Address</label></td>
<td><?php echo $this->Form->input('Senderinfo.email_add',array('label'=>false,'div'=>false,'size'=>50,'style'=>'width:330px')); ?></td>
</tr>
<tr>
<td><label>Mailing Address</label></td>
<td><?php echo $this->Form->input('Senderinfo.address',array('label'=>false,'div'=>false,'type'=>'textarea','cols'=>39,'rows'=>3,'class'=>'textarea','style'=>'width:330px')); ?></td>
</tr>
</tbody>
</table>
</fieldset>
<fieldset title=""><legend>RECEIVER'S INFORMATION</legend>
<table>
<tbody>
<tr>
<td><label>Contact No.<span class="red">*</span></label></td>
<td><?php echo $this->Form->input('Receiverinfo.contact',array('label'=>false,'div'=>false,'size'=>50,'style'=>'width:330px')); ?></td>
</tr>
<tr>
<td><label>Receiver's Name<span class="red">*</span></label></td>
<td><?php echo $this->Form->input('Receiverinfo.name',array('label'=>false,'div'=>false,'size'=>50,'style'=>'width:330px')); ?></td>
</tr>
<tr>
<td><label>Email Address</label></td>
<td><?php echo $this->Form->input('Receiverinfo.email_add',array('label'=>false,'div'=>false,'size'=>50,'style'=>'width:330px')); ?></td>
</tr>
<tr>
<td><label>Mailing Address</label></td>
<td><?php echo $this->Form->input('Receiverinfo.address',array('label'=>false,'div'=>false,'type'=>'textarea','cols'=>39,'rows'=>3,'class'=>'textarea','style'=>'width:330px')); ?></td>
</tr>
</tbody>
</table>
</fieldset>
<fieldset><legend>MONEY TRANSFER</legend>
<table>
<tbody>
<tr>
<td><label>Amount(tk)<span class="red">*</span></label></td>
<td><?php echo $this->Form->input('Transaction.sending_amount',array('label'=>false,'div'=>false,'size'=>50,'style'=>'width:330px')); ?></td>
</tr>
<tr>
<td><label>Charge(tk)<span class="red">*</span></label></td>
<td><?php echo $this->Form->input('Transaction.charge',array('label'=>false,'div'=>false,'size'=>50,'style'=>'width:330px')); ?></td>
</tr>
<tr>
<?php
$foo = "";
$options = array('1' => 'Paid','0' => ' Due');
$attributes = array(
'legend' => false,
'value' => true,
'checked'=> ($foo == "Paid"),
);
?>
<td>
<?php echo $this->Form->radio('transaction.status',$options, $attributes);?>
</td>
</tr>
</tbody>
</table>
</fieldset>
<fieldset><legend>CUSTOM MESSAGE</legend>
<table>
<tbody>
<tr>
<td style="width: 158px;"><label>Message</label></td>
<td><?php echo $this->Form->input('transaction.message',array('label'=>false,'div'=>false,'type'=>'textarea','cols'=>39,'rows'=>3,'class'=>'textarea','style'=>'width:330px')); ?></td>
</tr>
</tbody>
</table>
</fieldset>
<table>
<tbody>
<tr>
<td colspan="2" align="right"><input type="reset" value="Reset"> | <?php echo $this->Form->submit('SEND', array('div' => false,'formnovalidate' => true));?></td>
</tr>
</tbody>
</table>
<?php print $this->Form->end();?>
</content>
<div class="clear"></div>
Controller :
public function send_money()
{
$this->layout='agent';
if(empty($this->data) == false)
{
if($this->Senderinfo->save($this->data))
{
$this->Receiverinfo->save($this->data);
//$this->Session->setFlash('Data inserted successfully.');
//$this->redirect('send_money');
}
/*if($this->Receiverinfo->save($this->data))
{
//$this->Session->setFlash('Data inserted successfully.');
$this->redirect('send_money');
}
*/
}
else
{
//$this->set('errors', $this->Senderinfo->invalidFields());
//$this->set('errors', $this->Receiverinfo->invalidFields());
}
}
I want to insert the records in two table with perfect validation.But my validation part in not working perfectly.That means when u see my view page u'll see sender information,receiver information,money which is wrapped by html legend.I want to do validation required field at a time after clicking submit button.In this code whats happening is that when i press submit button sender information validation is working but receiver information portion validation is not working.when i put any value in sender portion,that time receiver information portion's validation works only.What should i have to do?

First of all; apparently there is a 'relation' between the 'sender' and 'receiver' in your application, but NOT in your model/database definition. Relying on the 'auto-incrementing' ID of your database (e.g. receiver 1 and sender 1 belong together) is not reliable. Auto-incrementing IDs will come 'out of sync' between both tables and you will end up with a situation where 'receiver 123' should actually be 'connected' to 'sender 125'.
If I understand correctly what this form does, is create a 'money transaction' in the database. Sender and Receiver should (in this case) probably not be stored in separate databases, unless you're going to offer an option to 'pick' an existing sender/receiver from a list.
In both situations there should be a table/model in your application that 'connects' the two, otherwise you will just have a random list of people 'sending' and 'receiving' money, but no way to know which person wants to send money to which recipient
If you're not going to 're-use' the senders/receivers, than a correct database-design should be something like:
id| sender_name | sender_email | sender_address | receiver_name | receiver_email | receiver_address
1 | Amid | 1#1.com | Parkstreet | SOS | 2#2.com | park 1
I would name this table 'money transfers' and the model 'Moneytransfer'
Having both in 1 model will simplify the validation and will guarantee that both sender and receiver info is present and correct.
If you really want to manually save two separate records (Based on my explanation above, I would strongly advise you to not do this) you should do this;
validate both records manually via $this->Mymodel->validates($data)
enclose both saves in a transaction and rollback if one of them fails
More information on manually validating inside your controller can be found here:
http://book.cakephp.org/2.0/en/models/data-validation/validating-data-from-the-controller.html
More information on using transactions in CakePHP can be found here:
http://book.cakephp.org/2.0/en/models/transactions.html
[update]
Browsing further through your 'form', there 'seems' to be a 'transaction' model as well?
If this is the case and the Model-relations are properly defined in CakePHP, you will be able to save all related records using Model::saveAssociated(). This will also enclose all saves in a transaction (atomic)
See here:
http://book.cakephp.org/2.0/en/models/saving-your-data.html#model-saveassociated-array-data-null-array-options-array

Related

how to get form input fields value in an array in cakephp

I am new to cakephp. Thanks all in advance. I am using Cakephp2.8.5 version. I have a form with input fields and a submit button. When I am submitting a form, the input fields should pass through the array and should store in a variable called $totalData and I want to store the array variable $totalData in a session variable in cakephp. I have written code in the Userscontroller's cartData function. Please help me find out how to declare an array and store it in a session variable in cakephp.
My index.ctp page:
<form method="post" action="<?php echo $this->webroot ?>users/cartData?>"">
<table><thead>
<th>Exam Name</th>
<th>Venue Name</th>
<th>Date of Exam</th>
<th>Price / Course</th>
<th>Number of Exams</th>
<th>Add to Cart</th>
</thead>
<tbody>
<tr>
<td>
<select name="course">
<option value="">--Select--</option>
<option value="ITIL Foundation">ITIL Foundation</option>
<option value="PMP">PMP</option>
<option value="Prince 2 Foundation">Prince 2 Foundation</option>
</select>
</td>
<td><input type="text" name="venue" id="venue"></td>
<td><input type="text" name="Userdate" id="Userdate" ></td>
<td><input type="text" name="txtprice" id="Userdate" ></td>
<td>
<select name="num_exams">
<option value="">--Select--</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
</td>
<td><input type="submit" name="btnSubmit" value="Submit"></td>
</tr></tbody>
</table>
My `UsersController.php` page :
<?php
App::uses('CakeEmail', 'Network/Email');
class UsersController extends AppController
{
public function cartData()
{
if($this->request->is('post')|| $this->request->is('put'))
{
$totalData = array(
'exam' => $this->Form->input('course'),
'venue' => $this->Form->input('venue'),
'date' => $this->Form->input('Userdate'),
'price' => $this->Form->input('txtprice'),
'orders' => $this->Form->input('num_exams')
);
// I have a confusion how to store array values in session variable
$_SESSION['total_data'][] = $totalData;
}
}
}
Always make the best effort to use the framework in all that's possible. Some very specific cases are a problem to use the Helpers on, but otherwise, always try and use them.
<?php
$courseOptions = array(
'ITIL Foundation' => 'ITIL Foundation',
'PMP' => 'PMP',
'Prince 2 Foundation' => 'Prince 2 Foundation'
);
$examOptions = array(1,2,3);
?>
<?=$this->Form->create('User', array('action' => 'cartData'))?>
<table>
<thead>
<tr>
<th>Exam Name</th>
<th>Venue Name</th>
<th>Date of Exam</th>
<th>Price / Course</th>
<th>Number of Exams</th>
<th>Add to Cart</th>
</tr>
</thead>
<tbody>
<tr>
<td>
<?=$this->Form->input('course', array('options' => $courseOptions)?>
</td>
<td><?=$this->Form->input('venue')?></td>
<td><?=$this->Form->input('userdate')?></td>
<td><?=$this->Form->input('txtprice')?></td>
<td><?=$this->Form->input('num_exams', array('options' => $examOptions)); ?></td>
<td><?=$this->Form->submit('Submit')?></td>
</tr>
</tbody>
</table>
<?=$this->Form->end()?>
All Form input helpers create an array based on the created form. In this case it generates a data[User][course] for name on each, and UserCourse for id (using first input as example).
On the controller side, you access your the data array on $this->request->data which will have that very structure (i.e. $this->request->data['User']['course'] to access the first input value).
Use the Session component and write your array to the session using:
$this->Session->write('cart', $totalData);
The Session component is probably already included in your AppController.php, if not add it there (or in your UsersController.php if you will only use it there):
var $components = array('Session');
(add 'Session' to any other components already listed)
$totalData = array(
'exam' => $this->Form->input('course'),
'venue' => $this->Form->input('venue'),
'date' => $this->Form->input('Userdate'),
'price' => $this->Form->input('txtprice'),
'orders' => $this->Form->input('num_exams')
);
Is this part of your code working? Can you show the debug of $totalData please?
$this->Form->input() is a method of the FormHelper, it is intended to be used in the view not controller in order to generate form inputs alongside $this->Form->create() and $this->Form->end().
In your controller form inputs are accessed using $this->request->data['Model']['fieldname']
You can do something like this in your view
<?php
$courseOptions = array(
'ITIL Foundation' => 'ITIL Foundation',
'PMP' => 'PMP',
'Prince 2 Foundation' => 'Prince 2 Foundation'
);
$examOptions = array('1' => '1', '2' => '2', '3' => '3');
echo $this->Form->create('User', array('action' => 'cartData'));
?>
<table>
<thead>
<tr>
<th>Exam Name</th>
<th>Venue Name</th>
<th>Date of Exam</th>
<th>Price / Course</th>
<th>Number of Exams</th>
<th>Add to Cart</th>
</tr>
</thead>
<tbody>
<tr>
<td>
<?php echo $this->Form->input('course', array('options' => $courseOptions)); ?>
</td>
<td><?php echo $this->Form->input('venue'); ?></td>
<td><?php echo $this->Form->input('userdate'); ?></td>
<td><?php echo $this->Form->input('txtprice'); ?></td>
<td><?php echo $this->Form->input('num_exams', array('options' => $examOptions)); ?></td>
<td><?php echo $this->Form->submit('Submit'); ?></td>
</tr>
</tbody>
</table>
<?php echo $this->Form->end(); ?>
You can then do something like this in your controller
<?php
App::uses('CakeEmail', 'Network/Email');
class UsersController extends AppController
{
public function cartData()
{
if($this->request->is('post')|| $this->request->is('put'))
{
$totalData = array(
'exam' => $this->request->data['User']['course'],
'venue' => $this->request->data['User']['venue'],
'date' => $this->request->data['User']['userdate'],
'price' => $this->request->data['User']['txtprice'],
'orders' => $this->request->data['User']['num_exams']
);
$this->Session->write('total_data', $totalData);
// Alternatively you can do something like this
$this->Session->write('total_data', $this->request->data['User']);
}
}
}
You may need to enable the Session component, I strongly advise reading the blog tutorial in the cookbook to get a grasp of these common components / helpers and how post data is accessed

How to insert multiple table for one form add in cakephp

so i want to create one form add for 3 tables, but i dont understand the scipt, i am googling but, i dont know, can anyone help me?
Table pln_nontaglish_suspect
| id | trx_id | no_regristrasi | tgl_regristrasi | nama | id_pel | rptag | switching_ref | admin_charge | iso | xml | inbox_id | telepon | info | jenis_transaksi | tagihan | partnet_cid | merchant | pln_ref | bank_code |dt_trx | reprint | create_date|
Table Mutations
| id | amount | note | jenis | inbox_id | balance | create_date | create_by | update_date | update_by | user_id | version |
Table Transactions
| id | user_id | product_id | destination | sender | sender_type | create_date | price_sell | price_buy | inbox_id | status | remark | saldo_awal | sn | receiver | resend
in the form add.ctp
<div id="page-container" class="row">
<div id="page-content" class="col-sm-9">
<!--<h2><?php echo __('Add Pln Nontaglist Suspect'); ?></h2>-->
<div class="plnNontaglistSuspects form">
<?php echo $this->Form->create('PlnNontaglistSuspect', array('role' => 'form')); ?>
<table>
<div style="display:none">
<?php
$now = new DateTime();
$today = $now->format("Y-m-d H:i:s");
$user = $this->Session->read('Auth.User.username');
$id = 'user_id';
$user_id = $_POST['Transaction.user_id'];
$inbox_id = $_POST['PlnNontaglistSuspect.inbox_id'];
echo $this->Form->input('PlnNontaglistSuspect.trx_no');
echo $this->Form->input('PlnNontaglistSuspect.idpel');
echo $this->Form->input('PlnNontaglistSuspect.rptag');
echo $this->Form->input('PlnNontaglistSuspect.admin_charge');
echo $this->Form->input('PlnNontaglistSuspect.xml');
echo $this->Form->input('PlnNontaglistSuspect.telpon');
echo $this->Form->input('PlnNontaglistSuspect.info');
echo $this->Form->input('PlnNontaglistSuspect.merchant');
echo $this->Form->input('PlnNontaglistSuspect.pln_ref');
echo $this->Form->input('PlnNontaglistSuspect.bank_code');
echo $this->Form->input('PlnNontaglistSuspect.dt_trx');
echo $this->Form->input('PlnNontaglistSuspect.reprint');
echo $this->Form->input('PlnNontaglistSuspect.create_date', array('value' => $today));
//input for table mutations
echo $this->Form->input('Mutation.note');
echo $this->Form->input('Mutation.jenis');
echo $this->Form->input('Mutation.inbox_id', array('value' => $inbox_id));
echo $this->Form->input('Mutation.balance');
echo $this->Form->input('Mutation.create_date', array('value'=>$today));
echo $this->Form->input('Mutation.create_by', array('value' => $user));
echo $this->Form->input('Mutation.update_date');
echo $this->Form->input('Mutation.update_by');
echo $this->Form->input('Mutation.user_id', array('value' => $user_id));
echo $this->Form->input('Mutation.version');
//input for table transactions
//echo $this->Form->input('Transaction.user_id', array('value' => $id));
echo $this->Form->input('Transaction.destination');
echo $this->Form->input('Transaction.sender');
echo $this->Form->input('Transaction.sender_type');
echo $this->Form->input('Transaction.create_date', array('value' => $today ));
echo $this->Form->input('Transaction.price_buy');
echo $this->Form->input('Transaction.status');
echo $this->Form->input('Transaction.saldo_awal');
echo $this->Form->input('Transaction.sn');
echo $this->Form->input('Transaction.receiver');
echo $this->Form->input('Transaction.resend');
?>
</div>
<legend>Tambah Nontaglish</legend>
<tr>
<td>No Regristrasi</td>
<td> : </td>
<td><?php echo $this->Form->input('PlnNontaglistSuspect.no_registrasi', array('label' => false,'class' => 'form-control')); ?></td>
</tr>
<tr>
<td>Tgl Regristrasi</td>
<td> : </td>
<td><?php echo $this->Form->input('PlnNontaglistSuspect.tgl_registrasi', array('label' => false, 'class' => 'form-control')); ?></td>
</tr>
<tr>
<td>Inbox Id</td>
<td> : </td>
<td><?php echo $this->Form->input('PlnNontaglistSuspect.inbox_id', array('label' => false, 'type' => 'text', 'class' => 'form-control')); ?></td>
</tr>
<tr>
<td>Produk Id</td>
<td> : </td>
<td><?php echo $this->Form->input('Transaction.product_id', array('label' => false, 'empty' => '----Select Produk Id----', 'class' => 'form-control')); ?></td>
</tr>
<tr>
<td>User Id</td>
<td> : </td>
<td><?php echo $this->Form->input('Transaction.user_id', array('label' => false, 'empty' => '----Select User Id----','class' => 'form-control'));?></td>
</tr>
<tr>
<td>Nama Pelanggan</td>
<td> : </td>
<td><?php echo $this->Form->input('PlnNontaglistSuspect.nama', array('label' => false, 'class' => 'form-control')); ?></td>
</tr>
<tr>
<td>Price Sell</td>
<td> : </td>
<td><?php echo $this->Form->Input('Transaction.price_sell', array('label' => false, 'class' => 'form-control'));?></td>
</tr>
<tr>
<td>Iso</td>
<td> : </td>
<td><?php echo $this->Form->input('PlnNontaglistSuspect.iso', array('label' => false,'class' => 'form-control')); ?></td>
</tr>
<tr>
<td>Switching Ref</td>
<td> : </td>
<td><?php echo $this->Form->input('PlnNontaglistSuspect.switching_ref', array('label' => false, 'class' => 'form-control')); ?></td>
</tr>
<tr>
<td>Tagihan</td>
<td> : </td>
<td><?php echo $this->Form->input('PlnNontaglistSuspect.tagihan', array('label' => false,'class' => 'form-control')); ?></td>
</tr>
<tr>
<td>Partner Cid</td>
<td> : </td>
<td><?php echo $this->Form->input('PlnNontaglistSuspect.partner_cid', array('label' => false, 'class' => 'form-control')); ?></td>
</tr>
<tr>
<td>Amount</td>
<td> : </td>
<td><?php echo $this->Form->input('Mutation.amount', array('label' => false, 'class' => 'form-control'));?></td>
</tr>
<tr>
<td>Remark</td>
<td> : </td>
<td><?php echo $this->Form->input('Transaction.remark', array('label' => false, 'class' => 'form-control'));?></td>
</tr>
<tr>
<td>Jenis Transaksi</td>
<td> : </td>
<td><?php echo $this->Form->input('PlnNontaglistSuspect.jenis_transaksi', array('label' => false,'class' => 'form-control')); ?></td>
</tr>
</table>
<?php echo $this->Form->submit('Submit', array('class' => 'btn btn-large btn-primary')); ?>
<?php echo $this->Form->end(); ?>
</div><!-- /.form -->
</div><!-- /#page-content .col-sm-9 -->
And In the Controller
public function add() {
$this->loadModel('Product');
$this->loadModel('User');
if ($this->request->is('post')) {
$this->PlnNontaglistSuspect->create();
if ($this->PlnNontaglistSuspect->save($this->request->data)) {
$this->Session->setFlash(__('The pln nontaglist suspect has been saved'), 'flash/success');
$this->redirect(array('action' => 'index'));
} else {
$this->Session->setFlash(__('The pln nontaglist suspect could not be saved. Please, try again.'), 'flash/error');
}
}
//$inboxes = $this->PlnNontaglistSuspect->Inbox->find('list');
$products = $this->Product->find('list');
$users = $this->User->find('list',array(
'fields'=>array('User.id','User.username'),
'order'=>array('User.username')
)
);
$this->set(compact('products','users'));
}
Having had a closer look your Models do not appear to be related, so saveAll or saveAssociated will not work in this case.
If you are in the PlnNontaglistSuspect Model you will need to load up your Mutation and Transaction Models and save them separately.
Example code:
public function add() {
//only try and save when the user has posted something
if ($this->request->is('post')) {
//in this example we are in the Mutation model
// so load up Suspect and Transaction
$this->loadModel('Suspect');
$this->loadModel('Transaction');
//create and save our Mutation record
$this->Mutation->create();
$this->Mutation->save($this->request->data);
//create and save our Suspect record
$this->Suspect->create();
$this->Suspect->save($this->request->data);
//create and save our Transaction record
$this->Transaction->create();
$this->Transaction->save($this->request->data);
//set a Flash message and redirect the user
$this->Session->setFlash(__('The mutation has been saved.'));
return $this->redirect(array('action' => 'index'));
}//end of if is post conditional
}//end of add function
(Please note this is not production ready - you need to add error handling in case any one of the three Models doesn't save. As you are saving three separate Models in one operation you will need to give some thought to how to approach this).
If the Models were related you could use a single saveAssociated or saveAll method as described here: http://book.cakephp.org/2.0/en/models/saving-your-data.html#model-saveassociated-array-data-null-array-options-array
One final point - you will make your life a lot easier if you stick to Cake conventions. For example one of your tables is pln_nontaglish_suspect, consider renaming this to pln_nontaglish_suspects as Cake expects plural table names by convention. Also, you have a create_date column in your tables, if you change this to created (datetime) Cake will automagically populate this with the time at save, likewise you can add a modified (datetime) column and Cake will record the time of any updates in this column.
More here:
http://book.cakephp.org/2.0/en/getting-started/cakephp-conventions.html
And:
http://book.cakephp.org/2.0/en/models/saving-your-data.html#using-created-and-modified
Cake becomes far more powerful when you use the conventions and helpers built into it.

Order by in find() cakephp

Table Unit(id, unitNo, summary).
id | unitNo
1 | 23
2 | 25
3 | 22
In UnitsController:
public function index() {
$this->set('units', $this->Unit->find('all'), array(
'order' => array('Unit.unitNo ASC'),
'fields' => array('Unit.id', 'Unit.unitNo'))
);
}
index.ctp
<table>
<tr>
<th>Unit</th>
<th>Summary</th>
</tr>
<!-- Here is where we loop through our $posts array, printing out post info -->
<?php foreach ($units as $unit): ?>
<tr>
<td>
<?php echo $this->Html->link($unit['Unit']['unitNo'], array('controller' => 'units', 'action' => 'view', $unit['Unit']['id']));
?>
</td>
<td><?php echo $unit['Unit']['summary']; ?></td>
</tr>
<?php endforeach; ?>
<?php unset($unit); ?>
</table>
I want to use order unitNo but the result is still ordering by id.
http://s1104.photobucket.com/user/thai92hp/media/Untitled.png.html
Can anyone help me to fix this problem?
Please give this a try:
public function index() {
$this->set('units', $this->Unit->find('all',
array(
'order' => array('Unit.unitNo ASC'),
'fields' => array('Unit.id', 'Unit.unitNo')
)
));
}
It seems to me that you've given your order settings to $this->set() as the third parameter but what you may want to do is to give it to $this->Unit->find() as the second parameter.

Delete multiple rows by ticking Checkbox

How do I delete multiple rows by checking a checkbox?
I have a table of records, and I'd like to to delete multiple rows at once.
This is my my deleteselected function:
UPDATED
public function order() {
if(!empty($this->data)) {
//If at lesst 1 check box is selected
if (isset($this->data) && !empty($this->data['order_id'])) {
$selectedReferences = $this->data['order_id'];
$flagReferenceAdded = false;
foreach ($selectedReferences as $singleReference) {
//NEW DELETE
$this->Order->id = $singleReference;
$this->Order->delete();
//NEW DELETE
}
//After delete
$this->Session->setFlash(
__('Your All record Are deleted.')
);
return $this->redirect(array(''));
}
else{
echo "Select at least 1 ORDER.";
}
}
and in my view.
<?php
echo $this->Form->create('Order',array('url' => array('controller' => 'admin', 'action' => 'order'))); ?>
<table class="table table-bordered table-hover">
<th>Name</th>
<th>Email</th>
<th>phone</th>
<th>view</th>
<th>delete</th>
<thead>
</tr>
</thead>
<tbody>
<?php foreach ($order as $orders): ?>
<tr>
<td><?php echo $orders['Order']['varfullname']; ?></td>
<td><?php echo $orders['Order']['varemailid']; ?></td>
<td><?php echo $orders['Order']['varphone']; ?></td>
<td>
<?php echo $this->Html->link('',
array('controller' => 'orders', 'action' => 'view', $orders['Order']['id']), array('title'=>'VIEW','class' => 'fa fa-search'));?>
</td>
<td><input type="checkbox" name="order_id[]" value ="<?php echo $orders['Order']['id'];?>" hiddenField = "false">
</td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
</br>
<?
echo $this->Form->end('Deleteselected'); ?>
</div>
</div>
</br>
</div>
<!-- /.row -->
after using below answer my delete selected working fine
Use in ctp
//in ctp Along with EACH record use Checkbox integration . Dont use Checkbox code u used.
<input type="checkbox" name="order_id[]" value ="<?php echo $referenceSingle['Order']['id'];?>" hiddenField = "false">
//In controller
if(!empty($this->data)) {
//If at lesst 1 check box is selected
if (isset($this->data) && !empty($this->data['order_id'])) {
$selectedReferences = $this->data['order_id'];
$flagReferenceAdded = false;
foreach ($selectedReferences as $singleReference) {
//NEW DELETE
$this->Order->id = $singleReference;
$this->Order->delete();
//NEW DELETE
}
//After delete
$this->Session->setFlash(
__('Your All record Are deleted.')
);
return $this->redirect(array(''));
}
else{
echo "Select at least 1 ORDER.";
}
}
UPDATE
Use Above Code in your Index method itself ,Dont create deleteAll method.
OR
Make <form action TO deleteAll
LIKE
echo $this->Form->create('searchCourse',array('url' => array('controller' => 'Courses', 'action' => 'index')));
UPDATE
For proper Workflow refer :
ALWAYS do paperwork and Algorithm ,Before Coding SIR.

Cakephp: pass parameter or data to another page

Our group create a database for patron to attend an event (booking) which has lots of entities.
We have three tables: patron, booking, booking_patron (join table).
We want to create 2 pages in the view (add.ctp and add2.ctp) of booking_patron.
Page add.ctp has a drop down box which lists booking ID and a submit button.
Page add2.ctp should appear the booking ID that we chose before (in add.ctp). Also in add2.ctp, we did make a function that user can create a patron and assign that patron to the booking ID.
BookingsPatronsController.php
public function add() {
$bookings = $this->BookingsPatron->Booking->find('list');
$this->set(compact('bookings', 'patrons'));
}
public function add2($booking_id = null) {
$patrons = $this->BookingsPatron->Patron->find('list');
$bookings = $this->BookingsPatron->Booking->find('list');
$this->set(compact('bookings', 'patrons'));
if ($this->request->is('post')) {
$this->BookingsPatron->Patron->create();
if ($this->BookingsPatron->Patron->save($this->request->data)) {
$this->Session->setFlash("Sign In Successful");
$this->BookingsPatron->create();
$this->Session->setFlash(__('Well.... done'));
$this->redirect(array('action' => 'add3'));
} else {
$this->Session->setFlash(__('We can not add your information. Please, try again.'));
}
}
}
The problem is: we don't know how to get the booking ID from add.ctp to add2.ctp.
At the moment, we use a drop down box that list booking ID in add2.ctp to choose the booking; we want to change that to a static text field that appears the booking ID from add.ctp.
We also have a function that can create a new patron in add2.ctp. We want to assign the new patron to the chosen booking ID from add.ctp
add.ctp
<?php echo $this->Form->input('Booking.booking_id');?>
<?php echo $this->Html->link(__('Create'), array('action' => 'add3')); ?>
add2.ctp
<?php echo $this->Form->create('BookingsPatron'); ?>
<fieldset>
<?php echo $this->Form->input('Booking.booking_id');?>
<table cellpadding="3" cellspacing="3">
<tr>
<td class="heading">Name: </td>
<td><?php echo $this->Form->input('Patron.patrons_name', array('label' => '', 'div' => 'formLabel'));?></td>
<td></td><td></td>
<td class="heading">E-mail: </td>
<td><?php echo $this->Form->input('Patron.patrons_email', array('label' => '', 'div' => 'formLabel'));?></td>
</tr>
<tr>
<td class="heading">Age: </td>
<td><?php echo $this->Form->input('Patron.patrons_age', array('label' => '', 'div' => 'formLabel'));?></td>
<td></td><td></td>
<td class="heading">Company: </td>
<td><?php echo $this->Form->input('Patron.patrons_company', array('label' => '', 'div' => 'formLabel'));?></td>
</tr>
<tr>
<td class="heading">Postcode: </td>
<td><?php echo $this->Form->input('Patron.patrons_postcode', array('label' => '', 'div' => 'formLabel'));?></td>
<td></td><td></td>
<td class="heading">Gender: </td>
<td><?php echo $this->Form->input('Patron.patrons_gender', array('label' => '', 'div' => 'formLabel', 'type' => 'select', 'options' => array('Male' => 'Male', 'Female' => 'Female')));?></td>
</tr>
<tr>
<td colspan="2">PH: 1300 7 34726</td>
<td colspan="3"></td>
<td><?php echo $this->Form->submit('Submit', array('class' => 'classSubmitButton', 'title' => 'Sbumit')); ?></td>
</tr>
</table>
</fieldset>
This should work
public function add() {
if ($this->request->is('post')) {
$this->Session->write('booking_id', $this->request->data['Booking']['booking_id']);
$this->redirect(array('action' => 'add2')); // Line added
}
$bookings = $this->BookingsPatron->Booking->find('list');
$this->set(compact('bookings', 'patrons'));
}
And to retreive the ID use this in your add2() function
$booking_id = $this->Session->read('booking_id');
Update
edit add.ctp -- This needs to be a form, not just a link, otherwise you don't submit the booking ID
<?php
echo $this->Form->create('Booking');
echo $this->Form->input('Booking.booking_id');
echo $this->Form->end(__('Create'));
?>

Resources