Showing results for 
Search instead for 
Did you mean: 

Steps needed to create a block and use it in a controller

Steps needed to create a block and use it in a controller

I'm working on a module that does a custom search and I want to use ajax to show the results. What I need to do in the controller is generate the html that would normally be on the results page and send it as json. So far I haven't been able to do that. I would be very thankful if someone could tell me the steps I need to take to load the correct products in a results block and generate it from a controller.


What I think I need to do:

1. Load product collection.

    How do I do this in such a way that the block knows what products to use?

2. Load the layout

    Is it necessary to do `$this->loadLayout(); $this->getLayout()` ? Do I need to specify what layout to load ?

3. Create or get block and json encode

    At the moment, from a controller that extends Mage_Core_Controller_Front_Action I can get the `cart_sidebar` block using `$this->loadLayout()->getLayout()->getBlock('cart_sidebar')`, but I get null if I replace 'cart_sidebar' with 'product_list'. I'm guessing this is because the block doesn't know what products to fill itsself with, but I don't know how to change that.


Any help would be greatly appreciated.


Re: Steps needed to create a block and use it in a controller

some answers to your questions

2,  'loadLayout & renderLayout' a very common way to load and render blocks. but its not always necessary. after you call loadLayout, it inits blocks under the instruction of layout files in design folder,  then you can call $this->getLayout()->getBlock($blockName) to get the block instance ( which potentially answers your 3rd question, do you have product_list block in your layout? ). Y

    You can also init blocks manually, this is usually seen in an AJAX controller.  like Mage_Captcha_RefreshController uses $this->getLayout()->createBlock($captchaModel->getBlockName())->setFormId($formId)->setIsAjax(true)->toHtml();


1, say you have the instance of the product list block $list (either returned by createBlock or retrieved by getBlock),  pass your search parameters to the block, like $list->setSku($this->getRequest()->getParam('sku')); then in your block, you can filter your product collection with $productCollection->addAttributeToFilter('sku', $this->getSku());


If its possible, read some magento tutorials (many good ones in magento wiki) so you can better understand layout and block in magento, its hard to explain all these in a short post