1

How to create custom graphql mutation in custom module in magento 2. And how to save custom form data in custom table using mutation.

THANKS.

1 Answer 1

4

I have create GraphQl mutation for contact us. Please follow below steps.

Step 1 :- You Create registration.php file

<?php
/**
 * @author Mohit Patel
 * @copyright Copyright (c) 2021
 * @package Mag_ContactUs
 */

\Magento\Framework\Component\ComponentRegistrar::register(
    \Magento\Framework\Component\ComponentRegistrar::MODULE,
    'Mag_ContactUs',
    __DIR__
);

Step 2 :- create etc/module.xml file

<?xml version="1.0"?>
<!--
/**
 * @author Mohit Patel
 * @copyright Copyright (c) 2021
 * @package Mag_ContactUs
 */
-->

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:noNamespaceSchemaLocation="urn:magento:framework:Module/etc/module.xsd">
    <module name="Mag_ContactUs" setup_version="2.0.0">
        <sequence>
            <module name="Magento_Backend"/>
            <module name="Magento_GraphQl"/>
        </sequence>
    </module>
</config>

Step 3 :- GraphQL queries are declared under etc/schema.graphqls

type Mutation {
    contactusFormSubmit(input: ContactusInput!): ContactusOutput @resolver(class: "\\Mag\\Mohit\\Model\\Resolver\\Contactus") @doc(description:"Contact us form")
}

input ContactusInput {
    fullname: String @doc(description: "The customer's full name")
    email: String @doc(description: "The customer's email address")
    telephone: String @doc(description: "The Telephone")
    message: String @doc(description: "The customer's message")
}

type ContactusOutput {
   success_message: String @doc(description: "Success Message")
}

Explaintion of graphqls :-

  • type Mutation > declares Mutation operations of our module.
  • contactusFormSubmit > name of our Mutation.
  • ContactusInput > it is input value and type.
  • ContactusOutput > declares output message.

Setp 4 :- Create Resolver Class Model/Resolver/Contactus.php

<?php
/**
 * @author Mohit Patel
 * @copyright Copyright (c) 2021
 * @package Mag_ContactUs
 */

namespace Mag\ContactUs\Model\Resolver;

use Magento\Framework\Exception\NoSuchEntityException;
use Magento\Framework\GraphQl\Config\Element\Field;
use Magento\Framework\GraphQl\Exception\GraphQlInputException;
use Magento\Framework\GraphQl\Exception\GraphQlNoSuchEntityException;
use Magento\Framework\GraphQl\Query\ResolverInterface;
use Magento\Framework\GraphQl\Schema\Type\ResolveInfo;


class Contactus implements ResolverInterface
{
    private $contactusDataProvider;

    /**
     * @param
     */
    public function __construct(
        \Mag\ContactUs\Model\Resolver\DataProvider\Contactus $contactusDataProvider
    ) {
        $this->contactusDataProvider = $contactusDataProvider;
    }

    /**
     * @inheritdoc
     */
    public function resolve(
        Field $field,
        $context,
        ResolveInfo $info,
        array $value = null,
        array $args = null
    ) {
        $fullname = $args['input']['fullname'];
        $email = $args['input']['email'];
        $telephone = $args['input']['telephone'];
        $message = $args['input']['message'];

        $success_message = $this->contactusDataProvider->contactUs(
            $fullname,
            $email,
            $telephone,
            $message
        );
        return $success_message;
    }
}

Setp 5 :- Create Data Provider Class in Model/Resolver/DataProvider/Contactus.php

<?php
/**
 * @author Mohit Patel
 * @copyright Copyright (c) 2021
 * @package Mag_ContactUs
 */

namespace Mag\ContactUs\Model\Resolver\DataProvider;

use Magento\Framework\App\Action\HttpPostActionInterface as HttpPostActionInterface;
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\App\ObjectManager;
use Magento\Framework\DataObject;

class Contactus
{
   /**
   * @var DataPersistorInterface
   */    
   private $dataPersistor;
   /**
   * @var MailInterface
   */
   private $mail;

   private $formKey;
   /**
   * @param
   */
    public function __construct(
        ConfigInterface $contactsConfig,
        MailInterface $mail,
        DataPersistorInterface $dataPersistor,
        \Magento\Framework\Data\Form\FormKey $formKey
    ) {
        $this->mail = $mail;
        $this->dataPersistor = $dataPersistor;
        $this->formKey = $formKey;
    }

    public function contactUs($fullname,$email,$subject,$message){
        $thanks_message = [];
        try {
            $this->sendEmail($fullname,$email,$subject,$message);
        }catch (LocalizedException $e) { }
        $thanks_message['success_message']="Thanks For Contacting Us";
        return $thanks_message;
    }
   /**
   * @param array $post Post data from contact form
   * @return void
   */
   private function sendEmail($fullname,$email,$telephone,$message)
    {
        $form_data = [];
        $form_data['name']      =   $fullname;
        $form_data['email']     =   $email;
        $form_data['telephone'] =   $telephone;
        $form_data['comment']   =   $message;
        $form_data['hideit']    =   "";
        $form_data['form_key']  =   $this->getFormKey();

        $this->mail->send(
            $email,
            ['data' => new DataObject($form_data)]
        );
    }
  /**
  * get form key
  *
  * @return string
  */
  public function getFormKey()
    {
        return $this->formKey->getFormKey();
    }
}

Setp 6 :- Final step you check output. Run this query

mutation {
    contactusFormSubmit(
        input:{
            fullname: "Mohit Patel"
            email: "[email protected]"
            telephone: "+123456798"
            message: "Hi i am testing Graphqls Mutation"       
        }
    ){
        success_message
    }
}

Output

enter image description here

Second Module I have make save data in my custom table. Please check below codes.In my custom table want to save product details and form data.

Step 1 and Step 2 :- Your create registration.php and module.xml. Both file code i have defind above.

Step 3 :- GraphQL queries are declared under etc/schema.graphqls

type Mutation {
    customFormSubmit(input: CustomFormInput!): CustomFormOutput @resolver(class: "\\Mag\\CustomForm\\Model\\Resolver\\CustomFormInput") @doc(description:"Notify your interest")
}

input CustomFormInput {
    product_id: Int @doc(description: "The Product Id")
    product_name: String @doc(description: "The Product Name")
    product_sku: String @doc(description: "The Product Sku")
    email: String @doc(description: "The customer's email address")
    mobile: String @doc(description: "The Mobile")
}

type CustomFormOutput {
   success: Boolean,
   message: String
}

Setp 4 :- Create Resolver Class Model/Resolver/CustomFormInput.php

<?php
/**
 * @author Mohit Patel
 * @copyright Copyright (c) 2021
 * @package Mag_CustomForm
 */

namespace Mag\CustomForm\Model\Resolver;

use Magento\Framework\Exception\NoSuchEntityException;
use Magento\Framework\GraphQl\Config\Element\Field;
use Magento\Framework\GraphQl\Exception\GraphQlInputException;
use Magento\Framework\GraphQl\Exception\GraphQlNoSuchEntityException;
use Magento\Framework\GraphQl\Query\ResolverInterface;
use Magento\Framework\GraphQl\Schema\Type\ResolveInfo;
use Mag\CustomForm\Model\CustomFormCheck;

class CustomForm implements ResolverInterface
{
    /**
     * @var CustomFormCheck
     */
    private $customFormCheck;

    /**
     * @param CustomFormCheck $customFormCheck
     */
    public function __construct(
        CustomFormCheck $customFormCheck
    ) {
        $this->customFormCheck = $customFormCheck;
    }

    /**
     * @inheritdoc
     */
    public function resolve(Field $field, $context, ResolveInfo $info, array $value = null, array $args = null)
    {
        if (empty($args['input']) || !is_array($args['input'])) {
            throw new GraphQlInputException(__('"input" value should be specified'));
        }

        return $this->customFormCheck->execute($args['input']);
    }
}

Explaintion :- In this file i have check data exits or not and return custom Form sucess and error message.

Setp 5 :- Create Data Provider Class in Model/CustomFormCheck.php

<?php
/**
 * @author Mohit Patel
 * @copyright Copyright (c) 2021
 * @package Mag_CustomForm
 */

namespace Mag\CustomForm\Model;

use Magento\Framework\Api\DataObjectHelper;
use Magento\Framework\Exception\CouldNotSaveException;
use Magento\Framework\Exception\LocalizedException;
use Magento\Framework\GraphQl\Exception\GraphQlInputException;
use Mag\CustomForm\Helper\Data;

class CustomFormCheck
{
    /**
     * @var Data
     */
    protected $helper;

    /**
     * @param Data $helper
     */
    public function __construct(
        Data $helper
    ) {
        $this->helper = $helper;
    }

    /**
     * @param array $data
     * @throws GraphQlInputException
     */
    public function execute($data)
    {
        try {
            $this->vaildateData($data);
            $response = $this->helper->executeData($data);
            
        } catch (LocalizedException $e) {
            throw new GraphQlInputException(__($e->getMessage()));
        }

        return $response;
    }

    /**
     * Handle bad request.
     *
     * @param $data
     * @throws LocalizedException
     */
    private function vaildateData($data)
    {
        if (!isset($data['email']) ||
            !isset($data['mobile'])
        ) {
            throw new LocalizedException(__('Must be set required data'));
        }
    }
}

Explaintion :- In this file i have call helper data file function. In helper Data.php file i have make executeData() function in this function i have save custom form data in custom table.

Setp 6 :- Final step you check output. Run this query

 mutation {
   customFormSubmit(
     input:{
        product_id: 3
        product_name: "Test Prodcut"
        product_sku: "Test Prodcut"
        email: "[email protected]"
        mobile: "11121231"
     }
   ){
        success
        message
   }
 }

Output

enter image description here

And save in DB.

enter image description here

Check More Links

How to create graphql query :- https://magento.stackexchange.com/a/351567/85907

How to extend/customise existing graphql query :- https://magento.stackexchange.com/a/351571/85907

THANKS.

4
  • I am new to Magento Graphql and I am trying to create mutation and save the data to custom table. Can you please help me to understand how to save the data to the database? Also if you have any kind of documents/blog where I can refer to extend the Graphql mutation on Magento2?
    – MagentoDev
    Commented May 27, 2022 at 13:51
  • @Siv let me know which data you need save in db. let me know i can help you. Commented Jun 17, 2022 at 17:07
  • Thanks. I have got the solution and got it worked.
    – MagentoDev
    Commented Jun 18, 2022 at 4:55
  • Good.if any need help let me know thanks. Commented Jun 18, 2022 at 5:51

Your Answer

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

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