magento create tier prices programmatically

Here a simple script to create tier prices programmatically

$product = Mage::getModel('catalog/product')->load(904);
$product->setPrice($tarif->getPrix());
    
$tier_price = array();
foreach($tarif->getQtyDetails() as $detail)
{
   $tier_price[] = array(
     'cust_group'    => 32000,
     'website_id'    => 0,
     'all_groups'    => 1,
     'price_qty'     => $detail->getMin(),
     'price'         => $detail->getPrix(),
     'website_price' => $detail->getPrix(),
  );
}
$product->setTierPrice($tier_price);

Magento assign attribute to attribute set

This is how to assign an existing attribute to an existing attribute set


$setup = new Mage_Catalog_Model_Resource_Eav_Mysql4_Setup('core_setup');
$setup->startSetup();

$attribute_set_name = ATTRIBUTE_SET_VISIT;
$attribute_code = $attr;
$group_name = GROUP_ADIN;

$attribute_set_id=$setup->getAttributeSetId('catalog_product', $attribute_set_name);
$attribute_group_id=$setup->getAttributeGroupId('catalog_product', $attribute_set_id, $group_name);
$attribute_id=$setup->getAttributeId('catalog_product', $attribute_code);

$setup->addAttributeToSet($entityTypeId='catalog_product',$attribute_set_id, $attribute_group_id, $attribute_id);

Magento product options create and delete

Here, some of my code to manipulate Magento product options.

Creation

You first need an array with the options you want to save

$values = array();
foreach($options as $option)
{
    $values[] = array(
        'title' => $option['name'],
        'price' => $option['price'],
        'price_type' => 'fixed',
        'sku' => $option['sku'],
        'sort_order' => $x,
        'is_delete' => '0',
        );
    $x++;
}
$newOption = array(
            'title' => "Public",
            'type' => 'drop_down',
            'is_require' => 1,
            'sort_order' => 20,
            'is_delete' => '',
            'previous_type' => '',
            'previous_group'    => '',
            'values' =>$values,
        );

Then add them to your product, I have seen a lot of different way to do it

$product->setCanSaveCustomOptions(true);
$product->getOptionInstance()->addOption($newOption);
//or
$product->getOptionInstance()->setOptions($newOption);

$product->getOptionInstance()->saveOptions();

$product->setHasOptions(1);
$product->setRequiredOptions(1);

$product->save();

or via OptionInstance

$optionInstance = $product->getOptionInstance();
$optionInstance->setOptions($newOption);
$optionInstance->setProduct($product);
$optionInstance->->saveOptions();

But it doesn’t work, I finally use this

$product->setProductOptions(array($newOption));
$product->setCanSaveCustomOptions(true);
$product->save()

To delete product options, there is several way too

$oldOptions = $product->getOptionInstance()->getOptions();
foreach ($oldOptions as $key => $option){
       $oldOptions[$key]['is_delete'] = 1;
}
$product->getOptionInstance()->setOptions($oldOptions);
$product->getOptionInstance()->saveOptions();

//or 
$optionInstance = $product->getOptionInstance()->unsetOptions();

But it doesn’t work too, so I use :

$options = Mage::getModel('catalog/product_option')->getCollection()->addFieldToFilter("product_id", $product->getId());
foreach($options as $option)
{
   $option->delete();
}

Some more informations:
To see options on admin, your product entity (table catalog_product_entity) should have attribute (column) has_options set to 1.
Options are saved in tables : catalog_product_option, catalog_product_option_price, catalog_product_option_title, catalog_product_option_type_price, catalog_product_option_type_title and catalog_product_option_value.

Magento create observers on custom entities

If you need to create an observer on your custom entities, just follow these few steps:

In this case, we will create an observer on the before save event of the tarif entity.

On your module config.xml file, declare your observer, this will bind your hook event to your class/method

<config>
   <global>
      <events>
            <tarif_save_before>
                <observers>
                    <adin_marketplace>
                        <type>singleton</type>
                        <class>adin_marketplace/observer</class>
                        <method>adinMarketplaceTarifSaveBefore</method>
                    </adin_marketplace>
                </observers>
            </tarif_save_before>
       </event>
   </global>
/config>

tarif_save_before means your observer will trigger on the before save event of the tarif entity.
To find out which entity to use, you can add (temporary) a mage::log() on this class : app/code/core/Mage/Core/Model/Abstract.php

 protected function _beforeSave()
    {
        if (!$this->getId()) {
            $this->isObjectNew(true);
        }
        Mage::dispatchEvent('model_save_before', array('object'=>$this));
        Mage::log('entity to use: '.$this->_eventPrefix.'_save_before');
        Mage::dispatchEvent($this->_eventPrefix.'_save_before', $this->_getEventData());
        return $this;
    }

adin_marketplace is my module.
adin_marketplace/observer class is the class file to use (app/code/local/Adin/Marketplace/Model/Observer.php )
adinMarketplaceTarifSaveBefore is the method inside my class.

Now, create your class and your method : app/code/local/Geophyle/Marketplace/Model/Observer.php

class Adin_Marketplace_Model_Observer {
public function adinMarketplaceTarifSaveBefore($observer)
{
    $event = $observer->getEvent();
    $tarif = $event->getTarif();
    //do some stuff...
}

And that’s all.
You change an .xml file, so don’t forget to clear your cache.

Magento app/code/core/Mage/Eav/Model/Entity/Abstract.php on line 1180 error

You try to save a product and you get this error : Invalid argument supplied for foreach().
This was unexpected and you don’t understand why.

The problem is, that you are not allowed to save products from the frontend.
The origData property is not filled

public function setOrigData($key=null, $data=null)
{
    if (Mage::app()->getStore()->isAdmin()) {
        return parent::setOrigData($key, $data);
    }

    return $this;
}

So when you try to save the product, this error is raised.

What to do when you encounter this error ?

A quick fix is to add this before saving, on your controller for example.

Mage::app()->setCurrentStore(Mage_Core_Model_App::ADMIN_STORE_ID);

A proper solution is to extend Mage_Catalog_Model_Product and replace setOrigData method

public function setOrigData($key = null, $data = null)
{
    if (is_null($key)) {
        $this->_origData = $this->_data;
    } else {
        $this->_origData[$key] = $data;
    }
    return $this;
}

Magento get countries dropdown list

Create a dropdown list with magento’s countries is easy :

<select name="billing_country" id="billing_country">
<?php
 $_countries = Mage::getResourceModel('directory/country_collection')->loadData()->toOptionArray(false);
 foreach($_countries as $_country)
 {
       echo '<option ';
       if($this->getCustomer()->getBillingCountry() == $_country['value']){ echo 'selected '; }
       echo 'value="'.$_country['value'].'">'.$_country['label'].'</option>';
 }
?>
</select>