How to identify active menu link in CakePHP - cakephp

I'm creating an accordion layout for an admin sidebar. Now I need to identify the active link and add a class active to that link. Here is my code:
<div class="accordion-group">
<div class="accordion-heading">
<a href="#collapseSeven" data-parent="#side_accordion" data-toggle="collapse" class="accordion-toggle">
<i class="icon-th"></i> Gallery Manager
</a>
</div>
<div class="accordion-body collapse" id="collapseSeven">
<div class="accordion-inner">
<ul class="nav nav-list">
<li>
<?php echo $this->Html->link('View All',array('controller' => 'gallaries', 'action' => 'index'));?>
</li>
<li>
<?php echo $this->Html->link('Add New',array('controller' => 'gallaries', 'action' => 'add'));?>
</li>
</ul>
</div>
</div>
</div>
What is the best way to do this? Thanks in advance!

I have found the solution :
$url = $this->Html->url('INPUT_THE_URL') ;
$active = $this->request->here == $url? true: false;

To check whether a given URL is currently active in Cakephp 2.x, you should check if it's normalized (in the sense of Router::normalize()) form is the same as the normalized form of the currently requested URL (in the sense of $this->request->here).
$currentUrl = Router::normalize($this->request->here);
$checkedUrl = Router::normalize($myUrl);
$isActive = $currentUrl === $checkedUrl;
Sometimes you might want a loose matching to show a page as active in a menu, if a child is currently shown. Think you want to display your menu link to the fruits overview site at /fruits/ as active while surfing the Banana detail site at /fruits/banana/. You can achieve this easily by looking for a partial match only.
$isActive = (0 === strpos($currentUrl, $checkedUrl));
For sure your matching might get more complex, for example if you're heavily making use of named params and the like and want to reflect it in your menu, but you should find your way from here.
A solution for your particular problem might look like this:
$currentUrl = Router::normalize($this->request->here);
$links = array(
array(
'label' => __('View All'),
'url' => array('controller' => 'galleries', 'action' => 'index'),
),
array(
'label' => __('Add New'),
'url' => array('controller' => 'galleries', 'action' => 'add'),
),
/* ... */
);
foreach ($links as $link) {
$linkLabel = $link['label'];
$linkUrl = Router::url($link['url']);
$linkHtml = $this->Html->link($linkLabel, $linkUrl);
$linkActive = $currentUrl === $linkUrl;
echo $this->Html->tag('li', $linkHtml, array(
'class' => $linkActive ? 'active' : '',
'escape' => false, // to not escape anchor markup
));
}
To make your live just that tiny bit easier by not even thinking about this question, you could also use a Helper for menu creation that someone else built like torifat/cake-menu_builder.

There are a number of ways, here are a few for adding the class to the container
<li <?php echo ($url == 'users/account')? 'class="current"' : ''?>>
<li <?php echo (preg_match("/addresses/", $url))? 'class="current"' : ''?>>
<li <?php echo ($this->params['controller'] == 'attributes')? 'class="current"' : ''?>>
Or you can pass it into the $options
$options = array();
if($this->controller == 'mycontroller' && $this->action == 'myaction'){
$options = array_merge($options, array('class'=>'active'));
}
echo $this->Html->link('Title', '/url', $options);

Here simple way to add active class:
<ul class="nav nav-list">
<li class="<?php echo (($this->params['controller']==='gallaries')&&($this->params['action']=='index') )?'active' :'' ?>">
<?php echo $this->Html->link('View All',array('controller' => 'gallaries', 'action' => 'index'));?>
</li>
<li class="<?php echo (($this->params['controller']==='gallaries')&& ($this->params['action']=='add') )?'active' :'' ?>">
<?php echo $this->Html->link('Add New',array('controller' => 'gallaries', 'action' => 'add'));?>
</li>
</ul>
I think this will helpful for you.

I know this is pretty old but i found a good solution.
Based on Faisal's answer i wrote my own simple Helper:
App::uses('AppHelper', 'View/AppHelper');
class PVHtmlHelper extends AppHelper {
public $helpers = array('Html');
public function link($title = null, $url = null, $options) {
if ($title == null || $url == null)
return;
$class = (($this->params['controller']===$url['controller']) && ($this->params['action']==$url['action']) )?'active' :'';
echo "<li class='" . $class . "'>" . $this->Html->link($title, $url, $options) . "</li>";
}
}
Maybe you need to modify the echo <li> inside the function to fit your needs.
Example:
echo $this->PVHtml->link('Login', array('controller' => 'users', 'action' => 'login'));

Related

how can i write helper link with image link in span tag cakephp

i want to generate this
<a href="/users/signup" class="sf-with-ul">
<span class="profile-avatar">
<img alt="" src="img/avatar/anonymous.png" height="40" width="40">
</span>
</a>
I have written
<?php echo $this->Html->link(
$this->Html->image('avatar/anonymous.png',array('height' =>40,'width'=>'40')), array('controller' => 'users', 'action' => 'signup'),
array('class' => 'sf-with-ul', 'escape' => false));?>
which generates
<span class="profile-name"></span><img src="/FindTutor/img/avatar/anonymous.png" height="40" width="40" alt="" />
Any help? Thanks in advance.
you can try this just change your image path
<?php echo $this->Html->link('<span class="profile-avatar">'. $this->Html->image('home/logo.png',array('width'=>'40px','height'=>'40px'), array('alt' => '')), array('controller' => 'users', 'action' => 'signup' ), array('class' => 'sf-with-ul', 'escape' => false)).'</span>';?>
Try this:
<?php
$img = $this->Html->image("avatar/anonymous.png",
array("height" => "40", "width" => "40")
);
$img_span = $this->Html->tag('span', $img,
array('class' => 'profile-avatar')
);
echo $this->Html->link($img_span,
array("controller" => "users", "action" => "signup"),
array("escape" => false)
);
?>
This looks a little lengthy but it's easier to understand and works exactly like what you're asking for.
Peace! xD

What is cakephp's 'maximum depth reached', I got this error while patination with message 'address not found'

I am new to cakephp and using 2.4 version with bootstrap css.
I have almost finished my project but getting some errors while creating search with pagination.
While pagination in Cakephp, first pages are working fine but last 2-3 pages shows error as the requested address was not found on this server.
tables are below.
universities, courses, semesters, subjects, units, topics
respectively these models having hasMany relationships from left to right.
e.g. universities hasMany courses, courses hasMany semesters.....
my search actions is as below.
public function searchresults() {
if($this->request->is('post')) {
$unid=$this->data['University']['universities'];
$searched = $this->data['University']['searchtxt'];
$this->Session->write('Searched.stext',$searched);
$this->Session->write('Searched.univ',$unid);
}
$unid=$this->Session->read('Searched.univ');
$searched = $this->Session->read('Searched.stext');
//Create Join to find total numbers of records after search
$this->Topic->bindModel(array(
'belongsTo' => array(
'Unit' => array(
'foreignKey' => false,
'type' => 'RIGHT',
'conditions' => array(
'Topic.unit_id = Unit.id' ,
)
),
'Subject' => array(
'foreignKey' => false,
'type' => 'RIGHT',
'conditions' => array(
'Unit.subject_id = Subject.id',
)
),
'Semester' => array(
'foreignKey'=> false,
'type'=>'RIGHT',
'conditions' => array (
'Subject.semester_id = Semester.id'
)
),
'Course' => array(
'foreignKey'=> false,
'type'=>'RIGHT',
'conditions' => array (
'Semester.course_id = Course.id'
)
),
'University' => array(
'foreignKey'=> false,
'type'=>'RIGHT',
'conditions' => array (
'Course.university_id = University.id'
)
)
)
));
$this->Paginator->settings=array(
'limit'=>10,
'page'=>1,
'conditions' => array('or'=>array(
'Topic.name LIKE' => '%'.$searched.'%',
'Topic.description LIKE' => '%'.$searched.'%'
)),
);
$data=$this->paginate('Topic');
//debug($data);
$this->set('searched',$searched);
$this->set('sresults',$data);
$this->set('uni_id',$unid);
}
my view's pagination part code is as below:
<div class="row"><!--Pagination links begins -->
<div class="col-sm-8 col-sm-offset-3">
<!-- Shows the next and previous links -->
<ul class="pagination largescreen">
<li class="disabled-page mobileview">
Page <?php echo $this->Paginator->counter(); ?>
</li>
<?php echo $this->Paginator->prev('«', array('tag'=>'li'), null, array('class' => 'disabled-page','tag'=>'li')); ?>
<!-- Shows the page numbers -->
<?php
echo $this->Paginator->numbers(array(
'tag'=>'li',
'separator'=>'',
'currentClass'=>'active',
'currentTag'=>'a',
'modulus'=>4
));
?>
<?php echo $this->Paginator->next('»', array('tag'=>'li'), null, array('class' => 'disabled-page','tag'=>'li')); ?>
</ul>
</div>
<div>
<ul class="pagination pagination-sm smallscreen" style="overflow:auto;">
<li class="disabled-page mobileview">
Page <?php echo $this->Paginator->counter(); ?>
</li>
<?php echo $this->Paginator->prev('«', array('tag'=>'li'), null, array('class' => 'disabled-page','tag'=>'li')); ?>
<!-- Shows the page numbers -->
<?php
echo $this->Paginator->numbers(array(
'tag'=>'li',
'separator'=>'',
'currentClass'=>'active',
'currentTag'=>'a',
'modulus'=>8
));
?>
<?php echo $this->Paginator->next('»', array('tag'=>'li'), null, array('class' => 'disabled-page','tag'=>'li')); ?>
</ul>
</div>
</div><!--Pagination links ends -->
Please help as i am stuck after searching a lot about this...

render elements in cakephp on home.ctp

I am using cakephp 2.4
in my apps I have a view in CategoriesController namely "Editorial" and I can show all the articles under that category by http://mydomain/categories/editorial
I am trying to show all the articles under "Editorial" category in the home.ctp by echo $this->element('editorials');
but it shows Notice (8): Undefined variable: articles [APP\View\Elements\Editorials.ctp, line 4]
CategoriesController.php
public function Editorial() {
$category = $this->Category->find('first', array(
'conditions' => array(
'Category.id' => 1
)
));
$this->set(compact('category'));
$this->Paginator = $this->Components->load('Paginator');
$this->Paginator->settings = array(
'Article' => array(
'recursive' => -1,
'contain' => array(
'Category'
),
'limit' => 5,
'conditions' => array(
'Article.category_id' => $category['Category']['id'],
),
'order' => array(
'Article.id' => 'ASC'
),
'paramType' => 'querystring',
)
);
$articles = $this->Paginator->paginate($this->Category->Article);
$this->set(compact('articles'));
}
View file:
<?php if (!empty($articles)): ?>
<?php echo $this->element('editorials'); ?>
<?php echo $this->element('pagination-counter'); ?>
<?php echo $this->element('pagination'); ?>
<?php endif; ?>
Elements/Editorials.ctp:
<div class="row">
<?php
$i = 0;
foreach ($articles as $art):
$i++;
if (($i % 4) == 0) { echo "\n<div class=\"row\">\n\n";}
?>
<div class="col col-sm-3">
<?php echo $this->Html->link($art['Article']['title'], array('controller' => 'articles', 'action' => 'view', 'id' => $art['Article']['id'])); ?>
<br />
</div>
<?php
if (($i % 4) == 0) { echo "\n</div>\n\n";}
endforeach;
?>
<br />
<br />
</div>
try to add $this->render('file'); in your Editorial action and replace file with view file name without.ctp
Something you can change:
1. In controller:
$this->set(compact('category', 'articles')); // one set()
2. In view: (Main Point)
<?php echo $this->element('editorials', array('articles' => $articles)); ?>
Here, you need to pass the articles variable to element like above, by default an element don't recognize the viewVars.

Yii - form with CMultiFileUpload won't submit files

I need some help with a little strange problem.
My problem is that submit button does not submit files to controller when using CMultiFileUpload.
I have this very simple view to upload multiple files:
<?php
$form = $this->beginWidget(
'CActiveForm',
array(
'id' => 'upload-form',
'htmlOptions'=>array('enctype' => 'multipart/form-data'),
));?>
<div class="row">
<?php echo $form->labelEx($model,'sourceCode'); ?>
<?php
$this->widget('CMultiFileUpload', array(
'model'=>$model,
'name' => 'sourceCode',
'attribute'=> 'sourceCode',
'max'=>5,
'accept' =>'zip',
'duplicate' => 'Duplicate file!',
'denied' => 'Invalid file type',));
echo $form->error($model,'sourceCode');?>
</div>
<div class="row buttons">
<?php echo CHtml::submitButton('Submit'); ?>
</div>
<?php $this->endWidget();?>
Here is my model:
class UploadSolutionForm extends CFormModel
{
public $sourceCode;
public function rules()
{
return array(
array('sourceCode', 'file', 'types'=>'zip', 'allowEmpty'=>false, 'wrongType'=>'Only .zip files allowed'),
);
}
public function attributeLabels()
{
return array(
'sourceCode' => 'Uploaded file',
);
}
}
And here is probably the simplest action ever:
public function actionUpload()
{
$model = new UploadSolutionForm();
if(isset($_POST['UploadSolutionForm']))
{
echo 'Got it!';
}
$this->render('solve',array('model'=>$model));
}
But when I click on submit it does not echo anything, but it does with this code (CMultiFileUpload is replaced with fileField):
<?php
$form = $this->beginWidget(
'CActiveForm',
array(
'id' => 'upload-form',
'htmlOptions'=>array('enctype' => 'multipart/form-data'),
));?>
<div class="row">
<?php echo $form->labelEx($model, 'sourceCode');?>
<br><?php echo $form->fileField($model, 'sourceCode');?>
<?php echo $form->error($model, 'sourceCode');?>
</div>
<div class="row buttons">
<?php echo CHtml::submitButton('Submit'); ?>
</div>
<?php
$this->endWidget();?>
Can someone tell me what's wrong?
Thanks in advance...
Try this it works
In your View file specify action attribute in form widget as shown in the below code
<?php
$form = $this->beginWidget(
'CActiveForm',
array(
'id' => 'upload-form',
'action'=>Yii::app()->createAbsoluteUrl('yourcontrollername/actionname'),
'htmlOptions'=>array('enctype' => 'multipart/form-data'),
));?>
<div class="row">
<?php $this->widget('CMultiFileUpload',array(
'name'=>'files',
'accept'=>'jpg|png',
'max'=>3,
'remove'=>Yii::t('ui','Remove'),
//'denied'=>'', message that is displayed when a file type is not allowed
//'duplicate'=>'', message that is displayed when a file appears twice
'htmlOptions'=>array('size'=>25),
)); ?>
</div>
<div class="row buttons">
<?php echo CHtml::submitButton('Submit'); ?>
</div>
<?php $this->endWidget();?>
In yourController actionUplaod as shown below
public function actionUpload(){
echo "hi";
var_dump($_FILES['files']);
}

Modifying HTML output on Main Menu Drupal 7

I've developing my own theme and I'm experiencing problem to generate menu link with my own class, here's my menus supposed to be:
<ul class="dropdown">
<li class="first current-menu-item menu-item-home menu-gray">
<span>HOME</span>
</li>
<li class="menu-red">
<span>Fashion</span>
</li>
<li class="menu-orange">
<span>Design</span>
</li>
</ul>
There's class "menu-red" or "menu-orange" will be different color on css. And this is how I print the main menus on template:
<?php
if ($main_menu):
print theme('links__system_main_menu',
array(
'links' => $main_menu,
'attributes' => array(
'id' => 'main-menu',
'class' => 'dropdown'
)
)
);
endif;
?>
I've tried to override the links__system_main_menu function with my own on template.php but still no luck.
Thanks for helping.
Regards,
#andriansandi
I'm got my answer from http://drupal.org/node/1033442#comment-5076932
Here:
function mytheme_links__system_main_menu($variables) {
$html = "<div>\n";
$html .= " <ul>\n";
foreach ($variables['links'] as $link) {
$html .= "<li>".l($link['title'], $link['path'], $link)."</li>";
}
$html .= " </ul>\n";
$html .= "</div>\n";
return $html;
}
This is how I do it.
function YOURTHEME_menu_tree($variables) {
return '<ul class="dropdown">' . $variables['tree'] . '</ul>';
}

Resources