R
R
rommcr2014-12-24 14:54:00
Yii
rommcr, 2014-12-24 14:54:00

How to pass additional parameters to a class serving a custom route rule?

It is required to route the request to different controller actions depending on the value of the POST variable (for example, $_POST['action'])
For example, a request to /controller/ with $_POST['action'] == 'value1' should lead to controller/value1Action, and a request to /controller/ with $_POST['action'] == 'value2' to controller/value2Action.
Is it possible to do this through the urlManager's rules parameter or do I need to change the application logic? If this is done through a custom class, then I would not want to hardcode the conditions, you need to pass them as a parameter. On the Zend Framework, I solved a similar problem, does Yii2 allow it?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
R
rommcr, 2014-12-24
@rommcr

public $allowedActions = ['action1', 'action2']
- this is exactly the kind of hardcoding that I would like to avoid. In order not to list all possible values ​​of action, but to pass them as parameters. Moreover, for different controllers there may be different sets.
Updated : and the casket just opened.
private $acceptable;

    function setAcceptable($acceptable)
    {
        $this->acceptable = $acceptable;
    }

and in the router configuration:
[
                    'acceptable' => 'action1,action2',
                    'class'      => 'components\MsgidSearch'
.......
                ],

A
Alexander Sazanovich, 2014-12-24
@uniqby

Something like this, I think, but in general everything is perfectly described here www.yiiframework.com/doc-2.0/guide-runtime-routing...

namespace app\components;

use yii\web\UrlRuleInterface;
use yii\base\Object;

class MyUrlRule extends Object implements UrlRuleInterface
{
    public $allowedActions = ['action1', 'action2'];

    public function parseRequest($manager, $request)
    {
        if (null !== ($action = Yii::$app->getRequest()->post('action') && in_array($action, $this->allowedActions)
        {
            return ['controller/'.$action]
        }

        return false;  // this rule does not apply
    }
}

[
    'components' => [
        'urlManager' => [
            'enablePrettyUrl' => true,
            'showScriptName' => false,
            'enableStrictParsing' => true,
            'suffix' => '.html',
            'rules' => [
                // ...
                [
                    'class' => 'app\components\MyUrlRule', 
                    // ...configure other properties...
                ],
            ],
        ],
    ],
]

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question