How To

How to Submit Contact Us Data using GraphQL API in Magento 2

Hello Magento Friends,

In today’s blog, I will guide you on How to Submit Contact Us Data using GraphQL API in Magento 2.

In Magento 2, the GraphQL API provides a powerful way to interact with the platform programmatically. Utilizing this feature, you can easily submit contact us data, thereby enabling a seamless and efficient communication channel between your customers and your business.

Let’s find out How to Submit Contact Us Data using GraphQL API in Magento 2.

Steps to Submit Contact Us Data using GraphQL API in Magento 2:

Step 1: First, we need to create a “schema.graphqls” file inside the etc folder

app\code\Vendor\Extension\etc\

Then add the code as follows

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

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

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

Step 2: After that, create the “Contactusgraphql.php” file inside the Resolver folder.

app\code\Vendor\Extension\Model\Resolver\

Now include the below-mentioned code

<?php
namespace Vendor\Extension\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 Contactusgraphql implements ResolverInterface
{
    private $contactusDataProvider;

    public function __construct(
        \Vendor\Extension\Model\Resolver\DataProvider\Contactus $contactusDataProvider
    ) {
        $this->contactusDataProvider = $contactusDataProvider;
    }

    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;
    }
}

Step 3: After that, we need to create the “Contactus.php” file inside the extension at the following path

app\code\Vendor\Extension\Model\Resolver\DataProvider\

And add the following code snippet

<?php
namespace Vendor\Extension\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
{
    private $dataPersistor;
    private $mail;
    private $formKey;

    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 with your comments and questions. We'll respond to you very soon.";
        return $thanks_message;
    }

    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)]
        );
    }

    public function getFormKey()
    {
        return $this->formKey->getFormKey();
    }
}

Step 4: Run the upgrade command and compile command, and then pass the query like the below in the server

mutation{  
    contactusFormSubmit(input:
    {    
        fullname:"Test"
        email:"test.magecomp@gmail.com"
        telephone:"919664788894"
        message: "test-message"
    }){  success_message
  }}

Output:

Conclusion:

By following the steps outlined in this guide, you can effectively leverage the Magento 2 GraphQL API to submit contact us data. This capability enables you to streamline the communication process and provide an enhanced user experience for your customers. Leveraging the power of GraphQL in Magento 2 allows for a more efficient and seamless data submission process.

If you face any difficulty in submitting contact us data using the GraphQL API, you can connect with me through the comment section. You can also Hire Magento Developer if you find difficulty working with GraphQL API.

Happy Coding!

Click to rate this post!
[Total: 1 Average: 5]
Dhiren Vasoya

Dhiren Vasoya is a Director and Co-founder at MageComp, Passionate 🎖️ Certified Magento Developer👨‍💻. He has more than 9 years of experience in Magento Development and completed 850+ projects to solve the most important E-commerce challenges. He is fond❤️ of coding and if he is not busy developing then you can find him at the cricket ground, hitting boundaries.🏏

Recent Posts

Boost Your SEM Game: Unveiling the Top 10 Tools for Marketers in 2024

Business survival in today’s digital world has become extremely difficult. Using traditional marketing techniques is…

8 hours ago

Five Essential Payroll Compliance Tips for eCommerce Startups

Are you setting up a payroll system for your eCommerce startup? Ensuring compliance with myriad…

1 day ago

Optimizing Laravel Blade: Unlocking Advanced Fetcher Techniques

In the expansive universe of Laravel development, Blade serves as the stellar templating engine, propelling…

1 day ago

Magento 2: Add Quantity Increment and Decrement on Category Page

Hello Magento Friends, In this blog, we will discuss about adding quantity increment and decrement…

3 days ago

How to Integrate ChatGPT with Laravel Application?

In this guide, we'll explore how to integrate ChatGPT, an AI-powered chatbot, with a Laravel…

6 days ago

What are Net Sales? How to Calculate Your Net Sales?

In the world of business, understanding financial metrics is crucial for making informed decisions and…

1 week ago