McB
McB

Reputation: 1232

Redirecting (back) to another controller in Yii

I've got a ProjectController and a ClientController.

I'd like to create the option from the project _form.php to have a link next to the client dropdown that redirects to ClientController::actionCreate but passes it some kind of variable to let it know if it is coming from ProjectController::actionUpdate or ::actionCreate.

I was ClientController::actionCreate to do its thing, then, if the user got there via ProjectController::actionCreate OR ::actionUpdate, redirect them back to that page and set the client_id in the project model to match whatever was just created.

If someone is just adding a new client via the regular menu, they can just go with the default redirection (I think it goes to view).

In my _form.php I'm using the following code to link to client::actionCreate

<?php echo "&nbsp;".Chtml::link('+New client',array('client/create',array('redir'=>'project/'.Yii::app()->controller->action->id)));?>

with the goal of somehow telling the client controller that it needs to send something back to project/update or project/create.

I'd like to use code like this in ClientController::actionCreate

public function actionCreate()
{
$model=new Client;
...
....
if(isset($_POST['Client']))
{
    $model->attributes=$_POST['Client'];
    if($model->save())
    {
        if(!empty($model->redir)){
            $this->redirect(array($model->redir,'id'=>$model->id));
        } else {
            $this->redirect(array('view','id'=>$model->id));
        }
    }
}
...
....
}

I'm very new to Yii, not sure what the best way to accomplish this would be.

Upvotes: 0

Views: 948

Answers (1)

Rafay Zia Mir
Rafay Zia Mir

Reputation: 2116

If i understood you correctly then You need to distinguish between different calls to same controller.I suppose you are not using YII generated code fro create and update because yii automatically calls the update controller if the call was from update view.I suppose you are using custom update form(not generated by Yii, Yii also generates views through gii). You can do this in these ways.

  1. You can create a hidden field in one of the views in which you want to distinguish. Suppose in update you can write
    <?php echo CHtml::hiddenField('name' , 'update'); ?>
    this values will be submitted in the form also. and in your controller you can check like this
if(isset($_POST['name']))
{
//do something here
}
  • Second you can pass it an status in the link like

<?php echo "&nbsp;".Chtml::link('+New
> client',array('client/create',array('redir'=>'project/'.Yii::app()->controller->action->id,'status'=>'update')));?>


and in your controller you can write as

  public function actionCreate($status=null)
    {
    if($status!=null)
     {
     //do something here
      }
    }

If the status was passed to this action then $status will not be null, if was not passed as parameter then it will be null

Upvotes: 1

Related Questions