S
S
sdgs4s4 .2017-10-25 19:04:55
Yii
sdgs4s4 ., 2017-10-25 19:04:55

Yii2 -> url without product id - how to implement?

Hello!
Tell me how to implement the output of the product without its id in the url ?
now:
/price/23-akademiceskogo-otpuska.html
need
/price/akademiceskogo-otpuska.html
config:

'price/<id:\d+>-<slug:[a-z0-9_-]+>.html' => 'price/view',

Controller:
public function actionView($id){
//        $id = Yii::$app->request->get('id');

        $reviews = Review::find()->where(['status' => '1'])->limit(30)->all();
        $price = Price::findOne($id);
        if(empty($price))
            throw new \yii\web\HttpException(404, 'Такого товара нет');
//        $product = Product::find()->with('category')->where(['id' => $id])->limit(1)->one();

        $this->setMeta($price->title, $price->keywords, $price->description);
        return $this->render('view', compact('price', 'reviews'));
    }

View
<a href="<?= \yii\helpers\Url::to(['price/view', 'id' => $price->id, 'slug' => $price->slug]) ?>

Help out!

Answer the question

In order to leave comments, you need to log in

1 answer(s)
M
Maxim Fedorov, 2017-10-25
@Encoderast

You need to remove the rules in the UrlManager and in the controller

public function actionView($id){
        ...
        $product = Product::findOne($id);
        ...
}

replaced by
public function actionView($slug){
        ...
        $product = Product::findOne(['slug'=>$slug]);
        ...
}

if there is such a field

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question