Magento на русском

Новости, обмен опытом, база знаний для разработчиков.

Создание Shipping Method Module – часть 1, заглушка

by @ 14:04 on 03.02.2009. Tags:
Filed under Методы доставки

Поставленная задача не тривиальная, описывать полностью не буду, а скажу в кратце, что надо создать новый Shipping Method со сложной логикой.

1.

Руководствуясь доками из wiki создаём папку для нашего модуля и конфиг:

/app/code/local/CompanyName/NewModule

/app/etc/module/CompanyName_NewModule.xml

Мой модуль будет называться Zground, а компания будет Oggettoweb, плюс еще я решил свои модули хранить отдельно от модулей других наших разработчиков, для сих целей была создана папочка для модуля вида:

/app/code/local/CompanyName/Me/NewModule

Далее будут встречаться некоторые различия в путях и названиях модуля, файлов и т.п.

Обозначу соответствия:

CompanyName – Oggettoweb/Verych

NewModule – Zground

Конфигурируем модуль:

Создаём app/code/local/YourCompany/NewModule/etc/config.xml

<?xml version=»1.0″?>
<config>
<modules>
<!– declare module’s version information –>
<Oggettoweb_Verych_Zground>
<!– this version number will be used for database upgrades –>
<version>0.1.0</version>
</Oggettoweb_Verych_Zground>
</modules>

<global>
<!– declare model group for new module –>
<models>
<!– model group alias to be used in Mage::getModel() –>
<newmodule>
<!– base class name for the model group –>
<class>Oggettoweb_Verych_Zground_Model</class>
</newmodule>
</models>

<!– declare resource setup for new module –>
<resources>
<!– resource identifier –>
<newmodule_setup>
<!– specify that this resource is a setup resource and used for upgrades –>
<setup>
<!– which module to look for install/upgrade files in –>
<module>Oggettoweb_Verych_Zground</module>
</setup>
<!– specify database connection for this resource –>
<connection>
<!– do not create new connection, use predefined core setup connection –>
<use>core_setup</use>
</connection>
</newmodule_setup>
</resources>
</global>
</config>

Редактируем app/etc/modules/YourCompany_NewModule.xml:

<?xml version=»1.0″?>
<config>
<modules>
<Oggettoweb_Verych_Zground>
<active>true</active>
<codePool>local</codePool>
</Oggettoweb_Verych_Zground>
</modules>
</config>

2.

Далее сформируем саму модель.

ShippingMethod – может иметь произвольное другое название.

Создайте app/code/local/YourCompany/NewModule/Model/Carrier/ShippingMethod.php:

<?php
/**
* Our test shipping method module adapter
*/
class Oggettoweb_Verych_Zground_Model_Carrier_ShippingMethod extends Mage_Shipping_Model_Carrier_Abstract
{
/**
* unique internal shipping method identifier
*
* @var string [a-z0-9_]
*/
protected $_code = 'newmodule';

/**
* Collect rates for this shipping method based on information in $request
*
* @param Mage_Shipping_Model_Rate_Request $data
* @return Mage_Shipping_Model_Rate_Result
*/
public function collectRates(Mage_Shipping_Model_Rate_Request $request)
{
// skip if not enabled
if (!Mage::getStoreConfig(’carriers/’.$this->_code.’/active’)) {
return false;
}

/**
* here we are retrieving shipping rates from external service
* or using internal logic to calculate the rate from $request
* you can see an example in Mage_Usa_Model_Shipping_Carrier_Ups::setRequest()
*/

// get necessary configuration values
$handling = Mage::getStoreConfig(’carriers/’.$this->_code.’/handling’);

// this object will be returned as result of this method
// containing all the shipping rates of this method
$result = Mage::getModel(’shipping/rate_result’);

// $response is an array that we have
foreach ($response as $rMethod) {
// create new instance of method rate
$method = Mage::getModel(’shipping/rate_result_method’);

// record carrier information
$method->setCarrier($this->_code);
$method->setCarrierTitle(Mage::getStoreConfig(’carriers/’.$this->_code.’/title’));

// record method information
$method->setMethod($rMethod['code']);
$method->setMethodTitle($rMethod['title']);

// rate cost is optional property to record how much it costs to vendor to ship
$method->setCost($rMethod['amount']);

// in our example handling is fixed amount that is added to cost
// to receive price the customer will pay for shipping method.
// it could be as well percentage:
/// $method->setPrice($rMethod['amount']*$handling/100);
$method->setPrice($rMethod['amount']+$handling);

// add this rate to the result
$result->append($method);
}

return $result;
}
}

Теперь нам надо подключить наш модуль к админке, чтобы иметь возможность выбирать его, включать и конфигурировать.

Создадим app/code/local/YourCompany/NewModule/etc/system.xml

<?xml version="1.0"?>
<config>
<sections>
<carriers>
<groups>
<carrier_name translate="label" module="shipping">
<label>Zground</label>
<frontend_type>text</frontend_type>
<sort_order>13</sort_order>
<show_in_default>1</show_in_default>
<show_in_website>1</show_in_website>
<show_in_store>1</show_in_store>
<fields>
<account translate="label">
<label>Account number</label>
<frontend_type>text</frontend_type>
<sort_order>7</sort_order>
<show_in_default>1</show_in_default>
<show_in_website>1</show_in_website>
<show_in_store>1</show_in_store>
</account>
<active translate="label">
<label>Enabled</label>
<frontend_type>select</frontend_type>
<source_model>adminhtml/system_config_source_yesno</source_model>
<sort_order>1</sort_order>
<show_in_default>1</show_in_default>
<show_in_website>1</show_in_website>
<show_in_store>1</show_in_store>
</active>
<contentdesc translate="label">
<label>Package Description</label>
<frontend_type>text</frontend_type>
<sort_order>12</sort_order>
<show_in_default>1</show_in_default>
<show_in_website>1</show_in_website>
<show_in_store>1</show_in_store>
</contentdesc>
<!--
If the free_shipping_enable flag enable, the system will check free_shipping_subtotal to give free shipping
otherwise will use shopping cart price rule behaviour
-->
<free_shipping_enable translate="label">
<label>Free shipping with minimum order amount</label>
<frontend_type>select</frontend_type>
<source_model>adminhtml/system_config_source_enabledisable</source_model>
<sort_order>21</sort_order>
<show_in_default>1</show_in_default>
<show_in_website>1</show_in_website>
<show_in_store>1</show_in_store>
</free_shipping_enable>
<free_shipping_subtotal translate="label">
<label>Minimum order amount for free shipping</label>
<frontend_type>text</frontend_type>
<sort_order>22</sort_order>
<show_in_default>1</show_in_default>
<show_in_website>1</show_in_website>
<show_in_store>1</show_in_store>
</free_shipping_subtotal>
<dutiable translate="label">
<label>Shipment Dutiable</label>
<frontend_type>select</frontend_type>
<source_model>adminhtml/system_config_source_yesno</source_model>
<sort_order>13</sort_order>
<show_in_default>1</show_in_default>
<show_in_website>1</show_in_website>
<show_in_store>1</show_in_store>
</dutiable>
<gateway_url translate="label">
<label>Gateway URL</label>
<frontend_type>text</frontend_type>
<sort_order>2</sort_order>
<show_in_default>1</show_in_default>
<show_in_website>1</show_in_website>
<show_in_store>1</show_in_store>
</gateway_url>
<handling_type translate="label">
<label>Calculate Handling Fee</label>
<frontend_type>select</frontend_type>
<source_model>shipping/source_handlingType</source_model>
<sort_order>10</sort_order>
<show_in_default>1</show_in_default>
<show_in_website>1</show_in_website>
<show_in_store>0</show_in_store>
</handling_type>
<handling_action translate="label">
<label>Handling Applied</label>
<frontend_type>select</frontend_type>
<source_model>shipping/source_handlingAction</source_model>
<sort_order>11</sort_order>
<show_in_default>1</show_in_default>
<show_in_website>1</show_in_website>
<show_in_store>0</show_in_store>
</handling_action>
<handling_fee translate="label">
<label>Handling fee</label>
<frontend_type>text</frontend_type>
<sort_order>12</sort_order>
<show_in_default>1</show_in_default>
<show_in_website>1</show_in_website>
<show_in_store>1</show_in_store>
</handling_fee>
<max_package_weight translate="label">
<label>Maximum Package Weight (Please consult your shipping carrier for maximum supported shipping weight)</label>
<frontend_type>text</frontend_type>
<sort_order>13</sort_order>
<show_in_default>1</show_in_default>
<show_in_website>1</show_in_website>
<show_in_store>1</show_in_store>
</max_package_weight>
<id translate="label">
<label>Access ID</label>
<frontend_type>text</frontend_type>
<backend_model>adminhtml/system_config_backend_encrypted</backend_model>
<sort_order>5</sort_order>
<show_in_default>1</show_in_default>
<show_in_website>1</show_in_website>
<show_in_store>1</show_in_store>
</id>
<password translate="label">
<label>Password</label>
<frontend_type>text</frontend_type>
<backend_model>adminhtml/system_config_backend_encrypted</backend_model>
<sort_order>6</sort_order>
<show_in_default>1</show_in_default>
<show_in_website>1</show_in_website>
<show_in_store>1</show_in_store>
</password>
<shipping_intlkey translate="label">
<label>Shipping key (International)</label>
<frontend_type>text</frontend_type>
<backend_model>adminhtml/system_config_backend_encrypted</backend_model>
<sort_order>8</sort_order>
<show_in_default>1</show_in_default>
<show_in_website>1</show_in_website>
<show_in_store>1</show_in_store>
</shipping_intlkey>
<shipping_key translate="label">
<label>Shipping key</label>
<frontend_type>text</frontend_type>
<backend_model>adminhtml/system_config_backend_encrypted</backend_model>
<sort_order>8</sort_order>
<show_in_default>1</show_in_default>
<show_in_website>1</show_in_website>
<show_in_store>1</show_in_store>
</shipping_key>
<sort_order translate="label">
<label>Sort order</label>
<frontend_type>text</frontend_type>
<sort_order>100</sort_order>
<show_in_default>1</show_in_default>
<show_in_website>1</show_in_website>
<show_in_store>1</show_in_store>
</sort_order>
<title translate="label">
<label>Title</label>
<frontend_type>text</frontend_type>
<sort_order>2</sort_order>
<show_in_default>1</show_in_default>
<show_in_website>1</show_in_website>
<show_in_store>1</show_in_store>
</title>
<sallowspecific translate="label">
<label>Ship to applicable countries</label>
<frontend_type>select</frontend_type>
<sort_order>90</sort_order>
<frontend_class>shipping-applicable-country</frontend_class>
<source_model>adminhtml/system_config_source_shipping_allspecificcountries</source_model>
<show_in_default>1</show_in_default>
<show_in_website>1</show_in_website>
<show_in_store>1</show_in_store>
</sallowspecific>
<specificcountry translate="label">
<label>Ship to Specific countries</label>
<frontend_type>multiselect</frontend_type>
<sort_order>91</sort_order>
<source_model>adminhtml/system_config_source_country</source_model>
<show_in_default>1</show_in_default>
<show_in_website>1</show_in_website>
<show_in_store>1</show_in_store>
</specificcountry>
<showmethod translate="label">
<label>Show method if not applicable</label>
<frontend_type>select</frontend_type>
<sort_order>92</sort_order>
<source_model>adminhtml/system_config_source_yesno</source_model>
<show_in_default>1</show_in_default>
<show_in_website>1</show_in_website>
<show_in_store>1</show_in_store>
</showmethod>
<specificerrmsg translate="label">
<label>Displayed Error Message</label>
<frontend_type>textarea</frontend_type>
<sort_order>80</sort_order>
<show_in_default>1</show_in_default>
<show_in_website>1</show_in_website>
<show_in_store>1</show_in_store>
</specificerrmsg>
</fields>
</carrier_name>
</groups>
</carriers>
</sections>
</config>

После этих действий наш модуль появится в админке.

Похожие Magento-статьи:

  1. Shiping method своими руками – часть 2. Наследование.
  2. Система конфигов в Magento
  3. Как отправить письмо в Magento?
  4. Программное создание ордера (заказа)

The URI to TrackBack this entry is: http://magento.verych.ru/2009/02/%d1%81%d0%be%d0%b7%d0%b4%d0%b0%d0%bd%d0%b8%d0%b5-shipping-method-module-%d1%87%d0%b0%d1%81%d1%82%d1%8c-1-%d0%b7%d0%b0%d0%b3%d0%bb%d1%83%d1%88%d0%ba%d0%b0/trackback/

Комментариев - 17 для “Создание Shipping Method Module – часть 1, заглушка”

  1. Александр:

    Подскажите как отключить в оформлении заказа
    -=Способ доставки =- и -= Информация об оплате =-

  2. Просто из Админки никак :(
    Если найдешь как (может модуль какой-нибудь) обязательно напиши!

  3. Александр:

    Если найду напишу

    Ну а если не из админки

  4. Написать модуль, который будет применять какой-нить Free Shipping и перекидывать на следующий шаг.

    Вообще это не тривиальная задача, ведь шипинг метод это одна из основных функциональных частей мадженты. Стоит ли эту часть вообще трогать?

    Я бы просто активировал Free Shipping Method в админке, а другие по-отключал.

  5. Александр:

    Но мне просто нужно чтобы этот шаг пропускался, а Free Shipping Method я уже активировал а все остальные поотключал.Не подскажешь как сделать чтобы этот шаг пропускался?

  6. задача довольно сложная, я делал подобное так:
    1. делаем реврайт для аяксовых запросов в баяне по УРЛу, пишем свой контроллер, в него копируем стандартный код обработчиков для каждого шага(в нашем случае переписываем saveShipping и убираем saveShippingMethod). на saveShipping вешаем заполнение метода доставки (по сути два шага выполняются вместе)
    2. корректируем opccheckout.js (занятие занудное, но без него никак). убираем закладку баяна. там еще есть строка со списком шагов, убираем shipping_method. правим объекты (не checkout, нужен shipping): там будет что-то вроде gotoSection: эта фигня есть и в js и в ответе на аякс, надо править там и там(код нашего контроллера).
    3. в конце я просто тыкал файрбагом, пока не поправил все exceptionы в js.
    щас времени нет, как появится, объясню с указкой и кусками кода ;)

  7. Александр:

    Буду благодарен если выложишь куски кода….

  8. Александр:

    Да, еще вопросик из этой же рубрики
    Как сделать чтобы -=Информация об оплате=- пропускалась или чтобы можно было ее убрать?

  9. Подозреваю, что точно таким же способом как описал vverhovodov

  10. Александр:

    vverhovodov? А где можно посмотреть??? Дай ссылку, пожалуйста.

  11. Коммент №6 к этому посту :)
    Тоже самое только для другой части баяна

  12. я бы дал, только боюсь что она не подойдет (http://localhost/блаблабла) %)

  13. Александр:

    Понял, а где еще можно посмотреть???

  14. ну здесь обычно три варианта: magentocommerce.com, гугол либо копаться в файлах и разбираться как оно работает. надеюсь, что принцип действия объяснил (псто №6). как будет время расскажу полностью, а пока у меня дедлайны..

  15. Андрей:

    Уважаемые, не подскажите, что делаю не так? В админке модуль появился, но на гармошке пользовательской части не выводится.

  16. Возможно не хватает шаблонов. Возможно он выключен ;) Возможно он использует конфиги другого метода, если был наследован, а тот выключен. Возможно кэш не обновился… Возможно просто в коде где-то косяки (чаще всего)

  17. Андрей:

    спасибо, буду ковыряться :)

Оставить комментарий

© 2009-2012 Magento по-русски 99% авторских статей