• 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Can't use $this->uri->segment in if check...

$section = isset($this->uri->segment(2)) ? $this->uri->segment(2) : 'overview_tutorials';
This doesn't work... For that matter, stuff like $this->session->userdata doesn't work either. But I need this! Is there some way to work around this?

I'll try to explain what I need, maybe you guys have got some other idea that could solve my problem:
I'm porting an existing backend to CI, his current backend has got a shitload of links in the navigation, so I want to reduce this and group them by their function. Each group has its subnav, directing to their controllers, if you click on one of the main nav links, you simply get taken to the first controller of the group...

At the moment I do this like this in my controller constructor:
$tutorial_array = array('overview_tutorials' => 'Overview', 'new_tutorial' => 'New tutorial', 'categories' => 'Categories', 'ranks' => 'Ranks');
$news_array = array('overview_news' => 'Overview', 'new_news' => 'New news-item');
$section = $this->uri->segment(2);
if(array_key_exists($section, $news_array)) {
    $data['subnav_array'] = $news_array;
    $data['nav_current'] = 2;
} else {
    $data['subnav_array'] = $tutorial_array;
    $data['nav_current'] = 1;

and my HTML looks like this
<ul id="nav">
    <li&lt;?php if($nav_current == 1) echo " id=\"current\""; ?&gt;><a href="/admin/overview_tutorials">Tutorials</a></li>
    <li&lt;?php if($nav_current == 2) echo " id=\"current\""; ?&gt;><a href="/admin/overview_news">News</a></li>
    &lt;?php foreach($subnav_array as $nav => $item) { ?&gt;
    <li><a href="/admin/&lt;?php echo $nav; ?&gt;">&lt;?php echo $item; ?&gt;</a></li>
    &lt;?php } ?&gt;
This works like a charm, the only thing is: I'm in trouble when someone visits mysite.com/admin/, because the second uri segment isn't set then. I could set a redirect on the index, but that'd be sloppy imo.

Any ideas? Thanks a bunch!

This will work:

$section = $this->uri->segment(2, 'overview_tutorials');

The second parameter of the segment() function is a default value to return if the segment you're looking for doesn't exist.

For sessions you could do something like:
$var = ($this->session->userdata('varname') != FALSE ? $this->session->userdata('varname') : 'default value');

Oh! Thanks!

This is what happens when I start coding at 2am, I forget to check the user guide and just start posting. Thanks!

Digg   Delicious   Reddit   Facebook   Twitter   StumbleUpon  

  Theme © 2014 iAndrew  
Powered By MyBB, © 2002-2020 MyBB Group.