Reputation: 5315
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.
Upvotes: 1
Views: 2593
Reputation: 2802
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');
Upvotes: 0
Reputation: 1533
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.
Upvotes: 0
Reputation: 5767
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');
Upvotes: 2