1

I'm working on my first Craft 3 plugin and want to add some buttons to my plugin's control panel section which post form data to a controller.

My plugin is called 'myplugin', the controller I wish to post to is called 'products' and the method in that controller is 'get-products'. I figured I should therefore create the URL on the forms as

{{ actionUrl('products/get-products') }}

However this yields a 404 error

HTTP 404 – Not Found – yii\web\NotFoundHttpException
Page not found.
↵
Caused by: Invalid Route – yii\base\InvalidRouteException
Unable to resolve the request "https:/local.mydomain.co.uk/index.php?p=admin/actions/products/get-products".
in /Users/pete/projects/myclient/dev/build/vendor/yiisoft/yii2/base/Module.php at line 537

If I call the URL directly by using https://local.mydomain.co.uk/admin/actions/myplugin/products/get-products then it behaves as expected.

Obviously I'm missing some really important bit of knowledge here and would love if someone could help me understand what's going on.

2

I think you should use {{ actionUrl('myplugin/products/get-products') }}.

But in a form, it's maybe even better/easier to use:

<input type="hidden" name="action" value="myplugin/products/get-products" />
  • Unfortunately neither of those worked initially. When performing that request from the front-end it works OK. But I have worked out what is wrong and can get it working using the latter suggestion. – foamcow Dec 4 '18 at 12:49
2

The problem was two-fold and partly related to my plugin requiring POST data.

If I set the URL to myplugin/products/get-products then it hits the correct controller.

I then set the form method to post and added the necessary {{ csrfInput() }} tag to generate the CSRF fields in the form.

Using {{ actionUrl() }} still doesn't work but I figured that's because it creates a GET request.

  • ActionUrl() does not create a get request. It creates a URL. If you'd use that and set the form's method to POST, it would work. – Paul Dec 4 '18 at 12:58
  • I used the incorrect terminology. It creates a url with querystring parameters such as index.php?p=admin/actions/myplugin/products/get-products. Adding a method parameter of POST to the form didn't seem to make a difference to that generated URL. – foamcow Dec 4 '18 at 18:39

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.