2016-05-13 3 views
0

Я новичок в mangeto framework, и я учусь создать форму в разделе области администратора. Тем не менее, это было в течение часа, что я не мог понять ошибки я получаю:Я не вижу кнопку сохранения в моей форме, хотя я ее создал в Admin Area Magento

Recoverable Error: Argument 1 passed to Mage_Adminhtml_Controller_Action::_addContent() must be an instance of Mage_Core_Block_Abstract, boolean given, called in /vagrant/magento/app/code/local/MasteringMagento/Example/controllers/Adminhtml/EventController.php on line 12.

Следующая моя edit.php файл, а также мой form.php файл edit.php:

class MasteringMagento_Example_Adminhtml_EventController extends Mage_Adminhtml_Controller_Action{ 
public function indexAction(){ 
    $this->loadLayout(); 
    $this->_addContent(
     $this->getLayout()->createBlock('example/adminhtml_event_edit')); 
    //go straight to the php file to render the form. otherwise this will not perfomed. 
    $this->renderLayout(); 
} 
public function saveAction(){ 
    $eventID = $this->getRequest()->getParam('event_id'); 
    $eventModel = Mage::getModel('example/event')->load($eventID); 
    if($data = $this->getRequest()->getPost()){ 
     try{ 
      $eventModel->addData($data)->save(); 
      Mage::getSingleton('adminhtml/session')->addSuccess(
       $this->__('Your event has been saved') 
      ); 
     }catch(Exception $e){ 
      Mage::getSingleton('adminhtml/session')->addError($e->getMessage()); 
     } 
     $this->_redirect('*/*/index'); 
    } 
} 

}

и form.php файл:

class MasteringMagento_Example_Block_Adminhtml_Event_Edit_Form extends Mage_Adminhtml_Block_Widget_Form{ 
protected function _prepareForm(){ 
    $form = new Varien_Data_Form(array('id'=>'edit_form', 
     'action'=>$this->getData('action'), 'method'=>'post')); 

    $fieldset = $form->addFieldset('base_fieldset', 
     array('legend'=>Mage::helper('example')->__('General Information'), 
      'class'=>'fieldset-wide')); 

    $fieldset->addField('name', 'text', array(
     'name' => 'name', 
     'label' => Mage::helper('example')->__('Event Name'), 
     'title' => Mage::helper('example')->__('Event Name'), 
     'required' => true 
    )); 

    $dateFormatIso = Mage::app()->getLocale()->getDateFormat(
     Mage_Core_Model_Locale::FORMAT_TYPE_SHORT); 
    $fieldset->addField('start', 'date', array(
     'name' => 'start', 
     'format' => $dateFormatIso, 
     'image' => $this->getSkinUrl('images/grid-cal.gif'), 
     'label' => Mage::helper('example')->__('Start Date'), 
     'title' => Mage::helper('example')->__('Start Date'), 
     'required' => true 
    )); 

    $fieldset->addField('end', 'date', array(
     'name' => 'end', 
     'format' => $dateFormatIso, 
     'image' => $this->getSkinUrl('images/grid-cal.gif'), 
     'label' => Mage::helper('example')->__('End Date'), 
     'title' => Mage::helper('example')->__('End Date'), 
     'required' => true 
    )); 

    $form->setUseContainer(true); 
    $this->setForm($form); 
    return parent::_prepareForm(); 
} 

}

Ошибка, которую я думаю от моего контроллера. Однако, если я направляю ссылку url в форму, она будет отображаться. Но если я направить его контейнер, который edit.php, ошибка выше, будет происходит:

class MasteringMagento_Example_Adminhtml_EventController extends Mage_Adminhtml_Controller_Action{ 
public function indexAction(){ 
    $this->loadLayout(); 
    $this->_addContent(
     $this->getLayout()->createBlock('example/adminhtml_event_edit')); 
    //go straight to the php file to render the form. otherwise this will not perfomed. 
    $this->renderLayout(); 
}} 

Это мой config.xml. Я включил базовый класс для блоков Magento:

<blocks> 
     <example> 
      <class>MasteringMagento_Example_Block</class> 
     </example> 
    </blocks> 

Пожалуйста, помогите мне определить проблему. Спасибо

ответ

0

createBlock() является абстрактный шаблон завода для блоков внутри Magento. Всякий раз, когда Magento не может разрешить фабричный класс из этого метода, возвращается логическое значение ... что имеет место в вашем примере, как говорится в сообщении об ошибке.

Проверьте класс MasteringMagento_Example_Block_Adminhtml_Event_Edit на предмет ошибок, связанных с орфографией, корпусом или классом. Также убедитесь, что файл вашего класса находится по адресу app/code/local/MasteringMagento/Example/Block/Adminhtml/Event/Edit.php.

0

В пурпуре каждый блок формы администратора загружается сначала контейнером формы.

Здесь вы звоните MasteringMagento_Example_Block_Adminhtml_Event_Edit класс:

$this->getLayout()->createBlock('example/adminhtml_event_edit') 

Этот класс, расположенный в приложения/код/​​местные/MasteringMagento/Пример/Block/Adminhtml/Post/edit.php, должны смотреть на что-то вроде это:

<?php 
/** 
* MasteringMagento_Example_Block_Adminhtml_Post_Edit 
*/ 
class MasteringMagento_Example_Block_Adminhtml_Post_Edit extends Mage_Adminhtml_Block_Widget_Form_Container 
{ 
    public function __construct() 
    { 
     // $this->_objectId = 'id'; 
     parent::__construct(); 
     $this->_blockGroup  = 'example'; 
     $this->_controller  = 'adminhtml_post'; 
     $this->_mode   = 'edit'; 
     $modelTitle = $this->_getModelTitle(); 
     $this->_updateButton('save', 'label', $this->_getHelper()->__("Save $modelTitle")); 
     $this->_addButton('saveandcontinue', array(
      'label'  => $this->_getHelper()->__('Save and Continue Edit'), 
      'onclick' => 'saveAndContinueEdit()', 
      'class'  => 'save', 
     ), -100); 

     $this->_formScripts[] = " 
      function saveAndContinueEdit(){ 
       editForm.submit($('edit_form').action+'back/edit/'); 
      } 
     "; 
    } 

    protected function _getHelper(){ 
     return Mage::helper('example'); 
    } 

    protected function _getModel(){ 
     return Mage::registry('exemple_youmodel'); 
    } 

    protected function _getModelTitle(){ 
     return 'Post'; 
    } 

    public function getHeaderText() 
    { 
     $model = $this->_getModel(); 
     $modelTitle = $this->_getModelTitle(); 
     if ($model && $model->getId()) { 
      return $this->_getHelper()->__("Edit $modelTitle (ID: {$model->getId()})"); 
     } 
     else { 
      return $this->_getHelper()->__("New $modelTitle"); 
     } 
    } 


    /** 
    * Get URL for back (reset) button 
    * 
    * @return string 
    */ 
    public function getBackUrl() 
    { 
     return $this->getUrl('*/*/index'); 
    } 

    public function getDeleteUrl() 
    { 
     return $this->getUrl('*/*/delete', array($this->_objectId => $this->getRequest()->getParam($this->_objectId))); 
    } 

} 

Как вы можете видеть, все ваши кнопки установлены в методе __construct().

Надеюсь, это поможет.

Смежные вопросы