I've read quite some posts about this, but I havn't been able to solve my problem.
When I try to validate my zend form captcha it always fails even with the correct text.
Here is my code:
// where i call my form
public function contactAction()
{
$this->view->form = new Forms_ContactForm();
}
//my form
class Forms_ContactForm extends Twitter_Form
{
public function init()
{
$this->setAction( 'email/email/contact' );
$this->setMethod('post');
$this->addElement('text', 'strFirstName', array(
'required' => true,
'label' => 'Your First Name' ) );
$this->addElement('text', 'strLastName', array(
'required' => true,
'label' => 'your Last Name' ) );
$this->addElement('text', 'strEmail', array( 'validators' => array(
array('EmailAddress') ),
'required' => true,
'label' => 'Your Email' ) );
$this->addElement('textarea', 'strContent', array(
'required' => true,
'label' => 'Your message' ) );
$this->addElement('captcha', 'captcha', array(
'label' => 'Please enter the 5 letters displayed below:',
'required' => true,
'name' => 'captchaField',
'captcha' => 'image',
'captchaOptions' => array(
'captcha' => 'image',
'font'=> 'static/font/arial.ttf',
'imgDir'=>'static/img/captcha',
'imgUrl'=> 'static/img/captcha/',
'wordLen' => 5,
'fsize'=>20,
'height'=>60,
'width'=>200,
'gcFreq'=>50,
'expiration' => 300)
));
$this->addElement('submit', 'submit', array('class' => 'Submit') );
}
}
// and my action to send it
public function contactAction()
{
if( $this->_request->isPost() )
{
$objForm = new Forms_ContactForm();
if( $objForm->isValid($_POST) )
{
$arrParams = $this->_request->getParams();
if( $arrParams['strFirstName'] && $arrParams['strLastName'] && $arrParams['strEmail'] && $arrParams['strContent'] )
{
$this->_objEmail = new Zend_Mail();
$this->_objEmail ->setFrom( $arrParams['strEmail'] );
$this->_objEmail ->setSubject( 'C' );
$this->_objEmail ->setBodyHtml( 'Message from: '. $arrParams['strFirstName'] . ' ' . $arrParams['strLastName'] .
'<BR>eMail address: ' . $arrParams['strEmail'] . '<BR><BR>'
. $arrParams['strContent'] );
$this->_objEmail ->addTo( 'mail#gmail.com' );
$this->view->bolSent = $this->_objEmail->send();
}
}
else
$this->view->form = $objForm;
}
}
It seems that in my contactAction, it generates a new captcha code, so that's why it soesnt match with the one I submitted, but I have no idea how to fix it.
Thank you for your time and help !!
Just saw something dodgy : when i dump my $_POST in contact action here is my result :
array
'strFirstName' => string 'fghjfghj' (length=8)
'strLastName' => string 'ffffffff' (length=8)
'strEmail' => string 'fvhkbno#biu.fr' (length=14)
'strContent' => string 'fewfew' (length=6)
'captchaField' => string 'cebfe69ead38dba86a6b557dc8853b24' (length=32)
The captcha I just entered dosent even appear and instead I have the captcha kay !!??
EDIT
thanks again for your replay !!!
Still not there even with your changes but I think I got whats wrong.
Here is my html for the captcha field:
<div class="control-group">
<label class="control-label required" for="captchaField-input">Please enter the 5 letters displayed below:</label>
<div class="controls">
<img width="200" height="60" src="static/img/captcha/ab2d15044a637338064b39cfd2675837.png" alt="">
<input type="hidden" id="captchaField-id" value="ab2d15044a637338064b39cfd2675837" name="captchaField[id]">
<input type="text" value="" id="captchaField-input" name="captchaField[input]">
<input type="text" value="ab2d15044a637338064b39cfd2675837" id="captchaField" name="captchaField">
</div>
</div>
When I have a look at my params sent, here is what I got :
captchaField ab2d15044a637338064b39cfd2675837
captchaField[id] ab2d15044a637338064b39cfd2675837
captchaField[input] 6af7u
It seems that cptchaField overwright [id] and [input]
I feel like I need to remove this captchaField but have no idea how so far !
I could do that with JS but there must be a clean way to do so !
EDIT AGAIN
Im using ajax to submit the form, with serialize. That could be the problem, ill have a look.
EDIT TER
It is not caused by ajax.
If I manually remove the line :
<input type="text" value="ab2d15044a637338064b39cfd2675837" id="captchaField" name="captchaField">
with firebug, everything is normal and the captcha validates well. Now the question is how to remove this line properly...
SOLUTION
After struggling a lot, here is the solution (remove decorator) !
$captcha = new Zend_Form_Element_Captcha('captchaField',
array('label' => "Please enter the 5 letters displayed below:",
'required'=>true,
'captcha' => array(
'captcha' => 'image',
'font'=> 'static/font/arial.ttf',
'imgDir'=>'static/img/captcha',
'imgUrl'=> 'static/img/captcha/',
'wordLen' => 5,
'fsize'=>20,
'height'=>60,
'width'=>200,
'gcFreq'=>50,
'expiration' => 300
)
));
$this->addElement($captcha);
$this->getElement('captchaField')->removeDecorator("viewhelper");
After struggling a lot, here is the solution (I simply had to remove decorator) !
$captcha = new Zend_Form_Element_Captcha('captchaField',
array('label' => "Please enter the 5 letters displayed below:",
'required'=>true,
'captcha' => array(
'captcha' => 'image',
'font'=> 'static/font/arial.ttf',
'imgDir'=>'static/img/captcha',
'imgUrl'=> 'static/img/captcha/',
'wordLen' => 5,
'fsize'=>20,
'height'=>60,
'width'=>200,
'gcFreq'=>50,
'expiration' => 300
)
));
$this->addElement($captcha);
$this->getElement('captchaField')->removeDecorator("viewhelper");
Thanks Haroon for your help and your time :)
I think you code needs to be like the below, i think in the contactAction.php file the public function contactAction() should handle displaying the form and the action when the form has been posted to ) :
//Display the form
$objForm = new Forms_ContactForm();
$this->view->form = $objForm;
//Handle the form, when it has been posted including validation etc
if( $this->_request->isPost() )
{
if( $objForm->isValid($_POST) )
{
//processing logic etc
}
}
Currently your code is generating a new Captcha to confirm against the data input, because you are instantiating the form after the form has been POSTed to. This instantian of the form needs to be done before the form has been posted to, as I have shown in the code example above.
EDIT
Try this:
$captcha = new Zend_Form_Element_Captcha('captchaField',
array('label' => "Please enter the 5 letters displayed below:",
'required'=>true,
'captcha' => array(
'captcha' => 'image',
'font'=> 'static/font/arial.ttf',
'imgDir'=>'static/img/captcha',
'imgUrl'=> 'static/img/captcha/',
'wordLen' => 5,
'fsize'=>20,
'height'=>60,
'width'=>200,
'gcFreq'=>50,
'expiration' => 300
)
));
$this->addElement($captcha);
This new code after the edit works for me using Zend Framework version 1.11.1
What version of Zend Framework are you sing and how is you Captcha being displayed in your view file??
When var dumping our your output, for the captcha elment you should expect something similar to the below where "5g4ef" is the data you inputted into the Captcha input element:
["captchaField"]=> array(2) { ["id"]=> string(32) "88bb26d62e9fa19b67937c35be4a8cc7" ["input"]=> string(4) "5g4ef" }
Related
I am having a problem with Validating Top Level Domains. Basically, anything with .tech as the TLD is failing the email validation.
I have inherited this project and don't know Zend very well but I have traced the problem back to the hostname not being valid here is the code on GitHub;
// Match hostname part
if ($this->_options['domain']) {
$hostname = $this->_validateHostnamePart();
}
$local = $this->_validateLocalPart();
// If both parts valid, return true
if ($local && $length) {
if (($this->_options['domain'] && $hostname) || !$this->_options['domain']) {
return true;
}
}
return false;
Now, I have some local code here;
class Form_InviteToSpaceForm extends Twitter_Bootstrap_Form_Horizontal
{
public function init()
{
// Set the method for the display form to POST
$this->setMethod('post');
$this->setAction('/team');
$this->addElement('textarea', 'email', array(
'label' => 'Email addresses',
'dimension' => 10,
'required' => true,
'placeholder' => "person1#email.com person2#email.com",//line breaks don't work on placeholders, have to force line wrap with spaces
'filters' => array('StringTrim'),
'validators' => array(
array('validator' => 'NotEmpty'),
array('validator' => 'EmailAddress', 'options' => array('messages' => array('emailAddressInvalidFormat' => 'Incorrect email address specified.')))
)
));
If I comment out the line with the last array('messages' => array('emailAddressInvalidFormat' => 'Incorrect email address specified.'))) then this whole validation is avoided. But I don't want to avoid using this. I just want to be able to extend and add .tech or whatever else comes up from genuine clients. How can I do this with Zend?
You can write custom validator extended from Zend validator
class My_Validate_Hostname extends Zend_Validate_Hostname
{
public function __construct($options = array())
{
parent::__construct($options);
$this->_validTlds = array_merge($this->_validTlds, array('tech'));
}
}
and pass it to email validator
$emailValidator = new Zend_Validate_EmailAddress(array('messages' => array('emailAddressInvalidFormat' => 'Incorrect email address specified.')));
$emailValidator->setHostnameValidator(new My_Validate_Hostname());
....
$this->addElement('textarea', 'email', array(
'label' => 'Email addresses',
'dimension' => 10,
'required' => true,
'placeholder' => "person1#email.com person2#email.com",//line breaks don't work on placeholders, have to force line wrap with spaces
'filters' => array('StringTrim'),
'validators' => array(
array('validator' => 'NotEmpty'),
)
))->addValidator($emailValidator);
I got authentication error with right email/pass of registered user when i added new element in login form in ZfcUser.
I added new element in bootstrap function with this lines:
<?php
namespace SystemUser;
use Zend\Mvc\ModuleRouteListener;
use Zend\Mvc\MvcEvent;
public function onBootstrap($e)
{
$events = $e->getApplication()->getEventManager()->getSharedManager();
$sharedEvents->attach('ZfcUser\Form\Login',
'init',
function($e)
{
// #var $form \ZfcUser\Form\Login
$form = $e->getTarget();
// Configure email input
$form->get('identity')
->setAttribute('placeholder', 'Your email')
->setAttribute('class', 'text-input')
->setAttribute('title', 'Your email');
// Configure password input
$form->get('credential')
->setAttribute('placeholder', 'Your password')
->setAttribute('class', 'text-input')
->setAttribute('title', 'Your password');
// Configure submit button
$form->get('submit')
->setAttribute('class', 'btn btn-primary submit');
// Add field "Keep me signed in."
$form->add(
array(
'type' => 'Zend\Form\Element\Checkbox',
'name' => 'keep_signed_in',
'options' => array(
'label' => 'Keep me signed in.',
'use_hidden_Element' => true,
'checked_value' => '1',
'unchecked_value' => '0'
),
'attributes' => array(
'id' => 'keep_signed_in',
),
)
);
}
);
}
But with new element 'keep_signed_in' login form allways returns error "Authentication failed. Please try again."
Please help. What I must to do for dropping this error with real auth params?
Thank you, guys!
It sounds like you are trying to do something which another module is already doing: https://github.com/goalio/GoalioRememberMe (i know that's not the answer to your question, but now you might not need an answer :))
I find out solution! :)
I forgot specify filter for this checkbox with required=false:
$sharedEvents->attach('ZfcUser\Form\LoginFilter', 'init', function($e) {
// #var $form \ZfcUser\Form\LoginFilter
$filter = $e->getTarget();
// Custom field keep_signed_in
$filter->add(array(
'name' => 'keep_signed_in',
'required' => false,
)
);
}
);
I am a new cake php developer.I am trying to insert multiple record but i cant.My table Structure is given below:
Table Name :
agents
==============================================
id | Contact | Name | email_add | Address
==============================================
Controller Code :
public function send_money()
{
$this->layout='agent';
$this->Agent->create();
$this->Agent->set($this->data);
if(empty($this->data) == false)
{
if($this->Agent->save($this->data))
{
$this->Session->setFlash('Information Added Successfully.');
$this->redirect('send_money');
}
}
else
{
$this->set('errors', $this->Agent->invalidFields());
}
}
Model Code Is :
<?php
App::uses('AppModel', 'Model');
/**
* Admin Login Model
*
*/
class Agent extends AppModel
{
public $name='Agent';
public $usetables='agents';
public $validate = array(
'contact' => array(
'contact_not_empty' => array(
'rule' => 'notEmpty',
'message' => 'Please Give Contact No',
'last' => true
),
),
'name' =>array(
'rule' => 'notEmpty', // or: array('ruleName', 'param1', 'param2' ...)
'allowEmpty' => false,
'message' => 'Please Enter Name.'
),
'email_add' => array(
'email_add' => array(
'rule' => 'email',
'allowEmpty' => true,
'message' => 'Please Enter Valid Email',
'last' => true
)),
);
}
?>
Its not possible to insert records with this code.What should I do?
Let me explain everything.
First of all your html form must be looks like following.
<?php echo $this->Form->create('User'); ?>
<tr>
<td>
<?php
echo $this->Form->input('User.0.address',array
(
'div' => null,
'label' => false,
'class' => 'span required'
));
?>
<?php
echo $this->Form->input('User.1.address',array
(
'div' => null,
'label' => false,
'class' => 'span required'
));
?>
<?php
echo $this->Form->input('User.2.address',array
(
'div' => null,
'label' => false,
'class' => 'span required'
));
?>
</td>
<td>
<input type="submit" value="Add" >
</td>
</tr>
<?php echo $this->Form->end(); ?>
As you can see to save many record at same time using cakephp you must define it as above it will parse input fields as array this is cakephp convention.
I mean User.0.address for first array element
User.1.address for second array element
User.2.address for third array element and so on.
Now.
In Controller file.
<?php
function add()
{
$this->User->saveAll($this->data['User']);
}
And yes here you are done saving multiple record at same time.
I just gave you how cakephp works all you need to do is set above hint as per your need.
Best of luck...
Cheers...
Feel Free to ask... :)
Try this saveall() in your query except save, hope this helps
if($this->Agent->saveall($this->data))
Let me know if it work.
I think this
php echo $this->Form->create('Agents', array('action' => 'send_money'));?>
should be replaced with
php echo $this->Form->create('Agent', array('action' => 'send_money'));?>
and use saveall() in place of save.
I'm just starting to use Zend Framework and was following the quick start documentation for the latest version (1.11.10). Everything was going just fine, but when I placed the form code and ran the application, the form did not render. My code is exactly like http://framework.zend.com/manual/en/learning.quickstart.create-form.html
On the view, I can dump the form just fine with var_dump($this->form);
I've tried echo $this->form(), echo $this->form->render(), but nothing appeared... What could it be?
This problem can occur when Zend can't find the template file for an element. Look at following code:
$element->setDecorators(array(
array('ViewScript',
array(
'viewScript' => 'directory/_input.phtml'
)
)
));
The file _input.phtml must be in the right folder for this Controller. Otherwise Zend can't find the template for input and can't successfully render your element and will not show anything.
Make sure you pass the form to the view from the controller.
In your action handler:
$this->view->form = $my_form;
In your view:
echo $this->form;
I suspected that this was the cause of your problem because Zend Framework doesn't complain if you try to echo a parameter that doesn't exist. (i.e. echo $this->some_fake_parameter won't do anything)
Ok so i tried your code, and it worked for me no problem.
Here is everything:
Controller
<?php
class IndexController extends Zend_Controller_Action
{
public function myTestAction()
{
$form = new Form_Guestbook();
// ... processing logics
if($this->getRequest()->isPost())
{
if($form->isValid($this->getRequest()->getPost()))
{
var_dump($form->getValues());
}
}
$this->view->assign('form', $form);
}
}
Form
<?php
class Form_Guestbook extends Zend_Form
{
public function init()
{
// Set the method for the display form to POST
$this->setMethod('post');
// Add an email element
$this->createElement('text', 'email', array(
'label' => 'Your email address:',
'required' => true,
'filters' => array('StringTrim'),
'validators' => array(
'EmailAddress',
)
));
// Add the comment element
$this->addElement('textarea', 'comment', array(
'label' => 'Please Comment:',
'required' => true,
'validators' => array(
array('validator' => 'StringLength', 'options' => array(0, 20))
)
));
// Add a captcha
$this->addElement('captcha', 'captcha', array(
'label' => 'Please enter the 5 letters displayed below:',
'required' => true,
'captcha' => array(
'captcha' => 'Figlet',
'wordLen' => 5,
'timeout' => 300
)
));
// Add the submit button
$this->addElement('submit', 'submit', array(
'ignore' => true,
'label' => 'Sign Guestbook',
));
// And finally add some CSRF protection
$this->addElement('hash', 'csrf', array(
'ignore' => true,
));
}
}
?>
View
<?php echo $this->form->render(); ?>
can be seen on: http://yaconiello.com/index/my-test
If this isnt working for you, you may be having a configuration error.
I had a problem like that (exact same form, since it is eclipse example)
My problem was due to misunderstanding. Since I thought that I have to directly access to the view script. I entered in the browser something like: hostname/application/view/script/something.php
But in zend all accesses should be through public folder. You have to access to the view like this: hostname/app_name/public/guestbook
hope that would help you
I have a Drupal form wherein someone inputs information, and I need to do a database query to check if it is valid before submitting. I would like to either have a button the user can click to check the validity (or have it be done automatically after the user leaves that field), and then display some information about his selection.
I know I can use hook_form_submit to review a form when it is submitted and then stop the process if there are any errors, but I would like the user to be able to confirm they have selected the correct thing before submitting the form.
I haven't personally tried this module, but it might be what you're looking for:
http://drupal.org/project/ajax
If you're just looking for a way to do real-time lookups (e.g. entering the book barcode and getting the title), you can also use Drupal's autocomplete feature, but it will require you to write your own autocomplete function to handle the database lookups.
Take a look at: Basic form with validate handler. You really just need to add a function similar to mymodule_myform_validate($form, &$form_state) { ... }. From the linked page:
"This adds a new form field and a way to validate it with a validate function, also referred to as a validate handler."
<?php
function my_module_menu() {
$items = array();
$items['my_module/form'] = array(
'title' => t('My form'),
'page callback' => 'my_module_form',
'access arguments' => array('access content'),
'description' => t('My form'),
'type' => MENU_CALLBACK,
);
return $items;
}
function my_module_form() {
return drupal_get_form('my_module_my_form');
}
function my_module_my_form($form_state) {
$form['name'] = array(
'#type' => 'fieldset',
'#title' => t('Name'),
'#collapsible' => TRUE,
'#collapsed' => FALSE,
);
$form['name']['first'] = array(
'#type' => 'textfield',
'#title' => t('First name'),
'#required' => TRUE,
'#default_value' => "First name",
'#description' => "Please enter your first name.",
'#size' => 20,
'#maxlength' => 20,
);
$form['name']['last'] = array(
'#type' => 'textfield',
'#title' => t('Last name'),
'#required' => TRUE,
);
// New form field added to permit entry of year of birth.
// The data entered into this field will be validated with
// the default validation function.
$form['year_of_birth'] = array(
'#type' => 'textfield',
'#title' => "Year of birth",
'#description' => 'Format is "YYYY"',
);
$form['submit'] = array(
'#type' => 'submit',
'#value' => 'Submit',
);
return $form;
}
// This adds a handler/function to validate the data entered into the
// "year of birth" field to make sure it's between the values of 1900
// and 2000. If not, it displays an error. The value report is // $form_state['values'] (see http://drupal.org/node/144132#form-state).
//
// Notice the name of the function. It is simply the name of the form
// followed by '_validate'. This is the default validation function.
function my_module_my_form_validate($form, &$form_state) {
$year_of_birth = $form_state['values']['year_of_birth'];
if ($year_of_birth && ($year_of_birth < 1900 || $year_of_birth > 2000)) {
form_set_error('year_of_birth', 'Enter a year between 1900 and 2000.');
}
}
?>