Question

I am using "yii-user" (modules/user), now the user url is mysite.com/user/user/view/id/1 and I want change to mysite.com/profile/username

User controller is :

public function actionView()
    {
        $model = $this->loadModel();
        $this->render('view',array(
            'model'=>$model,
        ));
    }

public function loadModel()
    {
        if($this->_model===null)
        {

            if(isset($_GET['id']))
                $this->_model=User::model()->findbyPk($_GET['id']);

            if($this->_model===null)
                throw new CHttpException(404,'The requested page does not exist.');

        }
        return $this->_model;
    }


    /**
     * Returns the data model based on the primary key given in the GET variable.
     * If the data model is not found, an HTTP exception will be raised.
     * @param integer the primary key value. Defaults to null, meaning using the 'id' GET variable
     */
    public function loadUser($id=null)
    {
        if($this->_model===null)
        {
            if($id!==null || isset($_GET['id']))
                $this->_model=User::model()->findbyPk($id!==null ? $id : $_GET['id']);
            if($this->_model===null)
                throw new CHttpException(404,'The requested page does not exist.');
        }
        return $this->_model;
    }

I try to add this url rule 'profile/<username>' => 'user/user/view', but it still not working because the model need id in url.

Any idea please?

Was it helpful?

Solution

You should simply modify your action to handle username, e.g. :

public function actionView($id=null, $username=null)
{
    if (isset($id))
        $model = User::model()->findByPk($id);
    else if isset($username))
        $model = User::model()->findByAttributes(array('username'=>$username));

    if ($model===null)
        throw new CHttpException(404,'The requested page does not exist.');

    $this->render('view',array(
        'model'=>$model,
    ));
}

And make sure :

  • username is unique,
  • you have the corresponding url rule in your config.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top