How to create a Plugin in Shopware-beragampengetahuan Blog – Beragampengetahuan
2 mins read

How to create a Plugin in Shopware-beragampengetahuan Blog – Beragampengetahuan

Contents

Introduction

Hello, tech geeks today we will see how to create a plugin in Shopware. Anyone can create a plugin in Shopware in less than 30 minutes. We will create a plugin in Shopware for adding blog functionality to our storefront. Let’s get started.

Prerequisites

Before start creating your plugin it is good to have:

  • Basic understanding of tech stack used in Shopware (Twig, Symfony, VueJs, etc.)
  • PHP OOPs and other concepts such as Symfony’s dependency injection, annotations, etc., are essential.

The steps for creating a plugin are as follows:

Directory structure

The overall general directory structure of a plugin looks like this,

hirearchy_up
Plugin directory structure

Step 1: Create a base setup for the plugin in shopware

Run the following command, it will generate a base for your plugin.

./bin/console plugin:create WkBlogPlugin

After this command, you will see the following files:

  • composer.json file includes your plugin’s general information, i.e. name, description, version, label, theme, etc.
  • WkBlogPlugin.php class under the src directory. When the plugin gets installed and uninstalled, it will execute this class. You can control things like deleting a table when the plugin gets uninstalled here.
  • services.xml file under src/Resources/config directory. This file registers your controllers, services, subscribers, schedules tasks, etc., for your plugin.

Step 2: Create migration and entities for the plugin in shopware

To create migrations for generating tables use the following command,

./bin/console database:create-migration -p WkBlogPlugin

Update the update method on the created class with the following code,

#src/Migration/Migration*.php

public function update(Connection $connection): void
{
   $connection->executeUpdate('
        CREATE TABLE IF NOT EXISTS `Wk_blog` (
            `id` BINARY(16) NOT NULL,
            `media_id` BINARY(16) NOT NULL,
            `title` VARCHAR(50),
            `created_at` DATETIME(3) NOT NULL,
            `updated_at` DATETIME(3) NULL,
            PRIMARY KEY (id),
            CONSTRAINT `fk.media.id` FOREIGN KEY (`media_id`)
                REFERENCES `media` (`id`)
        ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
        ');
}

The plugin automatically executes the migrations when installed, and to start using your table in the plugin, you need to create the entity definitions for the table. To see how to do that refer to How to Add Entities in Shopware.

Step 3: Create configurations for the plugin in shopware

Create a file named config.xml under src/Resources/config/ directory and add the following code,

#src/Resources/config/config.xml

<?xml version="1.0" encoding="UTF-8"?>
<config xmlns:xsi="
        xsi:noNamespaceSchemaLocation="
    <card>
        <title>Blog Plugin Settings</title>
        <title lang="de-DE">Blog-Plugin-Einstellungen</title>

        <input-field type="bool">
            <name>isShare</name>
            <label>Add Share Button on Blogs?</label>
            <label lang="de-DE">Schaltfläche „Teilen“ in Blogs hinzufügen?</label>
            <defaultValue>false</defaultValue>
        </input-field>
    </card>
</config>

This will render our configuration settings in administration like this,

create a plugin
Plugin configurations

To see all available input fields and how to use them refer to How to add configurations to plugin.

Step 4: Create a module in the administration

Make a file main.js under the src/Resources/app/administration/src directory. This is the root file for all your modules and services. You will include every module or service you create here as shown below

#src/Resources/app/administration/src/main.js

import './module/wk-blog';

Now, create an index.js file for your module under src/Resources/app/administration/src/module/Wk-blog directory as shown and add the following code.

src/Resources/app/administration/src/module/Wk-blog/index.js

import './page/Wk-blog-list';

import enGB from './snippet/en-GB';
import deDE from './snippet/de-DE';

Shopware.Module.register('Wk-blogs', {
    type: 'plugin',
    name: 'blogs',
    title: 'Wk-blog.settings.title',
    description: 'Manage Blogs',
    color: '#ff3d58',
    icon: 'default-shopping-paper-bag-product',
    
    snippets:{
        'de-DE': deDE,
        'en-GB': enGB
    },

    routes:{
        list:{
            component: 'blog-list',
            path: 'list',
            meta: {
                parentPath: 'sw.settings.index.plugins'
            }
        }
    },

    settingsItem: [{
        group: 'plugins',
        to: 'Wk.blogs.list',
        icon: 'default-object-rocket',
        name: 'exampleBlogs'
    }]
    
});

The settingsItem property is responsible for showing your plugin in the setting/extensions menu in Shopware. The routes property is responsible for registering your components to its particular route.

plugin in shopware
Blog module link under settings/extensions section.

Make your components and import those in the main.js file then use the routes key for registering them to their respective routes. For a detailed explanation of components refer to How to add components.

Step 5: Create a controller for Storefront

For rendering the data from table to storefront we need a controller, here’s how a controller looks like in Shopware

#src/Controller/Storefront/BlogController.php

<?php

namespace WkBlogPlugin\Controller\Storefront;

use Symfony\Component\Routing\Annotation\Route;
use Shopware\Storefront\Controller\StorefrontController;
use Shopware\Core\System\SalesChannel\SalesChannelContext;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;

/**
 * @Route(defaults={"_routeScope"={"storefront"}})
 */
class BlogController extends StorefrontController{

    private EntityRepository $blogRepository;
    public function __construct(
        EntityRepository $blogRepository
    ){
        $this->blogRepository = $blogRepository;
    }

    /**
     * 
     * @Route("/blogs",name="frontend.blogs.list",methods={"GET", "POST"})
     */
    public function blogs(Request $request): Response {
        //some logic to get data for blogs
        $data = [];

        //render storefront and send data to twig file
        return $this->renderStorefront('@wkBlogPlugin/storefront/page/blogs.html.twig', [
            'data' => $data
        ]);
    }
}

The _routeScope annotation is crucial while defining the controller. If you want to use it for storefront purposes then define it by “_routeScope”={“storefront”} and for using it with administration use “_routeScope”={“api”}.

The services.xml file registers all the services, controllers, entity definitions, page loaders, schedulers, etc.,

<service id="WkBlogPlugin\Controller\Storefront\BlogController" public="true">
  <tag name="controller.service_arguments"/>
  <argument type="service" id="wk_blog.repository"/>
   <call method="setContainer">
       <argument type="service" id="service_container" />
   </call>
</service>

After adding the controller create the twig file and render the data sent from the controller to that file. For the detailed explanation refer to the how to add templates in Shopware.

Conclusion

To wrap it up, creating a Shopware plugin is a fantastic way to boost your online store’s capabilities. Leverage the community and official resources, stay creative, and enjoy your coding journey!

If you need custom Shopware Development Services then feel free to reach us and also explore our exclusive range of Shopware Plugins.

rencana pengembangan website



metode pengembangan website

jelaskan beberapa rencana untuk pengembangan website, proses pengembangan website, kekuatan dan kelemahan bisnis pengembangan website
, jasa pengembangan website, tahap pengembangan website, biaya pengembangan website

#create #Plugin #ShopwareWebkul #Blog

Tinggalkan Balasan

Alamat email Anda tidak akan dipublikasikan. Ruas yang wajib ditandai *