cakephp pagination's and finds - cakephp

hi all I'm trying to have pagination in a table in one of my views, I have my find statement returning the correct set of results however I am unsure how I can make my table be able to sort the information I have found.
here is the controller, when I try paginate the find all i get is errors
public function index_admin(){
//displays all disputes related to account.id
//in a dashboard for an administrator user
$this->set('title_for_layout', 'Dispute');
$this->set('stylesheet_used', 'homestyle');
$this->set('image_used', 'eBOXLogoHome.png');
$this->layout='home_layout';
//gets the User.account_id
$id = $this->Auth->User('account_id');
$conditions=array("OR"=> array(
'Invoice.sender_id' => $id,
'Invoice.receiver_id' => $id));
$receiver=$this->Dispute->find('all',array(
'conditions'=>$conditions));
$this->set('receiver',$receiver);
$this->paginate('Dispute');
$this->set('id',$id);
}
here is the code for the view
<tr>
<th><?php echo $this->Paginator->sort('id', 'Invoice ID'); ?></th>
<th><?php echo $this->Paginator->sort('dispute_date', 'Dispute Created'); ?></th>
<th><?php echo $this->Paginator->sort('status', 'Status'); ?></th>
<th>Actions</th>
</tr>
<?php foreach($receiver as $receivers):?>
<tr>
</tr><tr>
<td><?php echo $receivers['Invoice']['id'] ;?></td>
<td><?php echo $receivers['Dispute']['dispute_date'] ;?></td>
<?php
if($receivers['Dispute']['active']==1)
{
$status = 'Active';
$bgcol = '#B9FAEA';
}
else
{
$status = 'Resolved';
$bgcol = '#FAB9B9';
}
?><td align='center' bgcolor='<?php echo $bgcol ?>'><?php echo $status ?></td>
<td><?php echo $this->Form->Html->link('View',
array('controller' => 'Messages','action'=>'viewMessage_admin',$receivers['Dispute']['id'])); ?>
<?php echo $this->Form->Html->link('Resolve',
array('controller' => 'Disputes','action'=>'resolve',$receivers['Dispute']['id'])); ?></td>
</tr>
<?php endforeach; ?>

You should call paginate instead of find, not after it:
$id = $this->Auth->User('account_id');
$conditions=array("OR"=> array(
'Invoice.sender_id' => $id,
'Invoice.receiver_id' => $id));
$receiver=$this->paginate('Dispute', $conditions);
$this->set('receiver',$receiver);
$this->set('id',$id);

CakePHP reference for pagination in controller side as wee as on view side so it will give you deep knowledge in paginator of cakePHP
http://book.cakephp.org/2.0/en/core-libraries/components/pagination.html
http://book.cakephp.org/1.3/view/1233/Pagination-in-Views
example
http://bakery.cakephp.org/articles/rtconner/2007/06/13/basic-pagination-overview-1-2

Related

Cakephp application form

I created an application form using cakephp 2.
Now I want to know, How can users view only their application details using their user id. Here is the Form controller, the application form and the table for displaying the form
//Form controller
public function index() {
$this->set('posts', $this->Post->find('all'));
}
public function view($id = null) {
if (!$id) {
throw new NotFoundException(__('Invalid post'));
}
$post = $this->Post->findById($id);
if (!$post) {
throw new NotFoundException(__('Invalid post'));
}
$this->set('post', $post);
}
public function add() {
if ($this->request->is('post')) {
$this->Post->create();
if ($this->Post->save($this->request->data)) {
$this->Flash->success(__('Your post has been saved.'));
return $this->redirect(array('action' => 'index'));
}
$this->Flash->error(__('Unable to add your post.'));
}
}
//Create form
echo $this->Form->create('Post');
echo $this->Form->input('esta',['label'=>'New or Estabilished']);
echo $this->Form->end('Save Post');
//Form display
<table>
<tr>
<th>Id</th>
<th>Title</th>
<th>Created</th>
</tr>
<?php foreach ($posts as $post): ?>
<tr>
<td><?php echo $post['Post']['id']; ?></td>
<td>
<?php echo $this->Html->link($post['Post']['describe_idea'],
array('controller' => 'posts', 'action' => 'view', $post['Post']['id'])); ?>
</td>
<td><?php echo $post['Post']['created']; ?></td>
</tr>
<?php endforeach; ?>
<?php unset($post); ?>
</table>
You said that you are using cakephp 2.x please find below code to find record
for Single Record
$posts = $this->Post->find('first', array(
'conditions' => array('id' => 1)
));
For Multiple record
$posts = $this->Post->find('all', array(
'conditions' => array('id' => 1)
));
Add filter in your action
CakePHP 3.x
$posts = $this->Posts->find()
->where([
'Posts.user_id' => $this->Auth->user('id')
]);
CakePHP 2.x
$posts = $this->Posts->find('all', [
'user_id' => $this->Auth->user('id')
]);
Note: Make sure to login user to set Auth data.

Cakephp 3.x update a record without form

In my users/index page I basically list every user in the users table by doing the following:
<?php foreach ($users as $user): ?>
<tr>
<td><?= h($user->name) ?></td>
<td><?= h($user->email) ?></td>
<td><?= h($user->phone_nr) ?></td>
<td><?= h($user->role)?></td>
</tr>
<?php endforeach; ?>
User.role field is an enum type with two choices: 'user' or 'admin'.
Instead of just listing the user's role, I need to have a dropdown to be able to change it right away. So basically I need something like:
echo $this->Form->input('role', ['type' => 'select','label' => 'Role', 'options' => ['user' => 'user', 'admin' => 'admin']]);
However, it doesn't work outside of a form and the table is obviously not a form.
Any help or guidance for how to solve is much appreciated.
EDIT
As requested, I provide the code snippet that is used to save user data (if saved from a form):
public function add()
{
$user = $this->Users->newEntity();
if ($this->request->is('post')) {
$user = $this->Users->patchEntity($user, $this->request->data);
if ($this->Users->save($user)) {
$this->Flash->success(__('The user has been saved.'));
return $this->redirect(['action' => 'index']);
} else {
$this->Flash->error(__('The user could not be saved. Please, try again.'));
}
}
}
A very simple approach could be the one described below. It makes use of no Ajax, just a simple POST request, which means the page is reloaded when the role is changed.
Modify your view as follows:
<?php foreach ($users as $user): ?>
<tr>
<td><?= h($user->name) ?></td>
<td><?= h($user->email) ?></td>
<td><?= h($user->phone_nr) ?></td>
<td><?= h($user->role)?></td>
<td>
<?= $this->Form->postButton('Toggle Role',
['controller'=>'users','action'=>'toggle_role',$user->id,$user->role])?>
</td>
</tr>
<?php endforeach; ?>
Add an action to your controller:
public function toggle_role($id,$existing_role){
$users = TableRegistry::get('Users');
$user = $users->get($id);
$user->role = ($existing_role == 'admin')?'user':'admin';
$users->save($user);
return $this->redirect($this->referer());
}
Note: The code is not tested, and lacks error handling
See
Creating Standalone Buttons and POST links

Displaying HABTM data in view

I have a simple cakephp 2.x app that I baked using the bake script. The two main tables are conditions and drugs. A condition HABTM drugs and vice verca. I'm trying to display the drugs that belong to a condition in the condition index, basic listing all conditions, but ONLY those drugs. I have tried doing it like this, to display the drugs belonging to a condition in a comma seperated list, which works in another 1.3 app:
<?php
$condition_drugs = '';
foreach($condition['Drug'] as $drug):
$condition_drugs .= $drug['drug'] . ', ';
//echo $drug['generic'];
endforeach;
//echo substr($condition_drugs, 0, -2);
echo $condition_drugs;
?>
But it gives the following two errors:
Undefined index: Drug [APP/View/Conditions/index.ctp, line 22], and Invalid argument supplied for foreach() [APP/View/Conditions/index.ctp, line 22]
I also looked at another article here that suggested doing it in a similar way. Is there something wrong with the code I have? Do I need a find in my model based on the ID? Here's the full index view code and controller:
View:
<div class="conditions index">
<h2><?php echo __('Conditions'); ?></h2>
<table cellpadding="0" cellspacing="0">
<tr>
<th><?php echo $this->Paginator->sort('condition'); ?></th>
<th><?php echo $this->Paginator->sort('principles'); ?></th>
<th><?php echo $this->Paginator->sort('treatment'); ?></th>
<th><?php echo $this->Paginator->sort('clinical_tips'); ?></th>
<th>Drugs</th>
<th class="actions"><?php echo __('Actions'); ?></th>
</tr>
<?php
foreach ($conditions as $condition): ?>
<tr>
<td><?php echo h($condition['Condition']['condition']); ?> </td>
<td><?php echo h($condition['Condition']['principles']); ?> </td>
<td><?php echo h($condition['Condition']['treatment']); ?> </td>
<td><?php echo h($condition['Condition']['clinical_tips']); ?> </td>
<td>
<?php
$condition_drugs = '';
foreach($condition['Drug'] as $drug):
$condition_drugs .= $drug['drug'] . ', ';
//echo $drug['generic'];
endforeach;
//echo substr($condition_drugs, 0, -2);
echo $condition_drugs;
?>
</td>
<td class="actions">
<?php echo $this->Html->link(__('View'), array('action' => 'view', $condition['Condition']['id'])); ?>
<?php echo $this->Html->link(__('Edit'), array('action' => 'edit', $condition['Condition']['id'])); ?>
<?php echo $this->Form->postLink(__('Delete'), array('action' => 'delete', $condition['Condition']['id']), null, __('Are you sure you want to delete # %s?', $condition['Condition']['id'])); ?>
</td>
</tr>
<?php endforeach; ?>
</table>
<p>
<?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}')
));
?> </p>
<div class="paging">
<?php
echo $this->Paginator->prev('< ' . __('previous'), array(), null, array('class' => 'prev disabled'));
echo $this->Paginator->numbers(array('separator' => ''));
echo $this->Paginator->next(__('next') . ' >', array(), null, array('class' => 'next disabled'));
?>
</div>
</div>
<div class="actions">
<h3><?php echo __('Actions'); ?></h3>
<ul>
<li><?php echo $this->Html->link(__('New Condition'), array('action' => 'add')); ?></li>
</ul>
</div>
Controller:
<?php
App::uses('AppController', 'Controller');
/**
* Conditions Controller
*
* #property Condition $Condition
*/
class ConditionsController extends AppController {
/**
* index method
*
* #return void
*/
public function index() {
$this->set('title_for_layout','Condition Index');
$this->Condition->recursive = 0;
$this->set('conditions', $this->paginate());
}
/**
* view method
*
* #throws NotFoundException
* #param string $id
* #return void
*/
public function view($id = null) {
$this->Condition->id = $id;
if (!$this->Condition->exists()) {
throw new NotFoundException(__('Invalid condition'));
}
$this->set('condition', $this->Condition->read(null, $id));
}
/**
* add method
*
* #return void
*/
public function add() {
if ($this->request->is('post')) {
$this->Condition->create();
if ($this->Condition->save($this->request->data)) {
$this->Session->setFlash(__('The condition has been saved'));
$this->redirect(array('action' => 'index'));
} else {
$this->Session->setFlash(__('The condition could not be saved. Please, try again.'));
}
}
$drugs = $this->Condition->Drug->find('list',array('fields'=>array('id','generic')));
$this->set(compact('drugs'));
}
/**
* edit method
*
* #throws NotFoundException
* #param string $id
* #return void
*/
public function edit($id = null) {
$this->Condition->id = $id;
if (!$this->Condition->exists()) {
throw new NotFoundException(__('Invalid condition'));
}
if ($this->request->is('post') || $this->request->is('put')) {
if ($this->Condition->save($this->request->data)) {
$this->Session->setFlash(__('The condition has been saved'));
$this->redirect(array('action' => 'index'));
} else {
$this->Session->setFlash(__('The condition could not be saved. Please, try again.'));
}
} else {
$this->request->data = $this->Condition->read(null, $id);
}
$drugs = $this->Condition->Drug->find('list',array('fields'=>array('id','generic')));
$this->set(compact('drugs'));
}
/**
* delete method
*
* #throws MethodNotAllowedException
* #throws NotFoundException
* #param string $id
* #return void
*/
public function delete($id = null) {
if (!$this->request->is('post')) {
throw new MethodNotAllowedException();
}
$this->Condition->id = $id;
if (!$this->Condition->exists()) {
throw new NotFoundException(__('Invalid condition'));
}
if ($this->Condition->delete()) {
$this->Session->setFlash(__('Condition deleted'));
$this->redirect(array('action' => 'index'));
}
$this->Session->setFlash(__('Condition was not deleted'));
$this->redirect(array('action' => 'index'));
}
}
To include habtm data, you need $recursive = 1;
You have set it to 0

CakePHP function not updating table

hi all when trying to update my database, this function isn't grabbing the id from the table and it isn't updating that line in the table. Its also throwing an error with
$this->Relationship->id = $this->request->data['id'];
here is the function in its entirety
public function approve($id=null){
$this->Relationship->id = $id;
if($this->request->is('get')){
$this->request->data=$this->Relationship->read();}
$this->Relationship->id = $this->request->data['id'];
if($this->Relationship->save($this->request->data)) {
$this->Session->setFlash('Your Relationship has been updated.');
$this->redirect(array('action' => 'request'));
} else {
$this->Session->setFlash('Unable to update your post.');
}
}
}
here is form/view
<?php
echo $this->Form->create('Relationship', array('action'=>'approve'));
echo $this->Form->input('expirydate',array('label'=>'Expiry Date: ', 'class' => 'dateclass'));
echo $this->Form->end('Submit');
?>
what I'm trying to do with this function is grab a the id, and edit two fields in that entry
It should be $this->request->data['Relationship']['id']; if you setup your form correctly. Also, you can just do
$this->Relationship->create($this->request->data);
$this->Relationship->save()
public function approve($id=null){
$this->set('title_for_layout', 'Relationships');
$this->set('stylesheet_used', 'homestyle');
$this->set('image_used', 'eBOXLogoHome.jpg');
$this->layout='home_layout';
if ($this->request->is('get')) {
$this->request->data = $this->Relationship->read(NULL, $id);
} else {
//sets active to 1
$this->Relationship->read(null, $id);
$this->Relationship->set(array('active' => true,));
if ($this->Relationship->save($this->request->data)) {
$this->Session->setFlash('Your post has been updated.');
$this->redirect(array('action' => 'request'));
} else {
$this->Session->setFlash('Unable to update your post.');
}
}
}
I also had to change a tinyint from 0=>1 in the database.The other issue I had was with my request view, it was not passing the id to the approve function. Once I changed the code to this it worked
<?php foreach($Relationships as $relationship):?>
<tr>
<td align='center'><?php echo $relationship['Relationship']['partyone']; ?></td>
<td align='center'><?php echo $relationship['Relationship']['partytwo']; ?></td>
<td> </td>
<td><?php echo $this->Html->link($relationship['Relationship']['partyone'], array('action'=>'approve', $relationship['Relationship']['id'])); ;?>
</td>
</tr>
<?php endforeach; ?>
</table>

CakePHP Find Related Data

My Gallery model is related to my image model, but when I retrive images from galleries_controller I cant see any result and instead see this error:
Warning (2): Invalid argument supplied for foreach() [APP\views\galleries\view.ctp, line 35]
Here is the code from my controller action:
function view($id = null) {
if (!$id) {
$this->Session->setFlash(__('Invalid gallery', true));
$this->redirect(array('action' => 'index'));
}
$this->set('gallery', $this->Gallery->read(null,$id));
$this->Gallery->Image->find('all',array('conditions' => array('Image.gallery_id'=> $id)));
$this->set('images', $images);
}
This is the loop I have in my galleries/view to iterate through the array.
<?php
$i = 0;
foreach ($images['Image'] as $image):
$class = null;
if ($i++ % 2 == 0) {
$class = ' class="altrow"';
}
?>
<tr<?php echo $class;?>>
<td><?php $image['id'] ;?></td>
<td><?php echo $image['name'];?></td>
<!--<td><?php echo $image['img_file'];?></td>-->
<td><?php echo $html->image('uploads' . DS . 'images' . DS . $image['img_file'], array('alt' => 'Gallery Image')); ?></td>
</tr>
<?php endforeach; ?>
You aren't setting anything with your set. Your find is being executed and then not stored in a variable. Furthermore, your view loop is iterating through incorrectly.
Change your controller to:
function view($id = null) {
if (!$id) {
$this->Session->setFlash(__('Invalid gallery', true));
$this->redirect(array('action' => 'index'));
}
$this->set('gallery', $this->Gallery->read(null,$id));
$images = $this->Gallery->Image->find('all',array('conditions' => array('Image.gallery_id'=> $id)));
$this->set('images', $images);
}
And your view code to:
<?php
$i = 0;
foreach ($images as $image):
$class = null;
if ($i++ % 2 == 0) {
$class = ' class="altrow"';
}
?>
<tr<?php echo $class;?>>
<td><?php $image['Image']['id'] ;?></td>
<td><?php echo $image['Image']['name'];?></td>
<!--<td><?php echo $image['Image']['img_file'];?></td>-->
<td><?php echo $html->image('uploads' . DS . 'images' . DS . $image['Image']['img_file'], array('alt' => 'Gallery Image')); ?></td>
</tr>
<?php endforeach; ?>
That having been said, since all you want to do is pull in associated images when a gallery is viewed, you should look into setting up your model associations and then doing a find on your gallery that will include the images you want like so:
$this->set('gallery',$this->Gallery->find('first', array('conditions' => array('Gallery.id' => $id), 'recursive' => 1));
If the above don't work, then there is something misconfigured in your models. Please post your model code so we can investigate further.

Resources