Showing posts with label Magento. Show all posts
Showing posts with label Magento. Show all posts

Jul 27, 2014

Magento - Customize your error page by store view.

In your magento home directory you can find file/folder structure.
Magento/
  errors/
     default/
        css/
        images/
        404.phtml
        503.phtml
        page.html
        report.phtml
     404.php
     503.php
     report.php
     processor.php
     local.xml

File description and uses.
404.php       -> I guess 404 page but seems not calls when i encounter.
503.php       -> Mostly for maintenance page(check your index.php)
report.php    -> this file calls when encounter un-handle exception.
processor.php -> Main class for error handling
local.xml     -> Error Handling configuration
    404.phtml -> 404 page template
    503.phtml -> Maintenance error handin template.
    page.html -> Main page or layout of the error excemption
    report.phtml -> Exception error template

Above info is just a head up about the file/folder structure and information. Now lets assume that you have store view with store code mobile(that simplify the store is for mobile). To create custom error for your store(Store front). Best way copy the default error and name it same to your store code.
$ cd MAGENTO_PATH_DIR/errors/
$ cp default mobile

Now is time for you to customize the mobile custom error page. For this to able to use, you have to modify MAGENTO/errors/local.xml

<config>
    <skin>default</skin> <!-- Change default in to mobile-->
    <!-- Some other setting below -->
</config>

Aside from modifying your local.xml. You can also access the site with a parameter skin and is your store code.
Example: http://localhost/magento?skin=mobile
or you can modify the MAGENTO/index.php and the code before below.
<?php
$_GET['skin']='mobile'; // Add aditional parameter on every request.
Mage::run($mageRunCode, $mageRunType);
?>

Jun 11, 2014

Magento - Adding existing product to new category via SQL

Most the time you edit the the product to assign the category or edit category and assign the products. Since magento admin is some too small on thousand product of catalog. Adding via SQL Query will faster to assigned.

Adding the Product into a category
INSERT INTO
catalog_category_product(category_id, product_id,position ) 
VALUES(48,85545,2);

Adding the Product to webstore
INSERT INTO catalog_category_product_index(
    category_id,
    product_id,
    position,
    is_parent,
    store_id,
    visibility
)
VALUES(
    48, -- CategoryID 
    85545, -- Product ID
    1, -- Posistion Normaly 1(1)
    1, -- Parent category ID
    3, -- Store ID
    4, -- Visibility
);

May 12, 2014

Magento: X_FORWARDED_FOR not recorded on core_session data.

If your site are behind proxies/LoadBalancer. x_forwarded_for will be use to determine the where is the original request came from. But suddenly magento can't able to log this data in you core_session data. To fixed this one find Mage_Core_Model_Session_Abstract_Varien class and getValidatorData method.

In the code section below
if (isset($_ENV['HTTP_X_FORWARDED_FOR'])) {

Add an inline elseif statement
}elseif (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {

Lets take look the original code.
public function getValidatorData()
    {
  // Some codes here ....
  if (isset($_ENV['HTTP_X_FORWARDED_FOR'])) {
    $parts[self::VALIDATOR_HTTP_X_FORVARDED_FOR_KEY] = (string)$_ENV['HTTP_X_FORWARDED_FOR'];
  }

  // Some codes here ....        
  return $parts;
}

After adding the inline elseif statement section this will be output
public function getValidatorData()
{
  // Some codes here ....
  if (isset($_ENV['HTTP_X_FORWARDED_FOR'])) {
    $parts[self::VALIDATOR_HTTP_X_FORVARDED_FOR_KEY] = (string)$_ENV['HTTP_X_FORWARDED_FOR'];
  }elseif (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
    $parts[self::VALIDATOR_HTTP_X_FORVARDED_FOR_KEY] = (string)$_SERVER['HTTP_X_FORWARDED_FOR'];
  }

  // Some codes here ....        
  return $parts;
}


NOTE/Disclamer: I don't know why magento developer didn't realize the _ENV global variable, only store data that set by server using setEvn method, and didnt event try to test and get the data in _SERVER global variable. BTW I just saw this bug on magento 1.5.X.

Jan 14, 2014

How to override magento model.

Overriding magento model is some tricky base, that's why I want to share how this models Override.


First Mage_Reports_Model_Event_Observer
<models>
    <reports>
        <rewrite>
            <event_observer>Globe_Reports_Model_Event_Observer</event_observer>
        </rewrite>
    </reports>
</models>



Second Mage_Reports_Model_Mysql4_Product_Index_Viewed_Collection
<!-- You configs -->
<models>
    <reports_mysql4>
        <rewrite>
            <product_index_viewed_collection>Globe_Reports_Model_Mysql4_Product_Index_Viewed_Collection</product_index_viewed_collection>
        </rewrite>
    </reports_mysql4>
</models>

// Your PHP class
class Globe_Reports_Model_Mysql4_Product_Index_Viewed_Collection extends Mage_Reports_Model_Mysql4_Product_Index_Viewed_Collection{

// Put possible override methods or 
//  addition methods you want here
}

Nov 19, 2013

Magento: How to override the home url.

The Goal here is, instead of modifying the CMS(in admin) for the home data. You can better create a custom module to handle this one. At this place you have control to the controller, block and template. Unlike when you use the CMS to update you home, you can only controller the block and template with the sample tag below
{{ block="module/block" template="module/block.phtml"}}
BTW, to do the use the custom module as your home goto System -> Configuration -> Web -> Default Pages -> Default Web URL






But if you want to, just to change the home page, you can try this System -> Configuration -> Web -> Default Pages
Change the value of

Default Web URL " cms
CMS Home Page :  Choose the available pages in the drop down

Oct 24, 2013

Magento: How to remove the SID parameter in you store URL?

There two this we can do here.

1. Modify the setting in your magento admin.
* Go to System > Configuration > Web > Session Validation Settings and set the value of Use SID on Frontend into No
2. Sometimes the setting from your admin was cache and hard to flush your magento cache coz of many reason. Slowing the page.
To do this, modify the your core magento class app/code/core/Mage/Core/Model/App.php and set the value of $_useSessionInUrl into false. Since the default is true.
protected $_useSessionInUrl = true;

Sep 5, 2013

Magento: How to enable Profiler in magento?

First thing you my uncomment below code in your index.php
Varien_Profiler::enable();

Enable the store profiler in your magento admin. See the configuration in.
System -> Configuration -> Developer -> Debug -> Profiler

NOTE: if you are working on costumed magento theme be sure the profiler block added in you page.xml
<default translate="label" module="page">
// Some other stup here.
<block type="core/profiler" output="toHtml" name="core_profiler" />
</default>

If you want to profile your own module you can declare do below code.
Varien_Profiler::start('NameOfFragmentToProfile');
//
// ... Some batch of code here.
//
Varien_Profiler::stop('NameOfFragmentToProfile');

Sep 3, 2013

Magento: How to select a collection with one field only.

Here's what one user did. I it work like a charm to me.
$colelction->getSelect()
    ->reset(Zend_Db_Select::COLUMNS) // THis is import thing
    ->columns('MAX(created) as max_created')
    ->group(array('status_id'));

As courtesy to eth original post Magento: Single field collection

Aug 6, 2013

Magento: How to reindex via ssh or in terminal/console

Since reindexing request long term of running in our webserver. I thing it is better to do this one the console, to liminated the posoble timeout error.


Below are some possible command you can use.
Index product attributes for layered navigation building
php shell/indexer.php -reindex catalog_product_attribute

Rebuild Catalog product fulltext search index
php shell/indexer.php -reindex catalogsearch_fulltext

Reorganize EAV product structure to flat structure
php shell/indexer.php -reindex catalog_category_flat

Index Product Stock Status
php shell/indexer.php -reindex cataloginventory_stock

Indexed category/products association
php shell/indexer.php -reindex catalog_category_product

Index product prices
php shell/indexer.php -reindex catalog_product_price

Rebuild Tag aggregation data
php shell/indexer.php -reindex tag_summary


Index product and categories URL rewrites
php shell/indexer.php -reindex catalog_url

If you want to reindex all.
php shell/indexer.php -reindexall


Also, for other useful command parameter you can use help screen that is accessable via SSH using the command:
php ./shell/indexer.php -help

Jul 17, 2013

Magento: Creating block and inject to you layout.

Here the simple code

// In your controller action
public function indexAction()
{
  //Get current layout state
  $this->loadLayout();
  $block = $this->getLayout()->createBlock(
    'Mage_Core_Block_Template',
    'my_block_name_here',
    array('template' => 'module/my_custumtemplate.phtml') 
  );

  // always to for surely the you block not invalid
  try{
    $this->getLayout()->getBlock('content')->append($block);
  }catch(Exception $e){
  }
  //Release layout stream... lol... sounds fancy
  $this->renderLayout();
}

Jul 3, 2013

Magento: How to minified your html content?

I know its very bad idea to modify the core code, but sorry I don't have time to test override the class.


To do this you need to modify Mage_Core_Block_Template class and its fetchView method.

public function fetchView($fileName)
{
  // ***********
  // Some other code up
  // *********************

  // This is the in the bottom code
  if (Mage::app()->getStore()->getCode() == 'admin'){
     // Admin must not to minify since, there was lot on inline comment(//)
     // which generate javascript error.
     return $html;
  }else{
    // Instead of just returning the html data, you need to
    //  remove the  un-needed extra space and new lines.
    $html = preg_replace('/\s+/', ' ', trim($html)); // remove new line

    // Remove space on every start on a tag </script> <div> become </script> <div>
    $html = preg_replace('/ </', '<',$html); // For more compression only you can skip this line.

    return $html; 
  }


}







WARNING:

This is not applicable if you have javascript in your template will an inline comment double slash(//). Since the code become one line, whole javascript after the // become comment. I know you know that. Suggestion pleas use the group comment(/*** Your comment inside */) or move all you javascript in a js file. :)

Cheerr

Jul 2, 2013

Magento: core_file_storage' doesn't exist'

This kind of error mostly happen if you just copy a database and checkout the source that you team is working for..

So here the solution I found, create to tables manually.
core_directory_storage
CREATE TABLE `core_directory_storage` (
  `directory_id` INT(10) UNSIGNED NOT NULL AUTO_INCREMENT,
  `name` VARCHAR(255) NOT NULL DEFAULT '',
  `path` VARCHAR(255) NOT NULL DEFAULT '',
  `upload_time` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
  `parent_id` INT(10) UNSIGNED NULL DEFAULT NULL,
  PRIMARY KEY (`directory_id`),
  UNIQUE INDEX `IDX_DIRECTORY_PATH` (`name`, `path`),
  INDEX `parent_id` (`parent_id`),
  CONSTRAINT `FK_DIRECTORY_PARENT_ID` FOREIGN KEY (`parent_id`) 
  REFERENCES `core_directory_storage` (`directory_id`) ON UPDATE     CASCADE ON DELETE CASCADE
)
COMMENT='Directory storage'
COLLATE='utf8_general_ci'
ENGINE=InnoDB
ROW_FORMAT=DEFAULT
core_file_storage
CREATE TABLE `core_file_storage` (
  `file_id` INT(10) UNSIGNED NOT NULL AUTO_INCREMENT,
  `content` LONGBLOB NOT NULL,
  `upload_time` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
  `filename` VARCHAR(255) NOT NULL DEFAULT '',
  `directory_id` INT(10) UNSIGNED NULL DEFAULT NULL,
  `directory` VARCHAR(255) NULL DEFAULT NULL,
  PRIMARY KEY (`file_id`),
  UNIQUE INDEX `IDX_FILENAME` (`filename`, `directory`),
  INDEX `directory_id` (`directory_id`),
  CONSTRAINT `FK_FILE_DIRECTORY` FOREIGN KEY (`directory_id`) 
    REFERENCES `core_directory_storage` (`directory_id`) ON UPDATE CASCADE ON DELETE CASCADE
)
COMMENT='File storage'
COLLATE='utf8_general_ci'
ENGINE=InnoDB
ROW_FORMAT=DEFAULT

May 2, 2013

magento: How to get the current login customer?

Get the customer session
$customer = Mage::getSingleton('customer/session')->getCustomer();

Get customer properties.
$customer->getId();
$customer->getEmail();
$customer->getName(); // Full name
$customer->getFirstName(); // First name
$customer->getLastName(); // Last name

You can also get other customer custom attribute, like nick_name
$customer->getNickName();


If you think you need to know the current admin user try this one.
Mage::getSingleton('admin/session')->getUser();

Oct 18, 2012

Magento: How to add static block in your layout file?

Here we need to do, create static block, and assume we set the "my_test_static_block" as our name/identifier.

As we already created the static block. Place the code below in you layout (xml) file

<block type="cms/block" name="test_main_block">
 <action method="setBlockId">
   <block_id>my_test_static_block</block_id>
 </action>
</block>


See attached image for the sample.

Magento: How to add static block in your template file?

Here we need to do, create static block, and assume we set the "my_test_static_block" as our name/identifier.

As we already created the static block. Place the code below in you template (phtml) file.

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

In you looking how to add static in your layout file you found in this link.


Happy reading.

Oct 4, 2012

Magento - How to access Toolbar property from your list template.

Here's the solution.
In you Catalog List Block add new method.
class Mage_Catalog_Block_Product_List extends ...{

    ....

    // I want to access the get pager in my list.phtml template.
    public function getPagerHtml(){
        return $page = $this->getToolbarBlock()->getPagerHtml();
    }
}

In you list.phtml template has now able to display the pager html.
<?php echo $this->getPagerHtml() ?>

If this help you, dont forget to comment. Enjoooy reading.

Sep 27, 2012

Magento - How to create multiple fields to sort?

Find the class and made modification on the class.
Mage_Catalog_Block_Product_List_Toolbar

Find the getAvailableOrders() and made some modification.
     public function getAvailableOrders()
    {
        $orders = array(
            'news_from_date,entity_id'         => 'Newest',
            'name,brand'              => 'Brand Name',
            'rating'        => 'Top Rated',
        );

        $this->_availableOrder = $orders;
        
        return $orders;
    }

Also try to look setCollection($collection)
    public function setCollection($collection)
    {
        $this->_collection = $collection;

        $this->_collection->setCurPage($this->getCurrentPage());

        // we need to set pagination only if passed value integer and more that 0
        $limit = (int)$this->getLimit();
        if ($limit) {
            $this->_collection->setPageSize($limit);
        }
        
        if ($this->getCurrentOrder()) {
            // parse the attribute
            $orders = explode(',', $this->getCurrentOrder());
            foreach($orders as $order){
                // Add the other statement for to sort
                $this->_collection->setOrder($order, $this->getCurrentDirection());
            }
        return $this;
    }

Thanks just simple code to made multiple sorting. But i not suggest you to modify the magento core as is. if you can able to override class it better.

class Globe_Catalog_Block_Product_List_Toolbar 
  extends Mage_Catalog_Block_Product_List_Toolbar{

 // Your method you want here and method you want to override, some example.

    public function setCollection($collection)
    {
        $this->_collection = $collection;

        $this->_collection->setCurPage($this->getCurrentPage());

        // we need to set pagination only if passed value integer and more that 0
        $limit = (int)$this->getLimit();
        if ($limit) {
            $this->_collection->setPageSize($limit);
        }
        
        if ($this->getCurrentOrder()) {
            // parse the attribute
            $orders = explode(',', $this->getCurrentOrder());
            foreach($orders as $order){
                // Add the other statement for to sort
                $this->_collection->setOrder($order, $this->getCurrentDirection());
            }
        return $this;
    }
  

   // ... You other method.
}

Mar 26, 2012

Magento: Hack - Nested addAttributeToFilter.

I already waste my one whole working day to look on this problem but still can file the solution. So I decide to modify the the magento core.

Here's the condition I want to do in addAttributeToFilter function.

(condition1) OR ((condition2) and (condition3) ..... )


To solve this Fucking problem I modify this class Mage_Eav_Model_Entity_Collection_Abstract.

public function addAttributeToFilter($attribute, $condition=null, $joinType='inner')
{
....Some Code here
if (is_array($attribute)) {
$sqlArr = array();
foreach ($attribute as $condition) {
$sqlArr[] = $this->_getAttributeConditionSql($condition['attribute'], $condition, $joinType);
}
$conditionSql = '('.join(') OR (', $sqlArr).')';
}else{
... your other code here.
}


Here my modify version.

public function addAttributeToFilter($attribute, $condition=null, $joinType='inner')
{
....Some Code here
if (is_array($attribute)) {
$sqlArr = array();
$myAND = array();
$andSqlArr = array();
/*
* @ win mode to support (x=a) or (y=1 and z=0)
* array(
* array(condition)
* 'and' =>
* array(
* array(condition)
* array(condition)
* ),
* )
*
* Output expected
* cond1 OR (cond2 and cond3)
*/
foreach ($attribute as $key => $condition) {
if ($key === "and"){
$myAND = $condition;
continue;
}
$sqlArr[] = $this->_getAttributeConditionSql($condition['attribute'], $condition, $joinType);
}
foreach ($myAND as $key => $andCond ){
$andSqlArr[] = $this->_getAttributeConditionSql(
$andCond['attribute'],
$andCond,
$joinType);
}
$conditionSql = '('.join(') AND (', $andSqlArr).')';
if ($andSqlArr){
$sqlArr[] = $conditionSql;
}

$conditionSql = '('.join(') OR (', $sqlArr).')';
}
... your other code here.
}


In your product collection.

$collection->addFieldToFilter(
array(
array("attribute"=>"your_attribute1", "in"=>array(1,2,3,)),
"and" => array(
array("attribute"=>"your_attribute2", "eq"=>1,),
array("attribute"=>"your_attribute3", "eq"=>1,),
),
)
);


Happy Coding. :)

Mar 22, 2012

Magento: Deleting Product

A simple way to delete product is:
$productId = 1;
Mage::getSingleton('catalog/product')
  ->load($productId)
  ->delete();
If you want to delete product by category
$collection = Mage::getSingleton('catalog/category')
  ->load(YOUR_CATEGORY_ID)
  ->getproductCollection();

// If you want to filter by attribute
$collection->addAttributeToFilter('YOUR_ATTRIBUTE_CODE', 'ATTRIBUTE_VALUE')
foreach($collection as $product){
   $product =Mage::getSingleton('catalog/product')
     ->load($product->getId())
   try {
   // Im not sure what is the use of this part
   Mage::dispatchEvent(
     'catalog_controller_product_delete',
     array('product' => $product));
   
   // Finally we not able to delete the product
   $product->delete();
   }catch (Exception $e) {
     echo "Can't delete product w/ id: $product";
   }
}
Reference: Delete magento Product

Nov 15, 2011

Magento: Custom category Field.

Add one row to eav_attribute


INSERT INTO `fl_mage`.`eav_attribute`
SET
`attribute_id` =0, -- AUto
`entity_type_id`=3,
`attribute_code`='category_url',
`attribute_model`=NULL ,
`backend_model`=NULL ,
`backend_type`='varchar',
`backend_table`=NULL ,
`frontend_model` =NULL,
`frontend_input` ='text',
`frontend_label`='Url' ,
`frontend_class`=NULL ,
`source_model`=NULL ,
`is_required` '0',
`is_user_defined`='0' ,
`default_value` =NULL,
`is_unique` ='0',
`note`=''
;

Add other one row to eav_entity_attribute


INSERT INTO `fl_mage`.`eav_entity_attribute`
SET
`entity_attribute_id` =NULL,
`entity_type_id` =3,
`attribute_set_id` =3,
`attribute_group_id` =3,
`attribute_id`=163, --Must be same to eav_attribute
`sort_order`=3
;

Finally one more row to catalog_eav_attribute


INSERT INTO `catalog_eav_attribute`
SET
`attribute_id`=163,
`frontend_input_renderer`=NULL,
`is_global`=0,
`is_visible`=1,
`is_searchable`=0,
`is_filterable`=0,
`is_comparable`=0,
`is_visible_on_front`=0,
`is_html_allowed_on_front`=0,
`is_used_for_price_rules`=0,
`is_filterable_in_search`=0,
`used_in_product_listing`=0,
`used_for_sort_by`=0,
`is_configurable`=1,
`apply_to`=0,
`is_visible_in_advanced_search`=0,
`position`=0,
`is_wysiwyg_enabled`=0,
`is_used_for_promo_rules`=0
;

That's simple as is, you can find the charm there. Happy reading.

TIPS: If you are confuse try to look the eav_attribute and compare the data on your admin category page.

Reference: