4

I'm creating a custom shipping method on Magento2. I got the admin working ok. There are 3 different services it choose from, lets say "14hrs", 24hrs and Economy.

The problems comes in the front end, checkout page. I can see my Method, but I can't figure out how to display the select for the services. I've read several shipping method module tutorials, but none talks about this.

Currently this is my CustomShipping.php:

namespace TCK\ASM\Model\Carrier;

use Magento\Quote\Model\Quote\Address\RateRequest;
use Magento\Shipping\Model\Rate\Result;
use Magento\Checkout\Model\Cart;
use TCK\ASM\Model\Source\Method;
class ASMShipping extends \Magento\Shipping\Model\Carrier\AbstractCarrier implements
    \Magento\Shipping\Model\Carrier\CarrierInterface
{
    /**
     * @var string
     */
    protected $_code = 'ASMShipping';

    /**
     * @param \Magento\Framework\App\Config\ScopeConfigInterface $scopeConfig
     * @param \Magento\Quote\Model\Quote\Address\RateResult\ErrorFactory $rateErrorFactory
     * @param \Psr\Log\LoggerInterface $logger
     * @param \Magento\Shipping\Model\Rate\ResultFactory $rateResultFactory
     * @param \Magento\Quote\Model\Quote\Address\RateResult\MethodFactory $rateMethodFactory
     * @param array $data
     */
    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,
        \Magento\Checkout\Model\Cart $cart,
        \TCK\ASM\Model\Source\MethodFactory $metodoFactory,
        array $data = []
    ) {
        $this->_rateResultFactory = $rateResultFactory;
        $this->_rateMethodFactory = $rateMethodFactory;
        $this->_metodoFactory = $metodoFactory;
        parent::__construct($scopeConfig, $rateErrorFactory, $logger, $data);
        $this->cart = $cart;
    }

    /**
     * @return array
     */
    public function getAllowedMethods()
    {
        return ['ASMShipping' => $this->getConfigData('name')];
    }

    /**
     * @param RateRequest $request
     * @return bool|Result
     */
    public function collectRates(RateRequest $request)
    {
        if (!$this->getConfigFlag('active')) {
            return false;
        }

        $err = null;
        $envio = array();
        //Mage2
         /** @var \Magento\Shipping\Model\Rate\Result $result */
        $result = $this->_rateResultFactory->create(); 
        /** @var \Magento\Quote\Model\Quote\Address\RateResult\Method $method */
        $method = $this->_rateMethodFactory->create(); 
        $method->setCarrier('ASMShipping');
        $method->setCarrierTitle($this->getConfigData('title'));
        $method->setMethod('ASMShipping');
        $method->setMethodTitle($this->getConfigData('name'));
        /*you can fetch shipping price from different sources over some APIs, we used price from config.xml - xml node price*/
        //$amount = $this->getConfigData('handling_fee');
        $amount=0;

        $envio["cpOrg"]=$request->_data['postcode'];
        $envio["codPaisOrg"] = '34';
        $envio["cpDst"] = $request->_data['dest_postcode'];
        $envio["peso"] = $request->_data['package_weight'];
        $envio["bultos"] = 1;
        $envio["precioProducto"] = $request->_data['package_value'];


        $amount=$request->_data['package_value'];
        $method->setPrice($amount);
        $method->setCost($amount);

        $result->append($method);

        $items=$this->cart->getQuote()->getAllVisibleItems();

        return $result;

    /** end func **/
    }
}

2 Answers 2

1

The solution es this: First I created a helper to manage the options (shipping methods) And then use it in the Model.

Helper:

namespace TCK\ASM\Helper;

use Magento\Framework\App\Helper\AbstractHelper;
use TCK\ASM\Model\Source\Method;

/**
 * Class Group
 * @package TCK\ASM\Helper
 */

    class Group extends AbstractHelper

{
    protected $resourceConnection;
    protected $asm;

    public function __construct(
        \Magento\Framework\App\ResourceConnection $resourceConnection,
        \TCK\ASM\Model\Source\Method $asm
    )
    {
        $this->resourceConnection = $resourceConnection;
        $this->asm = $asm;
    }
    /**
     * Stub
     * @return string
     */
    public function getGroupData($id)
    {

        $db = $this->resourceConnection->getConnection();
        $result = $db->query('SELECT * FROM customer_group WHERE customer_group_id=' . $id); 
        $row = $result->fetch();
        $values=$row['shipping_method'];
        $split=explode(",",$values);
        $count = count($split);

        $metodos=$this->asm->toOptionArray();

        $i=1;
        $s=0;
        for ($i; $i <= $count; $i++) {
            $info[$i]=$metodos[$split[$s]];
            $s++;
        }

        return $info;
    }

    public function getAllMethods()
    {
        $metodos=$this->asm->toOptionArray();

        return $metodos;
    }
}

Model:

namespace TCK\ASM\Model\Carrier;

use Magento\Quote\Model\Quote\Address\RateRequest;
use Magento\Shipping\Model\Rate\Result;
use Magento\Checkout\Model\Cart;
use Magento\Shipping\Model\Carrier\AbstractCarrier;
use Magento\Shipping\Model\Carrier\CarrierInterface;
use TCK\ASM\Model\Source\Method;
use TCK\ASM\Helper\Group;
class ASMShipping extends \Magento\Shipping\Model\Carrier\AbstractCarrier implements
    \Magento\Shipping\Model\Carrier\CarrierInterface
{
    /**
     * Code of the carrier
     * @var string
     */
    protected $_code='ASMShipping';
    /**
     * @var \Magento\Shipping\Model\Rate\ResultFactory
     */
    protected $_rateResultFactory;
    /**
     * @var \Magento\Quote\Model\Quote\Address\RateResult\MethodFactory
     */
    protected $_rateMethodFactory;
    /**
     * Rate result data
     *
     * @var Result
     */
    protected $_result;

    /**
     * @param \Magento\Framework\App\Config\ScopeConfigInterface $scopeConfig
     * @param \Magento\Quote\Model\Quote\Address\RateResult\ErrorFactory $rateErrorFactory
     * @param \Psr\Log\LoggerInterface $logger
     * @param \Magento\Shipping\Model\Rate\ResultFactory $rateResultFactory
     * @param \Magento\Quote\Model\Quote\Address\RateResult\MethodFactory $rateMethodFactory
     * @param Cart $cart
     * @param \TCK\ASM\Helper\Group $helper
     * @param \Magento\Framework\App\Filesystem\DirectoryList $directory_list
     * @param array $data
     */
    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,
        \Magento\Checkout\Model\Cart $cart,
        \Magento\Framework\App\Filesystem\DirectoryList $directory_list,
        \TCK\ASM\Helper\Group $helper,
        \Magento\Framework\App\ResourceConnection $resourceConnection,
        array $data = []
    ) {
        $this->_rateResultFactory = $rateResultFactory;
        $this->_rateMethodFactory = $rateMethodFactory;
        $this->directory_list = $directory_list;
        $this->cart = $cart;
        $this->helper = $helper;
        $this->resourceConnection = $resourceConnection;
        parent::__construct($scopeConfig, $rateErrorFactory, $logger, $data);
    }

    /**
     * Returns array of key-value pairs of all available methods
     * @return array
     */
    public function getAllowedMethods()
    {
        $group_info=$this->helper->getAllMethods();
        $carriers=array();
        foreach ($group_info as &$carrier) {
            $carriers[$group_info['label']]=$group_info['label'];
        }
        return $carriers;
    }

    /**
     * @param RateRequest $request
     * @return bool|Result|null
     */
    public function collectRates(RateRequest $request)
    {
        if (!$this->getConfigFlag('active')) {
            return false;
        }


        $objectManager = \Magento\Framework\App\ObjectManager::getInstance();
        $customerSession = $objectManager->create('Magento\Customer\Model\Session');

        if ($customerSession->isLoggedIn()) {
            $gid=$customerSession->getCustomerGroupId();
            $group_info=$this->helper->getGroupData($gid);
        }



        $err = null;
        $envio = array();
        /** @var \Magento\Shipping\Model\Rate\Result $result */
        //$result = $this->_rateResultFactory->create();
        $this->_result = $this->_rateResultFactory->create();
        /** @var \Magento\Quote\Model\Quote\Address\RateResult\Method $method */
        $method = $this->_rateMethodFactory->create();
        $method->setCarrier('ASMShipping');
        $method->setCarrierTitle($this->getConfigData('title'));
        $method->setMethod('ASMShipping');
        $method->setMethodTitle($this->getConfigData('name'));
        $amount=0;

        //Shipping logic         

        $ASM10=$this->_getQuote(0,$precioPeso, $archivo, $usarTableRate, $cp_cliente, $envio["peso"], $pais_cliente);
        $ASM14=$this->_getQuote(1,$precioPeso, $archivo, $usarTableRate, $cp_cliente, $envio["peso"], $pais_cliente);
        $ASM24=$this->_getQuote(2,$precioPeso, $archivo, $usarTableRate, $cp_cliente, $envio["peso"], $pais_cliente);
        $ECONOMY=$this->_getQuote(3,$precioPeso, $archivo, $usarTableRate, $cp_cliente, $envio["peso"], $pais_cliente);

        return $this->getResult();
    }
    /**
     * Get result of request
     * @return Result
     */
    public function getResult()
    {
        return $this->_result;
    }

    /**
     * @return $this
     */
    protected function _getQuote($grupo, $precioPeso, $archivo, $usarTableRate, $cp_cliente, $peso, $pais_cliente)
    {

        $group_info=$this->helper->getAllMethods();
        $servicio = $group_info[$grupo]['label'];
        $envio["metodo"]["servicio"]=$group_info[$grupo]['servicio'];
        $envio["metodo"]["horario"]=$group_info[$grupo]['horario'];
        /*Tarifas*/
        $tarifas = array();
        //Logic stuff


        $rate = $this->_rateMethodFactory->create();
        $rate->setCarrier($this->_code);
        $rate->setCarrierTitle($this->getConfigData('title'));
        $rate->setMethodTitle($group_info[$grupo]['label']);
        $rate->setPrice($importe);
        $rate->setCost(0);
        $this->_result->append($rate);
        return $this;
    }

}
4
  • Hello Oscar Azpeitia, above answer is working perfect for your question? Commented Sep 14, 2016 at 7:03
  • 1
    Yes @PayalPatel it is! Commented Sep 15, 2016 at 15:13
  • Ok, @OscarAzpeitia, Your model call using di.xml or config.xml ? Commented Sep 16, 2016 at 5:13
  • 1
    @PayalPatel di.xml Commented Sep 23, 2016 at 17:30
0
<?php
namespace Mageplaza\Simpleshipping\Model\Carrier;
use Magento\Quote\Model\Quote\Address\RateRequest;
use Magento\Shipping\Model\Rate\Result;
class Shipping extends \Magento\Shipping\Model\Carrier\AbstractCarrier implements
\Magento\Shipping\Model\Carrier\CarrierInterface
{
/**
 * @var string
 */
protected $_code = 'simpleshipping';

/**
 * @var \Magento\Shipping\Model\Rate\ResultFactory
 */
protected $_rateResultFactory;

/**
 * @var \Magento\Quote\Model\Quote\Address\RateResult\MethodFactory
 */
protected $_rateMethodFactory;

/**
 * Shipping constructor.
 *
 * @param \Magento\Framework\App\Config\ScopeConfigInterface          $scopeConfig
 * @param \Magento\Quote\Model\Quote\Address\RateResult\ErrorFactory  $rateErrorFactory
 * @param \Psr\Log\LoggerInterface                                    $logger
 * @param \Magento\Shipping\Model\Rate\ResultFactory                  $rateResultFactory
 * @param \Magento\Quote\Model\Quote\Address\RateResult\MethodFactory $rateMethodFactory
 * @param array                                                       $data
 */
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);
}

/**
 * get allowed methods
 * @return array
 */
public function getAllowedMethods()
{
    return [$this->_code => $this->getConfigData('name')];
}

/**
 * @return float
 */
private function getShippingPrice()
{
    $configPrice = $this->getConfigData('price');

    $shippingPrice = $this->getFinalPriceWithHandlingFee($configPrice);

    return $shippingPrice;
}

/**
 * @param RateRequest $request
 * @return bool|Result
 */
public function collectRates(RateRequest $request)
{
    if (!$this->getConfigFlag('active')) {
        return false;
    }

    /** @var \Magento\Shipping\Model\Rate\Result $result */
    $result = $this->_rateResultFactory->create();

    /** @var \Magento\Quote\Model\Quote\Address\RateResult\Method $method */
    $method = $this->_rateMethodFactory->create();

    $method->setCarrier($this->_code);
    $method->setCarrierTitle($this->getConfigData('title'));

    $method->setMethod($this->_code);
    $method->setMethodTitle($this->getConfigData('name'));

    $amount = $this->getShippingPrice();

    $method->setPrice($amount);
    $method->setCost($amount);

    $result->append($method);

    return $result;
}
}

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.