use bcspamblock in zend form

I want to integrate the bcspamblock and zend form, so first to do:
为了能自动防止机器人攻击,打算把bcspamblock整合到zend_form中。
1 创建element_bcSpamBlock.php文件,

<?php
class element_bcSpamBlock extends Zend_Form_Element_Xhtml{
/**
* Default form view helper to use for rendering
* @var string
*/
public $helper = 'bcSpamBlock';
}

2 创建helper文件:BcSpamBlock.php

<?php
include_once("bcspamblock.php");
class Zend_View_Helper_BcSpamBlock extends Zend_View_Helper_FormElement{

public function bcSpamBlock($name, $value='', $attribs = null){

$xhtml = bcspamblock_generate(true);
return $xhtml;
}
}

3 创建validator,但奇怪的是,这一步经测试,没发生实际作用,不知道是什么原因。

<?php
include_once("bcspamblock.php");
class Validator_SpamBlock extends Zend_Validate_Abstract {
const NOT_MATCH = '机器人阻止';//'spam blocked!';

protected $_messageTemplates = array(
self::NOT_MATCH => '机器人阻止'
);

public function isValid($value) {
$result=bcspamblock_verify();
return $result;
}
}

4 创建自定义的form

<?php

class ContactForm extends Zend_Form
{
public function __construct($options = null)
{
parent::__construct($options);
$this->setName('Contact');

$username = new Zend_Form_Element_Text('username');
$username->setLabel('用户名')->setRequired(true)
->addFilter('StripTags') ->addFilter('StringTrim')
->addValidator('StringLength',false,array(3,50));

$email=new Zend_Form_Element_Text('email');
$email->setLabel('E-Mail')
->setRequired(true)
->addFilter('StringTrim')
->addValidator('NotEmpty')
->addValidator('EmailAddress');

$subject=new Zend_Form_Element_Text('subject');
$subject->setLabel('主题')->setRequired(true);

$body=new Zend_Form_Element_Textarea('body');
$body->setLabel('内容')->setRequired(true)->setAttrib('rows',4);

$id = new Zend_Form_Element_Hidden('id');

$submit = new Zend_Form_Element_Submit('submit');
$submit->setAttrib('id', 'submitbutton')->setLabel('发送');

$spam=new element_bcSpamBlock('spam');
$spam->addPrefixPath('Validator','validator/','validate')
->addValidator('SpamBlock');

$this->addElements(array($id, $spam,$username,$email,$subject,$body,$submit));
}
}

5 在action中调用此form

function contactAction()
{
$form=new ContactForm();
$this->view->form=$form;
$this->view->addHelperPath('helper','Zend_View_Helper_');
if ($this->_request->isPost()) {
//发送邮件
$formData=$this->_request->getPost();
include_once("bcspamblock.php");
if (bcspamblock_verify() && $form->isValid($formData)) {
$mail=new Zend_Mail('utf-8');
....

因为第3步中的validator自动调用不成功,因此在此进行了手工的判断。

This entry was posted in Computer and tagged , , , . Bookmark the permalink.

发表评论

电子邮件地址不会被公开。 必填项已用 * 标注

*

您可以使用这些 HTML 标签和属性: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Please copy the string diS3j9 to the field below:

以新浪微博帐号登录