Skip to content

Instantly share code, notes, and snippets.

@pinedamg
Created July 23, 2012 18:10
Show Gist options
  • Star 7 You must be signed in to star a gist
  • Fork 6 You must be signed in to fork a gist
  • Save pinedamg/3165093 to your computer and use it in GitHub Desktop.
Save pinedamg/3165093 to your computer and use it in GitHub Desktop.
My Magento Snippets

My Magento Snippets

Checkout virtual - downloadable product

<?php

require_once '../app/Mage.php';
 
Varien_Profiler::enable();
Mage::setIsDeveloperMode(true);
ini_set('display_errors', 1);

umask(0);
Mage::app();

$storeId = Mage::app()->getStore()->getId();
$websiteId = 1;

/* @var $customer Mage_Customer_Model_Customer */
$customer = Mage::getModel('customer/customer');
$customer->setWebsiteId($websiteId)->loadByEmail('pinedamg+1@gmail.com');

Mage::getSingleton('customer/session')->loginById($customer->getId());

//Mage::getSingleton('checkout/session')
//    ->getQuote()
//    ->setBillingAddress($address);

$cart = Mage::getSingleton('checkout/cart');
/* @var $cart Mage_Checkout_Model_Cart */

$cart->truncate();
$cart->addProduct(
    1,
    $buyInfo = array(
        'qty'   =>  1,
        'links' =>  array(1)
    )
);

$cart->save();
//$cart->getItems()->clear()->save();

$checkout = Mage::getSingleton('checkout/type_onepage');
$checkout->initCheckout();
$checkout->saveCheckoutMethod('login');
$checkout->saveShippingMethod('flatrate_flatrate');
$checkout->savePayment(array('method'=>'checkmo'));

$checkout->saveOrder();
 
/* Clear the cart */
$cart->truncate();
$cart->save();
$cart->getItems()->clear()->save();        
 
/* Logout the customer you created */
Mage::getSingleton('customer/session')->logout();

My Magento Snippets

Remove field in product form adminhtml

<?php

class Baires_Vendors_Block_Adminhtml_Product_Edit_Tab_Settings
    extends Mage_Adminhtml_Block_Catalog_Product_Edit_Tab_Settings
{
    protected function _prepareForm()
    {
        parent::_prepareForm();
        if (!Mage::helper('vendors')->isVendor()) {
            return $this;
        }
        
        $this->getForm()->getElement('settings')->removeField('product_type');
    }
}

My Magento Snippets

Create Customer

<?php

require_once '../app/Mage.php';
 
Varien_Profiler::enable();
Mage::setIsDeveloperMode(true);
ini_set('display_errors', 1);
 
umask(0);
Mage::app();

Mage::app()->getStore()->setWebsiteId(1);
$customer = Mage::getModel('customer/customer');

$customer->setWebsiteId(Mage::app()->getWebsite()->getId())
    ->setEmail('pinedamg@gmail.com')
    ->setFirstname('Customer FirstName')
    ->setLastname('Customer LastName')
    ->setPassword('qwe123qwe')
    ->setGender(1)
    ->setWebsiteId(1)
    ->setConfirmation(null)
    ->save();

$_custom_address = array (
    'firstname' => 'Customer FirstName',
    'lastname' => 'Customer LastName',
    'street' => array (
        '0' => 'Street 1234',
        '1' => '',
    ),
 
    'city' => 'Buenos Aires',
    'region_id' => '',
    'region' => '',
    'postcode' => '1648',
    'country_id' => 'AR',
    'telephone' => '541146783154',
);

$customAddress = Mage::getModel('customer/address');

$customAddress->setData($_custom_address)
    ->setCustomerId($customer->getId())
    ->setIsDefaultBilling('1')
    ->setIsDefaultShipping('1')
    ->setSaveInAddressBook('1')

My Magento Snippets

Create Order Enterprise

<?php

require_once '../app/Mage.php';
Mage::app();

$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 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('flatrate');

$orderPayment = Mage::getModel('sales/order_payment')
->setStoreId($storeId)
->setCustomerPaymentId(0)
->setMethod('purchaseorder')
->setPo_number(' - ');
$order->setPayment($orderPayment);

// let say, we have 2 products
$subTotal = 0;
$products = array('1' => array('qty' => 1),'2' =>array('qty' => 1));
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();

My Magento Snippets

Create Order

<?php

require_once '../app/Mage.php';

Varien_Profiler::enable();
Mage::setIsDeveloperMode(true);
ini_set('display_errors', 1);

umask(0);
Mage::app();

$storeId = Mage::app()->getStore()->getId();
$websiteId = 1;

/* @var $customer Mage_Customer_Model_Customer */

for($i=0; $i<8; $i++) {

$quote = Mage::getModel('sales/quote')
    ->setStoreId(Mage::app()->getStore('default')->getId());

if ('existing') {
    // for customer orders:
    $customer = Mage::getModel('customer/customer')
        ->setWebsiteId(1)
        ->loadByEmail('customer@email.com');
    $quote->assignCustomer($customer);
} else {
    // for guest orders only:
    $quote->setCustomerEmail('customer@email.com');
}

$_qty_row = rand(1,8);
$_used = array();
for ($j=0; $j<$_qty_row; $j++) {
    $_id = rand(1,20);
    if (in_array($_id, $_used)) {
        continue;
    }
    $_used[] = $_id;
    $product = Mage::getModel('catalog/product')->load($_id);
    $buyInfo = array(
    'qty'   =>  rand(1,3),
        // custom option id => value id
        // or
        // configurable attribute id => value id
    );
    $quote->addProduct($product, new Varien_Object($buyInfo));
}

$addressData = array(
    'firstname' => 'Test',
    'lastname' => 'Test',
    'street' => 'Sample Street 10',
    'city' => 'Somewhere',
    'postcode' => '123456',
    'telephone' => '123456',
    'country_id' => 'US',
    'region_id' => 12, // id from directory_country_region table
);


$billingAddress = $quote->getBillingAddress()->addData($addressData);


$shippingAddress = $quote->getShippingAddress()->addData($addressData);

$shippingAddress->setCollectShippingRates(true)->collectShippingRates()
        ->setShippingMethod('flatrate_flatrate')
        ->setPaymentMethod('checkmo');

$quote->getPayment()->importData(array('method' => 'checkmo'));

$quote->collectTotals()->save();

$service = Mage::getModel('sales/service_quote', $quote);
$service->submitAll();
$order = $service->getOrder();

printf("Created order %s\n", $order->getIncrementId());
    
}

My Magento Snippets

Create Simple Product

<?php

require_once '../app/Mage.php';

Varien_Profiler::enable();
Mage::setIsDeveloperMode(true);
ini_set('display_errors', 1);

umask(0);
Mage::app();

/**
 * Adding Product 
 */

/** @TODO HACK */
Mage::app()->getStore()->setWebsiteId(1);

for ($i=0; $i<25; $i++) {

    $data = array(
        'name'                => 'Simple Product '.$i,
        'sku'                 => 'skusimple'.$i,
        'attribute_set_id'    => 4,
        'type_id'             => 'simple',
        'website_ids'         => array(1),
        'description'         => 'Simple Product Description '.$i,
        'short_description'   => 'Simple Product Short Description '.$i,
        'price'               => 25,
        'tax_class_id'        => 0,
        'visibility'          => Mage_Catalog_Model_Product_Visibility::VISIBILITY_BOTH,
        'status'              => Mage_Catalog_Model_Product_Status::STATUS_ENABLED,
        'category_ids'        => array(),
        'is_scope_store'      => 0,
        'has_options'         => 1,
        'required_options'    => 1,
        'stock_data'          => array(
            'manage_stock'    => 0,
            'is_in_stock'     => 1,
            'qty'             => 50,
        )
    );

    $product = Mage::getModel('catalog/product');
    $product->setData($data)->save();

}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment