2

I have created a form in cms page and direct it submit action to a controller how to do server side validation and save data to my database app/code/Dyode/Pricebeat/view/frontend/templates/pricebeat.phtml

<div class="wk-mp-design">
<fieldset class="fieldset info wk-mp-fieldset">
    <legend class="legend">
        <span><?php echo __('Pricebeat') ?></span>
    </legend>
    <form action="<?php echo $block->getUrl('pricebeat/user/post', ['_secure' => $this->getRequest()->isSecure()]) ?>" enctype="multipart/form-data" method="post" id="quote-request" data-form="quote-request" data-mage-init='{"validation":{}}' data-hasrequired="<?php /* @escapeNotVerified */ echo __('* Required Fields') ?>">
        <div class="field required">
            <label class="label"><?php echo __('First Name') ?>:</label>
            <div class="control">
                    <input type="text" id="first_name" name="first_name" title="First Name" class="input-text" class="input-text" data-validate="{required:true}"/>
            </div>
        </div>
        <div class="field required">
            <label class="label"><?php echo __('Last Name') ?>:</label>
            <div class="control">
                    <input type="text" id="last_name" name="last_name" title="Last Name" class="input-text" class="input-text" data-validate="{required:true}"/>
            </div>
        </div>
        <div class="field required">
            <label class="label"><?php echo __('Email Address') ?>:</label>
            <div class="control">
                    <input type="email" id="email" name="email" title="Email Address" class="input-text" class="input-text" class="input-text" class="input-text" class="input-text" data-validate="{required:true, 'validate-email':true}"/>
            </div>
        </div>
        <div class="field required">
            <label class="label"><?php echo __('Phone Number') ?>:</label>
            <div class="control">
                    <input type="text" id="phonenumber" name="phonenumber" title="Phone Number" class="input-text" class="input-text" class="input-text" class="input-text" data-validate="{required:true, 'validate-number':true}"/>
            </div>
        </div>
        <div class="field required">
            <label class="label"><?php echo __('Account Number') ?>:</label>
            <div class="control">
                    <input type="text" id="account_number" name="account_number" title="Account Number" class="input-text" class="input-text" class="input-text" class="input-text" data-validate="{required:true, 'validate-number':true}"/>
            </div>
        </div>
        <div class="field required">
            <label class="label"><?php echo __('Invoice/Order Number') ?>:</label>
            <div class="control">
                    <input type="text" id="invoice_number" name="invoice_number" title="Invoice Number" class="input-text" class="input-text" class="input-text" class="input-text" data-validate="{required:true, 'validate-number':true}"/>
            </div>
        </div>
            <label class="label"><?php echo __('Product Url') ?>:</label>
            <div class="control">
            <input type="text" id="product_url" name="product_url" title="Product Url" class="input-text" class="input-text" data-validate="{required:true}"/>
            </div>
            <?php echo __("Product image") ?>
            <div class="control">
                    <input type="file" id="attachment" name="attachment"  title="Attachment" class="input-text" class="input-text" data-validate="{required:true}"/>
            </div>
        <button class="button wk-mp-btn" title="<?php echo __('Submit') ?>" type="submit" id="submit-btn">
            <span><span><?php echo __('Submit') ?></span></span>
        </button>
    </form>
</fieldset>
</div>
<script type="text/x-magento-init">
{
    "#quote-request": {
        "validation": {}
    }
}

app/code/Dyode/Pricebeat/Controller/User/Post.php

<?php
 namespace Dyode\Pricebeat\Controller\User;
 use Magento\Framework\App\Action\Action;
 use Magento\Framework\App\Action\Context;
 use Magento\Framework\View\Result\PageFactory;

 class Post extends Action
  {
protected $resultPageFactory;

public function __construct(Context $context, PageFactory $pageFactory)
{
    $this->resultPageFactory = $pageFactory;
    parent::__construct($context);
}

public function execute()
{
   echo "hello from the controller";
   exit();

}
}

I have created a db using instal script app/code/Dyode/Pricebeat/Setup/InstallSchema.php

 <?php
   namespace Dyode\Pricebeat\Setup;
    class InstallSchema implements \Magento\Framework\Setup\InstallSchemaInterface
     {
       /**
         * install tables
         * @param \Magento\Framework\Setup\SchemaSetupInterface $setup
         * @param \Magento\Framework\Setup\ModuleContextInterface $context
          * @return void
          * @SuppressWarnings(PHPMD.ExcessiveMethodLength)
          */
           public function install(\Magento\Framework\Setup\SchemaSetupInterface $setup, \Magento\Framework\Setup\ModuleContextInterface $context)
     {
    $installer = $setup;
    $installer->startSetup();
    if (!$installer->tableExists('dyode_pricebeat_form')) {
        $table = $installer->getConnection()->newTable(
            $installer->getTable('dyode_pricebeat_form')
        )
        ->addColumn(
            'form_id',
            \Magento\Framework\DB\Ddl\Table::TYPE_INTEGER,
            null,
            [
                'identity' => true,
                'nullable' => false,
                'primary'  => true,
                'unsigned' => true,
            ],
            'Form ID'
        )
        ->addColumn(
            'first_name',
            \Magento\Framework\DB\Ddl\Table::TYPE_TEXT,
            255,
            ['nullable => false'],
            'First Name'
        )
        ->addColumn(
            'last_name',
            \Magento\Framework\DB\Ddl\Table::TYPE_TEXT,
            255,
            [],
            'Last Name'
        )
        ->addColumn(
            'email',
            \Magento\Framework\DB\Ddl\Table::TYPE_TEXT,
            255,
            [],
            'Email'
            )
        ->addColumn(
            'phonenumber',
            \Magento\Framework\DB\Ddl\Table::TYPE_INTEGER,
            255,
            [],
            'Phone Number'
        )
        ->addColumn(
            'account_number',
            \Magento\Framework\DB\Ddl\Table::TYPE_INTEGER,
            255,
            [],
            'Account Number'
        )
        ->addColumn(
            'invoice_number',
            \Magento\Framework\DB\Ddl\Table::TYPE_INTEGER,
            255,
            [],
            'Invoice Number'
        )
        ->addColumn(
            'product_url',
            \Magento\Framework\DB\Ddl\Table::TYPE_INTEGER,
            1,
            ['nullable => false'],
            'Product Url'
        )
        ->addColumn(
            'product_image_url',
            \Magento\Framework\DB\Ddl\Table::TYPE_INTEGER,
            1,
            ['nullable => false'],
            'Product Image Url'
        )

        ->addColumn(
            'imagethumbnail',
            \Magento\Framework\DB\Ddl\Table::TYPE_TEXT,
            255,
            [],
            'Image Thumbnail'
        )
        ->addColumn(
            'show_in_frontend',
            \Magento\Framework\DB\Ddl\Table::TYPE_INTEGER,
            1,
            ['nullable => false'],
            'form Show in Frontend'
        )
        ->addColumn(
            'status',
            \Magento\Framework\DB\Ddl\Table::TYPE_INTEGER,
            1,
            ['nullable => false'],
            'form Status'
        )
        ->addColumn(
            'created_at',
            \Magento\Framework\DB\Ddl\Table::TYPE_TIMESTAMP,
            null,
            [],
            ' Created At'
        )
        ->addColumn(
            'updated_at',
            \Magento\Framework\DB\Ddl\Table::TYPE_TIMESTAMP,
            null,
            [],
            ' Updated At'
        )
        ->setComment('Video Table');
        $installer->getConnection()->createTable($table);

        $installer->getConnection()->addIndex(
            $installer->getTable('dyode_pricebeat_form'),
            $setup->getIdxName(
                $installer->getTable('dyode_pricebeat_form'),
                ['firstname','lastname','email','phonenumber','account_number','product_url','imagethumbnail'],
                \Magento\Framework\DB\Adapter\AdapterInterface::INDEX_TYPE_FULLTEXT
            ),
            ['firstname','lastname','email','phonenumber','account_number','product_url','imagethumbnail'],
            \Magento\Framework\DB\Adapter\AdapterInterface::INDEX_TYPE_FULLTEXT
        );
    }
    $installer->endSetup();
  }
  }
1

3 Answers 3

0

You can try the below code for validation like below:

<?php
namespace Dyode\Pricebeat\Controller\User;
use Magento\Framework\App\Action\Action;
use Magento\Framework\App\Action\Context;
use Magento\Framework\View\Result\PageFactory;
use Magento\Framework\Exception\LocalizedException;
use Magento\Framework\HTTP\PhpEnvironment\Request;

class Post extends Action
{
    protected $resultPageFactory;

    public function __construct(Context $context, PageFactory $pageFactory)
    {
        $this->resultPageFactory = $pageFactory;
        parent::__construct($context);
    }

    public function execute()
    {
        $this->validatedParams()
        echo "hello from the controller";
        exit();
    }

    private function validatedParams()
    {
        $request = $this->getRequest();
        if (trim($request->getParam('first_name')) === '') {
            throw new LocalizedException(__('First Name is missing'));
        }

        if (trim($request->getParam('last_name')) === '') {
            throw new LocalizedException(__('Last Name is missing'));
        }

        if (false === \strpos($request->getParam('email'), '@')) {
            throw new LocalizedException(__('Invalid email address'));
        }
        //Add your more validations here
        return $request->getParams();
    }
}

You need to add more validation like I added in the above example.

7
  • why we use trim in first name and last name?
    – Nismath vi
    Sep 17, 2018 at 9:36
  • Because if someone type blank space then it is use. Sep 17, 2018 at 9:38
  • how to insert the form values to the db?
    – Nismath vi
    Sep 17, 2018 at 9:40
  • This is only for validation. Sep 17, 2018 at 9:43
  • You need to create model of that table as well so that you can save those values through model. Sep 17, 2018 at 9:45
0

You just have to follow the module-contact module Post.php controller

Path : vendor/magento/module-contact/Controller/Index/Post.php

/**
     * @return array
     * @throws \Exception
     */
    private function validatedParams()
    {
        $request = $this->getRequest();
        if (trim($request->getParam('name')) === '') {
            throw new LocalizedException(__('Name is missing'));
        }
        if (trim($request->getParam('comment')) === '') {
            throw new LocalizedException(__('Comment is missing'));
        }
        if (false === \strpos($request->getParam('email'), '@')) {
            throw new LocalizedException(__('Invalid email address'));
        }
        if (trim($request->getParam('hideit')) !== '') {
            throw new \Exception();
        }

        return $request->getParams();
    }
0

You should use Email Validator class:

\Magento\Framework\Validator\EmailAddress

Usage example: \Magento\CustomerGraphQl\Model\Resolver\IsEmailAvailable

/** @var \Magento\Framework\Validator\EmailAddress $this->emailValidator */
if (!$this->emailValidator->isValid($args['email'])) {
    throw new GraphQlInputException(__('Email is invalid'));
}

Your Answer

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

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