how to optimize the views in CakePHP v2 - cakephp

I have many view like Shops, Categories, Products, Toppings....
And using the hardcoded Model names very often. Sometimes singular ot plural. like in the Shop's index.ctp
<ul class="nav nav-tabs">
<li><?php echo $this->Html->link(__('New Shop'), array( 'action' => 'add'));?></li>
</ul>
<div class="page-header">
<h1><?php echo __('Shops'); ?></h1>
</div>
AND
<td><?php echo $shop['Shop']['id']; ?>
<td><?php echo $shop['Shop']['name']; ?>
<td><?php echo $shop['Shop']['street']; ?>
...
Is there a better way to dynamically use the model names?
Thank you.

Well, you can add $myshop = $shop['Shop']; at the top of your code so you can use $myshop['id'] but thats pretty much it. It's not weird to use variables where you need them.

If you really wanted to you could do the same that Controllers have, $this->modelClass property contains the model name.
In the controller
$this->set('modelClass', $this->modelClass);
In the view:
echo $shop[$modelClass]['field'];

Related

how to use cakePHP params to set unordered list items as active

I want to be able to set a navigational list item as active by using cakePHP params. This would visually tell the visitor which page they're currently on. I've figured out how to do it for the current controller but, I'm routing specific rows in the post controller for pages such as 'about us' and it's not working even though I'm trying to check for the 'pass' param. Here's the code:
In an element called "leftNavBar.ctp' I've got the following:
<?php
$current_pass = $this->params['pass'];
$current_controller = $this->params['controller'];
?>
<ul class="nav">
<li class="<?php if(in_array($current_pass, array(2))){echo 'active';} ?>">
<?php echo $this->Html->link(__("About Us",true),"/about-us") ?>
</li>
<li class="<?php if(in_array($current_controller, array('galleries'))){echo 'active';} ?>">
<?php echo $this->Html->link(__("Galleries",true),"/galleries") ?>
</li>
</ul>
This is the router instructions for the 'about us' page:
Router::connect('/about-us',array
('controller' => 'posts', 'action' => 'view', 2));
Because the Posts controller has other rows/list items that I also want to set as active in the left nav bar, what I want to figure out is how to be able to do that?
thanks
You can try setting variable inside the controller and access in view like
In Controller
function view($id) {
..........
..........
$this->set('current_pass',$id);
}
In View
<?php
$current_controller = $this->params['controller'];
?>
<ul class="nav">
<li class="<?php if(in_array($current_pass, array(2))){echo 'active';} ?>">
<?php echo $this->Html->link(__("About Us",true),"/about-us") ?>
</li>
<li class="<?php if(in_array($current_controller, array('galleries'))){echo 'active';} ?>">
<?php echo $this->Html->link(__("Galleries",true),"/galleries") ?>
</li>
</ul>
What I ended up doing with luck was the following:
<?php
$url = $this->Html->url() ;
$current_controller = $this->params['controller'];
?>
<ul class="nav">
<li <?php if($url == '/NAME-OF-URL-HERE/about-us') echo 'class="active"';?>>
<?php echo $this->Html->link(__("About Us",true),"/about-us") ?>
</li>
<li class="<?php if(in_array($current_controller, array('galleries'))){echo 'active';} ?>">
<?php echo $this->Html->link(__("Galleries",true),"/galleries") ?>
</li>
</ul>
This works well since not all URLS are handled the same way. Some URLs are controllers, others are specific IDs within controllers.
Hope this helps others.
Paul

Saving current view id 14 in /localhost/topp/events/view/14 to comments table field

Trying to save the current event id '14' in the url '/localhost/topp/events/view/14' to a event_id field in a comments table. I am using the add function in the comments controller and an 'add comment' button on the events view.ctp page. Any ideas? I have been advised to use a hidden id field and $this->params['pass']['0'] but not sure how to go about this, any advice is welcome. Thanks in advance.
My current comments controller add action code:
public function add() {
//$this->loadModel('Event');
if ($this->request->is('post')) {
$this->Comment->create();
$this->request->data['Comment']['user_id'] = $this->Auth->user('id');
//Commented below is the logic Iam trying to achieve but is wrong
//$this->request->data['Comment']['event_id'] = $this->request->data['Event']['id'];
if ($this->Comment->save($this->request->data)) {
$this->Session->setFlash(__('The comment has been saved'));
$this->redirect(array('controller' => 'events', 'action' => 'myevents'));
} else {
$this->Session->setFlash(__('The comment could not be saved. Please, try again.'));
}
}
}
//////////////////////////////////////// My Events View code with add comment link//////////////////////////
<div class="events view">
<?php echo $this->element('maintitle'); ?>
<?php echo $this->element('profile_area'); ?>
<h2><?php echo __('Event'); ?></h2>
<dl>
<td><?php echo $this->Html->image('/files/event/photo/'.$event['Event']['id'].'/thumb_'.$event['Event']['photo'], array("alt" => "No Event Image")); ?> </td>
<td><?php echo $this->Html->image('/files/event/photo2/'.$event['Event']['id'].'/thumb_'.$event['Event']['photo2'], array("alt" => "No Event Image")); ?> </td>
<td><?php echo $this->Html->image('/files/event/photo3/'.$event['Event']['id'].'/thumb_'.$event['Event']['photo3'], array("alt" => "No Event Image")); ?> </td>
<td><?php echo $this->Html->image('/files/event/photo4/'.$event['Event']['id'].'/thumb_'.$event['Event']['photo4'], array("alt" => "No Event Image")); ?> </td>
<dt></dt>
<dd>
<br>
</dd>
<dt><?php echo __('Name'); ?></dt>
<dd>
<?php echo h($event['Event']['name']); ?>
</dd>
<dt><?php echo __('Date'); ?></dt>
<dd>
<?php echo h($event['Event']['date']); ?>
</dd>
</dl>
</div>
<div class="related">
<h3><?php echo __('Related Comments'); ?></h3>
<?php if (!empty($event['Comment'])): ?>
<?php echo ('Add a comment for this event') ?>
<?php
$i = 0;
foreach ($event['Comment'] as $comment): ?>
<tr>
<td><?php echo $comment['comment']; ?></td>
<td class="actions">
</td>
</tr>
<?php endforeach; ?>
<?php endif; ?>
<div class="actions">
<ul>
<li><?php echo $this->Html->link(__('New Comment'), array('controller' => 'comments', 'action' => 'add')); ?> </li>
</ul>
</div>
</div>
Let me see if I got this right.
The form you posted is in the event view
The link "New Comment" redirects to another view "add", in the comments controller
This add view has a form to actually write a comment (I'm guessing this part,
you didn't put that code here)
You want the add function to have the event_id from where this came from.
Right?
You then need to pass the id of the event from event_view.ctp (I'm inventing names here) to comment_add.ctp.
So two ways to do it
First way: pass the id of the event in the link and recieve it in the action like this
//event_view.ctp
//I'm going to assume you know the event id here
$this->Html->link(__('New Comment'), array('controller' => 'comments', 'action' => 'add', $event_id)); ?>
That will create a link like comments/add/14, for example, where 14 is the event id. Now in the action, you receive the id
//pass it like parameter of the action
public function add($event_id = null) {
if ($this->request->is('post')) {
$this->Comment->create();
$this->request->data['Comment']['user_id'] = $this->Auth->user('id');
//check that the event_id isn't null and that the event actually exists first
$this->request->data['Comment']['event_id'] = $event_id;
/*etc*/
}
}
You don't need to pass the event_id to the comment_add view, if the user doesn't need to handle it, there's no need to add it to the form.
Second way: If you don't want to pass the event_id inside the url, you need to pass is by POST. To do that, the link you now have to add new comments needs to change to a form with the event_id hidden.
echo $this->Form->create('Comment', array('url'=>array('controller' => 'comments', 'action' => 'add')));
echo $this->Form->input('event_id', array('type'=>'hidden', 'value'=>$event_id);
echo $this->Form->end('New comment');
//instead of <?php echo $this->Html->link(__('New Comment'), array('controller' => 'comments', 'action' => 'add')); ?>
And in the action of the comments, check if the post you receive contains event_id, but not user_id, for example. I find this way a bit messy because every request you receive for that action is going to be a post, so it's be harder to differentiate when you want to display the form to be filled, and when you want to save it.
I like the first way better, and I recommend doing that. But I felt the need to point out there are other ways to do it. Depends what you want.

How to get controller view inside an element?

I have created an element having a text field(Status Bar same as Facebook) which i extended in home/display view.
Code for element:
<?php
echo $this->Html->css('notes');
echo $this->Html->script(array('jquery','jquery.elastic','notes'));
?>
<div class="notescontainer">
<div class="share">Share:</div>
<div class="notes">Notes</div>
<div class="loading"></div>
<div class="img_top"></div>
<div class="text_status">
<?php
echo $this->form->create('Note', array('action' => 'notes'));
echo $this->form->input('notes',array('class' => 'notesbar', 'label'=>'', 'placeholder' => 'Write down you notes ...'));
?>
</div>
<div class="button_outside_border" id="share">
<div class="button_inside_border">
<?php
echo $this->form->submit('Share',array('alt' => 'Add', 'class' => 'sharebutton'));
echo $this->form->end();
?>
</div>
</div>
<div class="clear"></div>
<div class="load_status_out"></div>
</div>
I want that when user shares the status it should re-appear on the same page that is display/home and for that i created a controller for retrieving the status entered by the user.
Controller:
<?php public function notes()
{
$this->set('allnotes', $this->Note->find('all'));
}?>
Controller View:
<?php
foreach($allnotes as $viewnotes):
{
echo $viewnotes['Note']['notes'];
echo "<br>";
}
endforeach;
?>
Now i want this controller view to be displayed on home/display view. Is there any way i can extend it in that element? I don`t want to add it directly on my home/display view as it already fully loaded.
You can use requestAction() to accomplish this, but in my experience it is buggy and a sign of design failure if you need it.
Alternatively you can turn all your view into elements, which can be embedded in each other in any arbitrary way. Then you can just call some shared code in the controller to populate all required models.

CakePHP - View Template - default values for fetched content?

This is the example in the book, of a simple View Template
// app/View/Common/view.ctp
<h1><?php echo $this->fetch('title'); ?></h1>
<?php echo $this->fetch('content'); ?>
<div class="actions">
<h3>Related actions</h3>
<ul>
<?php echo $this->fetch('sidebar'); ?>
</ul> </div>
And this is how it might be extended
// app/View/Posts/view.ctp
<?php
$this->extend('/Common/view');
$this->assign('title', $post);
My question is:
How can I set a default value/content for (let's say) the title, in order to overwrite if needed ?
Thank you!
Fetch the var. If its not empty, echo it, otherwise echo the default.
$title = $this->fetch('title');
echo !empty($title) ? $title : 'Default';

Help with the auto complete method in cakephp

I'm trying to have an auto complete box in my application,where the values are retrieved from a table.
I want to share a form with set of users in the Users table. i have a link called 'Share' and when I click the link, the autocomplete box is generated.
Now when I type in the text box any letter, I want it to be auto suggested.
This is my view file, /views/main/home.ctp
<?php echo $javascript->link('prototype');?>
<?php echo $javascript->link('scriptaculous');?>
<?php echo $javascript->link('effects');?>
<?php echo $javascript->link('controls');?>
$(document).ready(function(){
$(".Share<?=$r['Form']['id'];?>").click(function(){
$("#share<?=$r['Form']['id'];?>").toggle("show");
});
});
<li id="Share<?php echo $r['Form']['id']?>">
Share
<div id="share<?php echo $r['Form']['id']?>">
<?php echo $form->create('User', array('url' => '/forms/share'));?>
<?php echo $ajax->autoComplete('User.name', '/forms/autoComplete');?>
<?php echo $form->end('Share');?>
</div>
</li>
This is my auto_complete.ctp file:/views/forms/auto_complete.ctp
<?php echo $javascript->link('scriptaculous.js');?>
<?php echo $javascript->link('prototype.js');?>
<ul>
<?php foreach($users as $user): ?>
<li><?php echo $user['User']['name']; ?></li>
<?php endforeach; ?>
</ul>
And this this the function in the forms_controller: /forms/autoComplete
function autoComplete()
{
$this->set('users',$this->User->find('all',array('conditions'=>array('User.name LIKE' => $this->data['User']['name'].'%'))));
$this->layout = "ajax";
}
I get the results in the auto_complete.ctp file, i.e, if I type in the letter 's' in the autoComplete text box, I get the corresponding users in that file, but I do not get those values in the text box. Someone help me please.
Well I found the answer myself.
Autocomplete feature of cakephp does not work if you use JQuery.
I removed the line
<?php echo $javascript->link('jquery');?>
and it is working...
EDIT:
If you also want to work with jquery and need the jquery.js file, you would need to enable no-conflict mode in jQuery,as given in the site
http://docs.jquery.com/Using_jQuery_with_Other_Libraries

Resources