2008-12-22

form使用一例

类归于: symfony — 标签:, maker @ 14:51

symfony1.2中加入了一个很重要的特性, 就是form, 使用form可以快速的配置表单的相关操作, 增删改, 包括验证.

当然, 你也可以不对form进行设置, 因为form的生成是自动的, 当初始化model的时候是会在lib/form/下建立相应的的form, 和model一样, form也有一个用户可以自定义的类和一个base类.

下面是针对module shop的一个例子

__ lib/form/ShopForm.class.php __

class ShopForm extends BaseShopForm
{
// 用来生成选项的widget
var $last = array('Wang', 'Luo', 'Chen', 'Li');
public function configure()
{
$this->setWidgets(array(
// input text widget
'first' => new sfWidgetFormInput(array(), array('class' => 'class_name' , 'id' => 'id_name', 'value' => '屁股')),
// select widget
'last' => new sfWidgetFormSelect(array('choices' => $this->last)),
));
// set a label
$this->widgetSchema->setLabel('first', 'Your first name');
// set labels for widgets
$this->widgetSchema->setLabels(array( 'last' => 'Your last name',));
// 设置生成代码的方式, 可以是表格或者列表(li)
//$this->widgetSchema->setFormFormatterName('list');
// 设定生成的name的格式name="name[name]"
$this->widgetSchema->setNameFormat('name[%s]');
// 设定表单项的提示信息
$this->widgetSchema->setHelps(array('first' => 'first name', 'last' => 'last name'));
// 添加验证规则
$this->setValidators(array(
// 最小长度
'first' => new sfValidatorString(array('min_length' => 5), array('min_length' => '屁股的名字太短了')),
'last' => new sfValidatorString(array()),
));

// setPostValidator 是一个全局验证规则,错误信息会出现在表单上方
// validatorCallback 是一个自定义验证的方法
$this->validatorSchema->setPostValidator(new sfValidatorCallback(array('callback' => array($this, 'vcallback')), array('invalid' => '%value%错误了"')));
}

// 自定义验证方法
// $v应该是验证实例
// $s是form传进来的值
// $a应该是附加参数
function vcallback(&$v, $s, $a)
{
if (3>2)
// 如果验证失败返回一个validatorError实例
// validatorError的第三个参数用来替换上面callback时候的%value%
throw new sfValidatorError($v, 'invalid', array('value' => '屁股'));
}
}

__ apps/frontend/modules/shop/actions/actions.class.php __

public function executeIndex(sfWebRequest $request)
{
$this->form = new ShopForm();
if($request->isMethod('post'))
{
$this->form->bind($request->getParameter('name'));
if($this->form->isValid()){
// 如果通过验证则将参数传递到另外一个action中
$this->redirect('shop/submit?'.http_build_query($this->form->getValues()));
}
}
}

__ apps/frontend/modules/shop/templates/indexSuccess.php __

<form action='<?php echo url_for('shop/index');?>' method='post'>
<table border='1'>
<?php echo $form;?>
<tr>
<td colspan='2'>
<input type='submit' />
</td>
</tr>
</table>
</form>

评论暂缺 »

还没有任何评论。

这篇文章上的评论 RSS feed TrackBack URL

留下评论

WordPress 所驱动