esti
(Yii2Noob)
April 22, 2015, 4:30am
1
Is there any other way to fetch data in view file?
Normally it gets fetched by ID but i want it fetched by title of data, i have title field in my table and i want my data fetched by title with url like:
http://localhost/example/post/he-is-the-man.html
instead of
http://localhost/example/post/4
rupsk1607
(Webin2015)
April 22, 2015, 5:12am
2
hey sorry dear i post in yii2 syntax.
In your view action pass title parameter in place of id.
public function actionView($title)
{ $dataCountry = Country::find()->where(['countryName' => $title])->one();
return $this->render('view', [
'model' => $dataCountry,
]);
}.
u also have to change in ur urlrules to hide title parameter.
'<controller:\w+>/<title:\w+>' => '<controller>',
'<controller:\w+>/<action:\w+>/<title:\w+>' => '<controller>/<action>',
'<controller:\w+>/<action:\w+>' => '<controller>/<action>',
so that u can call that action by title
http://localhost/yii2demo/country/view/India
regards,
rups g
esti
(Yii2Noob)
April 22, 2015, 5:40am
3
Error 404
Unable to resolve the request "this-is-a-demo".
Did not worked!
rupsk1607
(Webin2015)
April 22, 2015, 5:41am
4
copy paste ur controller action and url rules if added.
esti
(Yii2Noob)
April 22, 2015, 5:49am
5
oops sorry to say i am having a syntax error in you code, this is my action as i changed as per your syntax
public function actionView($url)
{ $urldata = Page::find()->where(['url' => $url])->one();
return $this->render('view', [
'model' => $urldata,
]);
}
this is url rule
'<controller:\w+>/<url:\w+>' => '<controller>',
'<controller:\w+>/<action:\w+>/<url:\w+>' => '<controller>/<action>',
'<controller:\w+>/<action:\w+>' => '<controller>/<action>',
before i tried sorting my url and making them beautiful i had my controller like this:
public function actionView($id)
{
$this->render('view',array(
'model'=>$this->loadModel($id),
));
}
public function loadModel($id)
{
$model=Page::model()->findByPK($id);
if($model===null)
throw new CHttpException(404,'The requested page does not exist.');
return $model;
}
esti
(Yii2Noob)
April 22, 2015, 6:00am
6
If i try getting data from title my url gets messy
http://localhost/article/index.php/post/this%20is%20a%20demo%20for%20url
so i tried sorting it out keeping a field url in my database which i guess would help me making my url
http://localhost/article/index.php/post/this-is-a-demo-for-url