I have come up with a problem that my zend form valid does not work? Can anyone tell me how can I fix that problem?
The code - form setup:
<?php
class Application_Form_Register extends Zend_Form
{
public function init()
{
/* Form Elements & Other Definitions Here ... */
$this->setMethod('POST');
$this->setAttrib('class', 'register');
$this->setAttrib('id', 'register_form');
//Add email field
$this->addElement('text', 'register_email', array(
'label' => 'Your Email Address:',
'required' => true,
'filters' => array('StringTrim'),
'validators' => array('EmailAddress',)
)
);
$email_field = $this->getElement('register_email');
$email_field->setDecorators(array(
'ViewHelper',
'Label',
new Zend_Form_Decorator_HtmlTag(array('tag' => 'div', 'id' => 'register_email_label'))
));
$email_field->setAttrib('class', 'register_field');
$email_field->setAttrib('placeholder', 'eg: example#gmail.com');
//Add retype email
$this->addElement('text', 'retype_register_email', array(
'label' => 'Retype Your Email Address:',
'required' => true,
'filters' => array('StringTrim'),
'validators' => array('EmailAddress',)
)
);
$emailconfim_field = $this->getElement('retype_register_email');
$emailconfim_field->setDecorators(array(
'ViewHelper',
'Label',
new Zend_Form_Decorator_HtmlTag(array('tag' => 'div', 'id' => 'register_email_label'))
));
$emailconfim_field->setAttrib('class', 'register_field');
$emailconfim_field->setAttrib('placeholder', 'This field will be used when you login');
//Add first name field
$this->addElement('text', 'register_first_name', array(
'label' => 'First name: ',
'required' => true,
'filters' => array('StringTrim'),
)
);
$name_field = $this->getElement('register_first_name');
$name_field->setDecorators(array(
'ViewHelper',
'Label',
new Zend_Form_Decorator_HtmlTag(array('tag' => 'div', 'id' => 'register_name_label'))
));
$name_field->setAttrib('class', 'register_field');
$name_field->setAttrib('placeholder', 'eg: Michael');
//Add last name field
$this->addElement('text', 'register_last_name', array(
'label' => 'Last name: ',
'required' => true,
'filters' => array('StringTrim'),
)
);
$name_field = $this->getElement('register_last_name');
$name_field->setDecorators(array(
'ViewHelper',
'Label',
new Zend_Form_Decorator_HtmlTag(array('tag' => 'div', 'id' => 'register_name_label'))
));
$name_field->setAttrib('class', 'register_field');
$name_field->setAttrib('placeholder', 'eg: Lee');
//Add password field
$this->addElement('password', 'register_password', array(
'label' => 'Password: ',
'required' => true,
'filters' => array('StringTrim'),
)
);
$password_field = $this->getElement('register_password');
$password_field->setDecorators(array(
'ViewHelper',
'Label',
new Zend_Form_Decorator_HtmlTag(array('tag' => 'div', 'id' => 'register_password_label'))
));
$password_field->setAttrib('class', 'register_field');
$password_field->setAttrib('placeholder', 'Enter your password here');
//Add retype password field
$this->addElement('password', 'register_retype_password', array(
'label' => 'Confirm your password: ',
'required' => true,
'filters' => array('StringTrim'),
)
);
$password_confim_field = $this->getElement('register_retype_password');
$password_confim_field->setDecorators(array(
'ViewHelper',
'Label',
new Zend_Form_Decorator_HtmlTag(array('tag' => 'div', 'id' => 'register_repassword_label'))
));
$password_confim_field->setAttrib('class', 'register_field');
$password_confim_field->setAttrib('placeholder', 'Retype your password here');
//Add question field
$this->addElement('select', 'password_recovery_question', array(
'label' => 'Choose one question for password recovery',
'value' => 'question_list',
'multiOptions' => array(
'null' => 'Select one question',
'Name of your secondary school?' => 'Name of your secondary school?',
'What is your favorite game?' => 'What is your favorite game?',
'What is your home town?' => 'What is your home town?',
'What is your dream?' => 'What is your dream?',
'Whos is your best friend?' => 'Whos is your best friend?',
)
)
);
$password_question = $this->getElement('password_recovery_question');
$password_question->setDecorators(array(
'ViewHelper',
'Label',
new Zend_Form_Decorator_HtmlTag(array('tag' => 'div', 'id' => 'register_question_label'))
));
$password_question->setAttrib('class', 'register_field');
//Add answer to question field
$this->addElement('text', 'answer_to_question', array(
'label' => 'Your answer: ',
'required' => true,
'filters' => array('StringTrim'),
)
);
$answer = $this->getElement('answer_to_question');
$answer->setDecorators(array(
'ViewHelper',
'Label',
new Zend_Form_Decorator_HtmlTag(array('tag' => 'div', 'id' => 'register_answer_label'))
));
$answer->setAttrib('class', 'register_field');
//Add register button
$this->addElement('submit', 'submit', array(
'ignore' => true,
'label' => '注册',
)
);
$button = $this->getElement('submit');
$button->setDecorators(array(
'ViewHelper',
array('HtmlTag', array('tag' => 'div', 'id' => 'register_submit_label'))
));
$button->setAttrib('class', 'register_button');
}
}
The code - signup code:
public function signupAction()
{
// action body
$users = new Application_Model_DbTable_User();
$form = new Application_Form_Register();
$this->view->form = $form;
if($this->getRequest()->isPost()) {
echo "1";
if($form->isValid($_POST)) {
echo "2";
$data = $form->getValues();
$data_insert = array(
'c_email' => $data['register_email'],
'c_fname' => $data['register_first_name'],
'c_lname' => $data['register_last_name'],
'c_question' => $data['password_recovery_question'],
'c_answer' => $data['answer_to_question'],
'c_password' => sha1($data['register_password']),
);
$users->insert($data_insert);
if($data['register_password'] != $data['register_retype_password']) {
echo $this->view->errorMessage = 'Password does not match!';
return;
} elseif ($users->checkUnquie($data['register_email'])) {
echo $this->view->errorMessage = 'Username already exist';
return;
} else {
$users->insert($data_insert);
}
}
}
}
The problem is when I submit my form with data, it cannot read my data from form field. I have tried to debug, so I add echo after first if statement which does work(echo "1").
But the problem occur on the second if statement, echo "2" does not display on browser. So is there any other method that I valid the form?
$_POST is not recognized. should replace by $data = $this->_request->getPost();
Related
I am working on Zend framework 2. I have one form for saving shop information. I have validated the form using Zend's input filters. My issue is when I enter wrong data into the field or keep a mandatory field blank then it properly displays the error but entire form gets blank again.
I want the previously entered values as it is when the form shows errors.
Following is the function that renders the form.
public function settingsAction()
{
try {
$message = '';
$error = '';
$id = 0;
try {
$shop = $this->_getShop();
} catch (\Exception $ex) {
AppLogger::log($ex);
$error = $ex->getMessage();
}
if ($shop) {
$id = $shop->id;
}
else {
//redirect to login page
return $this->redirect()->toUrl($this->_getDomainUrl());
}
$form = new ShopForm($this->serviceLocator);
$config = $this->serviceLocator->get('config');
$apiUrls = $config['apiUrls'];
$request = $this->getRequest();
if ($request->isPost())
{
if (!$shop)
$shop = new Shop();
$form->setInputFilter($shop->getInputFilter());
$form->setData($request->getPost());
if ($form->isValid()) {
$url = $shop->url;
$token = $shop->token;
$config_id = $shop->config_id;
$password = $shop->password;
$shop->exchangeArray($form->getData(),false);
$shop->url = $url;
$shop->token = $token;
$shop->config_id = $config_id;
DAL::getShopTable($this->serviceLocator)->saveShop($shop);
$message = "Your settings has been saved successfully.";
}
else {
$error = 'There are values that need to be completed before you can save/update your preferences.';
foreach($form->getMessages() as $msg) {
$error = $error . $msg;
}
}
}
if ($shop)
{
echo "<pre>";print_r($shop);
$shop->selected_countries = unserialize($shop->selected_countries);
$form->bind($shop);
$form->get('return_address_country')->setAttribute('value', $shop->return_address_country);
}
$form->get('submit')->setAttribute('value', 'Save');
return array(
'id' => $id,
'form' => $form,
'apiUrls' => $apiUrls,
'message' => $message,
'uri' => $this->_selfURL(),
"error" => $error
);
}
catch (\Exception $ex) {
AppLogger::log($ex);
throw $ex;
}
}
I have used $form->setInputFilter($shop->getInputFilter()); for validations. A snippet from getInputFilter() is as follows:
public function getInputFilter()
{
if (!$this->inputFilter) {
$inputFilter = new InputFilter();
$inputFilter->add(array(
'name' => 'id',
'required' => true,
'filters' => array(
array('name' => 'Int'),
),
));
$inputFilter->add(array(
'name' => 'ship_to_code',
'required' => false,
'filters' => array(
array('name' => 'StripTags'),
array('name' => 'StringTrim'),
),
'validators' => array(
array(
'name' => 'StringLength',
'options' => array(
'encoding' => 'UTF-8',
'min' => 0,
'max' => 50,
),
),
),
));
$inputFilter->add(array(
'name' => 'default_phone',
'required' => false,
'filters' => array(
array('name' => 'StripTags'),
array('name' => 'StringTrim'),
),
'validators' => array(
array(
'name' => 'StringLength',
'options' => array(
'encoding' => 'UTF-8',
'min' => 0,
'max' => 50,
),
),
),
));
$inputFilter->add(array(
'name' => 'max_records_per_file',
'required' => true,
'filters' => array(
array('name' => 'Int'),
),
));
}
And the form is
$this->add(array(
'name' => 'id',
'type' => 'Hidden',
));
$this->add(array(
'name' => 'ship_to_code',
'type' => 'Text',
'options' => array(
'label' => 'Ship-To Code',
),
));
$this->add(array(
'name' => 'default_phone',
'type' => 'Text',
'options' => array(
'label' => 'Default Phone',
),
));
You can use the setdata() method of form in your setting action.
Here's updated code
if ($shop)
{
// echo "<pre>";print_r($shop);
// $shop->selected_countries = unserialize($shop->selected_countries);
$form->bind($shop);
$form->setData($request->getPost()); // set post data to form
}
I am working on a custom Magento extension. Version: 1.9.0.1.
I have a custom Adminhtml form, here it is:
Here is the Form code:
<?php
class VivasIndustries_SmsNotification_Block_Adminhtml_Sms_Status_Edit_Form extends Mage_Adminhtml_Block_Widget_Form
{
protected function _prepareForm()
{
$form = new Varien_Data_Form(array(
'id' => 'edit_form',
'action' => $this->getUrl('*/*/save', array('id' => $this->getRequest()->getParam('id'))),
'method' => 'post',
));
$fieldset = $form->addFieldset('edit_form', array('legend'=>Mage::helper('smsnotification')->__('SMS Information')));
$statuses = Mage::getResourceModel('sales/order_status_collection')
->toOptionArray();
$statuses = array_merge(array('' => ''), $statuses);
$fieldset->addField('state', 'select',
array(
'name' => 'state',
'label' => Mage::helper('smsnotification')->__('Order Status'),
'class' => 'required-entry',
'values' => $statuses,
'required' => true,
)
);
$fieldset->addField('smstext', 'textarea', array(
'label' => Mage::helper('smsnotification')->__('SMS Text'),
'class' => 'required-entry',
'required' => true,
'name' => 'smstext',
'onclick' => "",
'onchange' => "",
'after_element_html' => '<br><small>SMS text must <b>NOT</b> be longer then 160 characters!</small>',
'tabindex' => 1
));
if ( Mage::getSingleton('adminhtml/session')->getsmsnotificationData() )
{
$form->setValues(Mage::getSingleton('adminhtml/session')->getsmsnotificationData());
Mage::getSingleton('adminhtml/session')->setsmsnotificationData(null);
} elseif ( Mage::registry('smsnotification_data') ) {
$form->setValues(Mage::registry('smsnotification_data')->getData());
}
// Add these two lines
$form->setUseContainer(true);
$this->setForm($form);
////
return parent::_prepareForm();
}
}
I use this code to get the customer name from the order:
$CustomerName = $observer->getOrder()->getBillingAddress()->getName();
How can I check the whole text and if it finds CustomVariable_CustomerName to replace it with the real customer name ?
I edited standard contact form in SocialEngine. Added new 4 fields to it - BirthDate, address, country & postal code field.
First question - how to properly set the default value of Country Select = "USA"?
Second question - how to get posted data from new form's fields (BirthDate, address, country & postal code) to user's email? How need to edit my controller?
My code:
class Pagecontact_Form_Contact extends Engine_Form
{
private $page_id;
public function __construct($page_id)
{
$this->page_id = $page_id;
parent::__construct();
}
public function init()
{
parent::init();
$this
->setTitle('Send Message to Apply for Sponsorship')
->setAttrib('id', 'page_edit_form_contact')
->setAttrib('class', 'global_form');
$topicsTbl = Engine_Api::_()->getDbTable('topics', 'pagecontact');
$topics = $topicsTbl->getTopics($this->page_id);
$viewer_id = Engine_Api::_()->user()->getViewer()->getIdentity();
$options[0] = '';
foreach($topics as $topic)
{
$options[$topic['topic_id']] = $topic['topic_name'];
}
$this->addElement('Date', 'birthdate', array('label' => 'Birthdate:',
'class' => 'date_class', 'name' => 'birthdate'));
$this->addElement('Text', 'address', array('label' => 'Address:',
'class' => 'address_class', 'name' => 'address'));
$this->addElement('Select', 'country', array('label' => 'Country:',
'class' => 'country_class', 'name' => 'country')); //->setValue("USA");
$this->addElement('Text', 'postal', array('label' => 'Postal Code:',
'class' => 'postal_class', 'name' => 'postal'));
$this->addElement('Select', 'topic', array(
'label' => 'PAGECONTACT_Topic',
'class' => 'topic_class',
'multiOptions' => $options,
));
$this->getElement('topic')->getDecorator('label')->setOption('class','element_label_class topic_label_class');
$this->addElement('Hidden', 'visitor', array(
'value' => 0,
'order' => 3,
));
if ($viewer_id == 0)
{
$this->addElement('Text', 'sender_name', array(
'label' => 'PAGECONTACT_Full name',
'class' => 'subject_class',
'allowEmpty' => false,
'size' => 37,
'validators' => array(
array('NotEmpty', true),
array('StringLength', false, array(1, 64)),
),
'filters' => array(
'StripTags',
new Engine_Filter_Censor(),
new Engine_Filter_EnableLinks(),
),
));
$this->getElement('sender_name')->getDecorator('label')->setOption('class','element_label_class sender_name_label_class');
$this->addElement('Text', 'sender_email', array(
'label' => 'PAGECONTACT_Email',
'class' => 'subject_class',
'allowEmpty' => false,
'size' => 37,
'validators' => array(
array('NotEmpty', true),
array('StringLength', false, array(1, 64)),
),
'filters' => array(
'StripTags',
new Engine_Filter_Censor(),
new Engine_Filter_EnableLinks(),
),
));
$this->getElement('sender_email')->getDecorator('label')->setOption('class','element_label_class sender_email_label_class');
$this->addElement('Hidden', 'visitor', array(
'value' => 1,
'order' => 3,
));
}
$this->addElement('Text', 'subject', array(
'label' => 'PAGECONTACT_Subject',
'class' => 'subject_class',
'allowEmpty' => false,
'size' => 37,
'validators' => array(
array('NotEmpty', true),
array('StringLength', false, array(1, 64)),
),
'filters' => array(
'StripTags',
new Engine_Filter_Censor(),
new Engine_Filter_EnableLinks(),
),
));
$this->getElement('subject')->getDecorator('label')->setOption('class','element_label_class subject_label_class');
$this->addElement('Textarea', 'message', array(
'label' => 'PAGECONTACT_Message',
'maxlength' => '512',
'class' => 'message_class',
'filters' => array(
new Engine_Filter_Censor(),
new Engine_Filter_Html(array('AllowedTags' => 'a'))
),
));
$this->getElement('message')->getDecorator('label')->setOption('class','element_label_class message_label_class');
$this->addElement('Hidden', 'page_id', array(
'value' => $this->page_id,
'order' => 7,
));
$this->addElement('Button', 'send', array(
'label' => 'Send',
'type' => 'button',
'class' => 'btn_send_class',
'name' => 'submitted'
));
}
}
Controller:
public function sendAction()
{
$page_id = $this->_getParam('page_id');
$topic_id = $this->_getParam('topic_id');
$subject = $this->_getParam('subject');
$message = $this->_getParam('message');
$senderName = $this->_getParam('sender_name');
$senderEmail = $this->_getParam('sender_email');
$birthDate = $this->getRequest()->getPost('birthdate'); // Empty set
$address = $this->getRequest()->getPost('adress'); // Empty set
$country = "USA"; // Works
$postal = $this->getRequest()->getPost('postal'); // Empty set
$pagesTbl = Engine_Api::_()->getDbTable('pages', 'page');
$select = $pagesTbl->select()
->from(array($pagesTbl->info('name')), array('displayname'))
->where('page_id = ?', $page_id);
$query = $select->query();
$result = $query->fetchAll();
$pageName = $result[0]['displayname'];
$viewer = $this->_helper->api()->user()->getViewer();
$user_id = $viewer->getIdentity();
$topicsTbl = Engine_Api::_()->getDbTable('topics', 'pagecontact');
$emails = $topicsTbl->getEmails($page_id, $topic_id);
$i = 0;
$emails = explode(',',$emails);
foreach($emails as $email) {
$emails[$i] = trim($email);
$i++;
}
if ($user_id != 0) {
$senderName = $viewer['displayname'];
$senderEmail = $viewer['email'];
}
foreach($emails as $email) {
// Make params
$mail_settings = array(
'date' => time(),
'page_name' => $pageName,
'sender_name' => $senderName,
'sender_email' => $senderEmail,
'subject' => $subject,
'message' => $message." ".$birthDate." ".$address." ".$country." ".$postal,
);
// send email
Engine_Api::_()->getApi('mail', 'core')->sendSystem(
$email,
'pagecontact_template',
$mail_settings
);
};
}
}
Eugene,
There is not country field in the your form. But you can do in controller where you are calling the form function like.
{
$form->getElement('country')->setvalue('USA');
}
Please feel free to ask your questions.
I'm trying to build a VERY simple form and want to add the validation in the form itself. No need for million lines of code when adding it in the form just is about 3 lines.
Here are two of my fields:
$this->add(array(
'name' => 'username',
'attributes' => array(
'type' => 'text',
),
'options' => array(
'label' => 'Name*',
'required' => true,
),
'filters' => array(
array('StringTrim')
),
));
$this->add(array(
'name' => 'email',
'attributes' => array(
'type' => 'text',
),
'options' => array(
'label' => 'E-Mail*',
'required' => true,
),
'validators' => array(
array('regex', true, array(
'pattern' => '/[A-Z0-9._%-]+#[A-Z0-9.-]+\.[A-Z]{2,4}/i',
'messages' => 'Bitte eine gültige E-Mailadresse angeben'))
),
'filters' => array(
array('StringTrim')
),
));
The $form->isValid() ALWAYS returns true. Even if the field is empty. I have another field with a regex-validator, same thing... WTF, Zend?
My controller looks like this:
$form = new UserForm();
$form->setHydrator(new DoctrineEntity($entityManager));
$request = $this->getRequest();
if ($request->isPost()) {
$backenduser = new User();
$form->bind($user);
$form->setData($request->getPost());
if ($form->isValid()) {
....
}
Any ideas?
Validation- and Filtering-Definitions aren't part of the Form itself. See http://framework.zend.com/manual/2.0/en/user-guide/forms-and-actions.html
Try this, pass $_POST data.
if($form->isValid($_POST)) {
// success!
} else {
// failure!
}
I had written the hide and show script for the two elements by checking checkbox in zend, but the value 1 will be sent to the function for both check and uncheck, So it only shows the element but it doesn't hides the element. how to resolve it ?
$this->addElement('checkbox', 'Change_Password',
array('decorators' => $this->elementDecoratorsTr ,'label' => 'Want to Set password ? :',
'required' => false,
'onchange' => 'passwordShow(this.value)',
'Options' => array(
'checkbx1' => 'checkbx1'),
));
$this->addElement('Password', 'User_Password',array(
'decorators' => $this->elementDecoratorsTr,
'label' => 'Password:',
'style' => 'display:none;',
'required' => false,
'filters' => array('StringTrim'),
'validators' => array(array(
'validator' => 'StringLength'))
));
$this->addElement('Password', 'Confirm_Password',array(
'decorators' => $this->elementDecoratorsTr,
'label' => 'Confirm Password:',
'style' => 'display:none;',
'required' => false,
'filters' => array('StringTrim'),
'validators' => array(array(
'validator' => 'StringLength'))
));
Here is my script function to hide and show the two elements User_Password and Confirm_Password
<script>
function passwordShow(password)
{
alert(password);
if(password)
{
$("#User_Password").show();
$("#Confirm_Password").show();
}
else
{
$("#User_Password").hide();
$("#Confirm_Password").hide();
}
}
</script>