Posting in the Magento forums has been disabled pending the implementation of a new and improved forum solution which should better serve the community.

For new questions please post at magento.stackexchange.com, the community-run support site for the Magento community. We will be providing updates on the new forum solution soon. For questions or concerns please email community@magento.com.

Magento Forum

Model problem - How to call model functions in phtml
 
Jason Lai
Jr. Member
 
Total Posts:  22
Joined:  2009-08-23
Hong Kong
 

I tried to call functions of model class in phtml but it cannot return proper value.
it can only call functions of block class properly. 

Anyone can tell me why?

The following is an example.

in Xyz/Block/Xyz.php

class ABC_Xyz_Block_Xyz extends Mage_Core_Block_Template
{
    
public function _prepareLayout()
    
{
        
return parent::_prepareLayout();
    
}
    
     
public function getXyz()     
     

        
if (!$this->hasData('xyz')) {
            $this
->setData('xyz'Mage::registry('xyz'));
        
}
        
return $this->getData('xyz');
        
    
}

    
public function getEditUrl()
    
{
        
return $this->getUrl('*/*/edit');
    
}
}

in Xyz/Model/Xyz.php

class ABC_Xyz_Model_Xyz extends Mage_Core_Model_Abstract
{
    
public function _construct()
    
{
        parent
::_construct();
        
$this->_init('xyz/xyz');
    
}

    
public function getAddUrl()
    
{
        
return $this->getUrl('*/*/add'); // or $this->__(' bbb '); 
    
}

in xyz.phtml

<?php echo "aaa ".$this->getEditUrl() . "<br />"$this->getAddUrl()."<br />" ; >

only
$this->getEditUrl() can successfully print in the page.

 
Magento Community Magento Community
Magento Community
Magento Community
 
kiatng
Enthusiast
 
Total Posts:  875
Joined:  2008-09-03
Kuala Lumpur, Malaysia
 

That’s because the class scope does not overlap between Block and Model. You access model class anywhere with

Mage::getModel('moduleName/className')
 
Magento Community Magento Community
Magento Community
Magento Community
 
kiatng
Enthusiast
 
Total Posts:  875
Joined:  2008-09-03
Kuala Lumpur, Malaysia
 

Try

Mage::getModel('xyz/xyz')->getAddUrl();
 
Magento Community Magento Community
Magento Community
Magento Community
 
Jason Lai
Jr. Member
 
Total Posts:  22
Joined:  2009-08-23
Hong Kong
 

Thanks,

I found that I should follow the scope back. 

That means, phtml call block, block call model to get object or helper to get data.

 
Magento Community Magento Community
Magento Community
Magento Community
Magento Community
Magento Community
Back to top