最模板 - 外贸网站建设,外贸网站模板

最模板

当前位置: 首页 > Magento > Magento教程 >

8条代码片段方便地Magento开发商

时间:2014-06-14 11:13来源:未知 作者:最模板zuimoban 点击:
当与 Magento 工作多年,我建立了一个图书馆的最常用的代码片段。这些代码段会非常有帮助的当发展主题或自定义的扩展,他们节省你很多时间,让我们开始教程: 1.检查产品的库存情况
当与 Magento 工作多年,我建立了一个图书馆的最常用的代码片段。这些代码段会非常有帮助的当发展主题或自定义的扩展,他们节省你很多时间,让我们开始教程:
 
1.检查产品的库存情况
真的很有用的代码,以检查产品的库存情况。
 
 
protected function _isAvailable(Mage_Sales_Model_Order_Item $orderItem, $qty)
{
    if ($orderItem->getProductId()) {
        $stockItem = Mage::getModel('catalog/product')
                  ->load($orderItem->getProductId())
                  ->getStockItem();
 
        if ($stockItem->getIsInStock() && (int)$stockItem->getQty() >= $qty) {
            return true;
        }
    }
    return false;
}
2.在 Magento 中创建发票
下面是 php 代码在 Magento 中创建的订单的发票。
 
 
 
$order = Mage::getModel('sales/order')->loadByIncrementId('100000001');
try {
if(!$order->canInvoice())
{
Mage::throwException(Mage::helper('core')->__('Cannot create an invoice.'));
}
  
$invoice = Mage::getModel('sales/service_order', $order)->prepareInvoice();
  
if (!$invoice->getTotalQty()) {
Mage::throwException(Mage::helper('core')->__('Cannot create an invoice without products.'));
}
  
$invoice->setRequestedCaptureCase(Mage_Sales_Model_Order_Invoice::CAPTURE_ONLINE);
//Or you can use
//$invoice->setRequestedCaptureCase(Mage_Sales_Model_Order_Invoice::CAPTURE_OFFLINE);
$invoice->register();
$transactionSave = Mage::getModel('core/resource_transaction')
->addObject($invoice)
->addObject($invoice->getOrder());
  
$transactionSave->save();
}
catch (Mage_Core_Exception $e) {
  
}
3.检查是否有任何航运的方法可用
这是很有用的函数,知道是任何船舶的方法。
 
 
 
public function haveShippingMethods()
{
    if (count(Mage::getSingleton('checkout/session')->getQuote()->getShippingAddress()->getShippingRatesCollection())) {
        return true;
    }
    return false;
}
4.在主页上显示新产品
使用此代码片段显示在主页上的新产品。
 
 
 
{{block type=“catalog/product_new” name=“home.catalog.product.new”
alias=“product_homepage” template=“catalog/product/new.phtml”}}
5.在 Magento 中创建客户
只是使用这个珍贵的代码在 Magento 中创建一个客户帐户。
 
 
 
$customer = Mage::getModel('customer/customer');
$password = 'test1234';
$email = 'dtest@gmail.com';
$customer->setWebsiteId(Mage::app()->getWebsite()->getId());
$customer->loadByEmail($email);
if(!$customer->getId()) {
    $groups = Mage::getResourceModel('customer/group_collection')->getData();
    $groupID = '3';
 
    $customer->setData( 'group_id', $groupID );
    $customer->setEmail($email);
    $customer->setFirstname('test');
    $customer->setLastname('testing');
    $customer->setPassword($password);
 
    $customer->setConfirmation(null);
    $customer->save();
 
    echo $customer->getId();
}
6.在 Magento 中创建的贷项通知单
下面是一个 php 代码在 magento 中创建订单贷项通知单。
 
 
$order = Mage::getModel('sales/order')->load('100000001', 'increment_id');
        if (!$order->getId()) {
            $this->_fault('order_not_exists');
        }
        if (!$order->canCreditmemo()) {
            $this->_fault('cannot_create_creditmemo');
        }
        $data = array();
 
         
        $service = Mage::getModel('sales/service_order', $order);
        
        $creditmemo = $service->prepareCreditmemo($data);
 
        // refund to Store Credit
        if ($refundToStoreCreditAmount) {
            // check if refund to Store Credit is available
            if ($order->getCustomerIsGuest()) {
                $this->_fault('cannot_refund_to_storecredit');
            }
            $refundToStoreCreditAmount = max(
                0,
                min($creditmemo->getBaseCustomerBalanceReturnMax(), $refundToStoreCreditAmount)
            );
            if ($refundToStoreCreditAmount) {
                $refundToStoreCreditAmount = $creditmemo->getStore()->roundPrice($refundToStoreCreditAmount);
                $creditmemo->setBaseCustomerBalanceTotalRefunded($refundToStoreCreditAmount);
                $refundToStoreCreditAmount = $creditmemo->getStore()->roundPrice(
                    $refundToStoreCreditAmount*$order->getStoreToOrderRate()
                );
                // this field can be used by customer balance observer
                $creditmemo->setBsCustomerBalTotalRefunded($refundToStoreCreditAmount);
                // setting flag to make actual refund to customer balance after credit memo save
                $creditmemo->setCustomerBalanceRefundFlag(true);
            }
        }
        $creditmemo->setPaymentRefundDisallowed(true)->register();
        // add comment to creditmemo
        if (!empty($comment)) {
            $creditmemo->addComment($comment, $notifyCustomer);
        }
        try {
            Mage::getModel('core/resource_transaction')
                ->addObject($creditmemo)
                ->addObject($order)
                ->save();
            // send email notification
            $creditmemo->sendEmail($notifyCustomer, ($includeComment ? $comment : ''));
        } catch (Mage_Core_Exception $e) {
            $this->_fault('data_invalid', $e->getMessage());
        }
        echo $creditmemo->getIncrementId();
7.创建装运
下面是创建订单装运在 magento 的 php 代码。
 
 
 
$order = Mage::getModel('sales/order')->loadByIncrementId('100000001');
try {
    if($order->canShip()) {
        //Create shipment
        $shipmentid = Mage::getModel('sales/order_shipment_api')
                        ->create($order->getIncrementId(), array());
        //Add tracking information
        $ship = Mage::getModel('sales/order_shipment_api')
                        ->addTrack($order->getIncrementId(), array());       
    }
}catch (Mage_Core_Exception $e) {
 print_r($e);
}
8.在 Magento 建立秩序
您可以使用下面的 php 代码在 Magento 中创建订单。它需要一个有效的客户帐户与航运和帐单地址设置。
 
 
 
$id=1; // get Customer Id
$customer = Mage::getModel('customer/customer')->load($id);
 
$transaction = Mage::getModel('core/resource_transaction');
$storeId = $customer->getStoreId();
$reservedOrderId = Mage::getSingleton('eav/config')->getEntityType('order')->fetchNewIncrementId($storeId);
 
$order = Mage::getModel('sales/order')
->setIncrementId($reservedOrderId)
->setStoreId($storeId)
->setQuoteId(0)
->setGlobal_currency_code('USD')
->setBase_currency_code('USD')
->setStore_currency_code('USD')
->setOrder_currency_code('USD');
//Set your store currency USD or any other
 
// set Customer data
$order->setCustomer_email($customer->getEmail())
->setCustomerFirstname($customer->getFirstname())
->setCustomerLastname($customer->getLastname())
->setCustomerGroupId($customer->getGroupId())
->setCustomer_is_guest(0)
->setCustomer($customer);
 
// set Billing Address
$billing = $customer->getDefaultBillingAddress();
$billingAddress = Mage::getModel('sales/order_address')
->setStoreId($storeId)
->setAddressType(Mage_Sales_Model_Quote_Address::TYPE_BILLING)
->setCustomerId($customer->getId())
->setCustomerAddressId($customer->getDefaultBilling())
->setCustomer_address_id($billing->getEntityId())
->setPrefix($billing->getPrefix())
->setFirstname($billing->getFirstname())
->setMiddlename($billing->getMiddlename())
->setLastname($billing->getLastname())
->setSuffix($billing->getSuffix())
->setCompany($billing->getCompany())
->setStreet($billing->getStreet())
->setCity($billing->getCity())
->setCountry_id($billing->getCountryId())
->setRegion($billing->getRegion())
->setRegion_id($billing->getRegionId())
->setPostcode($billing->getPostcode())
->setTelephone($billing->getTelephone())
->setFax($billing->getFax());
$order->setBillingAddress($billingAddress);
 
$shipping = $customer->getDefaultShippingAddress();
$shippingAddress = Mage::getModel('sales/order_address')
->setStoreId($storeId)
->setAddressType(Mage_Sales_Model_Quote_Address::TYPE_SHIPPING)
->setCustomerId($customer->getId())
->setCustomerAddressId($customer->getDefaultShipping())
->setCustomer_address_id($shipping->getEntityId())
->setPrefix($shipping->getPrefix())
->setFirstname($shipping->getFirstname())
->setMiddlename($shipping->getMiddlename())
->setLastname($shipping->getLastname())
->setSuffix($shipping->getSuffix())
->setCompany($shipping->getCompany())
->setStreet($shipping->getStreet())
->setCity($shipping->getCity())
->setCountry_id($shipping->getCountryId())
->setRegion($shipping->getRegion())
->setRegion_id($shipping->getRegionId())
->setPostcode($shipping->getPostcode())
->setTelephone($shipping->getTelephone())
->setFax($shipping->getFax());
 
$order->setShippingAddress($shippingAddress)
->setShipping_method('flatrate_flatrate');
/*->setShippingDescription($this->getCarrierName('flatrate'));*/
/*some error i am getting here need to solve further*/
 
//you can set your payment method name here as per your need
$orderPayment = Mage::getModel('sales/order_payment')
->setStoreId($storeId)
->setCustomerPaymentId(0)
->setMethod('purchaseorder')
->setPo_number(' – ');
$order->setPayment($orderPayment);
 
// let say, we have 1 product
//check that your products exists
//need to add code for configurable products if any
$subTotal = 0;
$products = array(
    '1' => array(
    'qty' => 2
    )
);
 
foreach ($products as $productId=>$product) {
$_product = Mage::getModel('catalog/product')->load($productId);
$rowTotal = $_product->getPrice() * $product['qty'];
$orderItem = Mage::getModel('sales/order_item')
->setStoreId($storeId)
->setQuoteItemId(0)
->setQuoteParentItemId(NULL)
->setProductId($productId)
->setProductType($_product->getTypeId())
->setQtyBackordered(NULL)
->setTotalQtyOrdered($product['rqty'])
->setQtyOrdered($product['qty'])
->setName($_product->getName())
->setSku($_product->getSku())
->setPrice($_product->getPrice())
->setBasePrice($_product->getPrice())
->setOriginalPrice($_product->getPrice())
->setRowTotal($rowTotal)
->setBaseRowTotal($rowTotal);
 
$subTotal += $rowTotal;
$order->addItem($orderItem);
}
 
$order->setSubtotal($subTotal)
->setBaseSubtotal($subTotal)
->setGrandTotal($subTotal)
->setBaseGrandTotal($subTotal);
 
$transaction->addObject($order);
$transaction->addCommitCallback(array($order, 'place'));
$transaction->addCommitCallback(array($order, 'save'));
$transaction->save();
这些都是一些受欢迎的代码段。如果你正在寻找额外的代码片段,随时让我知道我将会添加他们或你也可以提交更多的代码片段,以分享的社区,将不胜感激 !
(责任编辑:最模板)
------分隔线----------------------------
栏目列表
推荐内容