Adminhtml-администратор - Как создать Новую форму администратора


Я использую Magento 1.9.0.1 и прямо сейчас разрабатываю новое расширение magento.

До сих пор я создал новую страницу adminhtml с таблицей сетки, которая извлекает данные из пользовательской таблицы MySQL:

Вот страница:

enter image description here

Эта страница извлекает данные из пользовательской таблицы MySQL VivasIndustries_SmsNotification вот ее структура:

enter image description here

Позвольте мне показать вам мои файлы расширений:

У меня есть в: /app/code/community/VivasIndustries/SmsNotification/etc/config.xml :

<?xml version="1.0"?>
<config>
  <modules>
    <VivasIndustries_SmsNotification>
      <version>0.1.0</version>
    </VivasIndustries_SmsNotification>
  </modules>
  <global>
    <models>
        <smsnotification>
            <class>VivasIndustries_SmsNotification_Model</class>
            <resourceModel>vivasindustries_smsnotification_resource</resourceModel>
        </smsnotification>
        <vivasindustries_smsnotification_resource>
        <class>VivasIndustries_SmsNotification_Model_Resource</class>
        <entities>
            <smsnotification>
            <table>VivasIndustries_SmsNotification</table>
            </smsnotification>
        </entities>
        </vivasindustries_smsnotification_resource>
    </models>
    <resources>
        <smsnotification_setup>
            <setup>
                <module>VivasIndustries_SmsNotification</module>
            </setup>
            <connection>
                 <use>core_setup</use>
             </connection>
        </smsnotification_setup>
        <smsnotification_read>
            <connection>
                <use>core_read</use>
            </connection>
        </smsnotification_read>
        <smsnotification_write>
            <connection>
                <use>core_write</use>
            </connection>
        </smsnotification_write>
    </resources>    
    <events>
        <sales_order_save_after>
            <observers>
                <vivasindustries_smsnotification>
                    <class>smsnotification/observer</class>
                    <method>orderSaved</method>
                </vivasindustries_smsnotification>
            </observers>
        </sales_order_save_after>
    </events>
    <helpers>
        <smsnotification>
            <class>VivasIndustries_SmsNotification_Helper</class>
        </smsnotification>
    </helpers>
    <blocks>
        <smsnotification>
             <class>VivasIndustries_SmsNotification_Block</class>
        </smsnotification>
    </blocks>
  </global>
  <adminhtml>
    <acl>
        <resources>
            <all>
                <title>Allow Everything</title>
            </all>
            <admin>
                <children>
                    <system>
                        <children>
                            <config>
                                <children>
                                    <vivas>
                                        <title>Vivas - All</title>
                                    </vivas>
                                </children>
                            </config>
                        </children>
                    </system>
                </children>
            </admin>
        </resources>
    </acl>
    </adminhtml>
    <admin>
        <routers>
            <adminhtml>
                <args>
                    <modules>
                        <VivasIndustries_SmsNotification before="Mage_Adminhtml">VivasIndustries_SmsNotification_Adminhtml</VivasIndustries_SmsNotification>
                    </modules>
                </args>
            </adminhtml>
        </routers>
    </admin>
</config>  

Вот что у меня есть в:/app/code/community/VivasIndustries/SmsNotification/Block/Adminhtml/Sms/Status.php :

<?php

class VivasIndustries_SmsNotification_Block_Adminhtml_Sms_Status extends Mage_Adminhtml_Block_Widget_Grid_Container
{
    public function __construct()
    {
        $this->_blockGroup = 'smsnotification';
        $this->_controller = 'adminhtml_sms_status';
        $this->_headerText = Mage::helper('smsnotification')->__('Send SMS on Order Status Changes');
        $this->_addButtonLabel = Mage::helper('smsnotification')->__('Create new SMS Rule');
        parent::__construct();
    }

    protected function _prepareLayout()
    {
        $this->setChild( 'grid',
            $this->getLayout()->createBlock( $this->_blockGroup.'/' . $this->_controller . '_grid',
                $this->_controller . '.grid')->setSaveParametersInSession(true) );
        return parent::_prepareLayout();
    }



}

Вот что у меня есть в:/app/code/community/VivasIndustries/SmsNotification/Block/Adminhtml/Sms/Status/Grid.php :

<?php

class VivasIndustries_SmsNotification_Block_Adminhtml_Sms_Status_Grid extends Mage_Adminhtml_Block_Widget_Grid
{
    public function __construct()
    {
        parent::__construct();
        $this->setId('smsnotification_grid');
        $this->setDefaultSort('id');
        $this->setDefaultDir('DESC');
        $this->setSaveParametersInSession(true);
        $this->setUseAjax(true);
    }


    protected function _prepareCollection()
    {
        $collection = Mage::getResourceModel('smsnotification/smsnotification_collection');
        $this->setCollection($collection);
        return parent::_prepareCollection();
    }


    protected function _prepareColumns()
    {
          $this->addColumn('id', array(
              'header'    => Mage::helper('smsnotification')->__('ID'),
              'align'     =>'right',
              'width'     => '50px',
              'index'     => 'id',
          ));

          $this->addColumn('Receiver', array(
              'header'    => Mage::helper('smsnotification')->__('Receiver'),
              'align'     =>'left',
              'index'     => 'Receiver',
          ));

        $this->addColumn('Phone', array(
            'header'    => Mage::helper('smsnotification')->__('Phone'),
            'align'     =>'left',
            'index'     => 'Phone',
        ));

        $this->addColumn('Date', array(
            'header'    => Mage::helper('smsnotification')->__('Date'),
            'align'     =>'left',
            'index'     => 'Date',

        ));


        return parent::_prepareColumns();
    }

    public function getRowUrl($row)
    {
        return $this->getUrl('*/*/edit', array('id'=>$row->getId()));
    }
}

Вот что у меня есть в: /app/code/community/VivasIndustries/SmsNotification/controllers/Adminhtml/SmsorderstatusesController.php:

<?php

class VivasIndustries_SmsNotification_Adminhtml_SmsorderstatusesController extends Mage_Adminhtml_Controller_Action
{
    public function indexAction()
    {
        $this->_title($this->__('SMS Center'))->_title($this->__('SMS Center'));
        $this->loadLayout();
        $this->_setActiveMenu('vivassms');
        $this->_addContent($this->getLayout()->createBlock('smsnotification/adminhtml_sms_status'));
        $this->renderLayout();
    }

    public function gridAction()
    {
        $this->loadLayout();
        $this->getResponse()->setBody(
            $this->getLayout()->createBlock('smsnotification/adminhtml_sms_status_grid')->toHtml()
        );
    }

   public function newAction()
    {  
        $this->loadLayout();
        $this->_setActiveMenu('vivassms');
        $this->renderLayout();
    }  

    public function editAction()
    {  
        $this->_initAction();

        // Get id if available
        $id  = $this->getRequest()->getParam('id');
        $model = Mage::getModel('smsnotification/smsnotification');


        $this->_initAction()
            ->_addBreadcrumb($id ? $this->__('Edit Baz') : $this->__('New Baz'), $id ? $this->__('Edit Baz') : $this->__('New Baz'))
            ->_addContent($this->getLayout()->createBlock('smsnotification/adminhtml_sms_status_edit')->setData('action', $this->getUrl('*/*/save')))
            ->renderLayout();
    }

    protected function _initAction()
    {
        $this->loadLayout()
            // Make the active menu match the menu config nodes (without 'children' inbetween)
            ->_setActiveMenu('vivassms')
            ->_title($this->__('Sales'))->_title($this->__('Baz'))
            ->_addBreadcrumb($this->__('Sales'), $this->__('Sales'))
            ->_addBreadcrumb($this->__('Baz'), $this->__('Baz'));

        return $this;
    }


    protected function _isAllowed()
    {
        return Mage::getSingleton('admin/session')->isAllowed('sales/foo_bar_baz');
    }
}

Прямо сейчас, когда я нажимаю на кнопку Create new SMS Rule, я получаю пустую страницу вот так:

enter image description here

Чего я хочу добиться, так это:

  1. Я хочу отобразить на пустой странице, показанной выше, 3 поля ввода (Приемник, телефон, Дата), в которые я могу вставить данные.
  2. Я хочу, чтобы у меня была кнопка Save, и я нажимаю ее. Данные, введенные в 3 поля, в которых я хочу быть сохранен таблица MySQL VivasIndustries_SmsNotification.

Почему я получаю пустую страницу, когда нажимаю на Create new SMS Rule и как я могу сделать то, что я хочу, в двух пунктах выше?

Заранее спасибо!

Author: Venelin Vasilev, 2015-02-11

1 answers

Похоже, вам нужна форма и контейнер формы. Это похоже на то, что вы уже сделали с сеткой.

Вы должны создать эти файлы:

/app/code/community/VivasIndustries/SmsNotification/Block/Adminhtml/Sms/Status/Edit.php

class VivasIndustries_SmsNotification_Block_Adminhtml_Sms_Status_Edit 
     extends Mage_Adminhtml_Block_Widget_Form_Container

/app/code/community/VivasIndustries/SmsNotification/Block/Adminhtml/Sms/Status/Edit/Form.php

class VivasIndustries_SmsNotification_Block_Adminhtml_Sms_Status_Edit_Form 
     extends Mage_Adminhtml_Block_Widget_Form

Проверьте раздел Блок контейнеров формы в этой статье (Это действительно хорошая статья). Вы следует отобразить эти блоки в соответствующем действии в контроллере и добавить дополнительное действие для обработки отправки формы. Это второе действие получает данные через POST, передает их модели и сохраняет в базе данных.

 2
Author: Vic, 2015-02-11 21:37:29