magento 自定义模块控制器无法获取 toHtml() 函数



我的自定义模块是一个支付网关,我有一个重定向控制器,这是脚本

class Asurepay_Custompay_AsurepayController extends Mage_Core_Controller_Front_Action {
    protected $_order;
    public function getOrder() {
        if ($this->_order == null) {
        }
        return $this->_order;
    }
    public function indexAction(){
        echo "index test 1";
    }
    public function redirectAction(){
        $session = Mage::getSingleton('checkout/session');
        $session->setAsurepayCustompayQuoteId($session->getQuoteId());
        $this->getResponse()->setBody($this->getLayout()->createBlock('asurepay/redirect')->toHtml());
        $session->unsQuoteId();
        $session->unsRedirectUrl();
    }
}

函数redirectAction((无法获取toHtml((函数

这是一个错误:

Fatal error: Call to a member function toHtml() on a non-object in my code

这个错误应该是什么?我在ModuleName/block/Rerect.php中有一个块,我有一个toHtml((。或者错误的原因应该是什么?

请求

这是我的重定向块,位于ModuleName/block/Rerect.php

class Asurepay_Custompay_Block_Standard_Redirect extends Mage_Core_Block_Abstract {
    protected function _toHtml() {
        $asure = Mage::getModel("custompay/asure");
        $form = new Varien_Data_Form();
        $form = new Varien_Data_Form();
        $form->setAction($standard->getConfig()->getGateurl)
            ->setId('asurepay_custompay_checkout')
            ->setName('asurepay_custompay_checkout')
            ->setMethod('POST')
            ->setUseContainer(true);
        foreach ($standard->getStandardCheckoutFormFields() as $field=>$value) {
            $form->addField($field, 'hidden', array('name'=>$field, 'value'=>$value, 'size'=>200));
        }
        $html = '<html><body>';
        $html.= $this->__('You will be redirected to AsurePay in a few seconds.');
        $html.= $form->toHtml();
        $html.= '<script type="text/javascript">document.getElementById("asurepay_checkout").submit();</script>';
        $html.= '</body></html>';
        return $html;
    }
}
$this->loadLayout();

此时块尚未加载。您必须调用加载布局,并且只有在您能够访问布局中定义的块之后。

这是导致问题的行

$this->getLayout()->createBlock('asurepay/redirect')->toHtml()

让我们用非链式语法重写一下,让稍微清楚一点

$layout = $this->getLayout();
$block  = $layout->createBlock('asurepay/redirect');
$html   = $block->toHtml();

当PHP向投诉时

Fatal error: Call to a member function toHtml() on a non-object in my code

据说$block变量(对createBlock的调用结果(不是对象。这意味着您对createBlock的呼叫由于某种原因而失败。

我有根据的猜测是你的config.xml文件设置不正确。根据块类名(Asurepay_Custompay_Block_Standard_Redirect(和config.xml中的标准约定,您的别名应该是

$layout->createBlock('custompay/standard_redirect');

然而,假设config.xml设置类似

<config>
    <!-- ... -->
    <global>
        <blocks>
            <custompay>
                <class>Asurepay_Custompay_Block</class>
            </custompay>                
        </blocks>
    </global>
    <!-- ... -->
</config>

如果你发布config.xml的内容,人们将能够诊断你的问题。

最新更新