1

Im trying to build a simple view with extra options(parameters). When I use the /product/ and /product/index the view will show, but I want to add paramaters to select a post per id.

As im working inside a already build yii2 project maybe the settings are not correct or need to be set, i dont know but when I do use a parameter it will show me a page not found error(inside the layout).

www.example.com/products/ // view works
www.example.com/products/index/ // view works
www.example.com/products/id/extraparam //view not working (how I want it to be)

controller

public $defaultAction = 'index';

public function actionIndex( $id , $par)
{

    $proid = $id; // we want to use this if present
    $extra = $par; // we want to use this if present

    // as we do not need the layout 
    $this->layout = false;

    return $this->render('index');
}
1

1 Answer 1

1

You will need to edit UrlManager settings in your main config.

'urlManagerFrontend'  => [
    'class'           => 'yii\web\UrlManager',
    'baseUrl'         => 'https://somedomain/', // if you want to prepend domain name to all links
    'enablePrettyUrl' => true,
    'showScriptName'  => false,
    'rules'           => [
        '<module:[a-z-]+>/<controller:[a-z-]+>/<action:[a-z-]+>/<id:\d+>/<param:[a-z-]+>' => '<module>/<controller>/<action>',
        '<module:[a-z-]+>/<controller:[a-z-]+>/<action:[a-z-]+>'                          => '<module>/<controller>/<action>',
        '<controller:[a-z-]+>/<id:\d+>'                                                   => '<controller>/view',
        '<controller:[a-z-]+>/<action:[a-z-]+>/<id:\d+>'                                  => '<controller>/<action>',
        '<controller:[a-z-]+>/<action:[a-z-]+>/<id:\d+>/<param:[a-z-]+>'                  => '<controller>/<action>',
        '<controller:[a-z-]+>/<action:[a-z-]+>'                                           => '<controller>/<action>',
    ],
],

you will have another param bound to some rules
(in this exapmple the param must match pattern [a-z-])
to create urls you will need to specify the param:

Url::to(['product/edit', 'id' => 4, 'param' => 'sample-product']);
// this will link to:   /product/edit/4/sample-product

you can experiment with custom rules, use multiple params, and so on.

do remember that yii will always use the first rule that matches url matched

'<controller:[a-z-]+>/<id:\d+>/<param:[a-z-]>' => '<controller>/view' 
// this will match your exact case for actionView
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.