One of my previous articles was about getting a product information using getData method. This article is a step forward in that direction. I’m gonna show you how to retrieve almost anything in Magetno using getModel and getData methods (function if you prefer).
Before I start with the title related content let me say a word or two of my development tool. For the last few weeks I’m using only one tool while developing on PHP platform, NetBeans 6.5. My favorite text editor still remains Notepad++. Although the the official release is NetBeans 6.5 beta, I’m using the night build versions. In my modest opinion this is the best free IDE solution currently out there. I simply love the code completion in PHP and in HTML plus the coolest thing ever, jQuery code completion support. Since I’m a big fan of jQuery, NetBeans is my number one choice. Some of you probably don’t see HTML code completion as that big of a deal. Well, I do. It saves you a lot of time finishing all those quotes next to attributes and auto closing all those markup.
There is quite a number of threads and discussions on Magento form about getModel and getData methods. Here I will show you a few ways of using both. One thing to have in mind. I’m working on locally installed Magento with default sample data package. For some reason I like to use the app/design/frontend/default/mycustom/template/catalog/product/view.phtml file.
Where mycustom in the folder name is the name of my theme folder. Let’s get started.
If you open the view.phtml file and write down the $cModel = Mage::getModel(‘catalog/product’); you would basically say create an instance of Mage_Catalog_Model_Product class. So where does the catalog/product comes from? What are the other available parameters one can put into the getModel function? What are the methods of I can use on this new instance object? All of these are logical questions. Questions so poorly covered by current Magento documentation.
As I sad it before, I said it again; Magetno is great software, it’s biggest flaw is the current lack of good documentation. Let us try to answer the questions mentioned above.
Where does the catalog/product parameter comes from? If you browse to /app/code/core/Mage/ folder you would see a list of logically named subfolders like Catalog, Checkout, Contacts, Core, Dataflow and so on. If you browse deeper into the Catalog folder, you will see it’s structure contains Model directory among all others. Browse into the Model directory and there you will see a bunch of files, among which is Product.php. This Product.php is whats called when you write down getModel(‘catalog/product’). In short getModel(‘catalog/product’) says go into the /app/code/core/Mage/ folder, open the folder named product, and create an instance of Product.php file located inside the Model subfolder (to be more precise, create the instance of the class cotained inside the Product.php file).
If we now echo the get_class($cModel); we would get the Mage_Catalog_Model_Product text displayed in our browser. This means that our $cModel variable is actually an instance of Mage_Catalog_Model_Product class. This matches the class name contained inside the app/code/core/Mage/Catalog/Model/Product.php file. Inside this Product.php file we can clearly see that Mage_Catalog_Model_Product class extends the Mage_Catalog_Model_Abstract class. What this means is that our $cModel can use all of the methods (functions) declared inside the Mage_Catalog_Model_Product class plus those declared inside the Mage_Catalog_Model_Abstract class.
To see the list of the methods available you can use IDE like NetBeans. NetBeans lists you all the methods of a class in the Navigator window, like the one provided in the screenshot. Or you can use the foreach loop to iterate and echo out the available method names like
echo ‘<ul>’;
foreach (get_class_methods(get_class($cModel)) as $cMethod) {
echo ‘<li>’ . $cMethod . ‘</li>’;
}
echo ‘</ul>’;
You can look at the screenshot for the result. You can see some pretty cool and useful methods like getName, getPrice, getTypeId, getStatus which we can execute on our $cModel variable like
echo ‘Product name: ‘ . $cModel->getName();
echo ‘Product price: ‘ . $cModel->getPrice();
However, the above code wont give you anything. You will not see any price displayed in the browser. Why, you might and should ask? Well, for what product are you requesting a price? Magento does not know that at this point. Some of you might ask, how is it that it does not know? We have a product view page open after all. Well, we do, but I’m showing you a code that you can use no matter what page you have open.
We can tell it to him in a single line of code using load() method. This method is also displayed on the list of available methods for this variable. So the above code fore retrieving the product name and price would work if we were to write it like
$cModel->load(53);
/*
Number 53 is the id number in default sample data, it’s assigned to Couch product you can see in this screenshots
*/
echo ‘<p>Product name: ‘ . $cModel->getName() . ‘</p>’;
echo ‘<p>Product price: ‘ . $cModel->getPrice() . ‘</p>’;
View.phtml file already has the instance of Mage_Catalog_Model_Product class trough $_product = $this->getProduct() variable. Here you can see the Magento creaters are using the getProduct() method on the $this variable. Variable $this contains huge amount of data in it, among which is current instance of Mage_Catalog_Model_Product class stored in some array structure. If you were to retrieve the list of available methods of $this variable, like we did on the $cModel variable, you were to see the getProduct() method among them like
echo ‘<ul>’;
foreach (get_class_methods(get_class($this)) as $cThis) {
echo ‘<li>’ . $cThis . ‘</li>’;
}
echo ‘</ul>’;
If you understood all of the stuff I showed you so far then you understand the power of getModel method. You create the instance of class and store it into some variable (like $cModel), load the data for that type of object by using load function, then ust the list of available functions on that variable (object).
Title of this post mentions getData method also. As you can see, getData is just one of multiple available methods for your new variable. So why mentioning it in the same context as getMethod?
Before I answer that question let me just explain how getData can be executed with or without any parameters passed to it. If you execute it without any parameters you get the array variable as a result. You can’t directly echo the array. You would have to map it to some field, like echo $arayVar['someField']. So I ask you, what are all the available fields? To find out you can do something like
echo ‘<pre>’;
print_r($cModel->getData());
echo ‘</pre>’;
Results are so tasteful. There is a bunch of data one can use in it’s custom design solutions. Let’s say you want to retrieve the SKU value. You can use some other method for that like getSku() method that needs to be executed on object of Product type or you can
echo $cModel->getData(‘sku’);
or
$cModelData = $cModel->getData();
echo $cModelData->sku;
Cool, right. If you look at the entire array of data thrown at us when we executed print_r($cModel->getData()); we can clearly see there are some nested arrays, and some array fields store entire objects, like stock_item field. It stores object of Mage_CatalogInventory_Model_Stock_Item type. When you run into stuff like this, you can do the following
$cStockItem = $cModel->getData(‘stock_item’);
or
$cStockItem = $cModelData->stock_item;
Now your $cStockItem variable is a object of type Mage_CatalogInventory_Model_Stock_Item and you can go ahead and use the same principle used until this point to find it’s methods and the data id holds.
Hope this was useful.










Great post thanks alot,
this has really helped me with a section of my site. One thing i am still not sure on is how you retrieve a collection of products from the db for example i’d like to retrieve a random bunch of 6 products that are instock and sellable but have no idea how to go about it.
My only idea is to get an array of all product ids then have a php function randomly pick one out and get the details via a $cModel->load(); and write it, then repeat!!
Seems a bit long winded, but thanks for this article and keep up the good info, magento rocks but i agree it needs a bit more doc
I want to display the block same as that of sales-order module in my custom module. How can i do that
thanks
getModel is used to call the function and get data from other model of the module, how do u i call the function in other block of the module.
You cant call the block directly since they all contain getChildHtml… does not work, they break and you are unable to see stuff that getChildHtml is suppose to output… do the getModel(of something)->load(by some id of something) play with it. There are infinite possibilities.
P.S. Go to Zend Framework site and go trough some tutorials on MVC structure and passing parameters between Model, Controller, View and stuff like that. Should help you since Magento is Zend based.
cool post,
i need a bit explanation on this sentence of your post in sense of custom modules:
” In short getModel(’catalog/product’) says go into the /app/code/core/Mage/ folder, open the folder named product, and create an instance of Product.php file located inside the Model subfolder (to be more precise, create the instance of the class cotained inside the Product.php file).”
you told in above that getModel(’catalog/product’) will tell megento to pick the module from Mage but what if i need to pick data through my custom module, how i’ll explicitly mention if it is Mage module or my custom module. Will it automatically map getModule(‘abc/model’) ?
please explain,
thanks
getModel(‘catalog/product’) is the same as if you did new Mage_Catalog_Model_Product(), autoloading will do the job. So first you try this second approach on your module
Cool ! But most of the attribute data are index keys.
$cModel->getData(‘manufacturer’) returns an integer (index key).
How do we retrieve the text associated with it ?
Is it possible to use this code in say the breadcrumbs to retreive the product information of whatever page I’m on? I tried doing:
$idParams = $this->getRequest()->getParam(‘id’);
$cModel = Mage::getModel(‘catalog/product’);
$cModel->load($idParams);
print_r($cModel->getSku());
but even when I’m not on a product page, it still takes the ID of the page I’m on and runs it agains the product database and returns an SKU for whatever product I have that is matching up to the category page I’m on id-wise.
Is there a different way to find what the current product is that’s being displayed?
Thank You so much for your tutorials. They are straightforward and easy to read, unlike the offical source.
ok, so I tried using getSingleton instead by doing this:
$cSingleton = Mage::getSingleton(‘catalog/product’);
echo ”;
echo ‘Product name:’;
echo $cSingleton->getName();
echo ”;
but I still can’t figure out how to retrieve the name of the product on the page from within the breadcrumbs. Anybody?
Same problem here. I’m trying to create a custom module and I need to show some products, but $product->getName() method doesn’t return anything. Any ideas?
Anyway, nice job with this blog,man. I found it very useful. Keep up the good work!
I’ve used your blog post extensively in learning how to pull down product data but I can’t seem to find a method or even anything from print_r($cModel->getData()) that would indicate where a Bundle product’s price data is stored. It seems like it might be in the Tier price array (and associated arrays), but alas they are empty when I attempt to output them. Do you have any insight branko?
Nice post.. dude… thanx that helped me a lot..
But how would I get a handle on the ProductAttribute Object?
$attributes = Mage::getModel(‘catalog/product/attribute’);
… doesn’t work. Oddly enough, it returns the Product object.
I would like to thanks Branko for this article. Very helpful. Cheers Mate for this. Much appreciated.
I have put the code in this comment in case some people are still struggling to get the desired results -:
This code you can copy as it is in /template/catalog/product/view.phtml file.
$_helper = $this->helper(‘catalog/output’);
$_product = $this->getProduct();
$cModel_PC = Mage::getModel(‘catalog/product’);
echo ”;
foreach (get_class_methods(get_class($cModel_PC)) as $cMethod) {
echo ” . $cMethod . ”;
}
echo ”;
echo ‘====’;
echo ”;
foreach (get_class_methods(get_class($_helper)) as $cMethod) {
echo ” . $cMethod . ”;
}
echo ”;
$cModel_PC->load($_helper->productAttribute($_product, $this->htmlEscape($_product->getId()), ‘Id’));
echo $cModel_PC->getData(‘description’);
echo $cModel_PC->getData(‘name’);
echo $cModel_PC->getData(‘manufacture’);
hi branko,
thanx a lot this article proved to be very useful for me.
just one doubt please clarify it:
My only idea is to get an array of all product ids then have a php function randomly pick one out and get the details via a $cModel->load(); and write it, then repeat!!
Seems a bit long winded,
is there not any way so that i can put any variable in load so that it could retrieve all the product information
@nirmesh
Thank you for for reading my blog. This is relatively old article now
Not sure what exactly you are trying to do in your example. Take a look at inchoo.net site (company I work for). You’ll find few additional Magento articles by me and my co-workers.
Cheers…
Very useful article indeed.
I was wondering how I shoul use those functions to display the product details (image, descriptions…) in a light popup clicking on an image to avoid reloading the page.
What should be the best way to do it, passing the product id to a js-php file that will create an instance of Mage_Catalog_Model_Product class, then load data?
Could I pass the array variable $_product to dynamically generate the detail product popup ?
Your suggestions are welcome
.
Sylvie
hi branko,
can u tell me how magento search works i wanted to know where and how magento form the query so that i can customize that query.
actually i need to add one more parameter while it search for a product.
please throw some light. ASAP.
Hi!
thanks for nice Article
But i am in wonder that how do i read the Random Quotes through a
file in magento.Is Magento support such features or Zend Provides some built-in Libraries for that.
Please reply
How can I create instace of Mage_Model_Catalog_Product in my phtml as I want to connect this with my helper.
Second thing I want to display some attributes to my customer dashboard page where I am displaying the item list of all order’s. So please guide me.
@Yogendra
Actually you can use full class name like
$product = new Mage_Model_Catalog_Product();
$product->load($productId);
Thanks for quick reply. One another thing I am wondering is that how magento is storing the entities values in database. I have created my own module and I have also created few attributes related to my entity_set. And I am also able to create dynamically as per magento database. Please have a look to this thread:
http://www.magentocommerce.com/boards/viewthread/41408/
So if you can guide me than it will really help me to understand magento to great extent. One more thing, we can filter collection by attribute and if I want to filter my collection with field then how can I do this. Thanks in advance brother to guide me.
hiii,
thank u for nice post. it is very very useful post..
thank you man
hiii,
i have one question…
when i write getData method it will give me proper data…but i am edit that data ..and now i want to save it.. so how can i save that data ???
example : i make one attribute..now i fetch it on product view page now on add to cart i want to save that attribute data. so how can i do this thing ??
thank you..
Hi…
This post is useful to get data. My question is…
How can I store new record into the database…?
Hi..
$cModelData = $cModel->getData();
echo $cModelData->sku;
This code isnt working. It should be following….
$cModelData = $cModel->getData();
echo $cModelData['sku'];
Because $cModel->getData() is returning array, it need to be accessed as an array element. Arrow operator here will give error.
@Mohit
There are number of articles and even some extensions you can download from this site that should cover your question.
really helpful man! The only thing I cant figure out is why they dont allow you to gather a products type via getData(‘type’);
Hello,
How would you recommend creating a new root category using Mage::getModel('catalog/category')?
Thank you,
Bob Brodie
Hello,
How would you recommend creating a new root category using Mage::getModel('catalog/category')?
Thank you,
Bob Brodie
Thank you So much man you are great………….
Great article. You're right, Magento is a powerful and well thought out application, but it has a lot of “secret” naming conventions that make it hard to learn. Thanks for explaining this.
Hi Mr. Branko
I just wanna ask it is possible to add some customized functionality when I clicked on the “Place Order” in onestepcheckout say.. after performing the place order request… a new page will open in a separate window..
In that sense, we want to somehow edit the behavior when “Place Order” is clicked