Skip to content

Instantly share code, notes, and snippets.

@phunehehe phunehehe/MyFormModel.php
Last active Dec 30, 2015

Embed
What would you like to do?
Antispam for Yii form
<div class="antispam">
<?= $form->textField($model, '_yii_antispam'); ?>
<?= $model->_yii_antispam_message ?>
<script type="text/javascript">
$('.antispam').hide();
$(".antispam input[name='<?= get_class($model) ?>[_yii_antispam]']").val('human');
</script>
</div>
<?php
/*
* Prevent automated POST (actually non-GET) requests by checking a form
* attribute set by JavaScript, in the hope that spammers will not execute
* JavaScript.
*
* Usage:
* 1. Extend MyFormModel instead of CFormModel
* class ContactForm extends MyFormModel {}
* 2. If necessary, use `array_merge(parent::rules(), array(...))` when
* defining validation rules
* public function rules() {
* return array_merge(parent::rules(), array(
* // rules
* ));
* }
* 3. When rendering, include `_antispam` inside the form widget
* <?= $this->renderPartial('//shared/_antispam', array(
* 'form' => $form,
* 'model' => $model)) ?>
*/
class MyFormModel extends CFormModel {
public $_yii_antispam;
public $_yii_antispam_message = 'Type "human" if you are not a robot.';
public function rules() {
return array(
array(
'_yii_antispam', 'compare',
'compareValue' => 'human',
'message' => $this->_yii_antispam_message,
),
);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.