Overriding the contact form module gets the fatal error in Magento2.2.5?

by Amy   Last Updated April 15, 2019 10:09 AM

I have overriden the contact form module, after disabling the default contact form validation and apply my custom validation gets the following error:

Fatal error: Uncaught TypeError: Argument 1 passed to Magento\Framework\DataObject::__construct() must be of the type array, null given, called in /var/www/html/magento/app/code/Amy/Contactform/Controller/Index/Post.php on line 119 and defined in /var/www/html/magento/vendor/magento/framework/DataObject.php:38 Stack trace: #0 /var/www/html/magento/app/code/Amy/Contactform/Controller/Index/Post.php(119): Magento\Framework\DataObject->__construct(NULL) #1 /var/www/html/magento/app/code/Amy/Contactform/Controller/Index/Post.php(84): Amy\Contactform\Controller\Index\Post->sendEmail(NULL) #2 /var/www/html/magento/vendor/magento/framework/Interception/Interceptor.php(58): Amy\Contactform\Controller\Index\Post->execute() #3 /var/www/html/magento/vendor/magento/framework/Interception/Interceptor.php(138): Amy\Contactform\Controller\Index\Post\Interceptor->___callParent('execute', Array) #4 /var/www/html/magento/vendor/magento/framework/Interception/Interceptor.php(153): Amy\Contactform\Controller\Index\Post\Interceptor->Magento\Framewor in /var/www/html/magento/vendor/magento/framework/DataObject.php on line 38

Here is my code:

/var/www/html/magento/app/code/Amy/Contactform/Controller/Index/Post.php:

<?php
/**
 *
 * Copyright © Magento, Inc. All rights reserved.
 * See COPYING.txt for license details.
 */
namespace Amy\Contactform\Controller\Index;

use Magento\Contact\Model\ConfigInterface;
use Magento\Contact\Model\MailInterface;
use Magento\Framework\App\Action\Context;
use Magento\Framework\App\Request\DataPersistorInterface;
use Magento\Framework\Controller\Result\Redirect;
use Magento\Framework\Exception\LocalizedException;
use Magento\Framework\HTTP\PhpEnvironment\Request;
use Psr\Log\LoggerInterface;
use Magento\Framework\App\ObjectManager;
use Magento\Framework\DataObject;
use Magento\Newsletter\Model\SubscriberFactory;

class Post extends \Magento\Contact\Controller\Index\Post
{
    /**
     * @var DataPersistorInterface
     */
    private $dataPersistor;

    /**
     * @var Context
     */
    private $context;

    /**
     * @var MailInterface
     */
    private $mail;

    /**
     * @var LoggerInterface
     */
    private $logger;

    /**
     * @var \Magento\Newsletter\Model\SubscriberFactory
     */
    protected $subscriberFactory;


    /**
     * @param Context $context
     * @param ConfigInterface $contactsConfig
     * @param MailInterface $mail
     * @param DataPersistorInterface $dataPersistor
     * @param LoggerInterface $logger
     */
    public function __construct(
        Context $context,
        ConfigInterface $contactsConfig,
        MailInterface $mail,
        DataPersistorInterface $dataPersistor,
        SubscriberFactory $subscriberFactory,
        LoggerInterface $logger = null
    ) {
        parent::__construct($context, $contactsConfig, $mail, $dataPersistor);
        $this->context = $context;
        $this->mail = $mail;
        $this->dataPersistor = $dataPersistor;
        $this->subscriberFactory = $subscriberFactory;
        $this->logger = $logger ?: ObjectManager::getInstance()->get(LoggerInterface::class);
    }

    /**
     * Post user question
     *
     * @return Redirect
     */
    public function execute()
    {

        if (!$this->isPostRequest()) {
            return $this->resultRedirectFactory->create()->setPath('*/*/');
        }
        try {
            $this->sendEmail($this->validatedParams());

            //  subscribe to newsletter---------CODE START
            if ($this->getRequest()->getParam('is_subscribed', false)) {
                $this->subscriberFactory->create()->subscribe($this->getRequest()->getParam('email'));
            }
            //  subscribe to newsletter---------CODE END


            $this->messageManager->addSuccessMessage(
                __('Thanks for contacting us. Your inquiry was submitted and will be responded to you as soon as possible.')
            );
            $this->dataPersistor->clear('contact_us');
        } catch (LocalizedException $e) {
            $this->messageManager->addErrorMessage($e->getMessage());
            $this->dataPersistor->set('contact_us', $this->getRequest()->getParams());
        } catch (\Exception $e) {
            $this->logger->critical($e);
            $this->messageManager->addErrorMessage(
                __('An error occurred while processing your form. Please try again later.')
            );
            $this->dataPersistor->set('contact_us', $this->getRequest()->getParams());
        }
        return $this->resultRedirectFactory->create()->setPath('contact/index');
    }

    /**
     * @param array $post Post data from contact form
     * @return void
     */
    private function sendEmail($post)
    {
        $this->mail->send(
            $post['subject'],
            $post['email'],
            ['data' => new DataObject($post)]
        );
    }

    /**
     * @return bool
     */
    private function isPostRequest()
    {
        /** @var Request $request */
        $request = $this->getRequest();
        return !empty($request->getPostValue());
    }

    /**
     * @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('lastname')) === '') {
        //     throw new LocalizedException(__('LastName is missing'));
        // }
        // if (trim($request->getParam('address1')) === '') {
        //     throw new LocalizedException(__('Address1 is missing'));
        // }
        // if (trim($request->getParam('address2')) === '') {
        //     throw new LocalizedException(__('Address2 is missing'));
        // }
        // if (trim($request->getParam('city')) === '') {
        //     throw new LocalizedException(__('City is missing'));
        // }
        // if (trim($request->getParam('stateprovince')) === '') {
        //     throw new LocalizedException(__('State is missing'));
        // }
        // if (trim($request->getParam('zipcode')) === '') {
        //     throw new LocalizedException(__('Zipcode is missing'));
        // }
        // if (trim($request->getParam('subject')) === '') {
        //     throw new LocalizedException(__('Subject 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();
    }
}

/var/www/html/magento/app/code/Amy/Contactform/view/frontend/templates/form.phtml:

<?php

$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
 $states = $objectManager->create('Magento\Directory\Model\RegionFactory')
        ->create()->getCollection()->addFieldToFilter('country_id','US');
//echo "<pre>";
//print_r($states->getData());
$regionList = $block->getRegion();
//$countryList = $block->getCountry();
/**
 * Copyright © Magento, Inc. All rights reserved.
 * See COPYING.txt for license details.
 */

// @codingStandardsIgnoreFile
/** @var \Magento\Contact\Block\ContactForm $block */
?>
<div class="container">
 <div class="row margincontrol">
<!-- <form class="form contact" 22-3-19-->
<form class=""
      action="<?= $block->escapeUrl($block->getFormAction()) ?>"
      id="contact-form"
      method="post"
      data-hasrequired="<?= $block->escapeHtmlAttr(__('* Required Fields')) ?>">
    <fieldset class="fieldset">
        <div class="legend empty_class"><h2 class="header_fontst"><?= $block->escapeHtml(__('Contact Us')) ?></h2></div> 

          <div class="col-sm-12 col-md-6 col-lg-6 hightposition field name required">
            <label class="label" for="name"><span class="font_app"><?= $block->escapeHtml(__('First Name')) ?></span></label>
            <div class="control">
                <input name="name" id="name" title="<?= $block->escapeHtmlAttr(__('Name')) ?>" value="<?= $block->escapeHtmlAttr($this->helper('Magento\Contact\Helper\Data')->getPostValue('name') ?: $this->helper('Magento\Contact\Helper\Data')->getUserName()) ?>" class="input-text" type="text"/>
            </div>
        </div>

          <div class="col-sm-12 col-md-6 col-lg-6 hightposition field lastname required">
            <label class="label boxspaing" for="last_name"><span class="font_app"><?= $block->escapeHtml(__('Last Name')) ?></span></label>
            <div class="control boxspaing">
                <input name="last_name" id="last_name" title="<?= $block->escapeHtmlAttr(__('LastName')) ?>" value="<?= $block->escapeHtmlAttr($this->helper('Magento\Contact\Helper\Data')->getPostValue('lastname') ?: $this->helper('Magento\Contact\Helper\Data')->getUserName()) ?>" class="input-text" type="text"/>
            </div>
        </div>

          <div class="col-sm-12 col-md-6 col-lg-6 hightposition field email required">
            <label class="label" for="email"><span class="font_app"><?= $block->escapeHtml(__('Email')) ?></span></label>
            <div class="control">
                <input name="email" id="email" title="<?= $block->escapeHtmlAttr(__('Email')) ?>" value="<?= $block->escapeHtmlAttr($this->helper('Magento\Contact\Helper\Data')->getPostValue('email') ?: $this->helper('Magento\Contact\Helper\Data')->getUserEmail()) ?>" class="input-text" type="email"/>
            </div>
        </div>

          <div class="col-sm-12 col-md-6 col-lg-6 hightposition field telephone required">
            <label class="label boxspaing" for="telephone"><span class="font_app"><?= $block->escapeHtml(__('Telephone')) ?></span></label>
            <div class="control boxspaing">
                <input name="telephone" id="telephone" title="<?= $block->escapeHtmlAttr(__('Phone Number')) ?>" value="<?= $block->escapeHtmlAttr($this->helper('Magento\Contact\Helper\Data')->getPostValue('telephone')) ?>" class="input-text" type="text"/>
            </div>
        </div>

          <div class="col-sm-12 col-md-6 col-lg-6 hightposition field address1 required">
            <label class="label" for="address1"><span class="font_app"><?= $block->escapeHtml(__('Address1')) ?></span></label>
            <div class="control">
                <input name="address1" id="address1" title="<?= $block->escapeHtmlAttr(__('Address1')) ?>" value="<?= $block->escapeHtmlAttr($this->helper('Magento\Contact\Helper\Data')->getPostValue('address1')) ?>" class="input-text" type="text"/>
            </div>
        </div>

          <div class="col-sm-12 col-md-6 col-lg-6 hightposition field address2">
            <label class="label boxspaing" for="address2"><span class="font_app"><?= $block->escapeHtml(__('Address2')) ?></span></label>
            <div class="control boxspaing">
                <input name="address2" id="address2" title="<?= $block->escapeHtmlAttr(__('Address2')) ?>" value="<?= $block->escapeHtmlAttr($this->helper('Magento\Contact\Helper\Data')->getPostValue('address2')) ?>" class="input-text" type="text"/>
            </div>
        </div>

          <div class="col-sm-12 col-md-6 col-lg-6 hightposition field city required">
            <label class="label" for="city"><span class="font_app"><?= $block->escapeHtml(__('City')) ?></span></label>
            <div class="control">
                <input name="city" id="city" title="<?= $block->escapeHtmlAttr(__('City')) ?>" value="<?= $block->escapeHtmlAttr($this->helper('Magento\Contact\Helper\Data')->getPostValue('city')) ?>" class="input-text" type="text"/>
            </div>
        </div>

           <div class="col-sm-12 col-md-6 col-lg-6 hightposition field stateprovince required">
            <label class="label boxspaing" for="stateprovince"><span class="font_app"><?php  echo __('State / Province') ?></span></label>
            <div class="control boxspaing">
        <select  class="select_img" name="stateprovince" id ="stateprovince" class="input-text" type="text">
        <option selected value>Select One</option>
        <?php foreach ($states as $_state):?>
          <option value="<?php echo $_state->getName();?>"><?php echo $_state->getName();?></option>
          <?php endforeach;?>
        </select>
        </div>
        </div>

        <div class="col-sm-12 col-md-6 col-lg-6 hightposition field zipcode required">
            <label class="label" for="zipcode"><span class="font_app"><?= $block->escapeHtml(__('Zipcode')) ?></span></label>
            <div class="control">
                <input name="zipcode" id="zipcode" title="<?= $block->escapeHtmlAttr(__('Zipcode')) ?>" value="<?= $block->escapeHtmlAttr($this->helper('Magento\Contact\Helper\Data')->getPostValue('zipcode')) ?>" class="input-text" type="text"/>
            </div>
        </div>


          <div class="col-sm-12 col-md-6 col-lg-6 hightposition field subject required">
            <label class="label boxspaing" for="subject"><span class="font_app"><?= $block->escapeHtml(__('Subject')) ?></span></label>
            <div class="control boxspaing">
                <select name="subject" id="subject" title="<?= $block->escapeHtmlAttr(__('Subject')) ?>" value="<?= $block->escapeHtmlAttr($this->helper('Magento\Contact\Helper\Data')->getPostValue('subject')) ?>" class="input-text" type="text"/>

                <option selected value>Select One</option>
                <option value="Repair">Repair</option>
                <option value="Warranty">Warranty</option>
                <option value="General Feedback">General Feedback</option>
                </select>
            </div>
        </div>

         <div class="col-sm-12 col-md-12 col-lg-12 field comment required" style="width: 100% !important;">
            <label class="label messagees" for="comment"><span class="font_app"><?= $block->escapeHtml(__('Message')) ?></span></label>

                <textarea name="comment" id="comment" title="<?= $block->escapeHtmlAttr(__('What’s on your mind?')) ?>" class="input-text" type="text"><?= $block->escapeHtml($this->helper('Magento\Contact\Helper\Data')->getPostValue('comment')) ?></textarea>

        </div>

<!--design code start -->
             <div class="col-sm-12 col-md-12 col-lg-12" style="margin-bottom: 5px;">
                <div class="control submitt">    
                      <!--   <input type="checkbox" name="" value="on"> -->
               <label class="submit_head phone_rig">
                 <input type="checkbox" name="is_subscribed" id ="is_subscribed" checked="checked" value="on">Subscribe to receive exciting news.
                 <span class="submit_class"></span>
               </label>
              </div>

        </div>
               <div class="col-sm-12 col-md-12 col-lg-12" style="margin-bottom: 5px;">
            <div class="control submitt">    
                  <!--   <input type="checkbox" name="" value="on"> -->
           <label class="submit_head phone_rig">
             <input type="checkbox" name="retailer" value="on" id="retailer"> Yes, I would like my information sent to an authorized retailer in my area. 
             <span class="submit_class"></span>
           </label>
          </div>

        </div>
        <div class="clearfix style_bottom"></div>
    <!-- dev code --> 

        <?= $block->getChildHtml('form.additional.info') ?>

          <div class="col-sm-12 col-md-12 col-lg-12">
    <div class="actions-toolbar">
        <div class="primary">
            <input type="hidden" name="hideit" id="hideit" value="" />
            <button type="submit" title="<?= $block->escapeHtmlAttr(__('Submit')) ?>" class="action submit primary">
                <span><?= $block->escapeHtml(__('Submit')) ?></span>
            </button>
        </div>
    </div>
    </div> 

    </fieldset>

</form>
</div>
</div>
<script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.11.1/jquery.validate.min.js"></script>
<script type="text/javascript">
require([
    'jquery'
], function($){

jQuery(document).ready(function(){

jQuery("#contact-form").validate({

rules: {
      name: "required",
      last_name: "required",
      email: {
        required: true,
        email: true
      },
      telephone:{
        required:true,
        number:true
      },
      address1: "required",
      city: "required",
      stateprovince: "required",
      zipcode: "required",
      subject: "required",
      comment: "required"
  },
  messages: {
      name: "Please enter your First Name",
      last_name: "Please enter your Last Name",
      email: "Please enter a valid Email Address",
      telephone: {
      required: "Please enter your Phone Number",
      number:"Please enter numbers Only"
      },
      address1: "Please enter your Address",
      city: "Please enter your City",
      stateprovince: "Please enter your State/Province",
      zipcode: "Please enter your Zipcode",
      subject: "Please enter your Subject",
      comment: "Please enter your Message"
},
  });
});

});
</script>

/var/www/html/magento/app/code/Amy/Contactform/Model/Mail.php:

<?php
/**
 * Copyright © Magento, Inc. All rights reserved.
 * See COPYING.txt for license details.
 */
namespace Amy\Contactform\Model;

use Magento\Framework\Mail\Template\TransportBuilder;
use Magento\Framework\Translate\Inline\StateInterface;
use Magento\Store\Model\StoreManagerInterface;
use Magento\Framework\App\ObjectManager;
use Magento\Framework\App\Area;
use Magento\Contact\Model\ConfigInterface;

class Mail extends \Magento\Contact\Model\Mail implements \Magento\Contact\Model\MailInterface
{
    /**
     * @var ConfigInterface
     */
    private $contactsConfig;

    /**
     * @var TransportBuilder
     */
    private $transportBuilder;

    /**
     * @var StateInterface
     */
    private $inlineTranslation;

    /**
     * @var StoreManagerInterface
     */
    private $storeManager;

    /**
     * Initialize dependencies.
     *
     * @param ConfigInterface $contactsConfig
     * @param TransportBuilder $transportBuilder
     * @param StateInterface $inlineTranslation
     * @param StoreManagerInterface|null $storeManager
     */
    public function __construct(
        ConfigInterface $contactsConfig,
        TransportBuilder $transportBuilder,
        StateInterface $inlineTranslation,
        StoreManagerInterface $storeManager = null
    ) {
        $this->contactsConfig = $contactsConfig;
        $this->transportBuilder = $transportBuilder;
        $this->inlineTranslation = $inlineTranslation;
        $this->storeManager = $storeManager ?: ObjectManager::getInstance()->get(StoreManagerInterface::class);
    }

    /**
     * Send email from contact form
     *
     * @param string $replyTo
     * @param array $variables
     * @return void
     */
    public function send($recipient, $replyTo, array $variables)
{
    /** @see \Magento\Contact\Controller\Index\Post::validatedParams() */
    $replyToName = !empty($variables['data']['name']) ? $variables['data']['name'] : null;
    if ($recipient == 'Repair'){
        $emails = ['[email protected]'];  // add your email list
    }else if ($recipient == 'General Feedback'){
        $emails = ['[email protected]','[email protected]'];  // add your email list 
     }else{
        $emails = ['[email protected]'];
    }

    $this->inlineTranslation->suspend();
    try {
        $transport = $this->transportBuilder
            ->setTemplateIdentifier($this->contactsConfig->emailTemplate())
            ->setTemplateOptions(
                [
                    'area' => Area::AREA_FRONTEND,
                    'store' => $this->storeManager->getStore()->getId()
                ]
            )
            ->setTemplateVars($variables)
            ->setFrom($this->contactsConfig->emailSender())
            ->addTo($emails)
            ->setReplyTo($replyTo, $replyToName)
            ->getTransport();

        $transport->sendMessage();
    } finally {
        $this->inlineTranslation->resume();
    }
}
}

Any help would be appreciated.



Related Questions


Updated April 14, 2017 14:09 PM

Updated July 13, 2017 10:09 AM

Updated May 18, 2018 10:09 AM

Updated November 07, 2018 09:09 AM