Skip to content

Instantly share code, notes, and snippets.

@hightemp
Forked from borriglione/gist:2237588
Created April 14, 2012 21:16

Revisions

  1. hightemp revised this gist Jul 8, 2012. 1 changed file with 99 additions and 2 deletions.
    101 changes: 99 additions & 2 deletions gistfile1.md
    Original file line number Diff line number Diff line change
    @@ -967,7 +967,7 @@ ALTER TABLE `eav_entity_store` AUTO_INCREMENT=1;
    SET FOREIGN_KEY_CHECKS=1;
    ```

    #Product navigation (getting previous and next items)
    ##Product navigation (getting previous and next items)
    ```php
    <?php
    /**
    @@ -1005,4 +1005,101 @@ SET FOREIGN_KEY_CHECKS=1;
    // get link for current category
    $more_url = $_ccat->getUrl();
    ?>
    ```
    ```

    ##Add custom columns to the Magento administration Catalog > Product grid
    ```php
    <?php
    class Zyn_Common_Block_Adminhtml_Catalog_Product_Grid extends Mage_Adminhtml_Block_Catalog_Product_Grid {

    protected function _prepareColumns() {

    $this->addColumn('zyn_featured',
    array(
    'header'=> 'Show on Homepage',
    'width' => '50px',
    'index' => 'zyn_featured',
    'type' => 'options',
    'options' => array(0 => 'No', 1 => 'Yes')
    ));

    parent::_prepareColumns();

    }

    protected function _prepareCollection() {
    $store = $this->_getStore();
    $collection = Mage::getModel('catalog/product')->getCollection()
    ->addAttributeToSelect('sku')
    ->addAttributeToSelect('name')
    ->addAttributeToSelect('attribute_set_id')
    ->addAttributeToSelect('type_id')
    ->addAttributeToSelect('zyn_featured');

    if (Mage::helper('catalog')->isModuleEnabled('Mage_CatalogInventory')) {
    $collection->joinField('qty',
    'cataloginventory/stock_item',
    'qty',
    'product_id=entity_id',
    '{{table}}.stock_id=1',
    'left');
    }
    if ($store->getId()) {
    $adminStore = Mage_Core_Model_App::ADMIN_STORE_ID;
    $collection->addStoreFilter($store);
    $collection->joinAttribute(
    'name',
    'catalog_product/name',
    'entity_id',
    null,
    'inner',
    $adminStore
    );
    $collection->joinAttribute(
    'custom_name',
    'catalog_product/name',
    'entity_id',
    null,
    'inner',
    $store->getId()
    );
    $collection->joinAttribute(
    'status',
    'catalog_product/status',
    'entity_id',
    null,
    'inner',
    $store->getId()
    );
    $collection->joinAttribute(
    'visibility',
    'catalog_product/visibility',
    'entity_id',
    null,
    'inner',
    $store->getId()
    );
    $collection->joinAttribute(
    'price',
    'catalog_product/price',
    'entity_id',
    null,
    'left',
    $store->getId()
    );
    }
    else {
    $collection->addAttributeToSelect('price');
    $collection->joinAttribute('status', 'catalog_product/status', 'entity_id', null, 'inner');
    $collection->joinAttribute('visibility', 'catalog_product/visibility', 'entity_id', null, 'inner');
    }

    $this->setCollection($collection);

    //parent::_prepareCollection();
    $this->getCollection()->addWebsiteNamesToResult();
    return $this;
    }
    }
    ?>
    ```
  2. hightemp revised this gist Jul 6, 2012. 1 changed file with 36 additions and 41 deletions.
    77 changes: 36 additions & 41 deletions gistfile1.md
    Original file line number Diff line number Diff line change
    @@ -969,45 +969,40 @@ SET FOREIGN_KEY_CHECKS=1;

    #Product navigation (getting previous and next items)
    ```php
    <div id="product-navigation">
    <?php
    /**
    * Determine the previous/next link and link to current category
    */
    $_ccat = $this->helper('catalog/data')->getCategory();
    $ppos = $_ccat->getProductsPosition();
    $current_pid = $this->helper('catalog/data')->getProduct()->getId();
    // build array from products positions
    $plist = array();
    foreach ($ppos as $pid => $pos) {
    $plist[] = $pid;
    }
    $curpos = array_search($current_pid, $plist);
    // get link for prev product
    $previd = isset($plist[$curpos+1])? $plist[$curpos+1] : $current_pid;
    $product = Mage::getModel('catalog/product')->load($previd);
    $prevpos = $curpos;
    while (!$product->isVisibleInCatalog()) {
    $prevpos += 1;
    $nextid = isset($plist[$prevpos])? $plist[$prevpos] : $current_pid;
    $product = Mage::getModel('catalog/product')->load($nextid);
    }
    $prev_url = $product->getProductUrl();
    // get link for next product
    $nextid = isset($plist[$curpos-1])? $plist[$curpos-1] : $current_pid;
    $product = Mage::getModel('catalog/product')->load($nextid);
    $nextpos = $curpos;
    while (!$product->isVisibleInCatalog()) {
    $nextpos -= 1;
    $nextid = isset($plist[$nextpos])? $plist[$nextpos] : $current_pid;
    $product = Mage::getModel('catalog/product')->load($nextid);
    }
    $next_url = $product->getProductUrl();
    // get link for current category
    $more_url = $_ccat->getUrl();
    ?>
    <a href="<?= $prev_url; ?>">Previous</a>
    <a href="<?= $more_url; ?>">To Category</a>
    <a href="<?= $next_url; ?>">Next</a>
    </div>
    <?php
    /**
    * Determine the previous/next link and link to current category
    */
    $_ccat = $this->helper('catalog/data')->getCategory();
    $ppos = $_ccat->getProductsPosition();
    $current_pid = $this->helper('catalog/data')->getProduct()->getId();
    // build array from products positions
    $plist = array();
    foreach ($ppos as $pid => $pos) {
    $plist[] = $pid;
    }
    $curpos = array_search($current_pid, $plist);
    // get link for prev product
    $previd = isset($plist[$curpos+1])? $plist[$curpos+1] : $current_pid;
    $product = Mage::getModel('catalog/product')->load($previd);
    $prevpos = $curpos;
    while (!$product->isVisibleInCatalog()) {
    $prevpos += 1;
    $nextid = isset($plist[$prevpos])? $plist[$prevpos] : $current_pid;
    $product = Mage::getModel('catalog/product')->load($nextid);
    }
    $prev_url = $product->getProductUrl();
    // get link for next product
    $nextid = isset($plist[$curpos-1])? $plist[$curpos-1] : $current_pid;
    $product = Mage::getModel('catalog/product')->load($nextid);
    $nextpos = $curpos;
    while (!$product->isVisibleInCatalog()) {
    $nextpos -= 1;
    $nextid = isset($plist[$nextpos])? $plist[$nextpos] : $current_pid;
    $product = Mage::getModel('catalog/product')->load($nextid);
    }
    $next_url = $product->getProductUrl();
    // get link for current category
    $more_url = $_ccat->getUrl();
    ?>
    ```
  3. hightemp revised this gist Jul 6, 2012. 1 changed file with 45 additions and 0 deletions.
    45 changes: 45 additions & 0 deletions gistfile1.md
    Original file line number Diff line number Diff line change
    @@ -965,4 +965,49 @@ TRUNCATE `eav_entity_store`;
    ALTER TABLE `eav_entity_store` AUTO_INCREMENT=1;

    SET FOREIGN_KEY_CHECKS=1;
    ```

    #Product navigation (getting previous and next items)
    ```php
    <div id="product-navigation">
    <?php
    /**
    * Determine the previous/next link and link to current category
    */
    $_ccat = $this->helper('catalog/data')->getCategory();
    $ppos = $_ccat->getProductsPosition();
    $current_pid = $this->helper('catalog/data')->getProduct()->getId();
    // build array from products positions
    $plist = array();
    foreach ($ppos as $pid => $pos) {
    $plist[] = $pid;
    }
    $curpos = array_search($current_pid, $plist);
    // get link for prev product
    $previd = isset($plist[$curpos+1])? $plist[$curpos+1] : $current_pid;
    $product = Mage::getModel('catalog/product')->load($previd);
    $prevpos = $curpos;
    while (!$product->isVisibleInCatalog()) {
    $prevpos += 1;
    $nextid = isset($plist[$prevpos])? $plist[$prevpos] : $current_pid;
    $product = Mage::getModel('catalog/product')->load($nextid);
    }
    $prev_url = $product->getProductUrl();
    // get link for next product
    $nextid = isset($plist[$curpos-1])? $plist[$curpos-1] : $current_pid;
    $product = Mage::getModel('catalog/product')->load($nextid);
    $nextpos = $curpos;
    while (!$product->isVisibleInCatalog()) {
    $nextpos -= 1;
    $nextid = isset($plist[$nextpos])? $plist[$nextpos] : $current_pid;
    $product = Mage::getModel('catalog/product')->load($nextid);
    }
    $next_url = $product->getProductUrl();
    // get link for current category
    $more_url = $_ccat->getUrl();
    ?>
    <a href="<?= $prev_url; ?>">Previous</a>
    <a href="<?= $more_url; ?>">To Category</a>
    <a href="<?= $next_url; ?>">Next</a>
    </div>
    ```
  4. hightemp revised this gist Apr 27, 2012. 1 changed file with 99 additions and 0 deletions.
    99 changes: 99 additions & 0 deletions gistfile1.md
    Original file line number Diff line number Diff line change
    @@ -866,4 +866,103 @@ $result["cart_count"] = Mage::helper('checkout/cart')->getSummaryCount();

    ```php
    (int) Mage::getModel('cataloginventory/stock_item')->loadByProduct($_product)->getQty();
    ```

    ## Clear all orders

    ```sql
    -- here are the tables modified for 1.5.0.1

    SET FOREIGN_KEY_CHECKS=0;

    TRUNCATE `sales_flat_order`;
    TRUNCATE `sales_flat_order_address`;
    TRUNCATE `sales_flat_order_grid`;
    TRUNCATE `sales_flat_order_item`;
    TRUNCATE `sales_flat_order_status_history`;
    TRUNCATE `sales_flat_quote`;
    TRUNCATE `sales_flat_quote_address`;
    TRUNCATE `sales_flat_quote_address_item`;
    TRUNCATE `sales_flat_quote_item`;
    TRUNCATE `sales_flat_quote_item_option`;
    TRUNCATE `sales_flat_order_payment`;
    TRUNCATE `sales_flat_quote_payment`;
    TRUNCATE `sales_flat_shipment`;
    TRUNCATE `sales_flat_shipment_item`;
    TRUNCATE `sales_flat_shipment_grid`;
    TRUNCATE `sales_flat_invoice`;
    TRUNCATE `sales_flat_invoice_grid`;
    TRUNCATE `sales_flat_invoice_item`;
    TRUNCATE `sendfriend_log`;
    TRUNCATE `tag`;
    TRUNCATE `tag_relation`;
    TRUNCATE `tag_summary`;
    TRUNCATE `wishlist`;
    TRUNCATE `log_quote`;
    TRUNCATE `report_event`;

    ALTER TABLE `sales_flat_order` AUTO_INCREMENT=1;
    ALTER TABLE `sales_flat_order_address` AUTO_INCREMENT=1;
    ALTER TABLE `sales_flat_order_grid` AUTO_INCREMENT=1;
    ALTER TABLE `sales_flat_order_item` AUTO_INCREMENT=1;
    ALTER TABLE `sales_flat_order_status_history` AUTO_INCREMENT=1;
    ALTER TABLE `sales_flat_quote` AUTO_INCREMENT=1;
    ALTER TABLE `sales_flat_quote_address` AUTO_INCREMENT=1;
    ALTER TABLE `sales_flat_quote_address_item` AUTO_INCREMENT=1;
    ALTER TABLE `sales_flat_quote_item` AUTO_INCREMENT=1;
    ALTER TABLE `sales_flat_quote_item_option` AUTO_INCREMENT=1;
    ALTER TABLE `sendfriend_log` AUTO_INCREMENT=1;
    ALTER TABLE `sales_flat_order_payment` AUTO_INCREMENT=1;
    ALTER TABLE `sales_flat_quote_payment` AUTO_INCREMENT=1;
    ALTER TABLE `sales_flat_shipment` AUTO_INCREMENT=1;
    ALTER TABLE `sales_flat_shipment_item` AUTO_INCREMENT=1;
    ALTER TABLE `sales_flat_invoice` AUTO_INCREMENT=1;
    ALTER TABLE `sales_flat_invoice_grid` AUTO_INCREMENT=1;
    ALTER TABLE `sales_flat_invoice_item` AUTO_INCREMENT=1;
    ALTER TABLE `sales_flat_shipment_grid` AUTO_INCREMENT=1;
    ALTER TABLE `tag` AUTO_INCREMENT=1;
    ALTER TABLE `tag_relation` AUTO_INCREMENT=1;
    ALTER TABLE `tag_summary` AUTO_INCREMENT=1;
    ALTER TABLE `wishlist` AUTO_INCREMENT=1;
    ALTER TABLE `log_quote` AUTO_INCREMENT=1;
    ALTER TABLE `report_event` AUTO_INCREMENT=1;

    -- lets reset customers
    TRUNCATE `customer_address_entity`;
    TRUNCATE `customer_address_entity_datetime`;
    TRUNCATE `customer_address_entity_decimal`;
    TRUNCATE `customer_address_entity_int`;
    TRUNCATE `customer_address_entity_text`;
    TRUNCATE `customer_address_entity_varchar`;
    TRUNCATE `customer_entity`;
    TRUNCATE `customer_entity_datetime`;
    TRUNCATE `customer_entity_decimal`;
    TRUNCATE `customer_entity_int`;
    TRUNCATE `customer_entity_text`;
    TRUNCATE `customer_entity_varchar`;
    TRUNCATE `log_customer`;
    TRUNCATE `log_visitor`;
    TRUNCATE `log_visitor_info`;

    ALTER TABLE `customer_address_entity` AUTO_INCREMENT=1;
    ALTER TABLE `customer_address_entity_datetime` AUTO_INCREMENT=1;
    ALTER TABLE `customer_address_entity_decimal` AUTO_INCREMENT=1;
    ALTER TABLE `customer_address_entity_int` AUTO_INCREMENT=1;
    ALTER TABLE `customer_address_entity_text` AUTO_INCREMENT=1;
    ALTER TABLE `customer_address_entity_varchar` AUTO_INCREMENT=1;
    ALTER TABLE `customer_entity` AUTO_INCREMENT=1;
    ALTER TABLE `customer_entity_datetime` AUTO_INCREMENT=1;
    ALTER TABLE `customer_entity_decimal` AUTO_INCREMENT=1;
    ALTER TABLE `customer_entity_int` AUTO_INCREMENT=1;
    ALTER TABLE `customer_entity_text` AUTO_INCREMENT=1;
    ALTER TABLE `customer_entity_varchar` AUTO_INCREMENT=1;
    ALTER TABLE `log_customer` AUTO_INCREMENT=1;
    ALTER TABLE `log_visitor` AUTO_INCREMENT=1;
    ALTER TABLE `log_visitor_info` AUTO_INCREMENT=1;

    -- Now, lets Reset all ID counters
    TRUNCATE `eav_entity_store`;
    ALTER TABLE `eav_entity_store` AUTO_INCREMENT=1;

    SET FOREIGN_KEY_CHECKS=1;
    ```
  5. hightemp revised this gist Apr 23, 2012. 1 changed file with 2 additions and 2 deletions.
    4 changes: 2 additions & 2 deletions gistfile1.md
    Original file line number Diff line number Diff line change
    @@ -793,7 +793,7 @@ UPDATE admin_user SET password=CONCAT(MD5('qX[password]'), ':qX') WHERE username
    ?>
    ```

    ## Remove a product from cart ##
    ## Remove product from cart ##

    ```php
    <?php
    @@ -831,7 +831,7 @@ UPDATE admin_user SET password=CONCAT(MD5('qX[password]'), ':qX') WHERE username
    ?>
    ```

    ## Is a product in cart? ##
    ## Is product in cart? ##

    ```php
    <?php
  6. hightemp revised this gist Apr 23, 2012. 1 changed file with 6 additions and 1 deletion.
    7 changes: 6 additions & 1 deletion gistfile1.md
    Original file line number Diff line number Diff line change
    @@ -841,7 +841,7 @@ UPDATE admin_user SET password=CONCAT(MD5('qX[password]'), ':qX') WHERE username
    {
    $productIds = Mage::helper('checkout/cart')->getCart()->getProductIds();

    if (in_array($_product->getId(), $productIds))
    if (in_array($product_id, $productIds))
    {
    return true;
    }
    @@ -861,4 +861,9 @@ UPDATE admin_user SET password=CONCAT(MD5('qX[password]'), ':qX') WHERE username
    ```php
    $result["cart_html"] = $app->getLayout()->getBlockSingleton('checkout/cart_sidebar')->setTemplate("checkout/cart/header.cart.phtml")->toHtml();
    $result["cart_count"] = Mage::helper('checkout/cart')->getSummaryCount();
    ```
    ## Get product quantity ##

    ```php
    (int) Mage::getModel('cataloginventory/stock_item')->loadByProduct($_product)->getQty();
    ```
  7. hightemp revised this gist Apr 16, 2012. 1 changed file with 7 additions and 17 deletions.
    24 changes: 7 additions & 17 deletions gistfile1.md
    Original file line number Diff line number Diff line change
    @@ -664,25 +664,15 @@ function createProduct($data)

    $fileName = Mage::getBaseDir('media').'/import/'.basename($data['image']);

    $mediaArray = array
    (
    'thumbnail' => $fileName,
    'small_image' => $fileName,
    'image' => $fileName,
    );

    if (is_file($fileName))
    if (is_file($filePath))
    {
    foreach ($mediaArray as $imageType => $fileName)
    try
    {
    try
    {
    $product->addImageToMediaGallery($fileName, $imageType, false, false);
    }
    catch (Exception $e)
    {
    echo $e->getMessage();
    }
    $product->addImageToMediaGallery($fileName, array('thumbnail','small_image','image'), false, false);
    }
    catch (Exception $e)
    {
    echo $e->getMessage();
    }
    }

  8. hightemp revised this gist Apr 15, 2012. 1 changed file with 5 additions and 0 deletions.
    5 changes: 5 additions & 0 deletions gistfile1.md
    Original file line number Diff line number Diff line change
    @@ -866,4 +866,9 @@ UPDATE admin_user SET password=CONCAT(MD5('qX[password]'), ':qX') WHERE username
    ?>
    ```

    ## Get header cart html and products count ##

    ```php
    $result["cart_html"] = $app->getLayout()->getBlockSingleton('checkout/cart_sidebar')->setTemplate("checkout/cart/header.cart.phtml")->toHtml();
    $result["cart_count"] = Mage::helper('checkout/cart')->getSummaryCount();
    ```
  9. hightemp revised this gist Apr 15, 2012. 1 changed file with 1 addition and 1 deletion.
    2 changes: 1 addition & 1 deletion gistfile1.md
    Original file line number Diff line number Diff line change
    @@ -807,7 +807,7 @@ UPDATE admin_user SET password=CONCAT(MD5('qX[password]'), ':qX') WHERE username

    ```php
    <?php
    function removeProductToCart($product_id)
    function removeProductFromCart($product_id)
    {
    try
    {
  10. hightemp revised this gist Apr 15, 2012. 1 changed file with 97 additions and 1 deletion.
    98 changes: 97 additions & 1 deletion gistfile1.md
    Original file line number Diff line number Diff line change
    @@ -770,4 +770,100 @@ UPDATE admin_user SET password=CONCAT(MD5('qX[password]'), ':qX') WHERE username
    * [password] - user password
    * [username] - user name
    **/
    ```
    ```

    ## Add a new product to cart ##

    ```php
    <?php
    function addProductToCart($product_id, $count)
    {
    try
    {
    $session = Mage::getSingleton('core/session', array('name'=>'frontend'));
    $cart = Mage::helper('checkout/cart')->getCart();

    $product = Mage::getModel('catalog/product')->load($product_id);
    $cart->addProduct($product, $count);

    $session->setLastAddedProductId($product->getId());
    $session->setCartWasUpdated(true);

    $cart->save();

    return true;
    }
    catch (Exception $e)
    {
    Mage::log("[addProductToCart] ".$e->getMessage());
    }

    return false;
    }
    ?>
    ```

    ## Remove a product from cart ##

    ```php
    <?php
    function removeProductToCart($product_id)
    {
    try
    {
    $session = Mage::getSingleton('core/session', array('name'=>'frontend'));
    $cart = Mage::helper('checkout/cart')->getCart();
    $cart->getProductIds();
    $items = $cart->getItems();

    foreach ($items as $item)
    {
    if ($item->getProduct()->getId() == $product_id)
    {
    $cart->removeItem($item->getId());
    break;
    }
    }

    $session->setCartWasUpdated(true);

    $cart->save();

    return true;
    }
    catch (Exception $e)
    {
    Mage::log("[removeProductToCart] ".$e->getMessage());
    }

    return false;
    }
    ?>
    ```

    ## Is a product in cart? ##

    ```php
    <?php
    function isProductInCart($product_id)
    {
    try
    {
    $productIds = Mage::helper('checkout/cart')->getCart()->getProductIds();

    if (in_array($_product->getId(), $productIds))
    {
    return true;
    }
    }
    catch (Exception $e)
    {
    Mage::log("[isProductInCart] ".$e->getMessage());
    }

    return false;
    }
    ?>
    ```


  11. hightemp revised this gist Apr 15, 2012. 1 changed file with 5 additions and 3 deletions.
    8 changes: 5 additions & 3 deletions gistfile1.md
    Original file line number Diff line number Diff line change
    @@ -765,7 +765,9 @@ $role->save();

    ```sql
    UPDATE admin_user SET password=CONCAT(MD5('qX[password]'), ':qX') WHERE username='[username]';
    ### where:
    ### [password] - user password
    ### [username] - user name
    /**
    * where:
    * [password] - user password
    * [username] - user name
    **/
    ```
  12. hightemp revised this gist Apr 15, 2012. 1 changed file with 29 additions and 0 deletions.
    29 changes: 29 additions & 0 deletions gistfile1.md
    Original file line number Diff line number Diff line change
    @@ -739,4 +739,33 @@ if(is_array($products))
    }
    }
    ?>
    ```

    ## Add a new user ##

    ```php
    <?php
    $user = Mage::getModel("admin/user")
    ->setUsername('username')
    ->setFirstname('Firstname')
    ->setLastname('Lastname')
    ->setEmail('username@example.com')
    ->setPassword('demopass123')
    ->save();
    $role = Mage::getModel("admin/role");
    $role->setParent_id(1);
    $role->setTree_level(1);
    $role->setRole_type('U');
    $role->setUser_id($user->getId());
    $role->save();
    ?>
    ```

    ## Change user's password ##

    ```sql
    UPDATE admin_user SET password=CONCAT(MD5('qX[password]'), ':qX') WHERE username='[username]';
    ### where:
    ### [password] - user password
    ### [username] - user name
    ```
  13. hightemp revised this gist Apr 15, 2012. 1 changed file with 25 additions and 0 deletions.
    25 changes: 25 additions & 0 deletions gistfile1.md
    Original file line number Diff line number Diff line change
    @@ -714,4 +714,29 @@ function createProduct($data)
    return false;
    }
    ?>
    ```

    ## Remove all products from store with id 1 ##

    ```php
    <?php
    $products = Mage::getResourceModel('catalog/product_collection')->setStoreId(1)->getAllIds();

    if(is_array($products))
    {
    foreach ($products as $key => $productId)
    {
    try
    {
    $product = Mage::getSingleton('catalog/product')->load($productId);
    Mage::dispatchEvent('catalog_controller_product_delete', array('product' => $product));
    $product->delete();
    }
    catch (Exception $e)
    {
    echo "<br/>Can't delete product w/ id: $productId";
    }
    }
    }
    ?>
    ```
  14. hightemp revised this gist Apr 14, 2012. 1 changed file with 56 additions and 1 deletion.
    57 changes: 56 additions & 1 deletion gistfile1.md
    Original file line number Diff line number Diff line change
    @@ -573,6 +573,61 @@ if ($parentId) {
    ?>
    ```

    ## Add a new category or update existing ##

    ```php
    <?php
    function createCategory($data, $parentId=false, $storeId=false)
    {
    echo "create category {$data['name']}\n";

    $category = Mage::getModel('catalog/category')->loadByAttribute('name', $data['name']);

    if (!$storeId)
    {
    $storeId = Mage_Core_Model_App::ADMIN_STORE_ID;
    }

    if (!$parentId)
    {
    $parentId = Mage_Catalog_Model_Category::TREE_ROOT_ID;

    if ($storeId)
    {
    $parentId = Mage::app()->getStore($storeId)->getRootCategoryId();
    }
    }

    if (!$category)
    {
    $category = new Mage_Catalog_Model_Category();

    $parentCategory = Mage::getModel('catalog/category')->load($parentId);
    $category->setPath($parentCategory->getPath());
    }

    $category->setName($data['name']);
    $category->setUrlKey(isset($data['urlKey']) ? $data['urlKey'] : $data['name']);
    $category->setIsActive(isset($data['isActive']) ? $data['isActive'] : 1);
    $category->setDisplayMode('PRODUCTS_AND_PAGE');
    $category->setIsAnchor(0);

    try
    {
    $category->save();
    echo "Success\n";
    return $category->getId();
    }
    catch (Exception $e)
    {
    echo "Exception: ".$e->getMessage()."\n";
    }

    return false;
    }
    ?>
    ```

    ## Add a new product or update existing ##

    ```php
    @@ -659,4 +714,4 @@ function createProduct($data)
    return false;
    }
    ?>
    ```
    ```
  15. hightemp revised this gist Apr 14, 2012. 1 changed file with 11 additions and 14 deletions.
    25 changes: 11 additions & 14 deletions gistfile1.md
    Original file line number Diff line number Diff line change
    @@ -607,7 +607,7 @@ function createProduct($data)
    );
    }

    $fileName = basename($data['image']);
    $fileName = Mage::getBaseDir('media').'/import/'.basename($data['image']);

    $mediaArray = array
    (
    @@ -616,20 +616,18 @@ function createProduct($data)
    'image' => $fileName,
    );

    foreach ($mediaArray as $imageType => $fileName)
    if (is_file($fileName))
    {
    $filePath = Mage::getBaseDir('media').'/import/'.$fileName;

    if (!is_file($filePath))
    continue;

    try
    foreach ($mediaArray as $imageType => $fileName)
    {
    $product->addImageToMediaGallery($filePath, $imageType, false, false);
    }
    catch (Exception $e)
    {
    echo $e->getMessage();
    try
    {
    $product->addImageToMediaGallery($fileName, $imageType, false, false);
    }
    catch (Exception $e)
    {
    echo $e->getMessage();
    }
    }
    }

    @@ -662,4 +660,3 @@ function createProduct($data)
    }
    ?>
    ```

  16. hightemp revised this gist Apr 14, 2012. 1 changed file with 164 additions and 1 deletion.
    165 changes: 164 additions & 1 deletion gistfile1.md
    Original file line number Diff line number Diff line change
    @@ -499,4 +499,167 @@ $parentIds = Mage::getResourceSingleton('catalog/product_type_configurable')
    $product = Mage::getModel('catalog/product')->load($parentIds[0]);
    echo $product->getId(); // ID = 462 (aka, Parent of 465)
    ?>
    ```
    ```

    ## Create a category using parent id ##

    ```php
    <?php
    /* supply parent id */
    $parentId = '10';

    $category = new Mage_Catalog_Model_Category();
    $category->setName('Storybloks');
    $category->setUrlKey('new-category');
    $category->setIsActive(1);
    $category->setDisplayMode('PRODUCTS');
    $category->setIsAnchor(0);

    $parentCategory = Mage::getModel('catalog/category')->load($parentId);
    $category->setPath($parentCategory->getPath());

    $category->save();
    unset($category);
    ?>
    ```

    ## Create a category within another category, which you know by name ##

    ```php
    <?php
    $parentId = null;

    $collection = Mage::getModel('catalog/category')->getCollection()
    ->setStoreId('0')
    ->addAttributeToSelect('name')
    ->addAttributeToSelect('is_active');
    foreach ($collection as $cat) {
    if ($cat->getName() == 'Storybloks Parent Category') {
    $parentId = $cat->getId();
    break;
    }
    }

    if ($parentId) {

    $urlKey = 'new-category';

    $currentCategory = Mage::getModel('catalog/category')->getCollection()
    ->addFieldToFilter('url_key', $urlKey)
    ->setCurPage(1)
    ->setPageSize(1)
    ->getFirstItem();

    if (!($currentCategory && $currentCategory->getId())) {
    $category = Mage::getModel('catalog/category');
    $category->setName('Storybloks Subcategory')
    ->setUrlKey($urlKey)
    ->setIsActive(1)
    ->setDisplayMode('PRODUCTS')
    ->setIsAnchor(0)
    ->setDescription('This is a storybloks subcategory')
    ->setCustomDesignApply(1)
    ->setCustomDesign('storybloks/new-category-style') /* create this template and layout
    in your design directory */
    ->setAttributeSetId($category->getDefaultAttributeSetId());

    $parentCategory = Mage::getModel('catalog/category')->load($parentId);
    $category->setPath($parentCategory->getPath());

    $category->save();
    unset($category);
    }
    }
    ?>
    ```

    ## Add a new product or update existing ##

    ```php
    <?php
    function createProduct($data)
    {
    echo "create product {$data['name']} {$data['price']}\n";

    $product = Mage::getModel('catalog/product')->loadByAttribute('sku', $data['sku']);

    if (!$product)
    {
    $product = new Mage_Catalog_Model_Product();

    $product->setTypeId('simple');
    $product->setWeight(1.0000);
    $product->setVisibility(Mage_Catalog_Model_Product_Visibility::VISIBILITY_BOTH);
    $product->setStatus(1);
    $product->setSku($data['sku']);
    $product->setTaxClassId(0);
    $product->setWebsiteIDs(array(1));
    $product->setStoreIDs(array(1));

    $product->setStockData
    (
    array
    (
    'is_in_stock' => 1,
    'qty' => $data['count'],
    'manage_stock' => 0,
    )
    );
    }

    $fileName = basename($data['image']);

    $mediaArray = array
    (
    'thumbnail' => $fileName,
    'small_image' => $fileName,
    'image' => $fileName,
    );

    foreach ($mediaArray as $imageType => $fileName)
    {
    $filePath = Mage::getBaseDir('media').'/import/'.$fileName;

    if (!is_file($filePath))
    continue;

    try
    {
    $product->addImageToMediaGallery($filePath, $imageType, false, false);
    }
    catch (Exception $e)
    {
    echo $e->getMessage();
    }
    }

    $product->setAttributeSetId(4);
    $product->setName($data['name']);
    $product->setCategoryIds($data['categoryIds']);
    $product->setKeywords($data['keywords']);
    $product->setDescription($data['description']);
    $product->setShortDescription($data['shortDescription']);
    $product->setPrice($data['price']);

    /** Yandex.Market **/
    $product->setYmlExport(1);
    $product->setBid(0);
    $product->setCBid(0);
    $product->setModel($data['name']);

    try
    {
    $product->save();
    echo "Success\n";
    return $product->getId();
    }
    catch (Exception $e)
    {
    echo "Exception: ".$e->getMessage()."\n";
    }

    return false;
    }
    ?>
    ```

  17. @borriglione borriglione revised this gist Mar 29, 2012. No changes.
  18. @quafzi quafzi revised this gist Mar 29, 2012. 1 changed file with 2 additions and 2 deletions.
    4 changes: 2 additions & 2 deletions gistfile1.md
    Original file line number Diff line number Diff line change
    @@ -41,8 +41,8 @@ $_category_url = $_category->getUrl();

    ```php
    <?php
    $_product_1 = Mage::getModel('catalog/product')->load(12);
    $_product_2 = Mage::getModel('catalog/product')->loadByAttribute('sku','cordoba-classic-6-String-guitar');
    $_product_1 = Mage::getModel('catalog/product')->load(12); // won't include a valid stock item
    $_product_2 = Mage::getModel('catalog/product')->loadByAttribute('sku','cordoba-classic-6-String-guitar'); // will include a valid stock item
    ?>
    ```

  19. @davidalexander davidalexander revised this gist Oct 18, 2011. 1 changed file with 12 additions and 0 deletions.
    12 changes: 12 additions & 0 deletions gistfile1.md
    Original file line number Diff line number Diff line change
    @@ -487,4 +487,16 @@ TRUNCATE TABLE `catalog_product_website`;
    TRUNCATE TABLE `catalog_product_entity`;
    TRUNCATE TABLE `cataloginventory_stock_item`;
    TRUNCATE TABLE `cataloginventory_stock_status`;
    ```

    ## Getting Configurable Product from Simple Product ID in Magento 1.5+ ##

    ```php
    <?php
    $simpleProductId = 465;
    $parentIds = Mage::getResourceSingleton('catalog/product_type_configurable')
    ->getParentIdsByChild($simpleProductId);
    $product = Mage::getModel('catalog/product')->load($parentIds[0]);
    echo $product->getId(); // ID = 462 (aka, Parent of 465)
    ?>
    ```
  20. @davidalexander davidalexander revised this gist Sep 8, 2011. 1 changed file with 1 addition and 1 deletion.
    2 changes: 1 addition & 1 deletion gistfile1.md
    Original file line number Diff line number Diff line change
    @@ -455,7 +455,7 @@ OR

    ## Delete all products ##

    ``sql
    ```sql
    TRUNCATE TABLE `catalog_product_bundle_option`;
    TRUNCATE TABLE `catalog_product_bundle_option_value`;
    TRUNCATE TABLE `catalog_product_bundle_selection`;
  21. @davidalexander davidalexander revised this gist Sep 8, 2011. 1 changed file with 36 additions and 1 deletion.
    37 changes: 36 additions & 1 deletion gistfile1.md
    Original file line number Diff line number Diff line change
    @@ -440,7 +440,6 @@ if($_product->getTypeId() == "configurable") {
    ?>
    ```


    ## Turn template hints on/off via database ##

    ```sql
    @@ -452,4 +451,40 @@ WHERE
    `path` = "dev/debug/template_hints"
    OR
    `path` = "dev/debug/template_hints_blocks";
    ```

    ## Delete all products ##

    ``sql
    TRUNCATE TABLE `catalog_product_bundle_option`;
    TRUNCATE TABLE `catalog_product_bundle_option_value`;
    TRUNCATE TABLE `catalog_product_bundle_selection`;
    TRUNCATE TABLE `catalog_product_entity_datetime`;
    TRUNCATE TABLE `catalog_product_entity_decimal`;
    TRUNCATE TABLE `catalog_product_entity_gallery`;
    TRUNCATE TABLE `catalog_product_entity_int`;
    TRUNCATE TABLE `catalog_product_entity_media_gallery`;
    TRUNCATE TABLE `catalog_product_entity_media_gallery_value`;
    TRUNCATE TABLE `catalog_product_entity_text`;
    TRUNCATE TABLE `catalog_product_entity_tier_price`;
    TRUNCATE TABLE `catalog_product_entity_varchar`;
    TRUNCATE TABLE `catalog_product_link`;
    TRUNCATE TABLE `catalog_product_link_attribute_decimal`;
    TRUNCATE TABLE `catalog_product_link_attribute_int`;
    TRUNCATE TABLE `catalog_product_link_attribute_varchar`;
    TRUNCATE TABLE `catalog_product_option`;
    TRUNCATE TABLE `catalog_product_option_price`;
    TRUNCATE TABLE `catalog_product_option_title`;
    TRUNCATE TABLE `catalog_product_option_type_price`;
    TRUNCATE TABLE `catalog_product_option_type_title`;
    TRUNCATE TABLE `catalog_product_option_type_value`;
    TRUNCATE TABLE `catalog_product_super_attribute`;
    TRUNCATE TABLE `catalog_product_super_attribute_label`;
    TRUNCATE TABLE `catalog_product_super_attribute_pricing`;
    TRUNCATE TABLE `catalog_product_super_link`;
    TRUNCATE TABLE `catalog_product_enabled_index`;
    TRUNCATE TABLE `catalog_product_website`;
    TRUNCATE TABLE `catalog_product_entity`;
    TRUNCATE TABLE `cataloginventory_stock_item`;
    TRUNCATE TABLE `cataloginventory_stock_status`;
    ```
  22. @davidalexander davidalexander revised this gist Aug 18, 2011. 1 changed file with 14 additions and 0 deletions.
    14 changes: 14 additions & 0 deletions gistfile1.md
    Original file line number Diff line number Diff line change
    @@ -438,4 +438,18 @@ if($_product->getTypeId() == "configurable") {
    <?php
    }
    ?>
    ```


    ## Turn template hints on/off via database ##

    ```sql
    UPDATE
    `core_config_data`
    SET
    `value` = 0
    WHERE
    `path` = "dev/debug/template_hints"
    OR
    `path` = "dev/debug/template_hints_blocks";
    ```
  23. @davidalexander davidalexander revised this gist Jul 31, 2011. 1 changed file with 26 additions and 0 deletions.
    26 changes: 26 additions & 0 deletions gistfile1.md
    Original file line number Diff line number Diff line change
    @@ -412,4 +412,30 @@ foreach ($session->getQuote()->getAllItems() as $item) {
    Zend_Debug::dump($item->debug());
    }
    ?>
    ```

    ## Get Simple Products of a Configurable Product ##

    ```php
    <?php
    if($_product->getTypeId() == "configurable") {
    $ids = $_product->getTypeInstance()->getUsedProductIds();
    ?>
    <ul>
    <?php
    foreach ($ids as $id) {
    $simpleproduct = Mage::getModel('catalog/product')->load($id);
    ?>
    <li>
    <?php
    echo $simpleproduct->getName() . " - " . (int)Mage::getModel('cataloginventory/stock_item')->loadByProduct($simpleproduct)->getQty();
    ?>
    </li>
    <?php
    }
    ?>
    </ul>
    <?php
    }
    ?>
    ```
  24. @davidalexander davidalexander revised this gist Jul 19, 2011. 1 changed file with 16 additions and 0 deletions.
    16 changes: 16 additions & 0 deletions gistfile1.md
    Original file line number Diff line number Diff line change
    @@ -396,4 +396,20 @@ if ($attr = $_product->getResource()->getAttribute('color')):
    echo $attr->getFrontend()->getValue($_product); // will display: red, green
    endif;
    ?>
    ```

    ## Cart Data ##

    ```php
    <?php
    $cart = Mage::getModel('checkout/cart')->getQuote()->getData();
    print_r($cart);
    $cart = Mage::helper('checkout/cart')->getCart()->getItemsCount();
    print_r($cart);
    $session = Mage::getSingleton('checkout/session');
    foreach ($session->getQuote()->getAllItems() as $item) {
    echo $item->getName();
    Zend_Debug::dump($item->debug());
    }
    ?>
    ```
  25. @davidalexander davidalexander revised this gist Jul 19, 2011. 1 changed file with 10 additions and 0 deletions.
    10 changes: 10 additions & 0 deletions gistfile1.md
    Original file line number Diff line number Diff line change
    @@ -385,5 +385,15 @@ $_product->getThisattribute();
    $_product->getAttributeText('thisattribute');
    $_product->getResource()->getAttribute('thisattribute')->getFrontend()->getValue($_product);
    $_product->getData('thisattribute');
    // The following returns the option IDs for an attribute that is a multiple-select field:
    $_product->getData('color'); // i.e. 456,499
    // The following returns the attribute object, and instance of Mage_Catalog_Model_Resource_Eav_Attribute:
    $_product->getResource()->getAttribute('color'); // instance of Mage_Catalog_Model_Resource_Eav_Attribute
    // The following returns an array of the text values for the attribute:
    $_product->getAttributeText('color') // Array([0]=>'red', [1]=>'green')
    // The following returns the text for the attribute
    if ($attr = $_product->getResource()->getAttribute('color')):
    echo $attr->getFrontend()->getValue($_product); // will display: red, green
    endif;
    ?>
    ```
  26. @davidalexander davidalexander revised this gist Jul 17, 2011. 1 changed file with 6 additions and 2 deletions.
    8 changes: 6 additions & 2 deletions gistfile1.md
    Original file line number Diff line number Diff line change
    @@ -113,10 +113,14 @@ to `page.xml`, and then add the `mytemplate.phtml` file. Any block added to the
    <?php $logged_in = Mage::getSingleton('customer/session')->isLoggedIn(); // (boolean) ?>
    ```

    ## Get the current category ##
    ## Get the current category/product/cms page ##

    ```php
    <?php $currentCategory = Mage::registry('current_category'); ?>
    <?php
    $currentCategory = Mage::registry('current_category');
    $currentProduct = Mage::registry('current_product');
    $currentCmsPage = Mage::registry('cms_page');
    ?>
    ```

    ## Run Magento Code Externally ##
  27. @davidalexander davidalexander revised this gist Jul 17, 2011. 1 changed file with 12 additions and 1 deletion.
    13 changes: 12 additions & 1 deletion gistfile1.md
    Original file line number Diff line number Diff line change
    @@ -1,7 +1,7 @@
    # Magento Snippets #

    ## Download extension manually using pear/mage ##
    Pear for 1.4, mage for 1.5. Goes into /downloader/.cache/community/
    Pear for 1.4, mage for 1.5. File downloaded into /downloader/.cache/community/

    ./pear download magento-community/Shipping_Agent
    ./mage download community Shipping_Agent
    @@ -371,4 +371,15 @@ $_countries = Mage::getResourceModel('directory/country_collection')
    'values' => Mage::getModel('adminhtml/system_config_source_country')->toOptionArray(),
    ));
    ?>
    ```

    ## Return Product Attributes ##

    ```php
    <?php
    $_product->getThisattribute();
    $_product->getAttributeText('thisattribute');
    $_product->getResource()->getAttribute('thisattribute')->getFrontend()->getValue($_product);
    $_product->getData('thisattribute');
    ?>
    ```
  28. @davidalexander davidalexander revised this gist Jul 17, 2011. 1 changed file with 13 additions and 1 deletion.
    14 changes: 13 additions & 1 deletion gistfile1.md
    Original file line number Diff line number Diff line change
    @@ -46,7 +46,17 @@ $_product_2 = Mage::getModel('catalog/product')->loadByAttribute('sku','cordoba-
    ?>
    ```

    ## Get Configurable product’s Children’s (simple product) custom attributes ##

    ## Get Configurable product's Child products ##

    ```php
    <?php
    // input is $_product and result is iterating child products
    $childProducts = Mage::getModel('catalog/product_type_configurable')->getUsedProducts(null, $product);
    ?>
    ```

    ## Get Configurable product's Children's (simple product) custom attributes ##

    ```php
    <?php
    @@ -282,6 +292,7 @@ if($_productCollection->count()) {
    echo $this->htmlEscape($_product->getName());
    endforeach;
    }
    ?>
    ```

    ## Update all subscribers into a customer group (e.g. 5) ##
    @@ -328,6 +339,7 @@ $countryList = Mage::getResourceModel('directory/country_collection')
    echo '<pre>';
    print_r( $countryList);
    exit('</pre>');
    ?>
    ```

    ## Create a Country Drop Down in the Frontend of Magento ##
  29. @davidalexander davidalexander revised this gist Jul 17, 2011. 1 changed file with 1 addition and 0 deletions.
    1 change: 1 addition & 0 deletions gistfile1.md
    Original file line number Diff line number Diff line change
    @@ -2,6 +2,7 @@

    ## Download extension manually using pear/mage ##
    Pear for 1.4, mage for 1.5. Goes into /downloader/.cache/community/

    ./pear download magento-community/Shipping_Agent
    ./mage download community Shipping_Agent

  30. @davidalexander davidalexander revised this gist Jul 17, 2011. 1 changed file with 1 addition and 1 deletion.
    2 changes: 1 addition & 1 deletion gistfile1.md
    Original file line number Diff line number Diff line change
    @@ -1,7 +1,7 @@
    # Magento Snippets #

    ## Download extension manually using pear/mage ##

    Pear for 1.4, mage for 1.5. Goes into /downloader/.cache/community/
    ./pear download magento-community/Shipping_Agent
    ./mage download community Shipping_Agent