Cakephp 3.x update a record without form - cakephp

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

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, display entire record row if a field is empty, otherwise do not display it

I have just started using CakePHP this week (required for my internship), and I am not really that good with PHP to begin with.
Anyhow, I require help with the following:
How can you make a record to only be displayed if it has an empty field?
Sample reference
Based on the above image, I only want the row with an empty Title/date to be displayed, while hiding the other.
And on a different page I want the same records to be displayed but this time around, only show the ones with completely filled fields, while hiding the ones with empty fields.
EDIT:
View:
<?php foreach ($users as $user): ?>
<tr>
<td><?= $this->Number->format($user->id) ?></td>
<td><?= h($user->username) ?></td>
<td><?= h($user->name) ?></td>
<td><?= h($user->phone) ?></td>
<td><?= h($user->email) ?></td>
<td><?= h($user->role) ?></td>
<td><?= $this->Number->format($user->status) ?></td>
<td class="actions">
<?= $this->Html->link(__('View'), ['action' => 'view', $user->id]) ?>
<?= $this->Html->link(__('Edit'), ['action' => 'edit', $user->id]) ?>
<?= $this->Form->postLink(__('Delete'), ['action' => 'delete', $user->id], ['confirm' => __('Are you sure you want to delete # {0}?', $user->id)]) ?>
</td>
</tr>
<?php endforeach; ?>
Model:
public function initialize(array $config)
{
parent::initialize($config);
$this->table('users');
$this->displayField('name');
$this->primaryKey('id');
}
public function validationDefault(Validator $validator)
{
$validator
->integer('id')
->allowEmpty('id', 'create');
$validator
->notEmpty('username', 'A username is required');
$validator
->notEmpty('password', 'A password is required');
$validator
->allowEmpty('name');
$validator
->allowEmpty('phone');
$validator
->email('email')
->allowEmpty('email');
$validator
->add('role', 'inList', [
'rule' => ['inList', ['admin', 'editor', 'sales_user', 'field_user']],
'message' => 'Please select a role']);
$validator
->add('status', 'inList', [
'rule' => ['inList', ['1', '2', '3']],
'message' => 'Please select a status']);
return $validator;
}
Controller:
public function index()
{
$users = $this->paginate($this->Users);
$this->set(compact('users'));
$this->set('_serialize', ['users']);
}
This is the first time I am posting a question, so please let me know if I need to include any further details or such.
Thank you.
this code selects the users where the name field is null.
public function index() {
$users = $this->users->find('all', array("conditions" => array('name' => '')));
$this->set("users", $users);
}

CakePhP Linking

hi all I have a cakephp page, when you hover over a link it displays the correct link however when you click the link it takes you to a completely different/wrong page.
i assume its an error with my view, so I'll include the relevant part of the site here, what is happening is the add link is taking users to fields/view NOT fields/add_new
<tr>
<td align='center'><?php echo $templates['Template']['name'] ;?></td>
<td align='center'><?php echo $templates['Template']['description']; ?> </td>
<td align='center'>
<?php echo $this->Form->Html->link('Add', array('controller' => 'Fields','action'=>'add_new',$templates['Template']['id'])); ;?> |
<?php echo $this->Form->Html->link('View', array('controller' => 'Fields','action'=>'view',$templates['Template']['id'])); ;?> |
<?php echo $this->Form->Html->link('Edit', array('controller' => 'Templates','action'=>'edit',$templates['Template']['id'])); ;?> |
<?php echo $this->Form->Html->link('Delete', array('controller' => 'Templates','action'=>'delete',$templates['Template']['id'])); ;?></td>
<tr>
function add_new($id=null){
//allows users to add another field to an existing template
$this->set('title_for_layout', 'Create Fields');
$this->set('stylesheet_used', 'homestyle');
$this->set('image_used', 'eBOXLogoHome.png');
$this->layout='home_layout';
if(($this->Field->save($this->request->data)))
{
$id = $this->data['Field']['template_id'];
$this->set('id',$id);
$this->redirect(array('controller'=>'Fields', 'action'=>'view',$id));
}
$this->set('id',$id);
}
The link function is part of the HtmlHelper class. So you need to remove the ->Form from your function call to:
<?php echo $this->Html->link('Add', array('controller' => 'fields', 'action'=>'add_new',$templates['Template']['id'])); ;?>
Also, Cake conventions call for the controller name to be lowercase, so specify your controller as:
('controller' => 'fields',
and not
('controller' => 'Fields',
function add_new($id=null){
//allows users to add another field to an existing template
$this->set('title_for_layout', 'Create Fields');
$this->set('stylesheet_used', 'homestyle');
$this->set('image_used', 'eBOXLogoHome.png');
$this->layout='home_layout';
//this sets the parameter as a variable
$this->set('id', $id);
//if the data posts to the databse
if($this->request->is('post'))
{
//creates an instance of field in the database
$this->Field->create();
//if the field saves to the database
if ($this->Field->save($this->request->data))
{ //if the user clicks this button
$id = $this->data['Field']['template_id'];
$this->set('id',$id);
$this->redirect(array('controller'=>'Fields', 'action'=>'view',$id));
}
}
}

cakephp pagination's and finds

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

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>

Resources