How to do add and edit in same method in codeigniter controller - forms

I am new to codeigniter and trying to add and edit a category with the same method add.
Here is my add method:
public function add($category_id = FALSE)
{
$this->load->helper('form');
$this->load->library('form_validation');
if($category_id === FALSE)
{
$this->data['mode'] = 'insert';
$this->data['hidden_fields'] = array('mode' => $this->data['mode']);
}
else
{
$this->data['mode'] = 'update';
$this->data['category_details'] = $this->category_model->get_category_details($category_id);
$this->data['category_id'] = isset($this->data['category_details'][0]['category_id']) ? $this->data['category_details'][0]['category_id'] : '';
$this->data['hidden_fields'] = array('category_id' => $this->data['category_id'], 'mode' => $this->data['mode']);
}
// Fill the form data for edit.
$this->data['name'] = isset($this->data['category_details'][0]['name']) ? $this->data['category_details'][0]['name'] : set_value('name');
$this->data['description'] = isset($this->data['exam_category_details'][0]['description']) ? $this->data['category_details'][0]['description'] : set_value('description');
$this->data['status_y'] = (isset($this->data['category_details'][0]['status']) && $this->data['category_details'][0]['status'] === 'Y') ? 'checked="checked"' : set_radio('status', 'Y', TRUE);
$this->data['status_n'] = (isset($this->data['category_details'][0]['status']) && $this->data['category_details'][0]['status'] === 'N') ? 'checked="checked"' : set_radio('status', 'Y');
// set the validation rules
$validation_rules = array(
array(
'field' => 'name',
'label' => 'Name',
'rules' => 'trim|required|min_length[5]|max_length[20]|xss_clean'
),
array(
'field' => 'description',
'label' => 'Description',
'rules' => 'trim|min_length[5]|max_length[256]|xss_clean'
)
);
$this->form_validation->set_rules($validation_rules);
// check if validation fails or upload logo fails
if ($this->form_validation->run() === FALSE)
{
$this->data['validation_errors'] = validation_errors();
$this->load->view($this->config->item('templates_path').'header', $this->data);
$this->load->view($this->config->item('templates_path').'sidebar_content', $this->data);
$this->load->view($this->config->item('templates_path').'navigation', $this->data);
$this->load->view('add_category', $this->data);
$this->load->view($this->config->item('templates_path').'footer');
}
else
{
$id = $this->category_model->update_category();
if($id !== FALSE && is_numeric($id))
{
$this->session->set_flashdata('msg_success', 'Operation Successful');
redirect('/exams/exam_category/');
}
else
{
// update exam category failed some where
log_message('error', 'Update exam category failed', TRUE);
show_error("Unable to Update exam category : ".$id);
}
}
}
The above method works fine for add and edit category, but if form validation fails I am loosing my form default values in both add and edit cases. I have used set_value method of codeignitor. How can I retain the form input values in case of validation fails?

Related

PrestaShop 1.6 add order product to custom email template

I copy order_conf.tpl and order_conf.txt file from mail folder and rename it. Now add override to classes/order/OrderHistory.php
I change function sendemail() to:
public function sendEmail($order, $template_vars = false)
{
$result = Db::getInstance()->getRow('
SELECT osl.`template`, c.`lastname`, c.`firstname`, osl.`name` AS osname, c.`email`, os.`module_name`, os.`id_order_state`, os.`pdf_invoice`, os.`pdf_delivery`
FROM `'._DB_PREFIX_.'order_history` oh
LEFT JOIN `'._DB_PREFIX_.'orders` o ON oh.`id_order` = o.`id_order`
LEFT JOIN `'._DB_PREFIX_.'customer` c ON o.`id_customer` = c.`id_customer`
LEFT JOIN `'._DB_PREFIX_.'order_state` os ON oh.`id_order_state` = os.`id_order_state`
LEFT JOIN `'._DB_PREFIX_.'order_state_lang` osl ON (os.`id_order_state` = osl.`id_order_state` AND osl.`id_lang` = o.`id_lang`)
WHERE oh.`id_order_history` = '.(int)$this->id.' AND os.`send_email` = 1');
if (isset($result['template']) && Validate::isEmail($result['email'])) {
ShopUrl::cacheMainDomainForShop($order->id_shop);
$topic = $result['osname'];
/*----------------------
-START OF INSERTED CODE-
----------------------*/
/* GET THE PRODUCTS */
$order_details = $order->getProducts();
$product_var_tpl_list = array();
foreach ($order_details as $id => &$order_detail) {
$product_var_tpl = array(
'reference' => $order_detail['product_reference'],
'name' => $order_detail['product_name'].(isset($order_detail['product_attributes']) ? ' - '.$order_detail['product_attributes'] : ''),
'unit_price' => Tools::displayPrice($order_detail['unit_price_tax_incl'], $this->context->currency, false),
'price' => Tools::displayPrice($order_detail['total_price_tax_incl'], $this->context->currency, false),
'quantity' => $order_detail['product_quantity'],
'customization' => $order_detail['customizedDatas']
);
$product_var_tpl_list[] = $product_var_tpl;
} // end foreach ($order_detail)
$product_list_txt = '';
$product_list_html = '';
if (count($product_var_tpl_list) > 0) {
$product_list_txt = $this->getEmailTemplateContent('order_conf_product_list.txt', Mail::TYPE_TEXT, $product_var_tpl_list);
$product_list_html = $this->getEmailTemplateContent('order_conf_product_list.tpl', Mail::TYPE_HTML, $product_var_tpl_list);
}
/* GET THE DISCOUNTS */
$cart_rules = $order->getCartRules();
foreach ($cart_rules as $id => &$cart_rule) {
$cart_rules_list[] = array(
'voucher_name' => $cart_rule['name'],
'voucher_reduction' => ($cart_rule['value'] != 0.00 ? '-' : '').Tools::displayPrice($cart_rule['value'], $this->context->currency, false)
);
}
$cart_rules_list_txt = '';
$cart_rules_list_html = '';
if (count($cart_rules_list) > 0) {
$cart_rules_list_txt = $this->getEmailTemplateContent('order_conf_cart_rules.txt', Mail::TYPE_TEXT, $cart_rules_list);
$cart_rules_list_html = $this->getEmailTemplateContent('order_conf_cart_rules.tpl', Mail::TYPE_HTML, $cart_rules_list);
}
/* GET ORDER DETAILS, delivery, invoice, amount... etc */
$invoice_address = new Address((int)$order->id_address_invoice);
$invoiceAddressPatternRules = Tools::jsonDecode(Configuration::get('PS_INVCE_INVOICE_ADDR_RULES'), true);
$deliveryAddressPatternRules = Tools::jsonDecode(Configuration::get('PS_INVCE_DELIVERY_ADDR_RULES'), true);
$country = new Country((int)$invoice_address->id_country);
$delivery_address = null;
$formatted_delivery_address = '';
if (isset($order->id_address_delivery) && $order->id_address_delivery) {
$delivery_address = new Address((int)$order->id_address_delivery);
}
$carrier = new Carrier((int)($order->id_carrier), $order->id_lang);
/* ATTACH INFORMATION TO SMARTY VARIABLE*/
$data = array(
'{lastname}' => $result['lastname'],
'{firstname}' => $result['firstname'],
'{id_order}' => (int)$this->id_order,
'{delivery_block_txt}' => AddressFormat::generateAddress($delivery_address, $deliveryAddressPatternRules, ', ', ' '),
'{invoice_block_txt}' => AddressFormat::generateAddress($invoice_address, $invoiceAddressPatternRules, ', ', ' '),
'{delivery_block_html}' => AddressFormat::generateAddress($delivery_address, $deliveryAddressPatternRules, '<br />',' ', array(
'firstname' => '<span style="font-weight:bold;">%s</span>',
'lastname' => '<span style="font-weight:bold;">%s</span>'
)),
'{invoice_block_html}' => AddressFormat::generateAddress($invoice_address, $invoiceAddressPatternRules, '<br />',' ', array(
'firstname' => '<span style="font-weight:bold;">%s</span>',
'lastname' => '<span style="font-weight:bold;">%s</span>'
)),
'{delivery_company}' => $delivery_address->company,
'{delivery_firstname}' => $delivery_address->firstname,
'{delivery_lastname}' => $delivery_address->lastname,
'{delivery_address1}' => $delivery_address->address1,
'{delivery_address2}' => $delivery_address->address2,
'{delivery_city}' => $delivery_address->city,
'{delivery_postal_code}' => $delivery_address->postcode,
'{delivery_country}' => $delivery_address->country,
'{delivery_state}' => $delivery_address->id_state ? $delivery_state->name : '',
'{delivery_phone}' => ($delivery_address->phone) ? $delivery_address->phone : $delivery_address->phone_mobile,
'{delivery_other}' => $delivery_address->other,
'{invoice_company}' => $invoice_address->company,
'{invoice_vat_number}' => $invoice_address->vat_number,
'{invoice_firstname}' => $invoice_address->firstname,
'{invoice_lastname}' => $invoice_address->lastname,
'{invoice_address2}' => $invoice_address->address2,
'{invoice_address1}' => $invoice_address->address1,
'{invoice_city}' => $invoice_address->city,
'{invoice_postal_code}' => $invoice_address->postcode,
'{invoice_country}' => $invoice_address->country,
'{invoice_state}' => $invoice_address->id_state ? $invoice_state->name : '',
'{invoice_phone}' => ($invoice_address->phone) ? $invoice_address->phone : $invoice_address->phone_mobile,
'{invoice_other}' => $invoice_address->other,
'{order_name}' => $order->getUniqReference(),
'{date}' => Tools::displayDate(date('Y-m-d H:i:s'), null, 1),
'{carrier}' => (!isset($carrier->name)) ? Tools::displayError('No carrier') : $carrier->name,
'{payment}' => Tools::substr($order->payment, 0, 32),
'{products}' => $product_list_html,
'{products_txt}' => $product_list_txt,
'{discounts}' => $cart_rules_list_html,
'{discounts_txt}' => $cart_rules_list_txt,
'{total_paid}' => Tools::displayPrice($order->total_paid, $this->context->currency, false),
'{total_products}' => Tools::displayPrice(Product::getTaxCalculationMethod() == PS_TAX_EXC ? $order->total_products : $order->total_products_wt, $this->context->currency, false),
'{total_discounts}' => Tools::displayPrice($order->total_discounts, $this->context->currency, false),
'{total_shipping}' => Tools::displayPrice($order->total_shipping, $this->context->currency, false),
'{total_wrapping}' => Tools::displayPrice($order->total_wrapping, $this->context->currency, false),
'{total_tax_paid}' => Tools::displayPrice(($order->total_products_wt - $order->total_products) + ($order->total_shipping_tax_incl - $order->total_shipping_tax_excl), $this->context->currency, false)
);
/*---------------------
!-END OF INSERTED CODE-
---------------------*/
if ($result['module_name']) {
$module = Module::getInstanceByName($result['module_name']);
if (Validate::isLoadedObject($module) && isset($module->extra_mail_vars) && is_array($module->extra_mail_vars)) {
$data = array_merge($data, $module->extra_mail_vars);
}
}
if ($template_vars) {
$data = array_merge($data, $template_vars);
}
$data['{total_paid}'] = Tools::displayPrice((float)$order->total_paid, new Currency((int)$order->id_currency), false);
if (Validate::isLoadedObject($order)) {
// Attach invoice and / or delivery-slip if they exists and status is set to attach them
if (($result['pdf_invoice'] || $result['pdf_delivery'])) {
$context = Context::getContext();
$invoice = $order->getInvoicesCollection();
$file_attachement = array();
if ($result['pdf_invoice'] && (int)Configuration::get('PS_INVOICE') && $order->invoice_number) {
Hook::exec('actionPDFInvoiceRender', array('order_invoice_list' => $invoice));
$pdf = new PDF($invoice, PDF::TEMPLATE_INVOICE, $context->smarty);
$file_attachement['invoice']['content'] = $pdf->render(false);
$file_attachement['invoice']['name'] = Configuration::get('PS_INVOICE_PREFIX', (int)$order->id_lang, null, $order->id_shop).sprintf('%06d', $order->invoice_number).'.pdf';
$file_attachement['invoice']['mime'] = 'application/pdf';
}
if ($result['pdf_delivery'] && $order->delivery_number) {
$pdf = new PDF($invoice, PDF::TEMPLATE_DELIVERY_SLIP, $context->smarty);
$file_attachement['delivery']['content'] = $pdf->render(false);
$file_attachement['delivery']['name'] = Configuration::get('PS_DELIVERY_PREFIX', Context::getContext()->language->id, null, $order->id_shop).sprintf('%06d', $order->delivery_number).'.pdf';
$file_attachement['delivery']['mime'] = 'application/pdf';
}
} else {
$file_attachement = null;
}
if (!Mail::Send((int)$order->id_lang, $result['template'], $topic, $data, $result['email'], $result['firstname'].' '.$result['lastname'],
null, null, $file_attachement, null, _PS_MAIL_DIR_, false, (int)$order->id_shop)) {
return false;
}
}
ShopUrl::resetMainDomainCache();
}
return true;
}
protected function getEmailTemplateContent($template_name, $mail_type, $var)
{
$email_configuration = Configuration::get('PS_MAIL_TYPE');
if ($email_configuration != $mail_type && $email_configuration != Mail::TYPE_BOTH) {
}
$theme_template_path = _PS_THEME_DIR_.'mails'.DIRECTORY_SEPARATOR.Context::getContext()->language->iso_code.DIRECTORY_SEPARATOR.$template_name;
$default_mail_template_path = _PS_MAIL_DIR_.Context::getContext()->language->iso_code.DIRECTORY_SEPARATOR.$template_name;
if (Tools::file_exists_cache($theme_template_path)) {
$default_mail_template_path = $theme_template_path;
}
if (Tools::file_exists_cache($default_mail_template_path)) {
Context::getContext()->smarty->assign('list', $var);
return Context::getContext()->smarty->fetch($default_mail_template_path);
}
return ' ';
}
In status I create new one status and add option to send my new email to customer, when in order I change status email is send to customer with data but there is missing all product detail from orders.
I don't know how I can correct get this product in my override file.
You don't have the needed templates in your context backoffice language.
Copy files:
/mails/en/order_conf_cart_rules.tpl
/mails/en/order_conf_cart_rules.txt
/mails/en/order_conf_product_list.tpl
/mails/en/order_conf_product_list.txt
To:
/mails/YOUR_BACKOFFICE_USER_LANG_ISO_CODE/order_conf_cart_rules.tpl
/mails/YOUR_BACKOFFICE_USER_LANG_ISO_CODE/order_conf_cart_rules.txt
/mails/YOUR_BACKOFFICE_USER_LANG_ISO_CODE/order_conf_product_list.tpl
/mails/YOUR_BACKOFFICE_USER_LANG_ISO_CODE/order_conf_product_list.txt

How to update data using session in codeigniter

This my code in codeigniter but it doesn't update in database, I'm beginner ni codeigniter, how could I fix this error, or what is wrong in my code?
THis is my Controller:
function edit() {
$role = $this->session->userdata('role');
$this->form_validation->set_rules('firstname', 'firstname', 'required|xss_clean');
$this->form_validation->set_rules('lastname', 'lastname', 'required|xss_clean');
if ($this->form_validation->run() == FALSE) {
//set page data
$data['title'] = 'Update Profile';
if($role!=''){
$data['admin'] = $this->M_user->get($this->session->userdata('user_id'));
}else{
$data['admin'] = $this->M_administrator->getAdmin($this->session->userdata('id_admin'));
}
$data['sitename'] = $this->M_website->getName();
$data['content'] = 'admin/myaccount/edit';
//parse template
$this->parser->parse('admin/template', $data);
} else {
if($role!=''){
if ($this->M_user->updateStatus($_POST['user_id'])) {
//SAVE ADMIN ACTION LOG
//save_admin_action(array('module' => Constant::AM_ACCOUNT, 'action' => Constant::AL_EDIT, 'title' => $this->form_validation['username'], 'object_id' => $id));
//redirect page
$this->session->set_flashdata('saved', TRUE);
redirect('admin/myaccount');
}
}else{
if ($this->M_administrator->updateStatus($_POST['id_admin'])) {
//SAVE ADMIN ACTION LOG
//save_admin_action(array('module' => Constant::AM_ACCOUNT, 'action' => Constant::AL_EDIT, 'title' => $this->form_validation['username'], 'object_id' => $id));
//redirect page
$this->session->set_flashdata('saved', TRUE);
redirect('admin/myaccount');
}
}
}
}
This is my model administrator:
function updateStatus($post, $id){
$data = array(
'firstname' => $post['firstname'],
'lastname' => $post['lastname']
);
$this->db->where('id_admin', $id);
if($this->db->update('admin', $data)){
return TRUE;
}else{
return FALSE;
}
}
user Model:
function updateStatus($post, $id){
$data = array(
'firstname' => $post['firstname'],
'lastname' => $post['lastname']
);
$this->db->where('user_id', $id);
if($this->db->update('user', $data)){
return TRUE;
}else{
return FALSE;
}
}
pass firstname and last name to your updatestatus model function if you are not getting that value in model so you are not able to change
print your query using $this->db->last_query(); to get query output and post your query here
Change your where clause to
$this->db->where('id_admin', $post);

Phalcon uniqueness on update

folks. The uniqueness validator in my form works as expected on adding new records, but on updating an exsisting record, it throws an error that the url already exists. It exists, in fact, but only in the current record.
Here is my controller:
$feed = Feeds::findFirst($id);
$feedForm = new FeedForm($feed, array('edit' => true));
if ($this->request->isPost() == true) {
$feedData = $this->request->getPost();
if ($feedForm->isValid($feedData, $feed)) {
if ($feed->save()) {
$this->flash->success("Feed successfuly updated.");
} else {
$this->flash->error("Update failed.");
}
} else {
foreach ($feedForm->getMessages() as $message) {
$this->flash->error($message);
}
}
}
And my form class:
class FeedForm extends FormBase {
public $options;
public function initialize($entity = null, $options = null) {
parent::initialize();
$this->setEntity($entity);
$this->options = $options;
$status = new Radio('status');
$status->addValidator(
new PresenceOf(
array(
'message' => 'The status is required.'
)
));
$this->add($status);
$name = new Text('name');
$name->addValidator(
new PresenceOf(
array(
'message' => 'The name is required.'
)
));
$name->addValidator(
new StringLength(
array(
'max' => 50,
'messageMaximum' => 'The name you entered is too long.'
)
));
$this->add($name);
$xml = new Text('xml');
$xml->addValidator(
new PresenceOf(
array(
'message' => 'The URL address is required.'
)
));
$xml->addValidator(
new StringLength(
array(
'max' => 2048,
'messageMaximum' => 'The URL address you entered is too long.'
)
));
$xml->addValidator(
new Url(
array(
'message' => 'The URL you entered is invalid.'
)
));
$xml->addValidator(
new Uniqueness(
array(
'model' => 'Sravnisite\Admin\Models\Feeds',
'table' => 'feeds',
'column' => 'xml',
'message' => 'The entered URL address already exists.'
)
));
$periodOptions = array();
for ($i = 4; $i <= 24; $i++) {
array_push($periodOptions, $i);
}
$this->add($xml);
$period = new Select('period', $periodOptions);
$period->addValidator(
new PresenceOf(
array(
'message' => 'The period is required.'
)
));
$this->add($period);
$shopID = new Select('shop_id', Shops::find(), array('using' => array('id', 'name')));
$shopID->addValidator(
new PresenceOf(
array(
'message' => 'The shop is required.'
)
));
$this->add($shopID);
}
}
Any ideas?
The form validation doesn't know to ignore the record you are updating - so for uniqueness it finds the record you're trying to update and gives an error. You could do some complicated find logic to keep the uniqueness validation in the form but it is better moved to the model. Your result would end up something like:
Controller
$feed = Feeds::findFirst($id);
$feedForm = new FeedForm($feed, array('edit' => true));
if ($this->request->isPost() == true) {
$feedData = $this->request->getPost();
if ($feedForm->isValid($feedData, $feed)) {
if ($feed->save()) {
$this->flash->success("Feed successfuly updated.");
} else {
$this->flash->error("Update failed.");
// Get each of the validation messages from the model
foreach ($feed->getMessages() as $message) {
$this->flash->error($message);
}
}
} else {
foreach ($feedForm->getMessages() as $message) {
$this->flash->error($message);
}
}
}
Form
// Exactly the same as you currently have but without the Uniqueness Validator
Model
class Feeds extends Phalcon\Mvc\Model
/**
* Validate that xml URLs are unique
*/
public function validation()
{
$this->validate(new Uniqueness(array(
"field" => "xml",
"message" => "The url must be unique."
)));
return $this->validationHasFailed() != true;
}

Basic Zend post workflow issue

I am new to this these technologies, so might not be asking to do this the easiest way, but: I want to create a form and ask for an ID value. Once submit is pressed, I want to take that ID, make an external XML call and then show the XML data. I am stuck on if I can do this in a single url:https://plesk.local:8443/modules/example/index.php/index/form. I would like to have both the form and the list data on the same page, so I can update the ID, press submit and see the new data...over and over...
I am trying to modify the basic "Example1" that Plesk includes. I can modify it and test it, but stuck on exactly how POST works. Ideally I want to have $this->view->form to have both a pm_Form_Simple and pm_View_List_Simple on the same $form view (if this makes sense).
So looking for help on
1) Can I use the same URL and handle the POST/GET from it
2) Can I have both a form and simple list on the same page?
thx!!!!!
Here is the sample controller:
<?php
class IndexController extends pm_Controller_Action
{
public function init()
{
parent::init();
// Init title for all actions
$this->view->pageTitle = 'Example Module';
// Init tabs for all actions
$this->view->tabs = array(
array(
'title' => 'Form',
'action' => 'form',
),
array(
'title' => 'List',
'action' => 'list',
),
);
}
public function indexAction()
{
// Default action will be formAction
$this->_forward('form');
}
public function formAction()
{
// Init form here
$form = new pm_Form_Simple();
$form->addElement('text', 'exampleText', array(
'label' => 'Example Text',
'value' => pm_Settings::get('exampleText'),
'required' => true,
'validators' => array(
array('NotEmpty', true),
),
));
$form->addControlButtons(array(
'cancelLink' => pm_Context::getModulesListUrl(),
));
if ($this->getRequest()->isPost() && $form->isValid($this->getRequest()->getPost())) {
// Form proccessing here
pm_Settings::set('exampleText', $form->getValue('exampleText'));
$this->_status->addMessage('info', 'Data was successfully saved.');
$this->_helper->json(array('redirect' => pm_Context::getBaseUrl()));
}
# NEW - start
if (0)
{
# I want to be back here after the POST
# Want to show the list here after I take the POST parameter and do an external XML call...
$list = $this->_getListRandom();
$this->view->list = $list;
}
# NEW - end
$this->view->form = $form;
}
public function listAction()
{
$list = $this->_getListRandom();
// List object for pm_View_Helper_RenderList
$this->view->list = $list;
}
public function listDataAction()
{
$list = $this->_getListRandom();
// Json data from pm_View_List_Simple
$this->_helper->json($list->fetchData());
}
private function _getListRandom()
{
$data = array();
#$iconPath = pm_Context::getBaseUrl() . 'images/icon_16.gif';
for ($i = 0; $i < 15; $i++) {
$data[] = array(
'column-1' => '' . (string)rand() . '',
'column-2' => (string)rand(),
);
}
$list = new pm_View_List_Simple($this->view, $this->_request);
$list->setData($data);
$list->setColumns(array(
'column-1' => array(
'title' => 'Random with link',
'noEscape' => true,
),
'column-2' => array(
'title' => 'Random with image',
'noEscape' => true,
),
));
// Take into account listDataAction corresponds to the URL /list-data/
$list->setDataUrl(array('action' => 'list-data'));
return $list;
}
}
Yes
Yes
I'm not expirienced in zend, so it just try, I suggest to replace formAction() with following code:
public function formAction()
{
// Init form here
$form = new pm_Form_Simple();
$form->addElement('text', 'exampleText', array(
'label' => 'Example Text',
'value' => pm_Settings::get('exampleText'),
'required' => true,
'validators' => array(
array('NotEmpty', true),
),
));
$form->addControlButtons(array(
'cancelLink' => pm_Context::getModulesListUrl(),
));
if ($this->getRequest()->isPost() && $form->isValid($this->getRequest()->getPost())) {
// Form proccessing here
pm_Settings::set('exampleText', $form->getValue('exampleText'));
$this->_status->addMessage('info', 'Data was successfully saved.');
$list = $this->_getListRandom();
$this->view->list = $list;
$this->view->form = $form;
// Redirects happens on next string, maybe you need to add something to getBaseUrl()
$this->_helper->json(array('redirect' => pm_Context::getBaseUrl()));
}
$this->view->form = $form;
}

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))),