Of tyrannies

Read More

“Of all tyrannies, a tyranny sincerely exercised for the good of its victims may be the most oppressive. It would be better to live under robber barons than under omnipotent moral busybodies. The robber baron’s cruelty may sometimes sleep, his cupidity may at some point be satiated; but those who torment us for our own good will torment us without end for they do so with the approval of their own conscience.” – C.S. Lewis

Magento 1.x Events Reference

The following is a list of many Magento Community Edition events with module and parameters.

Note that some events are dispatched with dynamically-calculated names, so this list is and always will be “incomplete”.

At the bottom there is example of using an event.

Magento Module Event Name Parameters
Mage Admin admin_session_user_login_success array(’user’⇒$user)
Mage Admin admin_session_user_login_failed array(’user_name’⇒$username, ‘exception’ ⇒ $e)
Mage Admin admin_user_authenticate_after array(’username’ ⇒ $username,’password’ ⇒ $password,’user’ ⇒ $this,’result’ ⇒ $result)
Mage Adminhtml adminhtml_block_html_before array(’block’ ⇒ $this)
Mage Adminhtml adminhtml_catalog_category_tabs array(’tabs’ ⇒ $this)
Mage Adminhtml adminhtml_catalog_category_tree_is_moveable array(’options’⇒$options)
Mage Adminhtml adminhtml_catalog_category_tree_can_add_root_category array(’category’ ⇒ $this→getCategory(),’options’ ⇒ $options,’store’ ⇒ $this→getStore()→getId())
Mage Adminhtml adminhtml_catalog_category_tree_can_add_sub_category array(’category’ ⇒ $this→getCategory(),’options’ ⇒ $options,’store’ ⇒ $this→getStore()→getId())
Mage Adminhtml adminhtml_product_attribute_types array(’response’⇒$response)
Mage Adminhtml adminhtml_catalog_product_edit_prepare_form array(’form’⇒$form)
Mage Adminhtml adminhtml_catalog_product_edit_element_types array(’response’⇒$response)
Mage Adminhtml adminhtml_catalog_product_attribute_set_main_html_before array(’block’ ⇒ $this)
Mage Adminhtml adminhtml_catalog_product_attribute_set_toolbar_main_html_before array(’block’ ⇒ $this)
Mage Adminhtml adminhtml_catalog_product_form_prepare_excluded_field_list array(’object’⇒$this)
Mage Adminhtml adminhtml_catalog_product_edit_prepare_form array(’form’⇒$form)
Mage Adminhtml adminhtml_catalog_product_edit_element_types array(’response’⇒$response)
Mage Adminhtml adminhtml_catalog_product_edit_tab_attributes_create_html_before array(’block’ ⇒ $this)
Mage Adminhtml adminhtml_cms_page_edit_tab_content_prepare_form array(’form’ ⇒ $form)
Mage Adminhtml adminhtml_cms_page_edit_tab_design_prepare_form array(’form’ ⇒ $form)
Mage Adminhtml adminhtml_cms_page_edit_tab_main_prepare_form array(’form’ ⇒ $form)
Mage Adminhtml adminhtml_cms_page_edit_tab_meta_prepare_form array(’form’ ⇒ $form)
Mage Adminhtml adminhtml_widget_grid_filter_collection array(’collection’ ⇒ $this→getCollection(), ‘filter_values’ ⇒ $this→_filterValues)
Mage Adminhtml adminhtml_widget_container_html_before array(’block’ ⇒ $this)
Mage Adminhtml adminhtml_controller_action_predispatch_start array()
Mage Adminhtml adminhtml_customer_prepare_save array(’customer’ ⇒ $customer, ‘request’ ⇒ $this→getRequest())
Mage Adminhtml adminhtml_customer_save_after array(’customer’ ⇒ $customer)
Mage Adminhtml on_view_report array(’report’ ⇒ ‘search’)
Mage Adminhtml catalog_category_prepare_save array(’category’ ⇒ $category,’request’ ⇒ $this→getRequest())
Mage Adminhtml catalog_controller_category_delete array(’category’⇒$category)
Mage Adminhtml catalog_product_new_action array(’product’ ⇒ $product)
Mage Adminhtml catalog_product_edit_action array(’product’ ⇒ $product)
Mage Adminhtml catalog_product_prepare_save array(’product’ ⇒ $product, ‘request’ ⇒ $this→getRequest())
Mage Adminhtml catalog_controller_product_delete array(’product’ ⇒ $product)
Mage Adminhtml catalog_product_to_website_change array(
Mage Adminhtml cms_page_prepare_save array(’page’ ⇒ $model, ‘request’ ⇒ $this→getRequest())
Mage Adminhtml adminhtml_cmspage_on_delete array(’title’ ⇒ $title, ‘status’ ⇒ ‘success’)
Mage Adminhtml adminhtml_cmspage_on_delete array(’title’ ⇒ $title, ‘status’ ⇒ ‘fail’)
Mage Adminhtml admin_permissions_role_prepare_save array(’object’ ⇒ $role, ‘request’ ⇒ $this→getRequest())
Mage Adminhtml adminhtml_controller_catalogrule_prepare_save array(’request’ ⇒ $this→getRequest())
Mage Adminhtml adminhtml_controller_salesrule_prepare_save array(’request’ ⇒ $this→getRequest())
Mage Adminhtml adminhtml_sales_order_create_process_data $eventData
Mage Adminhtml adminhtml_sales_order_creditmemo_register_before $args
Mage Adminhtml admin_system_config_changed_section_{$section} array(’website’ ⇒ $website, ‘store’ ⇒ $store)
Mage Adminhtml store_group_save array(’group’ ⇒ $groupModel)
Mage Adminhtml store_edit array(’store’⇒$storeModel)
Mage Adminhtml store_add array(’store’⇒$storeModel)
Mage Adminhtml store_delete array(’store’ ⇒ $model)
Mage Adminhtml sales_convert_order_to_quote array(’order’ ⇒ $order,’quote’ ⇒ $this→getQuote())
Mage Adminhtml sales_convert_order_item_to_quote_item array(’order_item’ ⇒ $orderItem,’quote_item’ ⇒ $item)
Mage Api api_user_authenticated array(’model’ ⇒ $this,’api_key’ ⇒ $apiKey)
Mage Bundle bundle_product_view_config $args
Mage Bundle prepare_catalog_product_index_select array(’select’ ⇒ $select,’entity_field’ ⇒ new Zend_Db_Expr(’e.entity_id’),’website_field’ ⇒ new Zend_Db_Expr(’cw.website_id’),’store_field’ ⇒ new Zend_Db_Expr(’cs.store_id’))
Mage Bundle prepare_catalog_product_price_index_table array(’index_table’ ⇒ array(’i’ ⇒ $this→_getDefaultFinalPriceTable()),’select’ ⇒ $select,’entity_id’ ⇒ ‘i.entity_id
Mage Bundle catalog_product_prepare_index_select array(’website’ ⇒ $website,’select’ ⇒ $select)
Mage Bundle catalog_product_get_final_price array(’product’⇒$product)
Mage Catalog catalog_block_product_list_collection array(’collection’⇒$this→_getProductCollection(),)
Mage Catalog catalog_product_view_config array(’response_object’⇒$responseObject)
Mage Catalog catalog_product_upsell array(’product’ ⇒ $product,’collection’ ⇒ $this→_itemCollection,’limit’ ⇒ $this→getItemLimit())
Mage Catalog catalog_controller_category_init_before array(’controller_action’⇒$this)
Mage Catalog catalog_controller_category_init_after array(’category’⇒$category, ‘controller_action’⇒$this)
Mage Catalog catalog_controller_product_init_before array(’controller_action’⇒$this)
Mage Catalog catalog_controller_product_init array(’product’⇒$product)
Mage Catalog catalog_controller_product_init_after array(’product’⇒$product, ‘controller_action’ ⇒ $this)
Mage Catalog catalog_controller_product_view array(’product’⇒$product)
Mage Catalog catalog_product_compare_add_product array(’product’⇒$product)
Mage Catalog catalog_product_compare_remove_product array(’product’⇒$item)
Mage Catalog catalog_helper_output_construct array(’helper’⇒$this)
Mage Catalog catalog_category_tree_move_before $eventParams
Mage Catalog $this→_eventPrefix.’_move_before’ $eventParams
Mage Catalog $this→_eventPrefix.’_move_after’ $eventParams
Mage Catalog catalog_category_tree_move_after $eventParams
Mage Catalog category_move $eventParams
Mage Catalog $this→_eventPrefix.’_validate_before’ array($this→_eventObject⇒$this)
Mage Catalog $this→_eventPrefix.’_validate_after’ array($this→_eventObject⇒$this)
Mage Catalog catalog_model_product_duplicate array(’current_product’⇒$this, ‘new_product’⇒$newProduct)
Mage Catalog catalog_product_is_salable_before array(’product’ ⇒ $this)
Mage Catalog catalog_product_is_salable_after array(’product’ ⇒ $this,’salable’ ⇒ $object)
Mage Catalog $this→_eventPrefix.’_delete_after_done’ array($this→_eventObject⇒$this)
Mage Catalog catalog_product_import_after array()
Mage Catalog catalog_product_website_update_before array(’website_ids’ ⇒ $websiteIds,’product_ids’ ⇒ $productIds,’action’ ⇒ $type)
Mage Catalog catalog_product_website_update array(’website_ids’ ⇒ $websiteIds,’product_ids’ ⇒ $productIds,’action’ ⇒ $type)
Mage Catalog catalog_product_status_update array(’product_id’ ⇒ $productId,’store_id’ ⇒ $storeId,’status’ ⇒ $value)
Mage Catalog catalog_product_get_final_price array(’product’⇒$product)
Mage Catalog catalog_category_change_products array(’category’ ⇒ $category,’product_ids’ ⇒ $productIds)
Mage Catalog $this→_eventPrefix . ‘_load_before’ array($this→_eventObject ⇒ $this)
Mage Catalog $this→_eventPrefix . ‘_load_after’ array($this→_eventObject ⇒ $this)
Mage Catalog $this→_eventPrefix . ‘_add_is_active_filter’ array($this→_eventObject ⇒ $this)
Mage Catalog catalog_category_tree_init_inactive_category_ids array(’tree’⇒$this)
Mage Catalog catalog_category_tree_init_inactive_category_ids array(’tree’⇒$this)
Mage Catalog catalog_category_tree_move_before array(’category’ ⇒ $category,’prev_parent’ ⇒ $prevNode,’parent’ ⇒ $newParent)
Mage Catalog catalog_category_tree_move_after array(’category’ ⇒ $category,’prev_node’ ⇒ $prevNode,’parent’ ⇒ $newParent)
Mage Catalog $this→_eventPrefix . ‘_load_before’ array($this→_eventObject ⇒ $this)
Mage Catalog $this→_eventPrefix . ‘_load_after’ array($this→_eventObject ⇒ $this)
Mage Catalog $this→_eventPrefix . ‘_add_is_active_filter’ array($this→_eventObject ⇒ $this)
Mage Catalog catalogindex_prepare_price_select $eventArgs
Mage Catalog catalog_prepare_price_select $eventArgs
Mage Catalog catalog_product_collection_load_before array(’collection’⇒$this)
Mage Catalog catalog_product_collection_load_after array(’collection’⇒$this)
Mage Catalog catalog_product_collection_before_add_count_to_categories array(’collection’⇒$this)
Mage Catalog catalog_product_collection_apply_limitations_after array(’collection’ ⇒ $this)
Mage Catalog catalog_product_compare_item_collection_clear’
Mage Catalog catalog_product_flat_prepare_columns array(’columns’ ⇒ $columnsObject)
Mage Catalog catalog_product_flat_prepare_indexes array(’indexes’ ⇒ $indexesObject)
Mage Catalog catalog_product_flat_rebuild array(’store_id’ ⇒ $store,’table’ ⇒ $this→getFlatTableName($store))
Mage Catalog catalog_product_flat_update_product array(’store_id’ ⇒ $store,’table’ ⇒ $this→getFlatTableName($store),’product_ids’ ⇒ $productIds)
Mage Catalog prepare_catalog_product_index_select array(’select’ ⇒ $select,’entity_field’ ⇒ new Zend_Db_Expr(’pid.entity_id’),’website_field’ ⇒ new Zend_Db_Expr(’cs.website_id’),’store_field’ ⇒ new Zend_Db_Expr(’cs.store_id’))
Mage Catalog prepare_catalog_product_index_select array(’select’ ⇒ $select,’entity_field’ ⇒ new Zend_Db_Expr(’pvd.entity_id’),’website_field’ ⇒ new Zend_Db_Expr(’cs.website_id’),’store_field’ ⇒ new Zend_Db_Expr(’cs.store_id’))
Mage Catalog prepare_catalog_product_index_select array(’select’ ⇒ $select,’entity_field’ ⇒ new Zend_Db_Expr(’l.parent_id’),’website_field’ ⇒ new Zend_Db_Expr(’cs.website_id’),’store_field’ ⇒ new Zend_Db_Expr(’cs.store_id’))
Mage Catalog prepare_catalog_product_index_select array(’select’ ⇒ $select,’entity_field’ ⇒ new Zend_Db_Expr(’e.entity_id’),’website_field’ ⇒ new Zend_Db_Expr(’cw.website_id’),’store_field’ ⇒ new Zend_Db_Expr(’cs.store_id’))
Mage Catalog prepare_catalog_product_price_index_table array(’index_table’ ⇒ array(’i’ ⇒ $this→_getDefaultFinalPriceTable()),’select’ ⇒ $select,’entity_id’ ⇒ ‘i.entity_id
Mage Catalog prepare_catalog_product_price_index_select array(’select’ ⇒ $select,’entity_field’ ⇒ new Zend_Db_Expr(’e.entity_id’),’website_field’ ⇒ new Zend_Db_Expr(’cw.website_id’),’store_field’ ⇒ new Zend_Db_Expr(’cs.store_id’))
Mage CatalogIndex catalogindex_plain_reindex_after array(’products’ ⇒ $products)
Mage CatalogIndex catalogindex_prepare_price_select $args
Mage CatalogIndex catalogindex_get_minimal_price $eventData
Mage CatalogIndex catalogindex_prepare_price_select $args
Mage CatalogIndex catalogindex_prepare_price_select $args
Mage CatalogIndex catalogindex_prepare_price_select $args
Mage CatalogIndex catalogindex_prepare_price_select $args
Mage CatalogRule catalogrule_before_apply array(’resource’⇒$this)
Mage CatalogRule catalogrule_after_apply array(’product’⇒$product,’product_condition’ ⇒ $productCondition)
Mage CatalogSearch catalogsearch_reset_search_result’
Mage Checkout checkout_cart_add_product_complete array(’product’ ⇒ $product, ‘request’ ⇒ $this→getRequest(), ‘response’ ⇒ $this→getResponse())
Mage Checkout checkout_controller_multishipping_shipping_post array(’request’⇒$this→getRequest(), ‘quote’⇒$this→_getCheckout()→getQuote())
Mage Checkout checkout_multishipping_controller_success_action’
Mage Checkout checkout_onepage_controller_success_action’
Mage Checkout checkout_controller_onepage_save_shipping_method array(’request’⇒$this→getRequest(), ‘quote’⇒$this→getOnepage()→getQuote())
Mage Checkout checkout_allow_guest array(’quote’ ⇒ $quote,’store’ ⇒ $store,’result’ ⇒ $result)
Mage Checkout checkout_cart_product_add_after array(’quote_item’⇒$result, ‘product’⇒$product)
Mage Checkout checkout_cart_update_items_before array(’cart’⇒$this, ‘info’⇒$data)
Mage Checkout checkout_cart_update_items_after array(’cart’⇒$this, ‘info’⇒$data)
Mage Checkout checkout_cart_info_item_unset_product_before array(
Mage Checkout checkout_quote_init array(’quote’⇒$quote)
Mage Checkout checkout_quote_destroy array(’quote’⇒$this→getQuote())
Mage Checkout checkout_type_multishipping_set_shipping_items array(’quote’⇒$this→getQuote())
Mage Checkout checkout_type_multishipping_create_orders_single array(’order’⇒$order, ‘address’⇒$address)
Mage Checkout checkout_type_onepage_save_order array(’order’⇒$order, ‘quote’⇒$this→getQuote())
Mage Checkout checkout_type_onepage_save_order_after array(’order’⇒$order, ‘quote’⇒$this→getQuote())
Mage Cms cms_controller_router_match_before array(’router’ ⇒ $this,’condition’ ⇒ $condition)
Mage Cms cms_page_get_available_statuses array(’statuses’ ⇒ $statuses)
Mage Core core_block_abstract_prepare_layout_before array(’block’ ⇒ $this)
Mage Core core_block_abstract_prepare_layout_after array(’block’ ⇒ $this)
Mage Core core_block_abstract_to_html_before array(’block’ ⇒ $this)
Mage Core core_block_abstract_to_html_after array(’block’ ⇒ $this)
Mage Core http_response_send_before array(’response’⇒$this)
Mage Core controller_action_layout_load_before array(’action’⇒$this, ‘layout’⇒$this→getLayout())
Mage Core controller_action_layout_generate_xml_before array(’action’⇒$this, ‘layout’⇒$this→getLayout())
Mage Core controller_action_layout_generate_blocks_before array(’action’⇒$this, ‘layout’⇒$this→getLayout())
Mage Core controller_action_layout_generate_blocks_after array(’action’⇒$this, ‘layout’⇒$this→getLayout())
Mage Core controller_action_layout_render_before’
Mage Core controller_action_layout_render_before_’.$this→getFullActionName()
Mage Core controller_action_predispatch array(’controller_action’⇒$this)
Mage Core controller_action_predispatch_’.$this→getRequest()→getRouteName() array(’controller_action’⇒$this)
Mage Core controller_action_predispatch_’.$this→getFullActionName() array(’controller_action’⇒$this)
Mage Core controller_action_postdispatch_’.$this→getFullActionName() array(’controller_action’⇒$this)
Mage Core controller_action_postdispatch_’.$this→getRequest()→getRouteName() array(’controller_action’⇒$this)
Mage Core controller_action_postdispatch array(’controller_action’⇒$this)
Mage Core controller_action_noroute array(’action’⇒$this, ‘status’⇒$status)
Mage Core controller_action_nocookies array(’action’ ⇒ $this,’redirect’ ⇒ $redirect)
Mage Core controller_front_init_before array(’front’⇒$this)
Mage Core controller_front_init_routers array(’front’⇒$this)
Mage Core model_load_after array(’object’⇒$this)
Mage Core $this→_eventPrefix.’_load_after’ array($this→_eventObject⇒$this)
Mage Core model_save_commit_after array(’object’⇒$this)
Mage Core $this→_eventPrefix.’_save_commit_after’ array($this→_eventObject⇒$this)
Mage Core model_save_before array(’object’⇒$this)
Mage Core $this→_eventPrefix.’_save_before’ array($this→_eventObject⇒$this)
Mage Core model_save_after array(’object’⇒$this)
Mage Core $this→_eventPrefix.’_save_after’ array($this→_eventObject⇒$this)
Mage Core model_delete_before array(’object’⇒$this)
Mage Core $this→_eventPrefix.’_delete_before’ array($this→_eventObject⇒$this)
Mage Core model_delete_after array(’object’⇒$this)
Mage Core $this→_eventPrefix.’_delete_after’ array($this→_eventObject⇒$this)
Mage Core model_delete_commit_after array(’object’⇒$this)
Mage Core $this→_eventPrefix.’_delete_commit_after’ array($this→_eventObject⇒$this)
Mage Core application_clean_cache array(’tags’ ⇒ $tags)
Mage Core core_locale_set_locale array(’locale’⇒$this)
Mage Core resource_get_tablename array(’resource’ ⇒ $this, ‘model_entity’ ⇒ $modelEntity, ‘table_name’ ⇒ $tableName)
Mage Core core_layout_update_updates_get_after array(’updates’ ⇒ $updatesRoot)
Mage Core core_layout_update_updates_get_after array(’updates’ ⇒ $updatesRoot)
Mage Core core_collection_abstract_load_before array(’collection’ ⇒ $this)
Mage Core core_collection_abstract_load_after array(’collection’ ⇒ $this)
Mage Customer customer_registration_is_allowed array(’result’ ⇒ $result)
Mage Customer customer_customer_authenticated array(’model’ ⇒ $this,’password’ ⇒ $password,)
Mage Customer customer_session_init array(’customer_session’⇒$this)
Mage Customer customer_login array(’customer’⇒$customer)
Mage Customer customer_login array(’customer’⇒$customer)
Mage Customer customer_login array(’customer’⇒$customer)
Mage Customer customer_logout array(’customer’ ⇒ $this→getCustomer())
Mage Eav adminhtml_block_eav_attribute_edit_form_init array(’form’ ⇒ $this→getForm())
Mage Eav eav_attribute_get_backend_type_by_input array(’model’⇒$this, ‘type’⇒$type)
Mage Eav eav_attribute_get_default_value_by_input array(’model’⇒$this, ‘type’⇒$type)
Mage Eav eav_collection_abstract_load_before array(’collection’ ⇒ $this)
Mage GoogleCheckout google_checkout_discount_item_price array(’quote’ ⇒ $this→getQuote(), ‘discount_item’ ⇒ $discountItem)
Mage Log log_log_clean_before array(’log’ ⇒ $object)
Mage Log log_log_clean_after array(’log’ ⇒ $object)
Mage Log log_visitor_collection_load_before array(’collection’ ⇒ $this)
Mage Oscommerce store_add array(’store’⇒$storeModel)
Mage Payment payment_method_is_active array(’result’ ⇒ $checkResult,’method_instance’ ⇒ $this,’quote’ ⇒ $quote,)
Mage Paypal checkout_type_onepage_save_order array(’order’⇒$order, ‘quote’⇒$this→getReview()→getQuote())
Mage Paypal checkout_type_onepage_save_order array(’order’⇒$order, ‘quote’⇒$this→getQuote())
Mage PaypalUk checkout_type_onepage_save_order array(’order’⇒$order, ‘quote’⇒$this→getReview()→getQuote())
Mage PaypalUk checkout_type_onepage_save_order array(’order’⇒$order, ‘quote’⇒$this→getQuote())
Mage Review review_controller_product_init_before array(’controller_action’⇒$this)
Mage Review review_controller_product_init array(’product’⇒$product)
Mage Review review_controller_product_init_after array(’product’⇒$product, ‘controller_action’ ⇒ $this)
Mage Review review_review_collection_load_before array(’collection’ ⇒ $this)
Mage Rss rss_catalog_category_xml_callback $args
Mage Rss rss_catalog_new_xml_callback $args
Mage Rss rss_catalog_special_xml_callback $args
Mage Rss rss_catalog_tagged_item_xml_callback $args
Mage Rss rss_order_new_collection_select array(’collection’ ⇒ $collection)
Mage Rule rule_environment_collect array(’env’⇒$this)
Mage Sales sales_order_place_before array(’order’⇒$this)
Mage Sales sales_order_place_after array(’order’⇒$this)
Mage Sales sales_quote_remove_item array(’quote_item’ ⇒ $item)
Mage Sales sales_quote_add_item array(’quote_item’ ⇒ $item)
Mage Sales $this→_eventPrefix . ‘_collect_totals_before’ array($this→_eventObject⇒$this)
Mage Sales $this→_eventPrefix . ‘_collect_totals_after’ array($this→_eventObject⇒$this)
Mage Sales $this→_eventPrefix . ‘_merge_before’ array($this→_eventObject⇒$this,’source’⇒$quote)
Mage Sales $this→_eventPrefix . ‘_merge_after’ array($this→_eventObject⇒$this,’source’⇒$quote)
Mage Sales sales_convert_order_to_quote array(’order’⇒$order, ‘quote’⇒$quote)
Mage Sales sales_convert_quote_to_order array(’order’⇒$order, ‘quote’⇒$quote)
Mage Sales sales_convert_quote_address_to_order array(’address’⇒$address, ‘order’⇒$order)
Mage Sales sales_convert_quote_address_to_order_address array(’address’ ⇒ $address, ‘order_address’ ⇒ $orderAddress)
Mage Sales sales_convert_quote_payment_to_order_payment array(’order_payment’ ⇒ $orderPayment, ‘quote_payment’ ⇒ $payment)
Mage Sales sales_convert_quote_item_to_order_item array(’order_item’⇒$orderItem, ‘item’⇒$item)
Mage Sales sales_quote_item_collection_products_after_load array(’product_collection’⇒$productCollection)
Mage Sales sales_sale_collection_query_before array(’collection’ ⇒ $this)
Mage Sales sales_order_creditmemo_refund array($this→_eventObject⇒$this)
Mage Sales sales_order_creditmemo_cancel array($this→_eventObject⇒$this)
Mage Sales sales_order_invoice_pay array($this→_eventObject⇒$this)
Mage Sales sales_order_invoice_cancel array($this→_eventObject⇒$this)
Mage Sales sales_order_item_cancel array(’item’⇒$this)
Mage Sales sales_order_payment_place_start array(’payment’ ⇒ $this)
Mage Sales sales_order_payment_place_end array(’payment’ ⇒ $this)
Mage Sales sales_order_payment_capture array(’payment’ ⇒ $this, ‘invoice’ ⇒ $invoice)
Mage Sales sales_order_payment_pay array(’payment’ ⇒ $this, ‘invoice’ ⇒ $invoice)
Mage Sales sales_order_payment_cancel_invoice array(’payment’ ⇒ $this, ‘invoice’ ⇒ $invoice)
Mage Sales sales_order_payment_void array(’payment’ ⇒ $this, ‘invoice’ ⇒ $document)
Mage Sales sales_order_payment_refund array(’payment’ ⇒ $this, ‘creditmemo’ ⇒ $creditmemo)
Mage Sales sales_order_payment_cancel_creditmemo array(’payment’ ⇒ $this, ‘creditmemo’ ⇒ $creditmemo)
Mage Sales sales_order_payment_cancel array(’payment’ ⇒ $this)
Mage Sales sales_quote_item_qty_set_after array(’item’⇒$this)
Mage Sales sales_quote_item_set_product array(’product’ ⇒ $product,’quote_item’⇒$this)
Mage Sales $this→_eventPrefix . ‘_import_data_before’ array($this→_eventObject⇒$this,’input’⇒$data,)
Mage Sales sales_quote_address_discount_item $eventArgs
Mage Sales sales_quote_address_discount_item $eventArgs
Mage SalesRule salesrule_validator_process array(’rule’ ⇒ $rule,’item’ ⇒ $item,’address’ ⇒ $address,’quote’ ⇒ $quote,’qty’ ⇒ $qty,’result’ ⇒ $result,)
Mage SalesRule sales_quote_address_discount_item $eventArgs
Mage SalesRule sales_quote_address_discount_item $eventArgs
Mage SalesRule salesrule_rule_condition_combine array(’additional’ ⇒ $additional)
Mage Sendfriend sendfriend_product array(’product’ ⇒ $product)
Mage Tag tag_tag_product_collection_load_after array(’collection’ ⇒ $this)
Mage Tax tax_rate_data_fetch array(’request’⇒$this)
Mage Tax tax_settings_change_after’
Mage Tax tax_settings_change_after’
Mage Tax tax_settings_change_after’
Mage Tax tax_settings_change_after’
Mage Tax tax_settings_change_after’
Mage Wishlist wishlist_add_product array(’wishlist’⇒$wishlist, ‘product’⇒$product)
Mage Wishlist wishlist_share array(’wishlist’⇒$wishlist)

This is what should be put in config.xml of your module to hook on an event.

Original post

 

Magento 1.X getUrl() Function Parameters

Read More

In many, many places throughout Magento you will come across uses of getUrl() that generates a web address. It takes just two parameters but is immensely versatile.

Parameter 1 – $routePath

The route path follows the Zend behaviour of “module/controller/action”.

The module part is self-explanatory. For example “cms” resolves to Mage_Cms.

The controller is the class that will handle the address. “cms/page” refers to the class Mage_Cms_PageController.

Lastly, the action is the method within that class. “cms/page/view” will callMage_Cms_PageController::viewAction().

If any of these parts is given as “*” it will use the current module, controller or action in use. If omitted it defaults to “index”. For example; If viewing a CMS page then the following is equivalent to “cms/page/index”. Note there is no “view”.

  1. Mage::getUrl(‘*/*’);

Parts that aren’t recognised are passed verbatim which makes for an easy shortcut. You can pass the path to a static file and it will be appended to the domain.

  1. Mage::getUrl(‘index.html’);

Parameter 2 – $routeParams

This is an array that converts key/values into pairs of path directories.

  1. Mage::getUrl(‘cms/page/view’array(‘id’ => 1));

There are several special values that effect the outcome. They all begin with an underscore and are reserved.

_absolute n/a No effect. URLs are always generated as absolute.
_current bool Uses the current module, controller, action and parameters
_direct string Simply append to the base URL, same effect as passing to $routePath. See _store
_escape bool Uses & instead of &
_forced_secure bool Uses the secure domain given in configuration
_fragment string The last part of the URL after a #
_ignore_category bool Only applies to Mage_Catalog_Model_Product_Url::getUrl(). Prevents category rewrite from being used.
_nosid bool Prevents a SID query parameter being used when referencing another store
_query string or array If an array it is converted into a string like ?key=value&key=value which will become the$_GET variable.
_secure bool Uses the secure domain if allowed in configuration
_store int or string Either the numeric store ID or textual store code. It will use the correct domain as the base URL.
_store_to_url bool Adds ___store to the query parameters. Useful for targetting a store that doesn’t have an unique domain.
_type string link is the default. direct_link is useful for bypassing the “store code in URLs” feature. js,media and skin append the domain (and possibly store code) with the relevant directory.
_use_rewrite bool Looks up the module/controller/action/parameters in the database for a search engine friendly equivalent.

Usage Examples

Current Page

  1. Mage::getUrl(array(
  2.     ‘_current’ => true,
  3.     ‘_use_rewrite’ => true
  4. ));

Full path is preserved. Fragment and queries are stripped.

Current Page, Secured, For Another Store

  1. Mage::getUrl(array(
  2.     ‘_current’ => true,
  3.     ‘_use_rewrite’ => true,
  4.     ‘_secure’ => true,
  5.     ‘_store’ => 2,
  6.     ‘_store_to_url’ => true
  7. ));

Session ID may well be added automatically to solve the cookie problem.

Static Page On Main Store

  1. Mage::getUrl(‘example.html’array(
  2.     ‘_nosid’ => true,
  3.     ‘_store’ => ‘default’,
  4.     ‘_type’ => ‘direct_link’
  5. ));

Session ID is stripped, the static will not be using it. A type of direct_link means a store code is not inserted

Original post

User management in Ubuntu

Show last user logins into the system
lastlog | less
Currently logged in users in the system
who

Add new user
adduser username usergroupname (perl calling useradd)
useradd username

Delete user
userdel username
userdel -r username removing home directory

deluser with /etc/deluser.conf (Debian and derivatives)
deluser --remove-home

 

 

Windows 10 Add better sendto functionality

Read More

Adds multiple file send to functionality
Create SendToMailRecipient.vbs somewhere executable with the code below
Create a shortcut link to it
Put the link in the directory opened with shell:sendto

Option Explicit
Dim objArgs, OutApp, oNameSpace, oInbox, oEmailItem, olMailItem
Dim a, oAttachments, subjectStr, olFormatHTML
olMailItem = 0
olFormatHTML = 2
Set objArgs = WScript.Arguments 'gets paths of selected files
Set OutApp = CreateObject("Outlook.Application") 'opens Outlook
Set oEmailItem = OutApp.CreateItem(olMailItem) 'opens new email
For a = 0 to objArgs.Count - 1
Set oAttachments = oEmailItem.Attachments.Add(objArgs(a))
subjectStr = subjectStr & Right(objArgs(a),Len(objArgs(a))-(InStrRev(objArgs(a),"\"))) & ", " 'recreates the default Subject e.g. Emailing: file1.doc, file2.xls
Next
If subjectStr = "" then subjectStr = "No Subject "
oEmailItem.Subject = "Emailing: " & Left(subjectStr, (Len(subjectStr)-2))
oEmailItem.BodyFormat = olFormatHTML
oEmailItem.Display

Thomas Sowell Quotes

Read More

31. “Activism is a way for useless people to feel important, even if the consequences of their activism are counterproductive for those they claim to be helping and damaging to the fabric of society as a whole.” Thomas Sowell in twitter

30. “The problem isn’t that Johnny can’t read. The problem isn’t even that Johnny can’t think. The problem is that Johnny doesn’t know what thinking is; he confuses it with feeling.”

29. “One of the consequences of such notions as ‘entitlements’ is that people who have contributed nothing to society feel that society owes them something, apparently just for being nice enough to grace us with their presence.”

28. “Each new generation born is in effect an invasion of civilization by little barbarians, who must be civilized before it is too late.”

27. “Virtually no idea is too ridiculous to be accepted, even by very intelligent and highly educated people, if it provides a way for them to feel special and important. Some confuse that feeling with idealism.”

26. “I wonder what radical feminists make of the fact that it was men who created the rule of ‘women and children first’ when it came to rescuing people from life-threatening emergencies.”

25. “The word ‘racism’ is like ketchup. It can be put on practically anything — and demanding evidence makes you a ‘racist.’

24. “To believe in personal responsibility would be to destroy the whole special role of the anointed, whose vision casts them in the role of rescuers of people treated unfairly by ‘society.’”

23. “What sense would it make to classify a man as handicapped because he is in a wheelchair today, if he is expected to be walking again in a month and competing in track meets before the year is out? Yet Americans are given ‘class’ labels on the basis of their transient location in the income stream. If most Americans do not stay in the same broad income bracket for even a decade, their repeatedly changing ‘class’ makes class itself a nebulous concept.

22. “There is much discussion of the haves and the have-nots, but very little discussion of the doers and the do-nots, those who contribute and those who merely take.”

21. “It would be hard to think of a more ridiculous way to make decisions than to transfer those decisions to third parties who pay no price for being wrong. Yet that is what at least half of the bright ideas of the political left amount to.”

20. “When you want to help people, you tell them the truth. When you want to help yourself, you tell them what they want to hear. People with careers as ethnic leaders usually tell their followers what they want to hear.”

19. “‘We are a nation of immigrants,’ we are constantly reminded. We are also a nation of people with ten fingers and ten toes. Does that mean that anyone who has ten fingers and ten toes should be welcomed and given American citizenship?”

18. “It is amazing how many people think that the government’s role is to give them what they want by overriding what other people want.”

17. “Those who cry out that the government should ‘do something’ never even ask for data on what has actually happened when the government did something, compared to what actually happened when the government did nothing.”

16. “Four things have almost invariably followed the imposition of controls to keep prices below the level they would reach under supply and demand in a free market: (1) increased use of the product or service whose price is controlled, (2) Reduced supply of the same product or service, (3) quality deterioration, (4) black markets.”

15. “Much of the social history of the Western world, over the past three decades, has been a history of replacing what worked with what sounded good.”

14. “Weighing benefits against costs is the way most people make decisions – and the way most businesses make decisions, if they want to stay in business. Only in government is any benefit, however small, considered to be worth any cost, however large.”

13. “Considering how often throughout history even intelligent people have been proved to be wrong, it is amazing that there are still people who are convinced that the only reason anyone could possibly say something different from what they believe is stupidity or dishonesty.”

12. “Since this is an era when many people are concerned about ‘fairness’ and ‘social justice,’ what is your ‘fair share’ of what someone else has worked for?”

11. “For the anointed, traditions are likely to be seen as the dead hand of the past, relics of a less enlightened age, and not as the distilled experience of millions who faced similar human vicissitudes before.”

10. “It is amazing how many of the intelligentsia call it ‘greed’ to want to keep what you have earned, but not greed to want to take away what somebody else has earned, and let politicians use it to buy votes.”

9. “If you cannot achieve equality of performance among people born to the same parents and raised under the same roof, how realistic is it to expect to achieve it across broader and deeper social divisions?”

8. “It is amazing how many people think that they can answer an argument by attributing bad motives to those who disagree with them. Using this kind of reasoning, you can believe or not believe anything about anything, without having to bother to deal with facts or logic.”

7. “Experience trumps brilliance.”

6. “There is usually only a limited amount of damage that can be done by dull or stupid people. For creating a truly monumental disaster, you need people with high IQs.”

5. “There are few modest talents so richly rewarded — especially in politics and the media — as the ability to portray parasites as victims, and portray demands for preferential treatment as struggles for equal rights.”

4. “In short, killing the goose that lays the golden egg is a viable political strategy, so long as the goose does not die before the next election and no one traces the politicians’ fingerprints on the murder weapon.”

3. ”The charge is often made against the intelligentsia and other members of the anointed that their theories and the policies based on them lack common sense. But the very commonness of common sense makes it unlikely to have any appeal to the anointed. How can they be wiser and nobler than everyone else while agreeing with everyone else?”

2. “No one will really understand politics until they understand that politicians are not trying to solve our problems. They are trying to solve their own problems – of which getting elected and re-elected are number one and number two. Whatever is number three is far behind.”

1. “There are no solutions; there are only trade-offs.”

Original article|

Heinlein quotes

Read More
  • Throughout history, poverty is the normal condition of man. Advances which permit this norm to be exceeded — here and there, now and then — are the work of an extremely small minority, frequently despised, often condemned, and almost always opposed by all right-thinking people. Whenever this tiny minority is kept from creating, or (as sometimes happens) is driven out of a society, the people then slip back into abject poverty. This is known as “bad luck”.
  • Never underestimate the power of human stupidity.
  • An armed society is a polite society. Manners are good when one may have to back up his acts with his life.
  • Political tags – such as royalist, communist, democrat, populist, fascist, liberal, conservative, and so forth – are never basic criteria. The human race divides politically into those who want people to be controlled and those who have no such desire.
  • A human being should be able to change a diaper, plan an invasion, butcher a hog, conn a ship, design a building, write a sonnet, balance accounts, build a wall, set a bone, comfort the dying, take orders, give orders, cooperate, act alone, solve equations, analyze a new problem, pitch manure, program a computer, cook a tasty meal, fight efficiently, die gallantly. Specialization is for insects.
  • There is no worse tyranny than to force a man to pay for what he does not want merely because you think it would be good for him.
  • Always listen to experts. They’ll tell you what can’t be done, and why. Then do it.
  • There are no dangerous weapons; there are only dangerous men.
  • Climate is what you expect, weather is what you get.
  • Violence, naked force, has settled more issues in history than has any other factor.
  • A generation which ignores history has no past — and no future.
  • You can sway a thousand men by appealing to their prejudices quicker than you can convince one man by logic.
  • At least once every human should have to run for his life, to teach him that milk does not come from supermarkets, that safety does not come from policemen, that ‘news’ is not something that happens to other people. He might learn how his ancestors lived and that he himself is no different–in the crunch his life depends on his agility, alertness, and personal resourcefulness.
  • Cheops’ Law: Nothing ever gets built on schedule or within budget.
  • Taxes are not levied for the benefit of the taxed.
  • No statement should be believed because it is made by an authority.

Magento Code Snippets

Read More

Download extension manually using pear/mage

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

Clear cache/reindex

<?php
// clear cache
Mage::app()->removeCache('catalog_rules_dirty');
// reindex prices
Mage::getModel('index/process')->load(2)->reindexEverything();
/*
1 = Product Attributes
2 = Product Attributes
3 = Catalog URL Rewrites
4 = Product Flat Data
5 = Category Flat Data
6 = Category Products
7 = Catalog Search Index
8 = Tag Aggregation Data
9 = Stock Status
*/
?>

Load category by id

<?php
$_category = Mage::getModel('catalog/category')->load(89);
$_category_url = $_category->getUrl();
?>

Load product by id or sku

<?php
$_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
?>

Get Configurable product’s Child products

<?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
// input is $_product and result is iterating child products
$conf = Mage::getModel('catalog/product_type_configurable')->setProduct($_product);
$col = $conf->getUsedProductCollection()->addAttributeToSelect('*')->addFilterByRequiredOptions();
foreach($col as $simple_product){
	var_dump($simple_product->getId());
}
?>

Log to custom file

<?php Mage::log('Your Log Message', Zend_Log::INFO, 'your_log_file.log'); ?>

Call Static Block

<?php echo $this->getLayout()->createBlock('cms/block')->setBlockId('block-name')->toHtml(); ?>

Add JavaScript to page

First approach: page.xml – you can add something like

<action method="addJs"><script>path/to/my/file.js</script></action>

Second approach: Find page/html/head.phtml in your theme and add the code directly to page.html.

Third approach: If you look at the stock page.html mentioned above, you’ll see this line

<?php echo $this->getChildHtml() ?>

Normally, the getChildHtml method is used to render a specific child block. However, if called with no paramater, getChildHtml will automatically render all the child blocks. That means you can add something like

<!-- existing line --> <block type="page/html_head" name="head" as="head">
	<!-- new sub-block you're adding --> <block type="core/template" name="mytemplate" as="mytemplate" template="page/mytemplate.phtml"/>
	...

to page.xml, and then add the mytemplate.phtml file. Any block added to the head block will be automatically rendered. (this automatic rendering doesn’t apply for all layout blocks, only for blocks where getChildHtml is called without paramaters).

Check if customer is logged in

<?php $logged_in = Mage::getSingleton('customer/session')->isLoggedIn(); // (boolean) ?>

Get the current category/product/cms page

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

Run Magento Code Externally

<?php
require_once('app/Mage.php'); //Path to Magento
umask(0);
Mage::app();
// Run you code here
?>

Programmatically change Magento’s core config data

<?php
// find 'path' in table 'core_config_data' e.g. 'design/head/demonotice'
$my_change_config = new Mage_Core_Model_Config();
// turns notice on
$my_change_config->saveConfig('design/head/demonotice', "1", 'default', 0);
// turns notice off
$my_change_config->saveConfig('design/head/demonotice', "0", 'default', 0);
?>

Changing the Admin URL

Open up the /app/etc/local.xml file, locate the <frontName> tag, and change the ‘admin’ part it to something a lot more random, eg:

<frontName><![CDATA[supersecret-admin-name]]></frontName>

Clear your cache and sessions.

Magento: Mass Exclude/Unexclude Images

By default, Magento will check the ‘Exclude’ box for you on all imported images, making them not show up as a thumbnail under the main product image on the product view.

# Mass Unexclude
UPDATE`catalog_product_entity_media_gallery_value` SET `disabled` = '0' WHERE `disabled` = '1';
# Mass Exclude
UPDATE`catalog_product_entity_media_gallery_value` SET `disabled` = '1' WHERE `disabled` = '0';

getBaseUrl – Magento URL Path

<?php
// http://example.com/
echo Mage::getBaseUrl(Mage_Core_Model_Store::URL_TYPE_WEB);
// http://example.com/js/
echo Mage::getBaseUrl(Mage_Core_Model_Store::URL_TYPE_JS);
// http://example.com/index.php/
echo Mage::getBaseUrl(Mage_Core_Model_Store::URL_TYPE_LINK);
// http://example.com/media/
echo Mage::getBaseUrl(Mage_Core_Model_Store::URL_TYPE_MEDIA);
// http://example.com/skin/
echo Mage::getBaseUrl(Mage_Core_Model_Store::URL_TYPE_SKIN);
?>

Get The Root Category In Magento

<?php
$rootCategoryId = Mage::app()->getStore()->getRootCategoryId();
$_category = Mage::getModel('catalog/category')->load($rootCategoryId);
// You can then get all of the top level categories using:
$_subcategories = $_category->getChildrenCategories();
?>

Get The Current URL In Magento

<?php echo Mage::helper('core/url')->getCurrentUrl(); ?>

Category Navigation Listings in Magento

Make sure the block that you’re working is of the type catalog/navigation. If you’re editing catalog/navigation/left.phtml then you should be okay.

<div id="leftnav">
	<?php $helper = $this->helper('catalog/category') ?>
	<?php $categories = $this->getStoreCategories() ?>
	<?php if (count($categories) > 0): ?>
		<ul id="leftnav-tree" class="level0">
			<?php foreach($categories as $category): ?>
				<li class="level0<?php if ($this->isCategoryActive($category)): ?> active<?php endif; ?>">
					<a href="<?php echo $helper->getCategoryUrl($category) ?>"><span><?php echo $this->escapeHtml($category->getName()) ?></span></a>
					<?php if ($this->isCategoryActive($category)): ?>
						<?php $subcategories = $category->getChildren() ?>
						<?php if (count($subcategories) > 0): ?>
							<ul id="leftnav-tree-<?php echo $category->getId() ?>" class="level1">
								<?php foreach($subcategories as $subcategory): ?>
									<li class="level1<?php if ($this->isCategoryActive($subcategory)): ?> active<?php endif; ?>">
										<a href="<?php echo $helper->getCategoryUrl($subcategory) ?>"><?php echo $this->escapeHtml(trim($subcategory->getName(), '- ')) ?></a>
									</li>
								<?php endforeach; ?>
							</ul>
							<script type="text/javascript">decorateList('leftnav-tree-<?php echo $category->getId() ?>', 'recursive')</script>
						<?php endif; ?>
					<?php endif; ?>
				</li>
			<?php endforeach; ?>
		</ul>
		<script type="text/javascript">decorateList('leftnav-tree', 'recursive')</script>
	<?php endif; ?>
</div>

Debug using zend

<?php echo Zend_Debug::dump($thing_to_debug, 'debug'); ?>

$_GET, $_POST & $_REQUEST Variables

<?php
// $_GET
$productId = Mage::app()->getRequest()->getParam('product_id');
// The second parameter to getParam allows you to set a default value which is returned if the GET value isn't set
$productId = Mage::app()->getRequest()->getParam('product_id', 44);
$postData = Mage::app()->getRequest()->getPost();
// You can access individual variables like...
$productId = $postData['product_id']);
?>

Get methods of an object

First, use get_class to get the name of an object’s class.

<?php $class_name = get_class($object); ?>

Then, pass that get_class_methods to get a list of all the callable methods on an object

<?php
$class_name = get_class($object);
$methods = get_class_methods($class_name);
foreach($methods as $method)
{
	var_dump($method);
}
?>

Is product purchasable?

<?php if($_product->isSaleable()) { // do stuff } ?>

Load Products by Category ID

<?php
$_category = Mage::getModel('catalog/category')->load(47);
$_productCollection = $_category->getProductCollection();
if($_productCollection->count()) {
	foreach( $_productCollection as $_product ):
		echo $_product->getProductUrl();
		echo $this->getPriceHtml($_product, true);
		echo $this->htmlEscape($_product->getName());
	endforeach;
}
?>

Update all subscribers into a customer group (e.g. 5)

UPDATE
	customer_entity,
	newsletter_subscriber
SET
	customer_entity.`group_id` = 5
WHERE
	customer_entity.`entity_id` = newsletter_subscriber.`customer_id`
AND
	newsletter_subscriber.`subscriber_status` = 1;

Get associated products

In /app/design/frontend/default/site/template/catalog/product/view/type/

<?php $_helper = $this->helper('catalog/output'); ?>
<?php $_associatedProducts = $this->getAllowProducts() ?>
<?php //var_dump($_associatedProducts); ?>
<br />
<br />
<?php if (count($_associatedProducts)): ?>
	<?php foreach ($_associatedProducts as $_item): ?> 
		<a href="<?php echo $_item->getProductUrl() ?>"><?php echo $_helper->productAttribute($_item, $_item->getName(), 'name') ?> | <?php echo $_item->getName() ?> | <?php echo $_item->getPrice() ?></a>
		<br />
		<br />
	<?php endforeach; ?>
<?php endif; ?>

Get An Array of Country Names/Codes in Magento

<?php
$countryList = Mage::getResourceModel('directory/country_collection')
                    ->loadData()
                    ->toOptionArray(false);
     
    echo '<pre>';
    print_r( $countryList);
    exit('</pre>');
?>

Create a Country Drop Down in the Frontend of Magento

<?php
$_countries = Mage::getResourceModel('directory/country_collection')
                                    ->loadData()
                                    ->toOptionArray(false) ?>
<?php if (count($_countries) > 0): ?>
    <select name="country" id="country">
        <option value="">-- Please Select --</option>
        <?php foreach($_countries as $_country): ?>
            <option value="<?php echo $_country['value'] ?>">
                <?php echo $_country['label'] ?>
            </option>
        <?php endforeach; ?>
    </select>
<?php endif; ?>

Create a Country Drop Down in the Magento Admin

<?php
    $fieldset->addField('country', 'select', array(
        'name'  => 'country',
        'label'     => 'Country',
        'values'    => Mage::getModel('adminhtml/system_config_source_country')->toOptionArray(),
    ));
?>

Return Product Attributes

<?php
$_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;
?>

Cart Data

<?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());
}
?>

Get Simple Products of a Configurable Product

<?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
}
?>

Turn template hints on/off via database

UPDATE
`core_config_data`
SET
`value` = 0
WHERE
`path` = "dev/debug/template_hints"
OR
`path` = "dev/debug/template_hints_blocks";

Delete all products

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`;

Getting Configurable Product from Simple Product ID in Magento 1.5+

<?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)
?>

Create a category using parent id

<?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
$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 category or update existing

<?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
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 = Mage::getBaseDir('media').'/import/'.basename($data['image']);

	if (is_file($filePath))
	{
		try 
		{
			$product->addImageToMediaGallery($fileName, array('thumbnail','small_image','image'), 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;
}
?>

Remove all products from store with id 1

<?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";
        }
    }
}
?>

Add a new user

<?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

UPDATE admin_user SET password=CONCAT(MD5('qX[password]'), ':qX') WHERE username='[username]';
/**
 * where:
 *	[password] - user password
 * 	[username] - user name
 **/

Add a new product to cart

<?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 product from cart

<?php
	function removeProductFromCart($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 product in cart?

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

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

		return false;
	}
?>

Get header cart html and products count

$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

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

Clear all orders

-- 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;

##Product navigation (getting previous and next items)

<?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(); 
?>

##Add custom columns to the Magento administration Catalog > Product grid

<?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;
    }
}
?>


Original article

Inverse selection in File Explorer

Read More

Use Invert Selection for Easier File Selection in Windows Explorer

The next time you need to select most of the files in an open Explorer window don’t waste your time holding down Ctrl and clicking each file manually. It’s much easier to select the ones you DON’T need, and then let Windows reverse your selection.

Inside an open window, hold down Ctrl as you select the file(s) you DON’T want to select (sounds backward, but wait…).

Select Edit, then Invert Selection, and Windows will turn your selection inside out leaving you with the files you wanted to select.

You can then delete or copy them as needed.