We sacrifice by not doing any other technology, so that you get the best of Magento.

We sacrifice by not doing any other technology, so that you get the best of Magento.

    Magento 2 : How to set custom product price while displaying at front end?

    If you want to change the main price with a custom price attribute. You can use the below method

    1. Create file di.xml on app/code/Magemonkeys/CustomPrice/etc/frontend

    <?xml version="1.0"?>
    <config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
        <type name="MagentoCatalogModelProduct">
            <plugin name="change_product" type="MagemonkeysCustomPricePluginModelProduct" sortOrder="1" />
        </type>
    </config>

    2. Create file Product.php on app/code/Magemonkeys/CustomPrice/Plugin/Model

    <?php
    namespace MagemonkeysCustomPricePluginModel;
     
    class Product
    {
        public function afterGetPrice(MagentoCatalogModelProduct $subject, $result)
        {        
            $result = $subject->getCustomPrice(); // you can set custom attribute price
            return $result;
        }
    }

     

    Magento 2: Create custom GraphQL data

    We can create custom api for GraphQL.

    As per the app/code/ standard, our module name is Magemonkeys/Customgraphql

    We can create schema.graphqls file in module etc folder.

    Below is the code for that file.

    type Query
    {
        CustomGraphql (
            username: String @doc(description: "Email of the customer")
            password: String @doc(description: "Password")
            fieldtype: String @doc(description: "Field Type")
        ): CustomGraphqlOutput @resolver(class: "Magemonkeys\Customgraphql\Model\Resolver\ResolverGraphql") @doc(description:"Customgraphql Datapassing")
    }
    type CustomGraphqlOutput
    {
        username: String
        password: String
        fieldtype: String
    }

    After that we need to create Model Resolver file.

    Create file ResolverGraphql.php in this location of module
    Magemonkeys/Customgraphql/Model/Resolver/

    Below is the code for that file.

    <?php
    namespace MagemonkeysCustomgraphqlModelResolver;
    
    use MagentoFrameworkGraphQlConfigElementField;
    use MagentoFrameworkGraphQlExceptionGraphQlInputException;
    use MagentoFrameworkGraphQlQueryResolverInterface;
    use MagentoFrameworkGraphQlSchemaTypeResolveInfo;
    use MagentoFrameworkExceptionNoSuchEntityException;
    use MagentoFrameworkGraphQlExceptionGraphQlNoSuchEntityException;
    
    class ResolverGraphql implements ResolverInterface
    {
        public function resolve(
            Field $field,
            $context,
            ResolveInfo $info,
            array $value = null,
            array $args = null)
        {
            if (!isset($args['username']) || !isset($args['password']) || !isset($args['fieldtype'])||
                empty($args['username']) || empty($args['password']) || empty($args['fieldtype']))
            {
                throw new GraphQlInputException(__('Invalid arguments list please check.'));
            }
            $output = [];
            $output['username'] = $args['username'];
            $output['password'] = $args['password'];
            $output['fieldtype'] = $args['fieldtype'];
          
            return $output ;
        }
    }

    After that you can check API in Postman API tool.

    That’s it.

     

    Magento 2: Change customer group before saving the customer using plugin

    Create di.xml file your module and add the below code
    <?xml version="1.0"?>
    <config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
        <type name="MagentoCustomerApiCustomerRepositoryInterface">
            <plugin name="save_customer_group" type="VendorModulePluginMagentoCustomerApiCustomerRepositoryPlugin" />
        </type>
    </config>
    Create plugin file under this directory Vendor/Module/Plugin/Magento/Customer/Api/CustomerRepositoryPlugin.php
    <?php
    namespace VendorModulePluginMagentoCustomerApi;
    
    use MagentoCustomerApiDataCustomerInterface;
    use MagentoCustomerApiCustomerRepositoryInterface;
    use MagentoFrameworkControllerResultFactory;
    use MagentoFrameworkUrlInterface;
    use MagentoFrameworkExceptionLocalizedException;
    
    class CustomerRepositoryPlugin
    {
        /**
         * @var Data
         */
        private $helper;
    
        /**
         * Constructor of class.
         *
         * @param Data $helper
         */
        public function __construct(
            MagentoFrameworkAppRequestInterface $request,
            MagentoCustomerModelResourceModelGroupCollectionFactory $groupCollection,
            MagentoFrameworkAppConfigScopeConfigInterface $scopeConfig,
            MagentoCustomerApiGroupRepositoryInterface $groupRepository,
            MagentoFrameworkMessageManagerInterface $messageManager,
            ResultFactory $resultFactory,
            UrlInterface $url
        ) {
            $this->request = $request;
            $this->groupCollection = $groupCollection;
            $this->scopeConfig = $scopeConfig;
            $this->groupRepository = $groupRepository;
            $this->messageManager = $messageManager;
            $this->resultFactory = $resultFactory;
            $this->url = $url;
        }
    
        /**
         *
         * @param CustomerRepositoryInterface $subject
         * @param CustomerInterface $customer
         * @return array
         */
        public function beforeSave(CustomerRepositoryInterface $subject, CustomerInterface $customer, $passwordHash = null)
        {
            $groupid = 5; //change customer group id here
            $customer->setGroupId($groupId);
            return [$customer, $passwordHash];
        }
    }
    

     

    Magento 2: Get customer data in GraphQL

    By using GraphQL, You can get data of logged in customers.

    Magento 2 can directly call api to get data by resolver.

    Module name : Magemonkeys::Custom

    create file schema.graphqls in etc folder in that module

    type Query
    {
        getCustomerData: Response 
        @resolver(class:"Magemonkeys\Custom\Model\Resolver\Getdataforcustomer")
    }
    
    type Response
    {
        customer_id: String
        customer_name: String
    }

    Create Getdataforcustomer.php in Model/Resolver Folder in that module

    namespace MagemonkeysCustomModelResolver;
    
    use MagentoFrameworkGraphQlQueryResolverInterface;
    use MagentoFrameworkGraphQlConfigElementField;
    use MagentoFrameworkGraphQlSchemaTypeResolveInfo;
    use MagentoFrameworkGraphQlExceptionGraphQlNoSuchEntityException;
    use MagentoFrameworkGraphQlExceptionGraphQlAuthorizationException;
    use MagentoCustomerGraphQlModelCustomerGetCustomer;
    
    class Getdataforcustomer implements ResolverInterface
    {
       private $getdataforCustomer;
         
       public function __construct(GetCustomer $getdataforCustomer)
       {
          $this->getCustomer = $getdataforCustomer;
       }
       public function resolve(Field $field, $context, ResolveInfo $info, array $value = null, array $args = null)
       {
          try
          {
             if (false === $context->getExtensionAttributes()->getIsCustomer())
             {
                throw new GraphQlAuthorizationException(__('The current customer not getting'));
             }
             $customerdata = $this->getCustomer->execute($context);
             $customername = $customerdata->getFirstName()." ".$customerdata->getLastName();
             $result = ['customer_id' => $customer->getId(),
                        'customer_name' => $customername
                       ];   
             return $result;
          }
          catch(Exception $exception)
          {
              throw new GraphQlNoSuchEntityException(__($exception->getMessage()));
          }
       }
    }

    After that run command to call api url

    That’s it.

     

    Magento 2 : How to USPS Shipping method title change programmatically?

    If you need some specific shipping title change, then use the below method

    For Ex. Priority Mail 1-Day instead of Priority Mail (2-3 Days)

    Firstly, you need to add the following file.

    1. Create file di.xml on app/code/Magemonkeys/UspsShipping/etc

    <?xml version="1.0" ?>
    <config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
       <preference for="MagentoQuoteModelQuoteAddressRateResultMethod" type="MagemonkeysUspsShippingPluginModelQuoteAddressRateResultMethod" />
    </config>

    2. Create file Method.php on app/code/Magemonkeys/UspsShipping/Plugin/Model/Quote/Address/RateResult

    <?php
    namespace MagemonkeysUspsShippingPluginModelQuoteAddressRateResult;
    
    class Method extends MagentoQuoteModelQuoteAddressRateResultMethod
    {
        public function setPrice($price)
        {
            if (strpos($this->getMethodTitle(), "Priority Mail 1-Day") !== false) {
                $this->setMethodTitle("Priority Mail (2-3 Days)");
            }
            $this->setData('price', $this->priceCurrency->round($price));
            return $this;
        }
    
    } ?>

    Difference between filterable (with result) and Filterable (with no result) in Magento 2 Attributes

    Layered navigation Filterable (with results):

    – This attribute will be shown only if there are products matching any of its attributes-options value.
    – filter is shown on the category page Layered Navigation. However only options values, where products are available will be listed for the filter.
    – In this case, products list filtration works if selected filters change from currently shown options.

    Layered navigation Filterable (no results):

    – In this case, All attribute options will be shown even if there won’t be any products matching or associated with them.
    – filter is shown on the category page Layered Navigation. if the filter is set to ‘no results’, it will list all options, even no products are associated with specific options.
    – If any attribute options not Associated with any products then its show Zero counts. Ex: Color Attribute with options Red (0).

    For more understanding, you can check these options from admin and check the difference in the front end to get a better idea.

    Thanks!

    Pagination is not working after upgrading to Magento Version 2.4.3

    If you face pagination not working issue after upgrading Magento 2.4.3 then follow below few steps.

    Step 1 : Open your theme’s list.phtml file like app/design/frontend/Magemonkeys/CustomTheme/Magento_Catalog/templates/product/list.phtml

    Step 2 : Find below code in the bottom section of the list.phtml file

    <?= $block->getToolbarHtml() ?>

    Step 3 : Replace above code with below code in the bottom section of the list.phtml file

    <?= $block->getChildBlock('toolbar')->setIsBottom(true)->toHtml() ?>

    Step 4 : After place above code, please run below mentioned commands

    php bin/magento setup:upgrade
    php bin/magento setup:static-content:deploy
    php bin/magento cache:clean

    That’s it.

    Now when you will refresh the category page, you will find pagination on working condition.

    Magento 2: Display the custom uploaded image in admin grid

    To display the custom uploaded image in admin grid, follow the below steps.

    1) Create or override the listing.xml file and add the below code

    <column name="custom_image" component="Magento_Ui/js/grid/columns/thumbnail" class="VendorModuleUiComponentListingColumnThumbnail">
        <settings>
            <filter>text</filter>
            <label translate="true">Custom Image</label>
            <hasPreview>1</hasPreview>
            <sortable>false</sortable>
        </settings>
    </column>
    under the Vendor/Module/view/adminhtml/ui_component

    2) Create Thumbnail.php and add the below code

    <?php
    namespace VendorModuleUiComponentListingColumn;
    
    use MagentoFrameworkUrlInterface;
    use MagentoFrameworkViewElementUiComponentContextInterface;
    use MagentoFrameworkViewElementUiComponentFactory;
    use MagentoStoreModelStoreManagerInterface;
    use MagentoUiComponentListingColumnsColumn;
    
    class Thumbnail extends Column
    {
        const NAME = 'thumbnail';
    
        const URL_PATH_EDIT = 'moudle/controller/edit';
    
        /**
         * @var StoreManagerInterface
         */
        protected $storeManager;
        /**
         * @var UrlInterface
         */
        protected $url;
     
        /**
         * Image constructor.
         * @param ContextInterface $context
         * @param UiComponentFactory $uiComponentFactory
         * @param StoreManagerInterface $storeManager
         * @param UrlInterface $url
         * @param array $components
         * @param array $data
         */
        public function __construct(
            ContextInterface $context,
            UiComponentFactory $uiComponentFactory,
            StoreManagerInterface $storeManager,
            UrlInterface $url,
            array $components = [],
            array $data = [],
            MagentoThemeBlockHtmlHeaderLogo $logo
        ) {
            parent::__construct($context, $uiComponentFactory, $components, $data);
            $this->storeManager = $storeManager;
            $this->url = $url;
            $this->_logo = $logo;
        }
    
        /**
         * Prepare Data Source
         *
         * @param array $dataSource
         * @return array
         */
        public function prepareDataSource(array $dataSource)
        {
            $mediaUrl = $this->storeManager->getStore()->getBaseUrl(UrlInterface::URL_TYPE_MEDIA);
             if (isset($dataSource['data']['items'])) {
                $fieldName = 'custom_image';
                foreach ($dataSource['data']['items'] as & $item) {
                    if (!empty($item['custom_image'])) {
                        $name = $item['custom_image'];
                        $item[$fieldName . '_src'] = $mediaUrl.'custom/image'.$name;
                        $item[$fieldName . '_alt'] = '';
                        $item[$fieldName . '_link'] = $this->url->getUrl(static::URL_PATH_EDIT, [
                            'id' => $item['id']
                        ]);
                        $item[$fieldName . '_orig_src'] = $mediaUrl.'custom/image'.$name;
                    }
                }
            }
            return $dataSource;
        }
    }

    under the Vendor/Module/Ui/Component/Listing/Column