0

In Magento2, I create a form by phtml file in admin, but when I submit it, it always redirect to admin homepage, not reach another admin controller, how to fix it?

I guess the problem is in the action url, but I don't have a idea to fix it.

form codes

<form action="<?php echo $block->getUrl('migration/index/post') ?>" method="post" style="text-align: center;">
    <label for="sku">Sku: </label>
    <input type="text" name="sku" id="sku" size="40">
    <input type="submit" value="Submit">
</form>
  • can u share your controller & etc\adminhtml\routes.xml file code in question? – Abdul Jan 11 '18 at 12:06
  • 2
    Add form_key field in your form.phtml file: code is: <input name="form_key" type="hidden" value="<?php /* @escapeNotVerified */ echo $block->getFormKey() ?>" / – Abdul Jan 11 '18 at 12:10
  • @Abdul Thanks, you are right, I forget form_key, but your codes don't work, I will add the working codes in the answer :) – Key Shang Jan 12 '18 at 2:19
0

Abdul's comment is right, I forget the form_key, but simply use $block->getFormKey() will not generate the form_key in phtml file. We need create the method in our block.

What is form_key

Form keys in Magento are a means of preventing against Cross Site Request Forgery, it instructs Magento to output and store a unique form key for a user session. All CSRF-protected Magento controller actions will verify against this before doing anything of value.

Create the getFormKey() in our block

<?php
namespace Vendor\Module\Block\Adminhtml\Index;

use Magento\Framework\Data\Form\FormKey;
use Magento\Framework\View\Element\Template;

class Form extends Template
{
    protected $_backendUrl;

    protected $formKey;

    /**
     * Form constructor.
     * @param Template\Context $context
     * @param array $data
     * @param FormKey $formKey
     */
    public function __construct(
        Template\Context $context,
        array $data = [],
        FormKey $formKey
    )
    {
        $this->formKey = $formKey;
        parent::__construct($context, $data);
    }

    /**
     * @return string
     */
    public function getFormKey()
    {
        return $this->formKey->getFormKey();
    }
}

Form Codes

<form action="<?php echo $block->getUrl('migration/index/post') ?>" method="post" style="text-align: center;">
    <input name="form_key" type="hidden" value="<?php echo $block->getFormKey() ?>">
    <label for="sku">Sku: </label>
    <input type="text" name="sku" id="sku" size="40">
    <input type="submit" value="Submit">
</form>

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.