An ExtJS form helper for CakePHP

ExtJS allows you to make really elaborate Javascript-based UI once you get the hang of it. Unfortunately (unless there is some project I missed) it hasn’t yet been integrated with CakePHP so you end up hand-coding a bunch of stuff in order to get simple stuff (like client-side form validation) to work. The world is ready for a helper class, or at least I was.

So I put this together. Currently it only supports text, password, and hidden fields but you get the idea. The CakePHP FormHelper class inspired some of the logic dealing with camelcasing the field names.

app/views/helpers/extjs.php

class ExtjsHelper extends AppHelper {

	function init()
	{
		return '';
	}
	function input($fieldName, $options = array())
	{
		// see the API definition of FormHelper::input()
		$view =& ClassRegistry::getObject('view');
		$this->setEntity($fieldName);
		
		$tokens =  $view->entity();
		$modelname = $tokens[0];
		$propertyname = $tokens[1];

		if (isset($options['type']))
			$type = $options['type'];
		else
		{
			if ($fieldName == 'id')
				$type = "hidden";
			elseif (in_array($this->field(), array('psword', 'passwd', 'password')))
				$type = "password";
			else $type = "text";
		}
		
		$label = (isset($options['label']) ? $options['label'] : Inflector::humanize($propertyname));
		$id = $modelname.Inflector::camelize($propertyname);
		$html = '';

		$value = (isset($options['value']) ? $options['value'] : '');
		$style = (isset($options['style']) ? ',style:"'.$options['style'].'"' : '');
		$width = (isset($options['width']) ? ',width:"'.$options['width'].'"' : '');
		$vtype = (isset($options['vtype']) ? ',vtype:"'.$options['vtype'].'"' : '');
		$allowBlank = (isset($options['allowBlank']) ? ',allowBlank:'.($options['allowBlank'] ? 'true':'false') : '');
		$emptyText = (isset($options['emptyText']) ? ',emptyText:"'.$options['emptyText'].'"' : '');
		
		if ($type != "hidden")
			$html .= '
'; $html .= ''; if ($type != "hidden") $html .= '
'; return $html; } }

Usage:

// include the ExtJS Javascript and CSS classes in the HEAD of your layout, 
// then create the form as usual

echo $form->create(...);
echo $extjs->init();
echo $extjs->input('email', 
		array(
			'style'=>'width:200px;margin:8px',
			'vtype'=>'email',
			'allowBlank' => false
			));
...
echo $form->end('Submit');

This will then post the same form data structure that Cake normally does.

One thought on “An ExtJS form helper for CakePHP”

  1. Pingback: extjstutorial.org

Leave a Reply

Your email address will not be published. Required fields are marked *