CakePhP Linking - cakephp

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));
}
}
}

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

How do I set a variable in a CakePHP model and access it in a view?

I have multiple models that I want to add the variable $section to, and then use that value in sidenav.ctp to dynamically change the sidebar. For example, my models are:
class Resource extends AppModel {
public $section = 'section1';
public $displayField = 'name';
public $order = 'modified DESC';
//validation, relationships, etc.
}
then I have another model like:
class Topic extends AppModel {
public $section = 'section2';
public $tablePrefix = '';
//validation, relationships, etc.
}
so in sidenav.ctp I want to do something like:
<?php if ($this->section == 'section1') { ?>
<li><?php echo $this->Html->link(__('Resources'), array('controller' => 'resources', 'action' => 'index')); ?></li>
<li><?php echo $this->Html->link(__('Topics'), array('controller' => 'topics', 'action' => 'index')); ?> </li>
<li><?php echo $this->Html->link(__('Log Out'), array('controller' => 'users', 'action' => 'logout')); ?> </li>
<?php } ?>
<?php if ($this->section == 'section2') { ?>
<li><?php echo $this->Html->link(__('Resources1'), array('controller' => 'resources', 'action' => 'index')); ?></li>
<li><?php echo $this->Html->link(__('Topics1'), array('controller' => 'topics', 'action' => 'index')); ?> </li>
<li><?php echo $this->Html->link(__('Log Out1'), array('controller' => 'users', 'action' => 'logout')); ?> </li>
<?php } ?>
but accessing $section this way doesn't work. I can't figure out how to set the value in the Model and then access it in the View. I'm aware that I could set the value in the Controller and then access it just by $section, but that would require me putting it in every function.
Try in your view file $this->name == 'ModelName'
like this example:
<li <?php if($this->name == 'Users'){?> class="active" <?php } ?> >
<a href="<?php echo $this -> Html -> url(array('plugin' => false, 'controller' => 'pages', 'action' => 'dashboard')); ?>">
<i class="fa fa-dashboard"></i>
<span><?php echo __('Dashboard', true); ?></span>
<span class="label label-warning pull-right">1</span>
</a>
</li>
OR
in your controllers beforeFilter or beforeRender methods:
//access variable from model
$this->set('sections',$this->User->section);
//or set direct
$this->set('sections','section1');
View's / Elements can be called and rendered by any controller, so they won't automatically know what data you want it to refer to unless you pass it from the model to the view.
The nearest you can do which isn't of any use would be to echo the Router model methods, but the results are dependent on the url you are at.
you can save define global variables
Configure::write('my_var','this is model variable');
and access this variable in your view file like this
echo Configure::read('my_var');

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