2014-10-10 1 views
0

Yii에서 라우터 규칙을 사용하여 URL의 키워드를 특정 행동의 $ _GET 매개 변수로 "변환"할 수 있습니까? 내가 원하는 무엇

,이 URL을 수 있도록하는 것입니다 :

http://example.com/MyModule/MyController/index/foo

에 가리 :

http://example.com?r=MyModule/MyController/index&id=12

foo12에.

그리고, 내가 "경로"URL 형식이 사용하고, 그리고 indexid=을 숨기기 위해 다른 URL 규칙을 사용하고 있기 때문에 URL은 위의 결국을 가리켜 야 :

http://example.com/MyModule/MyController/12

규칙을 설정하여이 possibe인가 구성 파일 urlManager 구성 요소에?

답변

0

매개 변수 $id 받아 들여야 액션 : 당신이해야 할 일은

public function actionView($id) { 
    $model = $this->loadModel($id); 

, 동일한 컨트롤러에 loadModel 기능을 수정하는 것입니다 : 다음

/** 
* @param integer or string the ID or slug of the model to be loaded 
*/ 
public function loadModel($id) { 

    if(is_numeric($id)) { 
     $model = Page::model()->findByPk($id); 
    } else { 
     $model = Page::model()->find('slug=:slug', array(':slug' => $id)); 
    } 

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

    if($model->hasAttribute('isDeleted') && $model->isDeleted) 
     throw new CHttpException(404, 'The requested page has been deleted for reasons of moderation.'); 

    // Not published, do not display 
    if($model->hasAttribute('isPublished') && !$model->isPublished) 
     throw new CHttpException(404, 'The requested page is not published.'); 

    return $model; 
} 

, 당신은 수정해야합니다 urlManager 규칙은 ID 대신 문자열을 허용합니다.

아래 기본 규칙에서 :\d+을 제거하십시오.

'<controller:\w+>/<id:\d+>' => '<controller>/view', 

그것은 다음과 같이해야합니다 :

'<controller:\w+>/<id>' => '<controller>/view', 

이 경로를가는 경우, 반드시 슬러그는 데이터베이스에서 고유하게, 당신은 또한 유효성 검사 규칙을 적용해야한다,주의해야 할 한 가지 더 모델에서 :