Subesh Pokhrel

Magento Developers Blog

Using Custom Table for Custom Module in Magento

If you want to create a custom module in Magento that has something to do with storing data into a custom table and using that later, then this is just the right post you have bumped into! I will presume that you already know about Models in Magento, what are they and how you can create them. Also I will presume that you will also know the basic module structure in Magento. You will have to place this in your config.xml [source language=”xml”] <global> <ymodel> <class>YNamespace_YModule_Model</class> <resourceModel>quotes_mysql4</resourceModel> </ymodel> <quotes_mysql4> <class>YNamespace_Ymodule_Model_Mymodel</class> <entities> <mymodel> <table>ymodel_ytable</table> </mymodel> </entities> </quotes_mysql4> </global> [/source] Then Create a Model [source language=”php”] <?php class YNamespace_Ymodule_Model_Mymodel extends Mage_Core_Model_Abstract { public function _construct() { parent::_construct(); $this->_init(‘ymodel/mymodel’); } } [/source] As you can see in constructor of this class it inits the model (tag) defined in the config file. As model uses Resources, you now need to create a resource the module uses. [source language=”php”] <?php class Ynamespace_Ymodel_Model_Mysql4_Ymodel extends Mage_Core_Model_Mysql4_Abstract { public function _construct() { $this->_init(‘ymodel/mymodel’, ‘id’); } } [/source] So using this resource you now can access Table and add/alter. But you must not explicitly create a object of this class to do that. Creating a model of class above will make this resource usable. [source language=”php”] $model=Mage::getModel("ymodel/mymodel") ->setName("Subesh") ->setLastname("Pokhrel") ->save(); [/source] This will create a new row in table now given that name and lastname is the columns of the table. To edit row of a table do the following [source language=”php”] $model=Mage::getModel("ymodel/mymodel")->load($id) ->setName("Subesh") ->setLastname("Pokharel") ->save(); [/source] Now to select, there is another procedure. Before that let me tell about collection. Think collections as the array of objects.When you Query in database you get result as collections in Magento and every row resulting from the query is a different Object.To create a collection [source language=”php”] <?php class Ynamespace_Ymodel_Model_Mysql4_Mymodel_Collection extends Mage_Core_Model_Mysql4_Collection_Abstract { public function _construct() { parent::_construct(); $this->_init(‘ymodel/mymodel’); } } [/source] To Select All the row of Table [source language=”php”] $allCollection=Mage::getModel("ymodel/mymodel")->getCollection(); [/source] You can add filters in the above query as required. To get individual Row you can just loop through the collection :) [source language=”php”] foreach($allCollection as $objRow){ print_r($objRow); } [/source] Hope this helps if any one is in need… and @inchoo..please don’t twitt this as any other..link…you find in a weekend… :P.

Moving Magento Shop From Development Enviornment to Production Enviornment or Production to Local

Today, I had really a good chance to move Magento Shop from Development Enviournment to Product Enviornment. On that course I faced some big difficulty in moving the database. I already had the files and DB of the development enviornment, imporing DB was a PIA. I uploaded all the files, which was easy. And next thing I did was uploaded DB dumpped files to root of Magento. Then I logged into SSH and logged into MYSQL. Then Used the following commands to import the dumpped DB files. But first made the database say “magento”. [source language=’sql’] /**Using the Previously created DB**/ mysql> use magento /**Import the Dumpped SQL**/ mysql>source pathToMagentoRoot/mySql.sql [/source] So after the command is executed I had the whole DB on production enviornment. Similarly we can also import dumpped data of Production on Local database running on WAMP server. To import Dumpped SQL data on WAMP, first create a database, say magento and then use the following commands [source language=’sql’] /** Using the Previously created DB. -p password part is optional if you have not configured password for MYSQL locally -u Username (root by default) **/ mysql> C:\wamp\bin\mysql\mysql5.0.51b\bin>mysql.exe -use magento -u root -p password /**Import the Dumpped SQL**/ mysql>source pathToSQLSource/mySql.sql [/source] By Now we have the database synced between Local and Production. Next is configuring the database name used by Magento. Browse to app/etc/local.xml and change in the following part. [source language=”xml”]

Creating Block From the Code in Magento

Here are some methods of creating block by code in Magento. This type of code can be used directly in template, not need to create a layout file or add a child node inside already existing layout file. You can use this to echo a different type of block inside already loading block and template. [source language=”php”] // Directly in the PHTML where you want to show the block getLayout()->createBlock(“module/block”)->setTemplate(“module/page.phtml”)->toHtml(); ?> [/source] What we have actually done is just load the layout and create an instance of a block class defined inside its paramerter, then assigned a template to the block and finally echoed as html. Simple! The code above will be equivalent to what we do as following in layout and in template file. [source language=’xml’] // In layout [/source] [source language=”php”] getChildHtml(“module.name”); ?> [/source] May be helpful!

Getting Rescent Rating Summary of a Product in Magento

Magento has a default option to show the overall rating’s summary of the product, which is shown in the product view page. This summary is based on all the review posted and approved for the particular product. In the summary the stars are shown accordingly, by taking the sum of all reviews and calculating the average rating. But I had a case where I needed to show those star ratings, only based on the last approved user ratings. What I did was just a small tweak in the Magento’s default working! Magento gets all the reviews and processes it accordingly, so what I did was just added limit filter to get the rescent rating only, and left the Magento default working do the rest. Tricky! huh…. Here the block that can achieve the same. [source language=”php”] getReviewsCollection()->setPageSize(1); return $collection; } /** * Getting Current Product’s name */ public function getProductName () { return Mage::registry(“product”)->getName(); } /** * Getting Rating summary only for the one Review (latest one) */ public function getRatingSummary () { return Mage::getModel(‘rating/rating’)->getReviewSummary($this->getReviewId()); } } [/source] And here is the phtml file. [source language=”html”] getRescentReview()->getItems(); ?> load(array_keys($_items)); $curRat=$_review->getData(‘review_id’); // Setting the current Review Id to the block’s Object, used in Namespace_Comment_Block_Comment line #26 $this->setReviewId($curRat); if($curRat!=1): ?>

__(‘Recente Reviews’) ?>

getProductName()?>

– [/source] By the end of this you will get the Rescent rating summary on your product detail page. Happy Coding in Magento!!

Getting the Product’s Price in Current Currency Format of Store

Magento gives an option to have different currency defined for each store. To get the product’s price based on the current store you can use the following code. It uses the default Magento’s helper class to do. [source language=”php”] currency($product->getFinalPrice(),true,false); ?> [/source] In the code above $product is the product, whose price you will want to format.

Get All Options of Select or Multiselect Attribute in Magento by Attribute Code

One of the things that a Magento developer deal, time and again is finding out all the options of color or manufacturer or size attribute. You may also need to find out what are the options available for color attribute before you add new option programmatically. Or you may need to add assign the option’s ID to a product. Here’s what you need to do, just load the attribute by attribute code, then load all its options. Easy, isn’t it! Code is below. [source language=”php”] // Add the attribute code here. $attribute=$product->getResource()->getAttribute(“color”); // Checking if the attribute is either select or multiselect type. if($attribute->usesSource()){ // Getting all the sources (options) and print as label-value pair $options = $attribute->getSource()->getAllOptions(false); echo ”
";
	print_r($options);
}

[/source] 

Getting All Custom Options of a Product in Magento

Custom options are the options that can be added to any product, which gives an option for the user of the site to select what type of product they actually want. Here is a scenario where custom option can be helpful. If you have a product say ball and your stores sells plastic,rubber,glass balls. So you need to give the user to select what type of ball they actually want. Yes, you can do this by using configurable product as well, but why create an attribute for one product only! In this case custom option might be very helpful. Here’s the code to get the all the custom options of a product. Please see that you need to specify the id of the product for which you are retriving custom option for. I’ve echoed some text as well to give you an idea what exactly you are getting in each loop. [sourcecode language=”php”] $product = Mage::getModel("catalog/product")->load(167); $i = 1; echo "<pre>"; foreach ($product->getOptions() as $o) { echo "<strong>Custom Option:" . $i . "</strong><br/>"; echo "Custom Option TYPE: " . $o->getType() . "<br/>"; echo "Custom Option TITLE: " . $o->getTitle() . "<br/>"; echo "Custom Option Values: <br/>"; // Getting Values if it has option values, case of select,dropdown,radio,multiselect $values = $o->getValues(); foreach ($values as $v) { print_r($v->getData()); } $i++; echo "———————————-<br/>"; } [/sourcecode] Happy coding in Magento!

Adding Custom Options to a Product in Magento

Adding custom option in Magento is pretty easy! You just need to know the format of an array, which is taken by catalog/product_option Model to set the custom option. I’ve deviced a simple function (setCustomOption) that just does that. The function, according to the input type and values assigned creates an array, which is then used by the catalog/product_option Model to save the option to the product. Here is the function. [source language=”php”] /** * @param $value - Must be comma seperated options. * @param $title - Title of the custom option. * @param $type - Type of custom option - drop_down,radio,checkbox,multiple,area,field. * @param $noOption - Specifies if the custom options has options or not. */ function setCustomOption ($value, $title, $type, $noOption = false) { $custom_options = array(); if ($type && $value != “” && $value) { $values = explode(‘,’, $value); if (count($values)) { /**If the custom option has options*/ if (! $noOption) { $is_required = 0; $sort_order = 0; $custom_options[] = array( ‘is_delete’ => 0 , ‘title’ => $title , ‘previous_group’ => ” , ‘previous_type’ => ” , ‘type’ => $type , ‘is_require’ => $is_required , ‘sort_order’ => $sort_order , ‘values’ => array() ); foreach ($values as $v) { $titleopt = ucfirst(trim($v)); switch ($type) { case ‘drop_down’: case ‘radio’: case ‘checkbox’: case ‘multiple’: default: $title = ucfirst(trim($v)); $custom_options[count($custom_options) - 1][‘values’][] = array( ‘is_delete’ => 0 , ‘title’ => $titleopt , ‘option_type_id’ => - 1 , ‘price_type’ => ” , ‘price’ => ” , ‘sku’ => ” , ‘sort_order’ => ” ); break; } } return $custom_options; } /**If the custom option doesn’t have options | Case: area and field*/ else { $is_required = 0; $sort_order = ”; $custom_options[] = array( “is_delete” => 0 , “title” => $title , “previous_group” => “text” , “price_type” => ‘fixed’ , “price” => ” , “type” => $type , “is_required” => $is_required ); return $custom_options; } } } return false; } [/source] And to save the custom option, first get the array built by the above function and pass it to the catalog/product_option Model’s function to save. Here’s how you do it. [source language=”php”] $arrayOption = array(); /** * For Creating dropdown,select,multiselect,radio type of custom option */ $arrayOption[] = setCustomOption(“OPT1,OPT2”, “Select Option”, “drop_down”); /** * For Creating textfield and textarea type of custom option */ $arrayOption[] = setCustomOption(“Anyvalue”, “Area”, “area”, true); /** * Load the product you want to assign custom option to */ $product = Mage::getModel(“catalog/product”)->load(167); foreach ($arrayOption as $options) { foreach ($options as $option) { $opt = Mage::getModel(‘catalog/product_option’); $opt->setProduct($product); $opt->addOption($option); $opt->saveOptions(); } } [/source] After running the code you will get something like this. [caption id=”attachment_156” align=”alignnone” width=”347” caption=”Custom Option added to a Product”]Custom Option added to a Product[/caption] Hope you like this post!

Showing Breadcrumbs Anywhere in Magento

In Magento, by default there is a reference place where breadcrumbs get showed, that is just above the content reference! But, sometimes you need to show the breadcrumbs twice! above and below the content. Or sometimes you just need to show the breadcrumbs inside the content, due to some designing issue! I’ve gone through these situation a lot, and thought why not post a solution in my blog? :D Here’s the “magic code” for breadcrumbs to show anywhere in Magento [source language=”PHP”] getLayout()->getBlock(“breadcrumbs”)->toHtml()?> [/source] Its very simple, it just gets the block breadcrumbs defined in page.xml and echoes it as html. Happy coding!

Debugging Technique in Magento - Chapter 1 :: Debugging Layout

I’ve been working in Magento, for 1 year now! During this whole year I have learnt a lot, and have been sharing my learnings through this Blog. One of the thing that strikes me a lot is the debugging technique. My collegue ask me a lot regarding Debugging Modules Functionalities, Debugging Module’s Layout and its template not showing in frontend and backend, Some products and category attribute not showing in the frontend, Installation of Magento Custom Module and its setup not working and many more. And guess what in most of the cases I’ve developed a procedure or debugging steps, which I follow time and again, to get to the core of the situation. Actually now, I thought of writting down these debugging technique’s procedure , so that I can tell, please do the following, before you call for my help! This is the first part of series of post. I’ll discuss here how to debug layout errors. I’ll come across other technique as well, later on. Case: If you have just added your Layout/Template and wondering why it is not working ? First and foremost, If you have installed a new Module or Changed Layout and is not working where/how it is supposed to work, clear the cache from Admin, even if you say i have disabled the cache. To test if your layout file say, example.xml, is actually being looked up while the page loads, first open your example.xml file and make some error on that file. The error may be invalid tag closing of XML. And then refresh your page. If XML load error is displayed then you are sure that your layout file is being referred. If not then first see what package/theme you are using in Design and confirm if the layout is uploaded or placed in correct path. After you are sure that layout is placed okai, then its now time to see whether your layout file is registed in config.xml of your Custom Module or not. Your layout file’s name should be set in config.xml of any module inside . Please check if your tags are correct and under correct parents. Normally layout are inside Frontend–>Layout–>Updates. If you are through to this point, then your problem may lie in the Block defined. But before that see if you have defined correct reference name. Later on debugging Block. The post may be listed below. Stay tuned.