Related
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
I have the following Auth Component:
public $components = array(
'Auth' => array(
'loginAction' => array(
'controller' => 'Veranstalter',
'action' => 'login',
),
'authenticate' => array(
'Form' => array(
'userModel' => 'Veranstalter',
'fields' => array(
'ID' => 'ID', //Default is 'username' in the userModel
'Password' => 'Passwort' //Default is 'password' in the userModel
)
)
)
)
);
As you can see, I want to use my Controller "Veranstalter" (I HAVE to use non-english words)
When I want to Login,
The Controller VeranstaltersController couldn't be found.
How do I solve this?
My Form Looks like this:
<h2>
Login
</h2>
<?php
echo $this->Form->create('Veranstalter', array('action' => 'login'));
?>
<table class="input">
<colgroup>
<col width="15">
<col width="75">
</colgroup>
<tr>
<th>
Veranstalter Nummer
</th>
<td>
<?php echo $this->Form->input('ID',array('type'=>'text','label'=>false)); ?>
</td>
</tr>
<tr>
<th>
Passwort
<td>
<?php echo $this->Form->input('Passwort',array('label'=>false)); ?>
</td>
</tr>
<tr>
<th>
Login
</th>
<th>
<?php echo $this->Form->end('Login');?>
</th>
</tr>
</table>
The url is wrong
The auth component uses the loginAction config variable exactly as configured:
protected function _unauthenticated(Controller $controller) {
...
$controller->redirect($this->loginAction);
Logically therefore, if the url you are looking at is not the url in the Auth component config, it is not responsible.
The form action is wrong
This code for the login form:
echo $this->Form->create('Veranstalter', array('action' => 'login'));
Will generate this markup:
<form ... action="/veranstalters/login">
^
Because that's how Form::create works. The first parameter is the name of a model, and if no url is specified in the options, the model name is inflected to know the name of the controller.
The simplest solution is therefore to specify the url in the form options:
echo $this->Form->create('Veranstalter', array('url' => '/veranstalter/login'));
This will generate the right url:
<form ... action="/veranstalter/login">
^
I made a simple function to handle update actions for user. A simple form that look like this
<div class="com-md-12 col-sm-12 no-pad no-margine" ng-controller="ProfileCtrl" ng-init="getProfile('{{$safeID}}')">
{!! Form::open(array('class' => 'form-horizontal signup-form', 'ng-submit' => 'updateProfile($event)')) !!}
<div class="form-group">
<div class="col-md-6 col-sm-6">
{!! Form::text('first_name', old('first_name'), array('class' => 'form-control', 'placeholder' => 'First Name*', 'ng-model' => 'uProfile.first_name')); !!}
{!! MessagerService::setInlineError($errors->first('first_name')) !!}
</div>
<div class="col-md-6 col-sm-6">
{!! Form::text('last_name', old('last_name'), array('class' => 'form-control', 'placeholder' => 'Last Name*', 'ng-model' => 'uProfile.last_name')); !!}
{!! MessagerService::setInlineError($errors->first('last_name')) !!}
</div>
</div>
<div class="form-group">
<div class="col-md-12 col-sm-12">
{!! Form::text('username', old('username'), array('class' => 'form-control', 'placeholder' => 'Screen Name*', 'ng-model' => 'uProfile.username')); !!}
{!! MessagerService::setInlineError($errors->first('username')) !!}
</div>
</div>
<div class="form-group">
<div class="col-md-6 col-sm-6">
{!! Form::text('dob', old('dob'), array('class' => 'form-control', 'id' => 'dob', 'placeholder' => 'Date of Birth*', 'ng-model' => 'uProfile.dob')); !!}
{!! MessagerService::setInlineError($errors->first('dob')) !!}
</div>
<div class="col-md-6 col-sm-6">
{!! Form::select('gender', ['' => '------ Gender ------', 'male' => 'Male', 'female' => 'Female'], old('gender'),
array('class' => 'form-control', 'ng-model' => 'uProfile.gender')) !!}
{!! MessagerService::setInlineError($errors->first('gender')) !!}
</div>
</div>
<div class="form-group">
<div class="col-md-12 col-sm-12">
<div class="input-group">
<span class="input-group-addon" id="p_url_pretext">example.com/</span>
{!! Form::text('profile_url', old('profile_url'), array('class' => 'form-control', 'placeholder' => 'Profile URL*', 'ng-model' => 'uProfile.profile_url')); !!}
</div>
{!! MessagerService::setInlineError($errors->first('profile_url')) !!}
</div>
</div>
<div class="form-group">
<div class="col-md-12 col-sm-12">
<button type="submit" class="btn btn-default cbtn-login" style="float: right;">Save updates</button>
</div>
</div>
{!! Form::close() !!}
</div>
with angular script that look like this
$scope.updateProfile = function(event){
event.preventDefault();
$http({
method : 'POST',
url : svrid('www') + '/ws/profile/update',
data : $.param($scope.uProfile), // pass in data as strings
headers : { 'Content-Type': 'application/x-www-form-urlencoded' } // set the headers so angular passing info as form data (not request payload)
}).success(function(data) {
console.log(data);
}).error(function(data) {
console.log(data);
});
};
Everything worked as i expected but I have noticed 1 weird behavior. Why are there so many unrecognized requests before my final POST action is being executed?
I noticed that supposed my action route is http://www.example.com:8000/ws/profile/update it somehow keeps on calling http://www.example.com:8000/ws/profile with 3 different requests POST, GET, and DELETE before it finally reaches the intended request as shown in image below
Anyone have any idea what causes such behavior to happen or have I coded something wrong in anywhere that leads to such incident?
Update 1: Here is the Plunkr file. Noted that i could not re-simulate the error because the site is currently at localhost
Update 2: I have narrowed down that the ng-init="getProfile('{{$safeID}}') might have been causing this problem. I tried removing that line and give it a constant value and the errors do not appear. What's with such behavior?
I have found out the problem that causes such behavior. It is mainly because of the jQuery's $.param function. What really happens is the $.param operation will run through all properties of you object. Using $.param as the object will not automatically convert to a url encoded string (though I think it should).
So what I as a workaround to this problem is create a manual serialization function like such
function serializeData( data ) {
// If this is not an object, defer to native stringification.
if ( ! angular.isObject( data ) ) {
return( ( data == null ) ? "" : data.toString() );
}
var buffer = [];
// Serialize each key in the object.
for ( var name in data ) {
if ( ! data.hasOwnProperty( name ) ) {
continue;
}
var value = data[ name ];
buffer.push(
encodeURIComponent( name ) + "=" + encodeURIComponent( ( value == null ) ? "" : value )
);
}
// Serialize the buffer and clean it up for transportation.
var source = buffer.join( "&" ).replace( /%20/g, "+" );
return( source );
}
pass the form payload to the serialization function then append it into angular's #http
$http({
method : 'POST',
url : svrid('www') + '/ws/profile/update',
data : serializeData($scope.uProfile), // pass in data as strings
headers : { 'Content-Type': 'application/x-www-form-urlencoded' } // set the headers so angular passing info as form data (not request payload)
}).success(function(data) {
$scope.uError = null;
}).error(function(data) {
$scope.uError = data;
console.log(data);
});
and everything works like a charm.
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 have a project in CakePHP application and I want to add pagination to it. I have added pagination to it, but when I click on a page number or go to the next page my application breaks.
The page relies on variables being passed to the controller in order to display the correct data. Here is my code for the view:
<table class="table table-striped">
<thead>
<tr>
<th>Job ID</th>
<th>Date</th>
<th>Site</th>
<th> </th>
</tr>
</thead>
<tbody>
<?php foreach ($data as $jobsheet) { ?>
<tr>
<td>
<?php echo $jobsheet['Jobsheet']['jobnum']; ?>
</td>
<td>
<?php echo date("l, jS F Y", strtotime($jobsheet['Jobsheet']['jobdate'])); ?>
</td>
<td>
<span class="companyname"><strong><?php echo $jobsheet['Siteaddress']['sitename'] ?></strong></span><br />
<?php echo $jobsheet['Siteaddress']['addressline1']; ?>,
<?php echo $jobsheet['Siteaddress']['addressline2']; ?>,
<?php if ( $jobsheet['Siteaddress']['addressline3'] = '') { ?>
<?php echo $jobsheet['Siteaddress']['addressline3']; ?>,
<?php } else { ?>
<?php } ?>
<?php echo $jobsheet['Siteaddress']['city']; ?>,
<?php echo $jobsheet['Siteaddress']['county']; ?>,
<?php echo $jobsheet['Siteaddress']['country']; ?>,
<?php echo $jobsheet['Siteaddress']['postcode']; ?>
</td>
<td><a data-toggle="modal" href="#viewjobsheet<?php echo $jobsheet['Jobsheet']['id']; ?>" onClick="document.getElementById('jbif<?php echo $jobsheet['Jobsheet']['id']; ?>').src='/modal/customers/<?php echo $company['Company']['id']; ?>/jobs/<?php echo $jobsheet['Jobsheet']['id']; ?>/view/';" title="View" class="icon-eye-open"></a>
</td>
</tr>
<?php } ?>
</tbody>
</table>
</div>
</div>
<div class="row">
<div class="controls">
<?php echo $this->Paginator->prev('« Previous', null, null, array('class' => 'disabled')); ?>
<?php echo $this->Paginator->numbers(); ?>
<?php echo $this->Paginator->next('Next »', null, null, array('class' => 'disabled')); ?>
<br />
<br />
<?php echo $this->Paginator->counter(array(
'format' => 'Page {:page} of {:pages}, showing {:current} records out of
{:count} total, starting on record {:start}, ending on {:end}'
));
?>
</div>
</div>
This is the controller:
function index(){
$companyid = $this->params['customer'];
$this->set('companyid', $companyid);
$siteid = $this->params['site'];
$this->loadModel('Jobsheet');
// Job Sheets
$jobsheets = $this->Jobsheet->find('all', array('conditions' => array('Jobsheet.company' => $companyid), 'recursive' => 2, 'order' => 'Jobsheet.jobdate DESC', 'limit' => '10'));
$this->set('jobsheets', $jobsheets);
$this->paginate = array(
'limit' => 10
);
$data = $this->paginate('Jobsheet');
$this->set(compact('data'));
}
While the pagination does work, it ends up loosing the variable and this breaks what I'm trying to do. What am i missing?
One method is to use PaginatorHelper::options (see the API)
For example, say we want to pass the variable $pass between Paginator page changes. So first pass the variable to the View.
public function index() {
$pass = 'testString';
$this->set(compact('pass'));
$this->set('posts', $this->paginate());
}
In the View, we can then add this to the parameters that Paginator passes when changing pages using Paginator::options and the url option.
<?php
$this->Paginator->options(array(
'url' => array(
'pass' => $pass
)
));
?>
So if you moved from page 1 to page 2, the resulting url would be something similar to:
http://localhost/cake/posts/index/pass:testString/page:2
This is also how Paginator passes sort orders and sort keys. So while "pass" in pass:testString can be anything you want, be sure not to use sort, direction, and page.
As long as you are changing pages through the Paginator links, the passed variables will remain. Note that you can access the values of the passed arguments in both the View and the Controller by the property:
$this->passedArgs