Magento create dropdown from product attribute option

Here a simple but complete example to create a dropdown list for a product attribute

//retrieve informations
$attribute_model        = Mage::getModel('eav/entity_attribute');
$attribute_code         = $attribute_model->getIdByCode('catalog_product', 'audience');
$attribute              = $attribute_model->load($attribute_code);
$attribute_options_model= Mage::getModel('eav/entity_attribute_source_table') ;
$attribute_table        = $attribute_options_model->setAttribute($attribute);
$options                = $attribute_options_model->getAllOptions(false);

//display them
echo '<select id="audience" class="select" name="audience">';
foreach($options as $option)
{
    echo '<option value="'.$option['value'].'">'.$helper->__($option['label']).'</option>';
}
echo '</select>';

Magento load template from controller

To load html content of a template inside a controller, for example for ajax response, you can do :

$block = $this->getLayout()->createBlock('adin_admin/adminhtml_scheduletcrender')->setTemplate('admin/scheduletcrender.phtml');
$block->assign(array('ateliers' => $ateliers));
$html = $block->toHtml();
$response = array('html' => $html);
     
//send response as json
$this->getResponse()->setHeader('Content-type', 'application/json');
$this->getResponse()->setBody(Mage::helper('core')->jsonEncode($response));

Magento – update attribute parameters programmatically

This is how you can update attribute parameters, the one saved in catalog_eav_attribute table

In this exemple we will enable the “used_in_product_listing” params of the “code_catalogue” attribute

$attributeId = Mage::getResourceModel('eav/entity_attribute')->getIdByCode('catalog_product','code_catalogue');
if ($attributeId) {
    $attribute = Mage::getModel('catalog/resource_eav_attribute')->load($attributeId);
    $attribute->setUsedInProductListing(1)->save();
}

And that’s all.

Magento – How to get current router module controller action ?

You can easily know “where you are” using these fonctions :

in template / block files

$this->getRequest()->getRouteName();
$this->getRequest()->getModuleName();
$this->getRequest()->getControllerName();
$this->getRequest()->getActionName();

in class files

Mage::app()->getRequest()->getRouteName();
Mage::app()->getRequest()->getModuleName();
Mage::app()->getRequest()->getControllerName();
Mage::app()->getRequest()->getActionName();

Magento SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry ‘000000254’ for key ‘UNQ_SALES_FLAT_ORDER_INCREMENT_ID’

In some cases, customers encounter this error on your website :

SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry '000000254' for key 'UNQ_SALES_FLAT_ORDER_INCREMENT_ID'

You don’t understand and drive you crazy ?
Don’t worry, I will help you.

First, this error probably happend when customer quit violenty the payment page, without canceling, so your order is not “finished” and your quote is not “released” (is_active = 1 in db). Customer come back, recover his quote and try to proceed it again.
The reserved_increment_id is not updated and when magento try to create the order, mySQL give him the previous error.

How a so obvious bug like this can exist ? and why does it crash only on my website, it seems to work fine on other website ?
Let me guest, your client (clients always have weird needs …) ask you to start order number at 0 instead of 100000000, or ask you to put a letter into it.

So, why does this reserved_increment_id is not updated ?
Let check on the function which update the reserved_increment_id field :

// /app/code/core/Mage/Sales/Model/Resource/Quote.php
    /**
     * Check is order increment id use in sales/order table
     *
     * @param int $orderIncrementId
     * @return boolean
     */
    public function isOrderIncrementIdUsed($orderIncrementId)
    {
        $adapter   = $this->_getReadAdapter();
        $bind      = array(':increment_id' => (int)$orderIncrementId);
        $select    = $adapter->select();
        $select->from($this->getTable('sales/order'), 'entity_id')
            ->where('increment_id = :increment_id');
        $entity_id = $adapter->fetchOne($select, $bind);
        if ($entity_id > 0) {
            return true;
        }

        return false;
    }

You see it, the little (int) in this line $bind = array(‘:increment_id’ => (int)$orderIncrementId); ?
This transform your increment_id in your request from “000000254” to “254”, mySQL doesn’t find an order with the increment_id “254” and your quote is not updated.

To fix it, override this function :
In your Sales/etc/config.xml file, add

<global>
  <model>
    <sales_resource>
                <rewrite>
                    <quote>Adin_Sales_Model_Resource_Sales_Quote</quote>
                </rewrite>
            </sales_resource>
   </model>
</global>

And create the new class file /app/code/local/Adin/Sales/Model/Resource/Sales/Quote.php

class Adin_Sales_Model_Resource_Sales_Quote extends Mage_Sales_Model_Resource_Quote {

    /**
     * Check is order increment id use in sales/order table
     *
     * @param int $orderIncrementId
     * @return boolean
     */
    public function isOrderIncrementIdUsed($orderIncrementId)
    {
        $adapter   = $this->_getReadAdapter();
        $bind      = array(':increment_id' => $orderIncrementId);
        $select    = $adapter->select();
        $select->from($this->getTable('sales/order'), 'entity_id')
            ->where('increment_id = :increment_id');
        $entity_id = $adapter->fetchOne($select, $bind);
        if ($entity_id > 0) {
            return true;
        }

        return false;
    }

}

That should do the tricks.

Magento render cms/block with widgets

You create a cms static block (cms/block) and dynamise it with widget, here an example:

 <div class="confirmation">
        <img src="{{skin url='images/image-order.jpg'}}" alt="" />
 </div>

You then render this block :

echo Mage::getModel('cms/block')
            ->setStoreId(Mage::app()->getStore()->getId())
            ->load(self::confirmationCmsBlockName)->render();

But the widget {{skin url=’images/image-order.jpg’}} is not executed and is display as {{skin url=’images/image-order.jpg’}}.

To execute the widget, you need to render as HTML a block and not a model

echo  Mage::app()->getLayout()->createBlock('cms/block')->setBlockId(self::confirmationCmsBlockName)->toHtml();

Magento get simple products from configurable product

This is how you can get all simple products linked from a configurable product

$configurableProduct = Mage::getModel('catalog/product')->load(1); 
$childProducts = Mage::getModel('catalog/product_type_configurable')->getUsedProducts(null,$configurableProduct);   
foreach($childProducts as $child) {
    echo $child->getId();
}

If you only need ids of the child product, you can do this

$childProductsId = Mage::getModel('catalog/product_type_configurable')->getChildrenIds(1);

Magento get configurable product from simple product

If you need to get the configurable product from a simple one, you can do this

$simpleProductId = 666;
$parentIds = Mage::getResourceSingleton('catalog/product_type_configurable')
                  ->getParentIdsByChild($simpleProductId);
$configurableProduct = Mage::getModel('catalog/product')->load($parentIds[0]);
echo $configurableProduct->getId(); 

Make a PDF into magento using zend_pdf

Here my code to generate a PDF file into Magento using the zend_pdf embeded library.

//in my controller
public function prindPdfAction()
{
        $pdf = new Zend_Pdf();
        $page = new Zend_Pdf_Page(Zend_Pdf_Page::SIZE_A4);
        $font = Zend_Pdf_Font::fontWithName(Zend_Pdf_Font::FONT_HELVETICA);
        $page->setFont($font, 12);

        //add a logo
        $image = Mage::getBaseDir('media').'/logo_pdf.jpg';
        if (is_file($image)) {
            $image = Zend_Pdf_Image::imageWithPath($image);
            $x = 20;
            $y = 700;
            $page->drawImage($image, $x, $y, $x + 118, $y + 112);
        }

        //add text
        $page->setFont($font, 16);
        $titre = "Ecole ";
        $page->drawText($titre, 155, $page->getHeight()-85, "UTF-8");

        //add pages to main document
        $pdf->pages[] = $page;

        //generate pdf
        $content =  $pdf->render();

        $fileName = 'details.pdf';
        //send it to the browser to download
        $this->_prepareDownloadResponse($fileName, $content);
}