Adding a custom option using an extension in Magento - magento

I'm creating a custom extension and I would like to add a custom option when a certain item is purchased.
For example, when the product "Name Tag" is purchased, the extension would detect that the specific product has been ordered and assign a custom option of "Year" to it. The user does not see this, but the attribute is added and displayed in the admin when viewing the order.
Are there any specific listeners our there to accomplish this?
EDIT Based on Ben's suggestions in the comments, I'm editing the comment to reflect progress I've made with the answers located here: https://stackoverflow.com/a/9496266/268165
I now have an extension running under Namespace_addYear and the following code running:
Namespace/addYear/etc/config.xml:
<?xml version="1.0" encoding="utf-8"?>
<config>
<modules>
<Namespace_addYear>
<version>1.0.0</version>
</Namespace_addYear>
</modules>
<global>
</global>
<frontend>
<events>
<catalog_product_load_after>
<observers>
<Namespace_addYear>
<type>model</type>
<class>addYear/observer</class>
<method>catalogProductLoadAfter</method>
</Namespace_addYear>
</observers>
</catalog_product_load_after>
</events>
</frontend>
</config>
Namespace/addYear/Model/Observer.php:
class Namespace_addYear_Model_Observer
public function catalogProductLoadAfter(Varien_Event_Observer $observer)
{
// set the additional options on the product
$action = Mage::app()->getFrontController()->getAction();
if ($action->getFullActionName() == 'checkout_cart_add')
{
// assuming you are posting your custom form values in an array called extra_options...
if ($options = $action->getRequest()->getParam('extra_options'))
{
$product = $observer->getProduct();
// add to the additional options array
$additionalOptions = array();
if ($additionalOption = $product->getCustomOption('additional_options'))
{
$additionalOptions = (array) unserialize($additionalOption->getValue());
}
foreach ($options as $key => $value)
{
$additionalOptions[] = array(
'label' => $key,
'value' => $value,
);
}
// add the additional options array with the option code additional_options
$observer->getProduct()
->addCustomOption('additional_options', serialize($additionalOptions));
}
}
}
}
The Observer.php was taken from the answer linked above. So far, I cannot get the store to do anything other than display a 404 page when I remove the tags in config.xml.
Is there anything someone can immediately see that is wrong?

Related

How to sort products by last price change? in Magento 1.9

We had a lot of price changes recently, and I just changed the prices on our basic 1.9 magento store. Now I wish to be able to sort out products based on:
latest price change/ latest changed by date/time. So I can go through the list and see if they were all changed correctly. How should I proceed?
Captain Obvious: hire a programmer/web dev.
I guess this is similar to this topic: Magento - Sort by Date Added, which based on the answers can be made without changing core files.
Yes you guessed correctly, I wish to use option 2. Now can this be done simply?
I'm not a coder or web dev, but I do have basic web knowledge and ftp access.
In Your collection use sort by updated_at
Example
$collection = Mage::getResourceModel('catalog/product_collection');
$collection->setVisibility(Mage::getSingleton('catalog/product_visibility')->getVisibleInCatalogIds());
$collection->addAttributeToSort('updated_at', 'desc');
As you only want to perform a verification, it can be done on the admin side.
You can display the Updated Time in the Catalog Product Grid.
In a custom module, let's set this in config.xml :
<config>
<global>
<blocks>
<adminhtml>
<rewrite>
<catalog_product_grid>Vendor_Module_Block_Adminhtml_Catalog_Product_Grid</catalog_product_grid>
</rewrite>
</adminhtml>
</blocks>
</global>
</config>
Then in app/code/local/<VENDOR>/<MODULE>/Block/Adminhtml/Catalog/Product/Grid.php :
<?php
class Vendor_Module_Block_Adminhtml_Catalog_Product_Grid extends Mage_Adminhtml_Block_Catalog_Product_Grid
{
public function setCollection($collection)
{
/* #var $collection Mage_Catalog_Model_Resource_Product_Collection */
// IF the attribute `updated_at` is already in the collection,
// THEN you can remove this function,
// ELSE uncomment this line :
// $collection->addAttributeToSelect('updated_at');
parent::setCollection($collection);
}
protected function _prepareColumns()
{
$store = $this->_getStore();
// after column price :
$this->addColumnAfter('updated_at',
array(
'header'=> Mage::helper('sales')->__('Updated At'),
'header_css_class' => 'a-center',
'type' => 'datetime',
'index' => 'updated_at',
'sortable'=>true,
),
'price'
);
return parent::_prepareColumns();
}
}
I haven't tested, but it should be working.
Then, you will be able to sort the grid on this new column.

Magento : How to add handle through observer

I am trying to use addHandle(), but using the following generates error:
public function HandleMe($observer)
$update = $observer->getEvent()->getLayout()->getUpdate();
$update->addHandle('handlename');
raises a "Fatal error: Call to a member function getUpdate()"
You have to load core/layout before you update the layout, So try follow below code,
public function addCustomHandles($observer) {
$update = Mage::getSingleton('core/layout')->getUpdate();
//Your code here..
}
Or refer below link,
Link 1
Link 2
try using following approach :
First add this to your config.xml in yourcustommodule:
<config>
<frontend>
<events>
<controller_action_layout_load_before>
<observers>
<yourcustomtheme_observer>
<class>yourcustomtheme/observer</class>
<method>addHandles</method>
</yourcustomtheme_observer>
</observers>
</controller_action_layout_load_before>
</events>
</frontend>
</config>
And then add following method to your observer
class YourPackage_YourCustomTheme_Model_Observer extends CLS_Core_Model_Abstract
{
public function addHandles($observer) {
$category = Mage::registry('current_category');
if ($category instanceof Mage_Catalog_Model_Category) {
$update = Mage::getSingleton('core/layout')->getUpdate();
$fertilility = (count($category->getChildrenCategories()->getData())) ? 'parent' : 'nochildren';
$update->addHandle('catalog_category_' . $fertilility);
}
return $this;
}
}
PS : this is only for reference, so that you can check whether you are correctly using observer and handles or not.

Add button to catalog category in magento

I want to add new button to category page on admin side with delete category and save category.I try the way to override the block Catalog_Category_Edit_Form but didn't work.My xml code is :
<adminhtml>
<rewrite>
<Catalog_Category_Edit_Form>Mymodule_Block_Rewrite_Editcate</Catalog_Category_Edit_Form>
</rewrite>
</adminhtml>
While my block code is
<?php
class Mymodule_Block_Rewrite_Editcate extends Mage_Adminhtml_Block_Catalog_Category_Edit_Form
{
private $parent;
protected function _prepareLayout()
{
// Delete button
$this->parent = parent::_prepareLayout();
$this->removeButton('delete_button');
return $this->parent;
}
}.
Can anyone help me the right way ? In above code i try to remove button to check my code works .
Sorry guys i find a solution .My new xml is look like
<adminhtml>
<rewrite>
<catalog_category_edit_form>Mymodule_Block_Adminhtml_Catalog_Category_Edit_Form</catalog_category_edit_form>
</rewrite>
</adminhtml>
And my block code is :
<?php
class Mymodule_Block_Adminhtml_Catalog_Category_Edit_Form extends Mage_Adminhtml_Block_Catalog_Category_Edit_Form
{
protected function _prepareLayout()
{
parent::_prepareLayout();
$this->addAdditionalButton('update_button', array('name' => 'update_button','title'=>'Copy Category','type'=>"button",'label'=> Mage::helper('catalog')->__('Copy Category') ));
return parent::_prepareLayout();
}
}.
This is it.Mian function is addAdditionButton.Only pass parameter to it.I have override it.

Magento change product name adding to cart

I want to change some values of some products while adding them to the cart in Magento CE 1.7
Im trying with the Observer checkout_cart_add_product_complete for this. Change the price (CustomPrice) works well if I try to change the product name or product images, its not saved.
Is there a way to change this attributes already on adding to cart?
public function checkout_cart_add_product_complete(Varien_Event_Observer $observer) {
[...]
// Set new Price
$lastAddedItem->setOriginalCustomPrice($originalProduct->getPrice());
$lastAddedItem->setCustomPrice($originalProduct->getPrice());
// Set Product-Name
$lastAddedItem->setName($originalProduct->getName());
// Set Product-Images
$lastAddedItem->setImage($originalProduct->getImage());
$lastAddedItem->setSmallImage($originalProduct->getSmallImage());
$lastAddedItem->setThumbnail($originalProduct->getThumbnail());
// Save updated Item and Cart
//$lastAddedItem->save();
Mage::getSingleton('checkout/cart')->save();
// Recalc Totals and save
$quote->setTotalsCollectedFlag(false);
$quote->collectTotals();
$quote->save();
Mage::getSingleton('checkout/session')->setCartWasUpdated(true);
}
The function Mage_Sales_Model_Quote_Item::setProduct resets some of the basic information each time a product is saved (updated). Luckily there is an event "sales_quote_item_set_product" you can latch onto.
config.xml
<config>
...
<global>
<events>
<sales_quote_item_set_product>
<observers>
<samples>
<type>singleton</type>
<class>samples/observer</class>
<method>salesQuoteItemSetProduct</method>
</samples>
</observers>
</sales_quote_item_set_product>
</events>
<global>
...
</config>
Observer.php
class Mynamespace_Samples_Model_Observer
{
public function salesQuoteItemSetProduct(Varien_Event_Observer $observer)
{
/* #var $item Mage_Sales_Model_Quote_Item */
$item = $observer->getQuoteItem();
$item->setName('Ians custom product name');
return $this;
}
}

How to add a column for example customer group id in Magento's Admin Order Grid

I want an additional column in the Order(s) Grid for Admin. Assuming its Customer Group Id.
My app/etc/modules/MyProject_Adminhtml looks like:
<?xml version="1.0"?>
<config>
<modules>
<MyProject_Adminhtml>
<active>true</active>
<codePool>local</codePool>
<depends>
<Mage_Sales />
</depends>
</MyProject_Adminhtml>
</modules>
</config>
My app/code/local/MyProject/Adminhtml/etc/config.xml looks like:
<?xml version="1.0"?>
<config>
<modules>
<MyProject_Adminhtml>
<version>1.0.0</version>
</MyProject_Adminhtml>
</modules>
<global>
<blocks>
<adminhtml>
<rewrite>
<sales_order_grid>MyProject_Adminhtml_Block_Sales_Order_Grid</sales_order_grid>
</rewrite>
</adminhtml>
</blocks>
</global>
</config>
And in app/code/local/MyProject/Adminhtml/Block/Sales/Order/Grid.php I have overridden Mage_Adminhtml_Block_Sales_Order_Grid
class MyProject_Adminhtml_Block_Sales_Order_Grid extends Mage_Adminhtml_Block_Sales_Order_Grid
{
protected function _prepareColumns()
{
.... unchanged code from Mage_Adminhtml_Block_Sales_Order_Grid::_prepareColumns ...
$this->addColumn('customer_group_id', array(
'header' => Mage::helper('sales')->__('Customer Group Id'),
'index' => 'customer_group_id',
'type' => 'text',
));
.... unchanged code from Mage_Adminhtml_Block_Sales_Order_Grid::_prepareColumns ...
}
}
Is there something I am missing because I don't see anything in Order Grid. I am using Magento 1.4.1.1
On Anda B's comment I wrote the following line:
var_dump($this->getLayout()->createBlock('MyProject_Adminhtml_Block_Sales_Order_Grid'));
in app/code/core/Mage/Adminhtml/controllers/Sales/Order/CreateController.php
Then, I selected 'Create New Order' and Cancel the order to see the result of execution of var_dump, and I see the following:
/var/www/magento/var/report/72990635: line 10: syntax error near unexpected token `}' /var/www/magento/var/report/72990635: line 10: `#9 {main}";s:3:"url";s:80:"/index.php/admin/sales_order_create/cancel/key/0624033594dd63d9e145fc538f4c6bbb/";s:11:"script_name";s:10:"/index.php";s:4:"skin";s:5:"admin";}'
You are almost there.
You will need to create a renderer for the GroupID as one does not exists in the core.
First, add the renderer to your addColumn like this:
$this->addColumn('customer_group_id', array(
'header' => Mage::helper('sales')->__('Customer Group Id'),
'index' => 'customer_group_id',
'type' => 'text',
'renderer' => 'adminhtml/widget_grid_column_renderer_customergroup',
));
Now you will need to create the directory /app/code/local/MyProject/Adminhtml/Widget/Grid/Column/Renderer/ as it probably doesn't exist.
Now create a Customergroup.php file containing this class:
class MyProject_Adminhtml_Block_Widget_Grid_Column_Renderer_Customergroup extends Mage_Adminhtml_Block_Widget_Grid_Column_Renderer_Abstract
{
private static $_customergroups = array();
public static function getCustomerGroupsArray() {
if(count(self::$_customergroups) == 0) {
$customer_group = Mage::getModel('customer/group');
$customer_groups = $customer_group->getCollection()->toOptionHash();
self::$_customergroups = $customer_groups;
}
return self::$_customergroups;
}
public function render(Varien_Object $row){
$value = $this->_getValue($row);
$customer_groups = self::getCustomerGroupsArray();
return isset($customer_groups[$value]) ? $customer_groups[$value] : false;
}
}
And finally you will need to add this to the config.xml in MyProject. Put this:
<widget_grid_column_renderer_customergroup>Myproject_Adminhtml_Block_Widget_Grid_Column_Renderer_Customergroup</widget_grid_column_renderer_customergroup>
right next to your other rewrite.
After you refresh your cache you should have your Group labels in your sales order grid.
PS.
if you want to add a filter to the top of the sales order grid to work with this column, add this to the 'addColumn' right after the renderer. (order is not actually important)
'options' => TheReadyStore_Adminhtml_Block_Widget_Grid_Column_Renderer_Customergroup::getCustomerGroupsArray(),
and change the type from 'text' to 'options'
Cheers
Roy
In modules/etc you have Atzen_Adminhtml but your project is MyProject_Adminhtml.
Except this problem the code should work: even if you don't have the customer_group_id in sales table, the new column should appear in the grid.

Resources