Posts tagged with: zend-form

Adding HTML Tags to a Zend Form Element

For the purposes of styling I had the need to put an opening <div> at the beginning of one element, and a closing </div> tag at the end of another. The Zend Framework guides don’t do a great job of detailing this.

On the element you want to add the opening div tag you would do the following:
[code=”php”]
$open_element->addDecorator(array(
array(‘openDiv’ =>’HtmlTag’),
array(‘tag’ => ‘div’, ‘openOnly’ => true)
));
[/code]

On the element you want to add the closing div tag:
[code=”php”]
$close_element->addDecorator(array(
array(‘closeDiv’ =>’HtmlTag’),
array(‘tag’ => ‘div’, ‘closeOnly’ => true)
));
[/code]


Custom Username Validator Using Zend_Validate_Abstract for Zend Framework

Do you find yourself having to use multiple steps to validate a new username? If you’ve got a create user screen, or some other form that requires the creation of a username (or some other input that must be unique and is in a datastore), you can create a custom validator that uses a database mapper to validate that the input is unique.

First step, create a lookup method in your mapper (or whatever class you use for datastore access) that will query your datastore to verify the input is unique. In this case, I’m using a MySQL database backend and am using a mapper/model hierarchy and am only showing the relavant function from my mapper class.

[sourcecode=”php”]

public static function isRegisteredUser($username)
{
try
{
$table = new Ashurex_Model_DbTable_UserView();
$stmt = $table->select()
->where(‘username = ?’)
->bind(array($username));

$row = $table->fetchRow($stmt);

if(!($row == null))
{
return true;
}
else
{
return false;
}
}
catch(Exception $e)
{
self::logException(__METHOD__,$ex);
return null;
}
}

[/sourcecode]

Next, we’ll create a custom validator that extends Zend_Validate_Abstract and utilizes our mapper function during validation.

[sourcecode=”php”]
class Ashurex_Validate_Text_Username extends Zend_Validate_Abstract
{
const INVALID = ‘textInvalid';
const NOT_NAME = ‘notName';
const STRING_EMPTY = ‘textStringEmpty';
const STRING_LENGTH = ‘textStringLength';
const NAME_TAKEN = ‘textNameTaken';

protected static $_filter = null;
protected $_allowEmpty;

protected $_messageTemplates = array(
self::INVALID => ‘Invalid characters entered’,
self::NOT_NAME => ‘Input contains characters not valid for a username’,
self::STRING_EMPTY => ‘No input entered’,
self::STRING_LENGTH => ‘Username must be between 6 and 64 characters’,
self::NAME_TAKEN => ‘Username is already taken’
);

public function isValid($value)
{
// Make sure a value was entered
if(($value == null)||($value == ”))
{
$this->_error(self::STRING_EMPTY);
return false;
}

// The value must be a string
if (!is_string($value)) {
$this->_error(self::INVALID);
return false;
}

// Set the internal value to the input
$this->_setValue($value);

// Validate that the input is alphanumeric
$al = new Zend_Validate_Alnum();
if(!$al->isValid($value))
{
$this->_error(self::INVALID);
return false;
}

// Validate that the string length meets requirements
$sl = new Zend_Validate_StringLength(array(‘min’ => 6,’max’ => 64));
if(!$sl->isValid($value))
{
$this->_error(self::STRING_LENGTH);
return false;
}

// Make sure the username doesn’t already exist
if(Ashurex_Model_Mapper_User::isRegisteredUser($value))
{
$this->_error(self::NAME_TAKEN);
return false;
}

return true;
}
}
[/sourcecode]

Finally, we can use our new validator just as we would any other validator. The following code is an excerpt from my custom create user form:
[sourcecode=”php”]
class Ashurex_Form_Admin_AddUser extends Zend_form
{
public function init()
{
$this->setName(‘add_user_form’);
$this->setMethod(‘post’);

$username = new Zend_Form_Element_Text(‘username’);
$username->setFilters(
array(
new Zend_Filter_StringTrim(),
new Zend_Filter_StringToLower(),
));
$username->setValidators(
array(
new Ashurex_Validate_Text_Username(),
));
$username->setRequired(true);
$username->setLabel(‘Username’);

… lots of other code follows …

}
}

[/sourcecode]


Zend Framework HTML5 Form Elements

By default, Zend Framework 1.11 doesn’t have any native HTML5 form elements, but with some help from Enrise you can use their HTML5 Form Elements. I won’t go over the intricacies of creating custom forms and elements, but I will quickly show how to use the Glitch_Form_Element objects in a useful manner.

One of the neat things about the Glitch HTML5 elements is that they auto-detect the doctype being used in your Zend Framework application and will switch how they render to HTML. For example, if your doctype is set to ‘HTML5′ the Glitch_Form_Element_Text_Email object will render as an HTML5 email input and look like:
[sourcecode language=”html”]

[/sourcecode]
However, if your doctype is set to something else, it will render it as a standard text input like so
[sourcecode language=”html”]

[/sourcecode]
Pretty slick, eh? The best part is, the functionality is already built in. All you have to do is make sure you are setting your doctype.
I set mine in my Bootstrap.php file like so:
[sourcecode language=”php”]
protected function _initView()
{
// create view here if you need to change default options, but front
// controller will create view automatically.
$documentType = new Zend_View_Helper_Doctype();
$documentType->doctype($this->_config->resources->view->doctype);
}
[/sourcecode]
My application.ini config file has the default configuration block:

Finally, my form class looks just about like any other Zend_Form:
[sourcecode language=”php”]
class Ashurex_Form_Admin_AddUser extends Zend_Form
{
public function init()
{
$this->setName(‘add_user_form’);
$this->setMethod(‘post’);

$username = new Zend_Form_Element_Text(‘username’);
$username->setFilters(
array(
new Zend_Filter_StringTrim(),
new Zend_Filter_StringToLower(),
));
$username->setValidators(
array(
new Zend_Validate_Alnum(),
new Zend_Validate_StringLength(array(‘min’ => 6,’max’ => 64)),
));
$username->setRequired(true);
$username->setLabel(‘Username’);

$firstname = new Zend_Form_Element_Text(‘first_name’);
$firstname->setLabel(‘First Name’);
$firstname->setRequired(true);
$firstname->setFilters(
array(
new Zend_Filter_StringTrim(),
));
$firstname->setValidators(
array(
new Ashurex_Validate_Text_PersonName(),
new Zend_Validate_StringLength(array(‘min’ => 1,’max’ => 64)),
));

$lastname = new Zend_Form_Element_Text(‘last_name’);
$lastname->setLabel(‘Last Name’);
$lastname->setRequired(true);
$lastname->setFilters(
array(
new Zend_Filter_StringTrim(),
));
$lastname->setValidators(
array(
new Ashurex_Validate_Text_PersonName(),
new Zend_Validate_StringLength(array(‘min’ => 1,’max’ => 64)),
));

$email = new Glitch_Form_Element_Text_Email(‘email’);
$email->setLabel(‘Email’);
$email->setRequired(true);
$email->setFilters(
array(
new Zend_Filter_StringTrim(),
new Zend_Filter_StringToLower(),
));

$submit = new Zend_Form_Element_Submit(‘submit’);
$submit->setRequired(false);
$submit->setIgnore(true);
$submit->setLabel(‘Save’);

$cancel = new Zend_Form_Element_Submit(‘cancel’);
$cancel->setRequired(false);
$cancel->setIgnore(true);
$cancel->setLabel(‘Cancel’);

$this->addElements(array($username,$email,$firstname,$lastname,$submit, $cancel));
}
}
[/sourcecode]