Codeigniter--add "active" css class to link, how to? - php

What's the quickest and easiest way to add the "active" class to a link, so it can be styled? I'm developing an app in CI, and I'd like a quick easy way to do this automatically.
jQuery is an option too...

You should really be using the CodeIgniter URI Class to do this instead of the $_SERVER['REQUEST_URI']
$this->uri->uri_string()
if ( $this->uri->uri_string() == '/contact' )
^^ that is the preferred way to do things due to some complexities that can happen with codeigniter's routing features

Depends on how you're outputting your link HTML.
If you're using the URL Helper module, then you can call the anchor() function to create your links, and pass it an array of attributes as the third parameter, ie:
$this->load->helper('url');
echo anchor('url/path', 'Click here', array('class' => 'active'));
If you're just outputting the HTML manually in your templates/views, obviously you can just create the class attribute yourself in the HTML.

If you have a lot of navigation items you can do it this way (very simplified)...
<ul>
<li<?= if ( $_SERVER['REQUEST_URI'] == '/contact' ): ?> id="active"<?php endif; ?>>contact</li>
</ul>
You'll have to edit it for your needs...
If you don't have that many nav items an easier way is to give each page a body id and then use css to make it active.
<style type="text/css">
body#contact #contact-nav { font-weight:bold; }
</style>
<body id="contact">
<ul id="navigation">
<li id="contact-nav">contact</li>
</ul>

You can do this way by creating helper with following
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
if ( ! function_exists('active_link'))
{
function active_link($controller)
{
$CI =& get_instance();
$class = $CI->router->fetch_class();
return ($class == $controller) ? 'active' : '';
}
}
then apply it in menu view
<li class="<?php echo active_link('services'); ?>">Services</li>

To adding active class (class=”active”) to a link , I’ve done it by doing this:
In view
<ul class="nav nav-tabs">
<li id="button_home" class='<?php echo $home;?>'><?php echo anchor('pages/index','Home');?></li>
<li id="button_about" class='<?php echo $about;?>'><?php echo anchor('pages/about','About')?></li>
</ul>
In controller
$data['home']="active";
Maybe it's not your solution. but it works for me.

Related

Laravel get current route

I have some navigation links and I want to get the current route in laravel 5 so that I can use the class active in my navigations. Here are the sample links:
<li class="active"> Home </li>
<li> Contact </li>
<li> About </li>
As you can see, in the Home link there is the active class which means that it is the current selected route. But since I am using laravel blade so that I would not repeat every navigation links in my blades, I can't use the active class because I only have the navigation links in my template.blade.php. How can I possibly get the current route and check if it is equal to the current link? Thank you in advance.
$uri = Request::path()
Check out the docs
You can use named routes like
Route::get('/', ['as'=>'home', 'uses'=>'PagesController#index']);
and then in the view you can do the following
<li {!! (Route::is('home') ? 'class="active"' : '') !!}>
{!! link_to_route('home', 'Home') !!}
</li>
So I got it working with some little tricks. For example the url in the address bar is http://localhost:8000/tourism/places.
If I will use the Request::path() method, I will get tourism/places. But what I wanted to get is the tourism part only so what I did is this:
$currentPath = Request::path();
$values = explode("/", $currentPath);
$final = $values[0];
Now the $final variable will have the value "tourism".
Now to make the variable load globally, I included the code in the AppServiceProvider.php inside the public function boot().
public function boot()
{
$currentPath = Request::path();
$values = explode("/", $currentPath);
$final = $values[0];
view()->share('final', $final);
}
And lastly in my blade template,
<li #if ($final== "tourism") class="active" #endif>
Places
</li>
Simple way is always better, just use the same function you use to generate links and it will give you all, including the flexibility to use wild cards
<a class="nav-link {{ Request::url() === route("products.list", [$group_key]) ? 'active' : '' }}"
href="{{ route("products.list", [$group_key]) }}"
>
LInk text
</a>
Plus, you still are going to have only one place to manage URL-s - your router files.

What is the code inside a paginator view?(Laravel)

<?php echo $users->links('view.name'); ?>
If I specify this view in laravel-4, what will be the code inside it? I can't find an example in the docs. Any example please?
according to this http://laravel.com/docs/pagination
If you use the paginator like this
<?php echo $users->links(); ?>
Laravel will use the default view which is defined inside app/config/view.php as
'pagination' => 'pagination::slider-3',
With this default option, your pagination will use the Illuminate/Pagination/views/slider-3.php view,
which is the following:
<?php if ($paginator->getLastPage() > 1): ?>
<ul class="pagination">
<?php echo $presenter->render(); ?>
</ul>
<?php endif; ?>
You can define your own view, and then use inside it the $paginator object to format it according to your needs.
You can see an example here.

How to create a view page displaying data only from a specific id? I'm using Yii Framework

In my main.php, I created a link and it's supposed to display all announcements that the current user posted but instead, I'm getting ALL the announcements from every user.
How do I change this?
This is my link code:
<a class="more" href="<?php echo Yii::app()->createUrl('announcement')?>" >
<?php switch_lang('View Announcements', '查看更多', FALSE)?>
</a>
And based on my code from the actionShow() from the controller, this is the code:
public function actionShow($id)
{
$post=$this->loadModel($id);
$comment=$this->newComment($post);
$attachments=Attachments::model()->findAllByAttributes(array(
'content_id' => $id,
));
$this->render('show',array(
'model'=>$post,
'comment'=>$comment,
'attachments'=>$attachments
));
}
If you are trying to work the show action of whatever controller it is a part of, do this -
<a class="more" href="<?php echo Yii::app()->createUrl('<controllername>/show',array('id'=>$id))?>" >
You can re-route the action to any name like the 'announcement' part you gave in the question in the urlManager of main.php subsequently.

Passing default data for a controller in Laravel

I want to build a menu from an array in Laravel. What I'm currently doing is putting the array in a view
$menu = ['home', 'users' => ['create users' , 'update user', 'activity log']];
and then looping through it to generate the menu:
<section>
<!-- Left Nav Section -->
<ul class="left">
<li class="divider"></li>
#foreach($menu as $key => $nav)
<li class="has-dropdown">
{{ $key }}
<ul class="dropdown">
#foreach($nav as $subnav)
<li>
{{ $subnav }}
</li>
#endforeach
</ul>
</li>
#endforeach
</ul>
</section>
Is there any other way that I can achieve the same result without putting the data in the view?
I also tried creating a constructor function in the controller:
public function __construct() {
$menu = ['home', 'users' => ['create users' , 'update user', 'activity log']];
return $menu;
}
But I guess that is not how it works. I appreciate any ideas on how I can go about this. Thanks in advance
View composers to the rescue!
They are executed every time before a view is rendered, so you can use this to pass standard data to them.
If you're using controller layouts you can bind data to the layout from within the constructor. Just make sure you call the parent constructor first so that the layout is instantiated properly.
public function __construct()
{
parent::__construct();
$this->layout->menu = ['home', 'users' => ['create users' , 'update user', 'activity log']];
}
That will bind a $menu variable to the layout, and will also be available to any nested views that are used with Blades #include.
Have a look at view composers:
http://www.laravel.com/docs/views#view-composers

Is there a way to have a navigation entry with no link in zend navigation?

I'm sure my question is pretty straight forward, and I've been looking for an answer to this, but I can't seem to make it work. I want to do something like this:
<?xml version="1.0" encoding="UTF-8"?>
<configdata>
<dashboard>
<label>Dashboard</label>
<controller>dashboard</controller>
<action>index</action>
<module>global</module>
</dashboard>
<bills>
<label>Bills</label>
<pages>
<create-bill>
<label>Create New Bill</label>
<controller>bill</controller>
<action>create</action>
<module>global</module>
</create-bill>
</pages>
</bills>
</configdata>
Please note that in the <bills> section, I want to have a category with just a label, that way when I add styling later, I can hover over "Bills" and "Create New Bill" and other links will be shown, but clicking on "Bills" shouldn't do anything because it's just a category header.
I hope that makes sense.
You must specify a type for your page otherwise Zend_Navigation will throw an exception. In cases like yours I always use a Zend_Navigation_Page_Uri as page type and specify its uri to #. To apply this to your config file you could do this
<bills>
<label>Bills</label>
<uri>#</uri>
<pages>
<create-bill>
<label>Create New Bill</label>
<controller>bill</controller>
<action>create</action>
<module>global</module>
</create-bill>
</pages>
</bills>
The generated markup still contains a link but it will not point anywhere.
Moreover, since you need to bind some javascript to it in order to show the menu, you could even disable it by returning false in the click handler for that links.
In order to attach javascript callbacks (or some css) to that kind of link you may find useful to attach a class to those links. Within the same configuration file, you could with this code
<bills>
<label>Bills</label>
<uri>#</uri>
<class>fakelink</class>
<pages>
<create-bill>
<label>Create New Bill</label>
<controller>bill</controller>
<action>create</action>
<module>global</module>
</create-bill>
</pages>
</bills>
In this case the generated markup would be
<li class="fakelink>
Bills
<ul>submenu here</ul>
</li>
and you could easily select that kind of links with a javascript library. For example with jQuery you could do this:
$(function() { $('.fakelinks > a').click(function () { return false; }); });
There is actually another way to solve this.
You can set custom properties on all Zend_Navigation_Page just by defining extra configuration options in your xml/array/...
Then by using a dedicated partial to render your menu/breadcrumbs you can perfectly skip rendering the <a> tag or render a completely different markup based on these properties.
<!-- ... -->
<page1>
<label>Page 1</label>
<uri>page1</uri>
<link>false</link> <!-- Custom property -->
<pages>
<page1_1>
<label>Page 1.1</label>
<uri>page1/page1_1</uri>
</page1_1>
<page1_2>
<label>Page 1.2</label>
<uri>page1/page1_2</uri>
</page1_2>
<page1_3>
<label>Page 1.3</label>
<uri>page1/page1_3</uri>
</page1_3>
</pages>
</page1>
<!-- ... -->
Note: I'm using the breadcrumbs example here but most of the Navigation View_Helpers have a setPartial() method, including the menu helper.
Then in your view script or layout you just specify that your breadcrumbs helper needs to use a partial.
<?php
echo $this->navigation()->breadcrumbs()->setPartial('my_breadcrumbs.phtml');
And in your partial you loop over the pages in year breadcrumb trail and check the custom properties for each page.
<?php
foreach($this->pages as $page)
{
$properties = $page->getCustomProperties();
// Check if we need to render the link tag
if($properties['link'] !== false){
echo '<a href="' . $page->getHref() . '">';
}
// Render the label
echo $page->getLabel();
// And check if we need to render the closing tag
if($properties['link'] !== false){
echo '</a>';
}
}
Note: By using a partial you'll lose some default functionality of the Breadcrumb View_Helper like setLinkLast, setSeparator, ... but these shouldn't pose too much of a problem.
If you're happy for your category labels to be spans then just specifying an empty URI will do the job. Zend_View_Helper_Navigation_Menu::htmlify() is what renders a Zend_Navigation_Page:
/**
* Returns an HTML string containing an 'a' element for the given page if
* the page's href is not empty, and a 'span' element if it is empty
*
* Overrides {#link Zend_View_Helper_Navigation_Abstract::htmlify()}.
*
* #param Zend_Navigation_Page $page page to generate HTML for
* #return string HTML string for the given page
*/
public function htmlify(Zend_Navigation_Page $page)
Example output:
<ul class="navigation">
<li>
<span id="menu-staff">Staff</span>
<ul>
<li>
Book Holiday
</li>
<li>
View Booked and Remaining Holiday
</li>
</ul>
</li>
</ul>
I went about it in a different way:
nav:
User:
label: Account Services
uri: #fakeUri
Then in my template code:
<?php foreach ($navSettings as $navSetting): ?>
<?php if ('#fakeUri' === $navSetting->getUri()): ?>
<?php echo $navSetting->getLabel() ?>
<?php else: ?>
<a href="<?php echo $navSetting->getUri() ?>"><?php echo $navSetting->getLabel()) ?>
<?php endif ?>
<?php endforeach ?>
<page_bills>
<label>Bills</label>
<type>uri</type>
<pages>
</pages>
</page_bills>

Categories