Home > Zend_Form > Using Select Element of Zend_Form

Using Select Element of Zend_Form

intro
This article provides an example of using select element(Zend_Form_Element_Select) of Zend_Form. It also shows how to use custom filter(My_Filter_ArrayValue) created in previous article. You can download the source code of this article from here.
You can see the screens from the demonstration site.

1.Create bootstrap.php and config.ini
Create the file application/bootstrap.php with the following content.
Please modify yourBaseUrl properly.

<?php
set_include_path('../library' . PATH_SEPARATOR . get_include_path());
define('APP_BASE', '../application');
define('CONFIG_PATH', APP_BASE . '/config.ini');
 
require_once 'Zend/Controller/Front.php';
require_once 'Zend/Layout.php';
require_once 'Zend/Db.php';
require_once 'Zend/Config/Ini.php';
require_once 'Zend/Db/Table/Abstract.php';
 
$layout = Zend_Layout::startMvc();
//$layout->getView()->baseUrl = '/yourBaseUrl';
 
$config = new Zend_Config_Ini(CONFIG_PATH, 'staging');
$params = $config->database->params->toArray();
$params['options'][Zend_Db::CASE_FOLDING] = Zend_Db::CASE_LOWER;
$dbAdapter = Zend_Db::factory($config->database->adapter, $params);
Zend_Db_Table_Abstract::setDefaultAdapter($dbAdapter);
 
Zend_Controller_Front::run(APP_BASE . '/controllers');

Create the file application/config.ini with the following content.
Please modify database.params.* properly.

[staging]
database.adapter         = pdo_mysql
database.params.host     = localhost
database.params.username = db_user
database.params.password = db_password
database.params.dbname   = db_name

The following tables are used in this article.

CREATE TABLE members
(
    id             integer AUTO_INCREMENT NOT NULL PRIMARY KEY,
    role_id        integer        NOT NULL,
    nick_name      varchar(100)   NOT NULL,
    email          varchar(200)   NOT NULL
);
 
CREATE TABLE roles
(
    id             integer AUTO_INCREMENT NOT NULL PRIMARY KEY,
    role_name      varchar(20)    NOT NULL,
    priviledges    varchar(10)    NOT NULL
);
2.Create Models
Create the file application/models/Members.php with the following content.

<?php
require_once 'Zend/Db/Table/Abstract.php';
require_once 'Zend/Filter.php';
require_once 'Zend/Filter/Input.php';
 
class Members extends Zend_Db_Table_Abstract
{
    protected $_name = 'members';
    protected $_referenceMap = array(
        'Role' => array(
            'columns'           => array('role_id'),
            'refTableClass'     => 'Roles',
            'refColumns'        => array('id')
        )
    );
 
    public function getOutputFilter($data = null)
    {
        $roles = new Roles();
        $role_options = $roles->getOptions();
        // add other filters
        $filters = array(
            'role_id' => array(array('ArrayValue', $role_options))
        );
        $of = new Zend_Filter_Input($filters, null, $data);
        $of->addFilterPrefixPath('My_Filter', 'My/Filter/');
        return $of;
    }
 
    public function getOptions()
    {
        $select = $this->select()
                       ->from($this->_name, array('id', 'nick_name'))
                       ->order('id ASC');
        $options = $this->getAdapter()->fetchPairs($select);
        return $options;
    }
}

Create the file application/models/Roles.php with the following content.

<?php
require_once 'Zend/Db/Table/Abstract.php';
 
class Roles extends Zend_Db_Table_Abstract
{
    protected $_name = 'roles';
 
    public function getOptions()
    {
        $select = $this->select()
                       ->from($this->_name, array('id', 'role_name'))
                       ->order('id ASC');
        $options = $this->getAdapter()->fetchPairs($select);
        return $options;
    }
}

Create the file application/models/forms/MemberForm.php with the following content.

<?php
require_once 'Zend/Form.php';
require_once APP_BASE . '/models/Roles.php';
 
class MemberForm extends Zend_Form
{
    public function __construct()
    {
        $roles = new Roles();
        $role_options = $roles->getOptions();
 
        parent::__construct();
        $role_id = $this->createElement('select', 'role_id');
        $role_id->setLabel('role_id')
                ->setMultiOptions($role_options)
                ->setRequired(true)
                ->addFilter('stringTrim')
                ->addValidator('int')
                ->addValidator('inArray', false, array(array_keys($role_options)));
        $nick_name = $this->createElement('text', 'nick_name');
        $nick_name->setLabel('nick_name')
                  ->setRequired(true)
                  ->addFilter('stringTrim')
                  ->addValidator('stringLength', false, array(1,100));
        $email = $this->createElement('text', 'email');
        $email->setLabel('email')
            ->setRequired(true)
            ->addFilter('stringTrim')
            ->addValidator('stringLength', false, array(1,200))
            ->addValidator('emailAddress', false);
 
        $this->addElements(array(
            $nick_name, $email, $role_id
        ));
    }
}

Create the file application/models/forms/RoleForm.php with the following content.

<?php
require_once 'Zend/Form.php';
 
class RoleForm extends Zend_Form
{
    public function __construct()
    {
        parent::__construct();
        $role_name = $this->createElement('text', 'role_name');
        $role_name->setLabel('role_name')
                     ->setRequired(true)
                     ->addFilter('stringTrim')
                     ->addValidator('stringLength', false, array(1,20));
        $priviledges = $this->createElement('text', 'priviledges');
        $priviledges->setLabel('priviledges')
              ->setRequired(true)
              ->addFilter('stringTrim')
              ->addValidator('stringLength', false, array(1,10));
 
        $this->addElements(array(
            $role_name, $priviledges
        ));
    }
}
3.Create Controllers
Create the file application/constorllers/MemberController.php with the following content.
The controller extends My_Controller_Simple created before.

<?php
require_once 'My/Controller/Simple.php';
require_once APP_BASE . '/models/Members.php';
require_once APP_BASE . '/models/forms/MemberForm.php';
 
class MemberController extends My_Controller_Simple
{
    protected $_session_name = "Member";
    protected $_table_class = "Members";
    protected $_form_class = "MemberForm";
 
    protected function _getOutputFilter($data = null)
    {
        $members = new Members();
        return $members->getOutputFilter($data);
    }
 
    public function preDispatch()
    {
        $this->view->name = "member";
        $this->view->of = $this->_getOutputFilter();
    }
 
    public function indexAction()
    {
        $this->_forward('list');
    }
}
4.Create Views
Create the file application/views/scripts/member/list.phtml with the following content.

 
<h1><?= $this->translate($this->name . '.title.list') ?></h1>
 
<?php if (!$this->list) : ?>
<span><?= $this->translate($this->name . 'label.no_data') ?></span>
<?php else : ?>
<a href="<?=$this->url(array('action'=>'add'))?>">
<?= $this->translate($this->name . '.label.new') ?></a>
<table>
<?php   $this->header = true; ?>
<?php   foreach($this->list as $row) :
          $values = $row->toArray();
          $this->of->setData($values);
          if ($this->header) : ?>
<tr>
<?php       foreach($values as $key => $value) : ?>
<th><?= $this->translate($key) ?></th>
 
<?php       endforeach; ?>
<th><?= $this->translate('detail') ?></th>
<th><?= $this->translate('edit') ?></th>
<th><?= $this->translate('delete') ?></th>
 
<?php       $this->header = false; ?>
</tr>
 
<?php     endif; ?>
<tr>
<?php       foreach($values as $key => $value) : ?>
<td><?= $this->of->$key ?></td>
 
<?php       endforeach; ?>
<td><a href="<?=$this->url(array('action'=>'detail'))?>?id=<?=$values['id']?>">
  <?= $this->translate('detail') ?></a></td>
<td><a href="<?=$this->url(array('action'=>'update'))?>?id=<?=$values['id']?>">
  <?= $this->translate('edit') ?></a></td>
<td><a href="<?=$this->url(array('action'=>'delete'))?>?id=<?=$values['id']?>">
  <?= $this->translate('delete') ?></a></td>
</tr>
 
<?php   endforeach; ?>
</table>
 
<span><?= $this->translate($this->name . '.label.max') ?></span>
<?php endif; ?>

The following content shows the usage of filter for displaying label of select element.

          $values = $row->toArray();
          $this->of->setData($values);
          //....
<?php       foreach($values as $key => $value) : ?>
<th><?= $this->translate($key) ?></th>
 
<?php       endforeach; ?>
 

Create the file application/views/scripts/member/detail.phtml with the following content.
It uses the filter in same way as upper-mentioned content.

 
<h1><?= $this->translate($this->name . '.title.detail') ?></h1>
 
<?php if ($this->values) : ?>
<?php   $this->of->setData($this->values); ?>
<dl>
<?php foreach($this->values as $key => $value) : ?>
<dt><?= $this->translate($key) ?></dt>
<dd><?= $this->of->$key ?></dd>
 
<?php endforeach; ?>
</dl>
 
<?php endif; ?>
<?php if ($this->form) : ?>
<?= $this->form ?>
<?php endif; ?>

Create the file application/views/scripts/member/form.phtml with the following content.

 
<h1><?= $this->translate($this->name . '.title.' . $this->action) ?></h1>
 
<?= $this->form ?>

Create the file application/views/scripts/computer/finish.phtml with the following content.

 
<h1><?= $this->translate($this->name . '.title.finish.' . $this->action) ?></h1>
 
<a href="<?=$this->url(array('action'=>'list'))?>">
<?= $this->translate('back') ?></a>

5.Check
Access the web server and check the select element of form and displaying of it.

Comments:0

Comment Form
Remember personal info

Trackbacks:0

Trackback URL for this entry
http://www.oplabo.com/article/34/trackback
Listed below are links to weblogs that reference
Using Select Element of Zend_Form from Open Programming Laboratory

Home > Zend_Form > Using Select Element of Zend_Form

Japanese
Search
Feeds

Return to page top