Magento: create custom Controller

2019-09-16 09:13发布

问题:

i have created one news module . it is working fine..

http://domain.com/magento/news

this page is displaying all the news items. with title, content and date.

i want to make view more link for content when user click on view more link it will redirect user to specific newsitem page

http://domain.com/magento/news/newsitem-1

i created another controller newsitemController.php with following code :

  public function infoAction(){

$this->loadLayout();
$this->getLayout()->getBlock('content')
     ->append($this->getLayout()->createBlock('news/newsitem')  );
$this->renderLayout();
}

also created block name info.php with below code:

public function _prepareLayout()
    {
        return parent::_prepareLayout();
    }

    public function getnewsitem()    
    { 
        if(!$this->hasData('news')) {
            $this->setData('news', Mage::registry('news'));
        }
        return $this->getData('news');
    }

not getting output..

need help to get output.

回答1:

In your info.php add the following function to get the url of the news item.

public function getItemUrl($newsItem)
{
    return $this->getUrl('*/*/view', array('id' => $newsItem->getId()));
}

In your controller add following function to view the news detail page.

 public function viewAction()
  {
       $model = Mage::getModel('magentostudy_news/news');
       $model->load($newsId);
       $this->loadLayout();
       $itemBlock = $this->getLayout()->getBlock('news.info');
       $this->renderLayout();

  }

By doing this you can simply access the info page attaching this link on read more like

 foreach ($this->getCollection() as $newsItem)
 {
 //Other Code
 <a href="<?php echo $this->getItemUrl($newsItem) ?>">Read More..</a>
 }