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'));
?>
Related
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.
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.
I have 4 tables named customers, calls, employees and companies. Customers belong to a company and an employee. Calls belong to a customer and an employee. At the moment in my call index file it shows the relevant customer name and employee name. I want to display, for a call the relevant customer name, the customers company name they belong to and the employee name. I don't know how to display the relevant company name based on the customer. Can someone help? This is my code:
call/ index.ctp
<?php
$usertype=$this->SESSION->read('User.usertype');
?>
<div class="calls index">
<h2><?php echo __('Call Details'); ?> </h2>
<table cellpadding="0" cellspacing="0">
<tr>
<th><?php echo $this->Paginator->sort('id'); ?></th>
<th><?php echo $this->Paginator->sort('Call Date'); ?></th>
<th><?php echo $this->Paginator->sort('Call Time'); ?></th>
<th><?php echo $this->Paginator->sort('Comments'); ?></th>
<th><?php echo $this->Paginator->sort('Next Call Date'); ?></th>
<th><?php echo $this->Paginator->sort('Customer Name'); ?></th>
<th><?php echo $this->Paginator->sort('Employee Name'); ?></th>
<th class="actions"><?php echo __(''); ?></th>
</tr>
<?php foreach ($calls as $call): ?>
<tr>
<td><?php echo h($call['Call']['id']); ?> </td>
<td><?php echo h($call['Call']['call_date']); ?> </td>
<td><?php echo h($call['Call']['call_time']); ?> </td>
<td><?php echo h($call['Call']['comments']); ?> </td>
<td><?php echo h($call['Call']['next_call_date']); ?> </td>
<td>
<?php echo $this->Html->link($call['Customers']['customer_name'], array('controller' => 'customers', 'action' => 'view', $call['Customers']['id'])); ?>
</td>
<td>
<?php echo $this->Html->link($call['Employees']['employee_name'], array('controller' => 'employees', 'action' => 'view', $call['Employees']['id'])); ?>
</td>
<td class="actions">
<?php echo $this->Html->link(__('View'), array('action' => 'view', $call['Call']['id'])); ?>
</td>
</tr>
callsController:
class CallsController extends AppController {
/**
* Components
*
* #var array
*/
public $components = array('Paginator');
/**
* index method
*
* #return void
*/
public function index() {
$this->Call->recursive = 0;
$this->set('calls', $this->Paginator->paginate());
}
/**
* view method
*
* #throws NotFoundException
* #param string $id
* #return void
*/
public function view($id = null) {
if (!$this->Call->exists($id)) {
throw new NotFoundException(__('Invalid call'));
}
$options = array('conditions' => array('Call.' . $this->Call->primaryKey => $id));
$this->set('call', $this->Call->find('first', $options));
}
/**
* add method
*
* #return void
*/
public function add() {
if ($this->request->is('post')) {
$this->Call->create();
if ($this->Call->save($this->request->data)) {
$this->Session->setFlash(__('The call has been saved.'));
return $this->redirect(array('action' => 'index'));
} else {
$this->Session->setFlash(__('The call could not be saved. Please, try again.'));
}
}
$customers= $this->Call->Customers->find('list',array('order'=>'customer_name ASC','fields'=>array('id','customer_name')));
$employees= $this->Call->Employees->find('list',array('order'=>'employee_name ASC','fields'=>array('id','employee_name')));
$this->set(compact('customers', 'employees'));
}
/**
* edit method
*
* #throws NotFoundException
* #param string $id
* #return void
*/
public function edit($id = null) {
if (!$this->Call->exists($id)) {
throw new NotFoundException(__('Invalid call'));
}
if ($this->request->is(array('post', 'put'))) {
if ($this->Call->save($this->request->data)) {
$this->Session->setFlash(__('The call has been saved.'));
return $this->redirect(array('action' => 'index'));
} else {
$this->Session->setFlash(__('The call could not be saved. Please, try again.'));
}
} else {
$options = array('conditions' => array('Call.' . $this->Call->primaryKey => $id));
$this->request->data = $this->Call->find('first', $options);
}
$customers= $this->Call->Customers->find('list',array('order'=>'customer_name ASC','fields'=>array('id','customer_name')));
$employees= $this->Call->Employees->find('list',array('order'=>'employee_name ASC','fields'=>array('id','employee_name')));
$this->set(compact('customers', 'employees'));
}
/**
* delete method
*
* #throws NotFoundException
* #param string $id
* #return void
*/
public function delete($id = null) {
$this->Call->id = $id;
if (!$this->Call->exists()) {
throw new NotFoundException(__('Invalid call'));
}
$this->request->onlyAllow('post', 'delete');
if ($this->Call->delete()) {
$this->Session->setFlash(__('The call has been deleted.'));
} else {
$this->Session->setFlash(__('The call could not be deleted. Please, try again.'));
}
return $this->redirect(array('action' => 'index'));
}}
the array looks like this:
Array
(
[Call] => Array
(
[id] => 7
[call_date] => 2013-04-27
[call_time] => 08:31:00
[comments] => Require installation
[next_call_date] => 2014-04-27
[customers_id] => 2
[employees_id] => 3
)
[Customers] => Array
(
[id] => 2
[customer_name] => Snith Jams
[customer_address] => 192 Waverley Road
[customer_suburb] => Caulfield East
[customer_state] => VIC
[customer_postcode] => 3145
[customer_dob] => 2014-04-09
[customer_anniversary] => 2014-04-10
[customer_phone1] => 0492832921
[customer_phone2] => 0392817894
[customer_phone3] => 0482938281
[customer_fax] =>
[customer_email] => tsmith#hotmail.com
[customer_gender] => M
[customer_type] => Silver
[customer_PW] => a1c680c2bfcca40816dd81eff3980cc9828c9088
[customer_username] => samman
[companies_id] => 3
[employees_id] => 11
)
[Employees] => Array
(
[id] => 3
[employee_name] => Jones
[date_hired] => 2013-02-04
[employee_phone_number] => 0449997582
[employee_email] => indianajones#gmail.com
[employee_address] => 22 Queens street Melbourne CBD
[employee_dob] => 1966-01-31
[access_level] => staff
[employee_username] => jones12
[employee_pw] => 603fce7dcbec3c9cba24e87d058a3341e37779b8
)
)
callsController:
public $components = array('Paginator');
public function index() {
$this->Call->recursive = 2;
$this->set('calls', $this->Paginator->paginate());
}
calls/index.ctp:
<div class="calls index">
<h2><?php echo __('Call Details'); ?> </h2>
<table cellpadding="0" cellspacing="0">
<tr>
<th><?php echo $this->Paginator->sort('id'); ?></th>
<th><?php echo $this->Paginator->sort('Call Date'); ?></th>
<th><?php echo $this->Paginator->sort('Call Time'); ?></th>
<th><?php echo $this->Paginator->sort('Comments'); ?></th>
<th><?php echo $this->Paginator->sort('Next Call Date'); ?></th>
<th><?php echo $this->Paginator->sort('Customer Name'); ?></th>
<th><?php echo $this->Paginator->sort('Company Name'); ?></th>
<th><?php echo $this->Paginator->sort('Employee Name'); ?></th>
<th class="actions"><?php echo __(''); ?></th>
</tr>
<?php foreach ($calls as $call): ?>
<tr>
<td><?php echo h($call['Call']['id']); ?> </td>
<td><?php echo h($call['Call']['call_date']); ?> </td>
<td><?php echo h($call['Call']['call_time']); ?> </td>
<td><?php echo h($call['Call']['comments']); ?> </td>
<td><?php echo h($call['Call']['next_call_date']); ?> </td>
<td>
<?php echo $this->Html->link($call['Customers']['customer_name'], array('controller' => 'customers', 'action' => 'view', $call['Customers']['id'])); ?>
</td>
<td>
<?php echo $this->Html->link($call['Customers']['Companies']['company_name']); ?>
</td>
<td>
<?php echo $this->Html->link($call['Employees']['employee_name'], array('controller' => 'employees', 'action' => 'view', $call['Employees']['id'])); ?>
</td>
<?php echo pr($call); ?>
<td class="actions">
<?php echo $this->Html->link(__('View'), array('action' => 'view', $call['Call']['id'])); ?>
</td>
</tr>
<?php endforeach; ?>
</table>
just set recursive to 2
$this->Call->recursive = 2;
(or $this->Calls->recursive = 2 it depends if your model is Call or Calls)
and you can access to Company information like this
$call['Customer']['Company']['name']
Because it seems you are not following cake naming conventions (you are using plural for Models' names) maybe you'll need to use
$call['Customers']['Companies']['name']
I suggest you to follow the conventions, anyway if you print your array doing pr($call); you'll see how the array is structured and how to access your data
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
I want to paginate in view for a custom array. My controller and view code is given below.
Controller Code:
public function admin_detail(){
$totalByDate = $this->Pbscodemetric->find('all',array('fields'=>array('created')));
$createdDate = Set::extract('/Pbscodemetric/created', $totalByDate);
$uniqueCreatedDate = array_unique($createdDate);
$finalArray = array();
foreach($uniqueCreatedDate as $created){
$downloadsArr = $this->Pbscodemetric->find('all',array('fields'=>array('downloads_iphone','downloads_ipad','downloads_android'),'conditions'=>array('created'=>$created)));
$download_iphone = array_sum(Set::extract('/Pbscodemetric/downloads_iphone',$downloadsArr));
$download_ipad = array_sum(Set::extract('/Pbscodemetric/downloads_ipad',$downloadsArr));
$downloads_android = array_sum(Set::extract('/Pbscodemetric/downloads_android',$downloadsArr));
$finalArray[$created] = array(
'downloads_iphone' => $download_iphone,
'downloads_ipad' => $download_ipad,
'downloads_android' => $downloads_android
);
}
$this->set('finalArray',$finalArray);
}
View Code:
<div class="pbscodemetrics index">
<h2><?php echo __('Pbscodemetrics List Detail'); ?></h2>
<table cellpadding="0" cellspacing="0">
<tr>
<th>Date</th>
<th>iPhone</th>
<th>iPad</th>
<th>Android</th>
</tr>
<?php
foreach($finalArray as $key => $final){?>
<tr>
<td><?php echo $key;?></td>
<td><?php echo $final['downloads_iphone'];?></td>
<td><?php echo $final['downloads_ipad'];?></td>
<td><?php echo $final['downloads_android'];?></td>
</tr>
<?php }?>
</table>
</div>
<div class="actions">
<?php echo $this->element('nav');?>
</div>
Now I want to set pagination. I know in CakePHP default pagination needs Model name. But How can I do that for the above code?
Can anyone help me please..
You could implement a custom pagination, see Custom Query Pagination in the Cookbook. However, it looks like what you're doing there could be done using grouping and the SQL SUM function, that way you could then simply use the built-in pagination. Example:
$alias = $this->Pbscodemetric->alias;
$this->Pbscodemetric->virtualFields = array
(
'downloads_iphone_sum' => sprintf('SUM(`%s.downloads_iphone`)', $alias),
'downloads_ipad_sum' => sprintf('SUM(`%s.downloads_ipad`)', $alias),
'downloads_android_sum' => sprintf('SUM(`%s.downloads_android`)', $alias)
);
$this->paginate = array
(
'fields' => array
(
'downloads_iphone_sum',
'downloads_ipad_sum',
'downloads_android_sum',
'created'
),
'group' => 'created',
'order' => array
(
'created' => 'desc'
),
'limit' => 10
);
$data = $this->paginate($alias);
This will give you Paginator helper compatible results with summed downloads_iphone, downloads_ipad and downloads_android columns, grouped by the created column. It uses virtual fields in order to retreive results in the default CakePHP style, ie they will be accessible like this:
<?php foreach($results as $result): ?>
<tr>
<td><?php echo $result['Pbscodemetric']['created'];?></td>
<td><?php echo $result['Pbscodemetric']['downloads_iphone_sum'];?></td>
<td><?php echo $result['Pbscodemetric']['downloads_ipad_sum'];?></td>
<td><?php echo $result['Pbscodemetric']['downloads_android_sum'];?></td>
</tr>
<?php endforeach; ?>