can't figure out how to validate zend_form - zend-framework

I'm trying to figure out how to get this zend form to validate. I don't understand:
Are the addValidator() arguments specific validators? Is there a list somewhere of those validators?
I've got this in the forms/contact.php:
class Application_Form_Contact extends Zend_Form
{
public function init()
{
$this->setAction('index/process');
$this->setMethod('post');
$name = new Zend_Form_Element_Text('name');
$name->setLabel('Name:');
// $name->addValidator('alnum');
$name->setRequired(true);
$email = new Zend_Form_Element_Text('email');
$email->setLabel('Email:')->setRequired(true);
$confirm = new Zend_Form_Element_Text('confirm');
$confirm->setLabel('Confirm Email:')->setRequired(true);
$phone = new Zend_Form_Element_Text('phone');
$phone->setLabel('Phone:')->setRequired(true);
$subject = new Zend_Form_Element_Select('subject');
$subject->setLabel('Subject:')->setRequired(true);
$subject->setMultiOptions(array('Performance'=>'Performance',
'Workshop'=>'Workshop',
'Other'=>'Other'
));
$message = new Zend_Form_Element_Textarea('message');
$message->setLabel('Message:')->setRequired(true);
$message->setAttrib('rows','6');
$message->setAttrib('cols','30');
$submit = new Zend_Form_Element_Submit('Submit');
$this->addElements(array( $name,
$email,
$confirm,
$phone,
$subject,
$message,
$submit
));
$this->setElementDecorators(array
('ViewHelper',
array(array('data' => 'HtmlTag'), array('tag' => 'td')),
array('Label' , array('tag' => 'td')),
array(array('row' => 'HtmlTag') , array('tag' => 'tr'))
));
$submit->setDecorators(array('ViewHelper',
array(array('data' => 'HtmlTag'), array('tag' => 'td')),
array(array('emptyrow' => 'HtmlTag'), array('tag' => 'td', 'placement' => 'PREPEND')),
array(array('row' => 'HtmlTag') , array('tag' => 'tr'))
));
$this->setDecorators(array(
'FormElements',
array('HtmlTag' , array('tag' => 'table' , 'class' => 'formTable')),
'Form'
)
);
}
}
my controller is:
public function indexAction()
{
$this->view->form = new Application_Form_Contact();
}
public function processAction()
{
// $this->view->form = new Application_Form_Contact();
//
if ($this->_request->isPost()) {
$formData = $this->_request->getPost();
// echo 'success';
$this->view->data = $formdata;
} else {
// $form->populate($formData);
}
}
I'm a newbie, so I'm probably making some obvious errors that I don't see. I'm trying to do basic validation:
all fields must be filled out
all html gets stripped
email and confirm
email fields must match
email must be valid format.
Any help would be greatly appreciated!

Have you tried isValid() ?:
$form = new forms_ContactForm();
if ($this->_request->isPost()) {
$formData = $this->_request->getPost();
if ($form->isValid($formData)) {
echo 'success';
exit;
} else {
$form->populate($formData);
}
}
$this->view->form = $form;
from
About the validators:
$firstName = new Zend_Form_Element_Text('firstName');
$firstName->setLabel('First name')
->setRequired(true)
->addValidator('NotEmpty');
$lastName = new Zend_Form_Element_Text('lastName');
$lastName->setLabel('Last name')
->setRequired(true)
->addValidator('NotEmpty');
$email = new Zend_Form_Element_Text('email');
$email->setLabel('Email address')
->addFilter('StringToLower')
->setRequired(true)
->addValidator('NotEmpty', true)
->addValidator('EmailAddress');
Heres the link to the Zend documentation about Zend fiorms and validators.
Creating Form Elements Using Zend_Form_Element

Related

Translate zend framework 1 form labels and error message

I have a web site which is in English and Arabic. I converted the text into Arabic but the form labels and error message is not converting. I am using gettext adapter and how do i convert this labels. I am using Zend_Form and creating object of this form and passign this to view.
Bootstrap file
protected function _initTranslate() {
$translate = new Zend_Translate('gettext', APPLICATION_PATH . "/lang/", null, array('scan' => Zend_Translate::LOCALE_DIRECTORY));
$registry = Zend_Registry::getInstance();
$registry->set('Zend_Translate', $translate);
//Zend_Form::setDefaultTranslator($translate);
$translate->setLocale('ar');
}
public function _initRoutes() {
$this->bootstrap('FrontController');
$this->_frontController = $this->getResource('FrontController');
$router = $this->_frontController->getRouter();
$langRoute = new Zend_Controller_Router_Route(
':lang', array(
'lang' => 'ar',
'module' => 'default',
'controller' => 'index',
'action' => 'index'
), array(
'lang' => 'en|ar'
)
);
$defaultRoute = new Zend_Controller_Router_Route(
':controller/:action', array(
'module' => 'default',
'controller' => 'index',
'action' => 'index'
)
);
$defaultRoute = $langRoute->chain($defaultRoute);
$router->addRoute('langRoute', $langRoute);
$router->addRoute('defaultRoute', $defaultRoute);
}
protected function _initLanguage() {
$front = Zend_Controller_Front::getInstance();
$front->registerPlugin(new My_Controller_Plugin_Language());
}
Form
class Application_Form_Contactus extends Zend_Form {
public function init() {
// Set the method for the display form to POST
$this->setMethod('post');
$this->addElement('text', 'name', array('label' => 'Name', 'class' => 'inputbox',
'filters' => array('StringTrim'),
'required' => true));
// Add an email element
$this->addElement('text', 'email', array('label' => 'Email', 'class' => 'inputbox',
'required' => true, 'filters' => array('StringTrim'), 'validators' => array('EmailAddress')));
$this->addElement('submit', 'submit', array(
'required' => false,
'label' => 'Send',
'value' => 'save',
'class' => 'submit-but',
'attribs' => array('type' => 'submit'),
));
}
}
Controller
$form = new Application_Form_Contactus();
$form->setAction($this->view->getSiteUrl() . 'Contactus');
$translate = Zend_Registry::get('Zend_Translate');
$form->element->setTranslator($translate);
$this->view->form = $form;
view
echo $this->form;
Try to attach to the Zend_Form object as a global translator. This will also translate validation error messages :
Zend_Form::setDefaultTranslator($translate);
Or you can do this :
Zend_Validate_Abstract::setDefaultTranslator($translator);
Please see zend form i18n
Try to set default translator.
Zend_Form::setDefaultTranslator($translate);
One more alternate way could be:
$form = new Application_Form_Contactus();
$translate = Zend_Registry::get('Zend_Translate');
foreach ($form->getElements() as $key => $element) {
$element->setTranslator($translate);
}

CakePHP 2 sends out 2 emails each time

I've come across a strange error in CakePHP when sending a contact form to a recipient via e-mail. When a contact form is filled out and is submitted, CakePHP then sends the e-mail to recipient absolutely fine. But instead of sending one email once it seems to send two emails at the same time.
My controller code is this:
var $helpers = array('Html', 'Form', 'Js');
var $components = array('Email', 'Session');
public function index() {
$this->layout = 'modal';
if(isset($this->data['Contact'])) {
$userName = $this->data['Contact']['yourname'];
$userPhone = $this->data['Contact']['yourtelephone'];
$userEmail = $this->data['Contact']['youremail'];
$userMessage = $this->data['Contact']['yourquestion'];
$email = new CakeEmail();
$email->viewVars(array(
'userName' => $userName,
'userPhone' => $userPhone,
'userEmail' => $userEmail,
'userMessage' => $userMessage
));
$email->subject(''.$userName.' has asked a question from the website');
$email->template('expert', 'standard')
->emailFormat('html')
->to('recipient-email#gmail.com')
->from('postman#website.co.uk', 'The Postman')
->send();
if ($email->send($userMessage)) {
$this->Session->setFlash('Thank you for contacting us');
}
else {
$this->Session->setFlash('Mail Not Sent');
}
}
}
And this is the code for the contact form:
<?php
echo $this->Form->create('Contact', array('url' => '/contact/ask-the-expert/', 'class' => 'contact'));
echo $this->Form->input('yourname', array(
'type' => 'text',
'label' => 'Your Name <span class="star">*</span>',
));
echo $this->Form->input('yourtelephone', array(
'type' => 'text',
'label' => 'Your Telephone',
));
echo $this->Form->input('youremail', array(
'type' => 'text',
'label' => 'Your Email <span class="star">*</span>',
));
echo $this->Form->input('yourquestionAnd ', array(
'type' => 'textarea',
'label' => 'Your Question <span class="star">*</span>',
));
echo $this->Form->submit();
echo $this->Form->end();
?>
Cheers!
Put your Mail Send code inside if ($this->request->is('post')) {} and try.
UPDATE
updated the code.
var $helpers = array('Html', 'Form', 'Js');
var $components = array('Email', 'Session');
public function index() {
$this->layout = 'modal';
if(isset($this->data['Contact'])) {
$userName = $this->data['Contact']['yourname'];
$userPhone = $this->data['Contact']['yourtelephone'];
$userEmail = $this->data['Contact']['youremail'];
$userMessage = $this->data['Contact']['yourquestion'];
$email = new CakeEmail();
$email->viewVars(array(
'userName' => $userName,
'userPhone' => $userPhone,
'userEmail' => $userEmail,
'userMessage' => $userMessage
));
$email->subject(''.$userName.' has asked a question from the website');
$email->template('expert', 'standard')
->emailFormat('html')
->to('recipient-email#gmail.com')
->from('postman#website.co.uk', 'The Postman')
if ($email->send($userMessage)) {
$this->Session->setFlash('Thank you for contacting us');
}
else {
$this->Session->setFlash('Mail Not Sent');
}
}
}

Register form doesn't work

I got RegisterController.php and inside of it I got:
class RegisterController extends AppController {
public $name = 'Register';
public $components = array('Session');
public function index() {
if ($this->request->is('account')) {
// if ($this->Post->save($this->request->data)) {
echo "got it";
$this->Session->setFlash('Your post has been saved.');
$this->redirect(array('action' => 'index'));
// }
}
}
}
My /View/Register/index.tcp file:
<?php
echo $this->Form->create('Account');
echo $this->Form->input('username');
echo $this->Form->input('password');
$options = array(
'label' => 'Register',
'class' => 'submit'
);
echo $this->Form->end($options);
?>
And my /Model/Account.php file:
<?php
class Account extends AppModel {
public $name = 'Account';
public $validate = array(
'username' => array(
'rule' => 'notEmpty'
),
'password' => array(
'notEmpty' => array(
'rule' => 'notEmpty',
'message' => 'Can not be empty.'
),
'minLength' => array(
'rule' => array('minLength', '8'),
'message' => 'Min. 8 chars.'
)
)
);
}
?>
The problem is that, I'm clicking on the submit button, and nothing happends. It should at least check for validation.
Where is the error?
Should work if you add the action in options:
echo $this->Form->create('Account', array('action' => 'your/url'));

Zend Framework Custom Validator on Form Elements

Hi I am trying to set up element custom validator in a zend form this is what I have.
class Siteanalysis_Form_User_ChangePassword extends SA_Form_Abstract
{
public function init()
{
// add path to custom validators
$this->addElementPrefixPath(
'Siteanalysis_Validate',
APPLICATION_PATH . '/modules/siteanalysis/models/validate/',
'validate'
);
$this->addElement('text', 'passwdVerify', array(
'filters' => array('StringTrim'),
'validators' => array('PasswordVerification',array('StringLength', true, array(6, 128))),
'decorators' => array('ViewHelper','Errors',
array('HtmlTag', array('id' => 'passwdVerify')),
array('Label', array('placement'=>'prepend','class'=>'label'))),
'required' => true,
'label' => 'Confirmar contraseña nueva',
));
$this->addElement('submit', 'change', array(
'label' => 'Cambiar',
'required' => false,
'ignore' => true,
'decorators' => array('ViewHelper')
));
}
}
class Siteanalysis_Validate_PasswordVerification extends Zend_Validate_Abstract
{
const NOT_MATCH = 'notMatch';
protected $_messageTemplates = array(
self::NOT_MATCH => 'Verifique que las contraseñs sean iguales.'
);
public function isValid($value, $context = null)
{
$value = (string) $value;
$this->_setValue($value);
if (is_array($context)) {
if (isset($context['passwdNew'])
&& ($value == $context['passwdNew']))
{
return true;
}
} elseif (is_string($context) && ($value == $context)) {
return true;
}
$this->_error(self::NOT_MATCH);
return false;
}
}
The problem is that its not calling the PasswordVerification custom validator, does any one see something wrong with it?
Thanks.
Update: Test Setup
$form = new Siteanalysis_Form_User_ChangePassword();
$value = 'Adam';
$data = array('passwdVerify' => $value);
$validation = $form->isValid($data);
if ( $validation === false ) {
$element = $form->getElement('passwdVerify');
$errors = $element->getErrors();
$msg = $element->getMessages();
} else {
$values = $form->getValidValues($data);
}
If $value is
empty I get $errors "isEmpty"
'Adam' I get $errors "noMatch" and "stringLengthTooShort"
'AdamSandler' I get $errors "noMatch"
Your validators array should look like this:
'validators' => array('PasswordVerification' => array('StringLength', true, array(6, 128)))
not
'validators', array('PasswordVerification',array('StringLength', true, array(6, 128))),

zend array[] element with validator

hello i have a form where the user can click on a button and dinamically add new elements(with Jquery)
<input name="sconto[]" type="text"><br>
<input name="sconto[]" type="text"><br>
<input name="sconto[]" type="text"><br>
...
I have a custom validator for float numbers in format with comma and dot separation like 20.50 and 20,50
The problem is i can't seem to find how to make zend apply it it to each element of the array.
So how should i declare this element and how to apply the validator? xD
this is my validator
protected $_messageTemplates = array(
self::NON_E_NUMERO => 'non sembra essere un numero'
);
public function isValid($value, $context = null)
{
$pos_virgola = strpos($value, ",");
if ($pos_virgola !== false)
$value = str_replace(",", ".", $value);
if (!is_numeric($value))
{
$this->_error(self::NON_E_NUMERO, $value);
return false;
}
else
return true;
}
}
the form i don't know how to do it, i use this but obviously it doesn't work
$sconto = $this->createElement('text','sconto')->setLabel('sconto');
//->setValidators(array(new Gestionale_Validator_Float()));
$this->addElement($sconto);
...
$sconto->setDecorators(array(//no ViewHelper
'Errors',
'Description',
array(array('data' => 'HtmlTag'), array('tag' => 'td', /*'class' => 'valore_campo', */'id'=>'sconto')),
array('TdLabel', array('placement' => 'prepend', 'class' => 'nome_campo'))
));
If Marcin comment is not what you want to do, then this is another way to create multi text element.
Create a custom decorator 'My_Form_Decorator_MultiText'. You will need to register your custom decorator class. Read Zend Framework doc for details http://framework.zend.com/manual/en/zend.form.decorators.html
class My_Form_Decorator_MultiText extends Zend_Form_Decorator_Abstract {
public function render($content) {
$element = $this->getElement();
if (!$element instanceof Zend_Form_Element_Text) {
return $content;
}
$view = $element->getView();
if (!$view instanceof Zend_View_Interface) {
return $content;
}
$values = $element->getValue();
$name = $element->getFullyQualifiedName();
$html = '';
if (is_array($values)) {
foreach ($values as $value) {
$html .= $view->formText($name, $value);
}
} else {
$html = $view->formText($name, $values);
}
switch ($this->getPlacement()) {
case self::PREPEND:
return $html . $this->getSeparator() . $content;
case self::APPEND:
default:
return $content . $this->getSeparator() . $html;
}
}
}
Now your validation class will validate each element value
class My_Validate_Test extends Zend_Validate_Abstract {
const NON_E_NUMERO = 'numero';
protected $_messageTemplates = array(
self::NON_E_NUMERO => 'non sembra essere un numero'
);
public function isValid($value, $context = null) {
if (!is_numeric($value)) {
$this->_error(self::NON_E_NUMERO, $value);
return false;
}
else
return true;
}
}
This is how you can use the new decorator
$element = new Zend_Form_Element_Text('sconto', array(
'validators' => array(
new My_Validate_Test(),
),
'decorators' => array(
'MultiText', // new decorator
'Label',
'Errors',
'Description',
array('HtmlTag', array('tag' => 'dl',))
),
'label' => 'sconto',
'isArray' => true // must be true
));
$this->addElement($element);
Hope this helps