CakePHP - How to pass a $variable to the find function in a controller
All,
I wanted to know how I could pass a $variable from view, for example, current article id ( $article['Article']['id'] ) to the find('all') call in a function in articles_controller.php.
function getRelated($id = null){
$relatedarticles = $开发者_运维知识库this->Article->find(
'all',
array(
'fields' => array(
'Article.title'
),
'limit' => 4,
'order' => 'Article.id ASC',
'recursive' => 1,
'conditions' => array(
'Article.category_id =' => $id
)
)
);
if (!empty($this->params['requested'])) {
return $relatedarticles;
} else {
$this->set(compact('relatedarticles'));
}
}
And then from the view, I would call something like this. I cant seem to get this to work... what is the best way to do this?
<div id="articles_view_related">
Related News
<?php
$currentid = $articles['Article']['id'];
$relatedarticles = $this->requestAction('/articles/getRelated/id:$currentid');
//debug($relatedarticles);
?>
<ul>
<?php
foreach($relatedarticles as $relatedarticle){
?>
<li>
<?php
echo $relatedarticle['Article']['title'];
?>
</li>
<?php
}
?>
</ul>
</div>
thank you for all your help
I'm struggling to work out why you are doing this task in this way, but here is your answer nonetheless:
$relatedarticles = $this->requestAction('/articles/getRelated/'.$currentid);
You don't need id:$currendId
, because of the parameter in your action, anything after /controller/action/ in a URL will be declared as $id
in getRelated($id = null);
eg: /articles/getRelated/23
and $id
will equal 23.
What you should be doing, is declaring the getRelated()
method in your model, and then using the controller action to get the contents, and pass it to the view.
eg:
$relatedArticles = $this->Article->getRelated($article['Article']['id']);
$this->set(compact('relatedArticles));
For data manipulation you want to repeat, stick it in your models :)
精彩评论