Yii - calling an action method from another action method
The header can be confusing, but here's an explanation with code.
Based on some conditions, I can call actionContact
even if the user has called actionIndex
.
Solution: 1
public function actionIndex()
{
$a = 5;
if($a == 5){
$this->actionContact();
}
else{
$this->render('index');
}
}
public function actionContact()
{
// Some codes
$this->render('contact');
}
Solution: 2
public function actionIndex()
{
$a = 5;
if($a == 5){
// Repeat code from actionContact method
$this->render('contact');
}
else{
$this->render('index');
}
}
Solution: 3 I can redirect the contact address.
I think solution 1 works great for me and I would prefer that. But since I'm new to yii I would like to know if this is the way to go?
source to share
If this is not a problem you can use forward
http://www.yiiframework.com/doc/api/1.1/CController#forward-detail
public function actionIndex()
{
$a = 5;
if($a == 5){
// Forward user to action "contact"
$this->forward('contact');
}
else{
$this->render('index');
}
}
public function actionContact()
{
// Some codes
$this->render('contact');
}
source to share
You can use the fourth option, which reorganizes the part that is common to indexing and contact action by the third method:
public function common() {
// ...
}
public function actionIndex() {
// ... call $this->common()
}
public function actionContact() {
// ... call $this->common()
}
However, the best option depends on your specific case. For example, when you decide that you need to invoke another action, do you want to display its view too?
source to share