1

For the new shipment method, I created a toggle button yes/no to enable/disable module function. But the issue is while selecting yes or no module unable to work in that button function. please check below code and images and module code and give any clue how can I bind logic into the button. enter image description here Packt/Shipme/etc/adminhtml/system.xml

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Config:etc/system_file.xsd">
    <system>
        <section id="carriers"><group id="shipme" translate="label" type="text" sortOrder="50"
                                      showInDefault="1" showInWebsite="1" showInStore="1">
            <label>Shipme</label>
            <field id="status" type="checkbox" translate="label" sortOrder="10" showInDefault="1" showInWebsite="1" showInStore="0">

              <frontend_model>Packt\Shipme\Block\Adminhtml\System\Config\Advanced</frontend_model>
              <attribute type="shared">1</attribute>
            </field>
            <field id="name" translate="label" type="text" sortOrder="20"
                   showInDefault="1" showInWebsite="1" showInStore="1">
                <label>Method Name</label>
            </field>
            <field id="title" translate="label" type="text" sortOrder="20"
                   showInDefault="1" showInWebsite="1" showInStore="1">
                <label>Method Title</label>
            </field>
            <field id="express_enabled" translate="label" type="select"
                   sortOrder="30" showInDefault="1" showInWebsite="1" showInStore="0"><label>Enable express</label>
                <source_model>Magento\Config\Model\Config\Source\Yesno</source_model>
            </field>
            <field id="express_title" translate="label" type="text"
                   sortOrder="40" showInDefault="1" showInWebsite="1" showInStore="1">
                <label>Title express</label>
            </field>
            <field id="express_price" translate="label" type="text"
                   sortOrder="50" showInDefault="1" showInWebsite="1" showInStore="1">
                <label>Price express</label>
            </field>
            <field id="business_enabled" translate="label" type="select"
                   sortOrder="60" showInDefault="1" showInWebsite="1" showInStore="0">
                <label>Enable business</label>
                <source_model>Magento\Config\Model\Config\Source\Yesno</source_model>
            </field>
            <field id="business_title" translate="label" type="text"
                   sortOrder="70" showInDefault="1" showInWebsite="1" showInStore="1">
                <label>Title business</label>
            </field>
            <field id="business_price" translate="label" type="text"
                   sortOrder="80" showInDefault="1" showInWebsite="1" showInStore="1">
                <label>Price business</label>
            </field>
            <field id="specificerrmsg" translate="label" type="textarea"
                   sortOrder="90" showInDefault="1" showInWebsite="1" showInStore="1">
                <label>Displayed Error Message</label>
            </field>
            <field id="sallowspecific" translate="label" type="select"
                sortOrder="100" showInDefault="1" showInWebsite="1" showInStore="0">
                <label>Ship to Applicable Countries</label>
                <frontend_class>shipping-applicable-country</frontend_class>
                <source_model>Magento\Shipping\Model\Config\Source\Allspecificcountries</source_model>
            </field>
            <field id="specificcountry" translate="label" type="multiselect"
                sortOrder="110" showInDefault="1" showInWebsite="1" showInStore="0">
                    <label>Ship to Specific Countries</label>
                <source_model>Magento\Directory\Model\Config\Source\Country</source_model>
                <can_be_empty>1</can_be_empty>
            </field>
        </group>
        </section>
    </system>
</config>

/Packt/Shipme/etc/config.xml

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Store:etc/con
fig.xsd">
    <default>
        <carriers>
            <shipme>
                <model>Packt\Shipme\Model\Carrier\Shipme</model>
                <active>1</active>
                <name>Shipme Shipping</name>
                <title>Shipme Shipping</title>
                <express_enabled>1</express_enabled>
                <express_title>Express delivery</express_title>
                <express_price>4</express_price><business_enabled>1</business_enabled>
                <business_title>Business delivery</business_title>
                <business_price>5</business_price>
                <specificerrmsg>This shipping method is currently unavailable.
                    If you would like to ship using this shipping method, please contact
                    us.</specificerrmsg>
            </shipme>
        </carriers>
    </default>
</config>

/Shipme/Model/Carrier/Shipme.php

<?php
namespace Packt\Shipme\Model\Carrier;
use Magento\Shipping\Model\Rate\Result;
class Shipme extends \Magento\Shipping\Model\Carrier\AbstractCarrier implements
    \Magento\Shipping\Model\Carrier\CarrierInterface {
    protected $_code = 'shipme';
    /**
     * @var \Magento\Shipping\Model\Rate\ResultFactory
     */
    protected $_rateResultFactory;
    /**
     * @var \Magento\Quote\Model\Quote\Address\RateResult\MethodFactory
     */
    protected $_rateMethodFactory;
    public function __construct(
        \Magento\Framework\App\Config\ScopeConfigInterface $scopeConfig,
        \Magento\Quote\Model\Quote\Address\RateResult\ErrorFactory
        $rateErrorFactory,
        \Psr\Log\LoggerInterface $logger,
        \Magento\Shipping\Model\Rate\ResultFactory $rateResultFactory,
        \Magento\Quote\Model\Quote\Address\RateResult\MethodFactory
        $rateMethodFactory,
        array $data = []
    ) {
        $this->_rateResultFactory = $rateResultFactory;
        $this->_rateMethodFactory = $rateMethodFactory;
        parent::__construct($scopeConfig, $rateErrorFactory, $logger,
            $data);
    }
    public function
    collectRates(\Magento\Quote\Model\Quote\Address\RateRequest $request) {
        if (!$this->getConfigFlag('active')) {
            return false;
        }
        $result = $this->_rateResultFactory->create();
//Check if express method is enabled
        if ($this->getConfigData('express_enabled')) {
            $method = $this->_rateMethodFactory->create();
            $method->setCarrier($this->_code);$method->setCarrierTitle($this->getConfigData('name'));
            $method->setMethod('express');
            $method->setMethodTitle($this->getConfigData('express_title'));
            $method->setPrice($this->getConfigData('express_price'));
            $method->setCost($this->getConfigData('express_price'));
            $result->append($method);
        }
//Check if business method is enabled
        if ($this->getConfigData('business_enabled')) {
            $method = $this->_rateMethodFactory->create();
            $method->setCarrier($this->_code);
            $method->setCarrierTitle($this->getConfigData('name'));
            $method->setMethod('business');
            $method->setMethodTitle($this->getConfigData('business_title'));
            $method->setPrice($this->getConfigData('business_price'));
            $method->setCost($this->getConfigData('business_price'));
            $result->append($method);
        }
        return $result;
        }
         public function getAllowedMethods() {
            return ['shipme' => $this->getConfigData('name')];
        }
            public function isTrackingAvailable()
        {
           return true;
        }
}

Shipme/Block/Adminhtml/System/Config/Advanced.php

    <?php

    namespace Packt\Shipme\Block\Adminhtml\System\Config;

    class Advanced extends \Magento\Config\Block\System\Config\Form\Field
    {
    /**
     * Template path
     *
     * @var string
     */
    protected $_template = 'system/config/advance/check.phtml';

    /**
     * Render fieldset html
     *
     * @param \Magento\Framework\Data\Form\Element\AbstractElement $element
     * @return string
     */
    public function render(\Magento\Framework\Data\Form\Element\AbstractElement $element)
    {
        $columns = $this->getRequest()->getParam('website') || $this->getRequest()->getParam('store') ? 5 : 4;
        return $this->_decorateRowHtml($element, "<td class='label'>Enable Shipme</td><td>" . $this->toHtml() . '</td><td></td>');
    }
    }

Shipme/view/adminhtml/templates/system/config/advance/check.phtml

<style>
.switch {
    position: relative;
    display: inline-block;
    width: 37px;
    height: 22px;
    vertical-align: middle;

}

.switch input {
    opacity: 0;
    width: 0;
    height: 0;
}

.slider {
    position: absolute;
    cursor: pointer;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background-color: #ccc;
    -webkit-transition: .4s;
    transition: .4s;
    vertical-align: middle;

}
.sliderOne {
    position: absolute;
    cursor: pointer;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background-color: #ccc;
    -webkit-transition: .4s;
    transition: .4s;
    vertical-align: middle;

}

.slider:before {
    position: absolute;
    content: "";
    height: 22px;
    width: 22px;
    left: -7.75px;
    bottom: 0px;
    background-color: white;
    -webkit-transition: .4s;
    transition: .4s;
    vertical-align: middle;

}
.sliderOne:before {
    position: absolute;
    content: "";
    height: 22px;
    width: 22px;
    left: .5px;
    bottom: 0px;
    background-color: white;
    -webkit-transition: .4s;
    transition: .4s;
    vertical-align: middle;

}

input:checked + .slider {
    background-color: #79a22e;
}

input:focus + .slider {
    box-shadow: 0 0 0px #2196F3;

}

input:checked + .sliderOne {
    background-color: #79a22e;
}

input:focus + .sliderOne {
    box-shadow: 0 0 0px #2196F3;

}

input:checked + .slider:before {
    -webkit-transform: translateX(22px);
    -ms-transform: translateX(22px);
    transform: translateX(22px);

}
input:checked + .sliderOne:before {
    -webkit-transform: translateX(22px);
    -ms-transform: translateX(22px);
    transform: translateX(22px);

}

/* Rounded sliders */
.slider.round {
    border-radius: 35px;

}

.slider.round:before {
    border-radius: 100%;
    display: inline-block;

}

.sliderOne.round {
    border-radius: 35px;

}

.sliderOne.round:before {
    border-radius: 100%;
    display: inline-block;

}

</style>
<script>
function myFunction() {

    if(document.getElementById('spa').classList.contains("slider")) {
        document.getElementsByClassName("slider")[0].setAttribute("class","sliderOne round");
        document.getElementById('toggle').innerHTML = "  &nbsp; No";
    }else{
        document.getElementsByClassName("sliderOne")[1].setAttribute("class","slider round");
        document.getElementById('toggle').innerHTML = "  &nbsp; Yes";
    }
}
</script>
<label class="switch">
    <input type="checkbox" onclick="myFunction()" checked>
    <span class="slider round" id="spa"></span>
</label>
<span id="toggle"></span>
  • i think you miss getConfigData() function – Rk Rathod Nov 23 '19 at 11:44
  • in shipme.php have already if (!$this->getConfigFlag('active')) { return false; }. – irshad Nov 23 '19 at 11:57
  • @irshad, Let me know if you need any help here then – Kishan Savaliya Nov 25 '19 at 5:28
3

Replace your below files with these content

Shipme/Block/Adminhtml/System/Config/Advanced.php

<?php

namespace Packt\Shipme\Block\Adminhtml\System\Config;

class Advanced extends \Magento\Config\Block\System\Config\Form\Field
{
    protected $_template = 'system/config/advance/check.phtml';

    protected $_configPath = 'carriers/shipme/status'; //replace your config path here

    protected $_groupName = 'shipme'; // replace this with your group name

    protected $_fieldName = 'status'; // replace this with your field name

    public function render(\Magento\Framework\Data\Form\Element\AbstractElement $element)
    {
        return $this->_decorateRowHtml($element, "<td class='label'>Enable </td><td>" . $this->toHtml() . '</td><td></td>');
    }

    public function getConfigPath(){
        return $this->_configPath;
    }

    public function getGroupName(){
        return $this->_groupName;
    }

    public function getFieldName(){
        return $this->_fieldName;
    }
}

Shipme/view/adminhtml/templates/system/config/advance/check.phtml

<?php $configPath = $this->getConfigPath(); ?>
<?php $groupName = $this->getGroupName(); ?>
<?php $fieldName = $this->getFieldName(); ?>
<?php $inputFieldName = "groups[".$groupName."][fields][".$fieldName."][value]"; ?>
<?php $isEnabled = $this->helper('Vendor\Shipme\Helper\Data')->getConfig($configPath); ?>

<label class="switch">
    <input type="checkbox" class="enable-disable-checkbox" name="<?php echo $inputFieldName; ?>" value="<?php echo $isEnabled; ?>">
    <span class="slider round" id="enable-disable-config"></span>
</label>
<span id="toggle">
    <span class="toggle-yes"><?php echo "&nbsp;&nbsp;  Yes"; ?></span>
    <span class="toggle-no"><?php echo "&nbsp;&nbsp;  No"; ?></span>
</span>

<style>
    .switch {
        position: relative;
        display: inline-block;
        width: 37px;
        height: 22px;
        vertical-align: middle;
    }

    .switch input {
        opacity: 0;
        width: 0;
        height: 0;
    }

    .slider {
        position: absolute;
        cursor: pointer;
        top: 0;
        left: 0;
        right: 0;
        bottom: 0;
        background-color: #ccc;
        -webkit-transition: .4s;
        transition: .4s;
        vertical-align: middle;
    }
    .sliderOne {
        position: absolute;
        cursor: pointer;
        top: 0;
        left: 0;
        right: 0;
        bottom: 0;
        background-color: #ccc;
        -webkit-transition: .4s;
        transition: .4s;
        vertical-align: middle;
    }

    .slider:before {
        position: absolute;
        content: "";
        height: 22px;
        width: 22px;
        left: -7.75px;
        bottom: 0px;
        background-color: white;
        -webkit-transition: .4s;
        transition: .4s;
        vertical-align: middle;
    }
    .sliderOne:before {
        position: absolute;
        content: "";
        height: 22px;
        width: 22px;
        left: .5px;
        bottom: 0px;
        background-color: white;
        -webkit-transition: .4s;
        transition: .4s;
        vertical-align: middle;
    }

    input.checked-checkbox + .slider {
        background-color: #79a22e;
    }

    input:focus + .slider {
        box-shadow: 0 0 0px #2196F3;

    }

    input.checked-checkbox + .sliderOne {
        background-color: #79a22e;
    }

    input:focus + .sliderOne {
        box-shadow: 0 0 0px #2196F3;

    }

    input.checked-checkbox + .slider:before {
        -webkit-transform: translateX(22px);
        -ms-transform: translateX(22px);
        transform: translateX(22px);

    }
    input.checked-checkbox + .sliderOne:before {
        -webkit-transform: translateX(22px);
        -ms-transform: translateX(22px);
        transform: translateX(22px);

    }

    /* Rounded sliders */
    .slider.round {
        border-radius: 35px;
    }

    .slider.round:before {
        border-radius: 100%;
        display: inline-block;
    }

    .sliderOne.round {
        border-radius: 35px;
    }

    .sliderOne.round:before {
        border-radius: 100%;
        display: inline-block;
    }
</style>

<script type="text/javascript">  
(function  () {    
    require(["jquery"], function($) {
        $(document).ready(function($) {

            var isEnabled = "<?php echo $isEnabled; ?>";

            if(isEnabled != 0){
                $(".enable-disable-checkbox").addClass("checked-checkbox");
                $("#enable-disable-config").addClass('sliderOne');
                $(".toggle-yes").show();
                $(".toggle-no").hide();
            }else{
                $(".toggle-yes").hide();
                $(".toggle-no").show();
            }

            $(".enable-disable-checkbox").on("click", function(e){
                if($("#enable-disable-config").hasClass('sliderOne')){
                    $(".enable-disable-checkbox").removeClass("checked-checkbox");
                    $("#enable-disable-config").removeClass('sliderOne');
                    $(".toggle-yes").hide();
                    $(".toggle-no").show();
                    $(".enable-disable-checkbox").attr('value', 0);
                }else{
                    $(".enable-disable-checkbox").addClass("checked-checkbox");
                    $("#enable-disable-config").addClass('sliderOne');
                    $(".toggle-yes").show();
                    $(".toggle-no").hide();
                    $(".enable-disable-checkbox").attr('value', 1);
                }
            });
        }); 
    });
})();
</script>

Create one Helper file here in your module

Shipme/Helper/Data.php

Content for this file is..

<?php

namespace Vendor\Shipme\Helper;

use Magento\Framework\App\Helper\Context;
use Magento\Framework\App\Helper\AbstractHelper;

class Data extends AbstractHelper
{
    protected $_scopeConfig;

    public function __construct(
        \Magento\Framework\App\Config\ScopeConfigInterface $scopeConfig
    ) {
        $this->_scopeConfig = $scopeConfig;
    }

    public function getConfig($configPath)
    {
        return $this->_scopeConfig->getValue(
            $configPath,
            \Magento\Store\Model\ScopeInterface::SCOPE_STORE
        );
    }
}

Or you can follow this module : Download module

Hope this will help you!

| improve this answer | |
  • Kishan Savaliya@: thanks, your module working for toggle yes/no slide .. but while slide yes or no module enable/disable do not work. for frontend. – irshad Nov 23 '19 at 15:12
  • @irshad, What you mean by enable/disable ? Can you please explain me that ? – Kishan Savaliya Nov 23 '19 at 15:13
  • So I can check what is missing there ? – Kishan Savaliya Nov 23 '19 at 15:13
  • 1
    Okay then change 'active' with 'status' and check. – Kishan Savaliya Nov 25 '19 at 5:36
  • 1
    upvoted @kishan – irshad Nov 25 '19 at 6:43

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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