zend 2 - custom field name in validation message - php

I would like to customize input name to show in my view when happen an error in validation of the form
$this->add(array(
'name' => 'generica_descricao', // I WOULD LIKE TO CALL HIM DESCRIÇÃO
//'custom_name' => 'Descrição',
'required' => true,
'validators' => array(
array(
'name' => 'NotEmpty',
'options' => array(
'messages' => array(
'isEmpty' => 'O campo não pode ser vazio'
),
),
),
));
and when i call getMessage() as the code above
if (!$form->isValid()) {
$resultado = new Resultado(Resultado::FLAG_WARNING, $form->getMessages());
$resultado->setaRetornoLayoutErro($this->getServiceLocator());
return $resultado->getJson();
}
they will return
array('Descrição' => 'O campo não pode ser vazio');
then i will can give this array to my view and show dialog with the correctly messages, can anybody help how do that in zend?

I found a best way, create a new method that extends the default form getting the name from the label in the form.
abstract class GenericForm extends Form {
public function getMessagesTranslated($elementName = null) {
$mensagensOriginais = $this->getMessages($elementName);
foreach ($mensagensOriginais as $chave => $mensagens) {
$label = TranslateUtil::translate($this->get($chave)->getLabel());
$mensagensOriginais[$label] = $mensagensOriginais[$chave];
unset($mensagensOriginais[$chave]);
}
return mensagensOriginais;
}

I customize my filter with a method that translates the field name, is not what i want but it works for now:
generic filter
abstract function convertErrorsArrayKeyToFriendlyNames($erros);
specific filter:
public function convertErrorsArrayKeyToFriendlyNames($erros) {
foreach ($erros as $chave => $valor) {
if ($chave == 'generica_descricao') {
$erros['Descrição'] = $erros[$chave];
unset($erros[$chave]);
} else if ($chave == 'generica_ordem') {
$erros['Ordem'] = $erros[$chave];
unset($erros[$chave]);
} else if ($chave == 'generica_ativo') {
$erros['Ativo'] = $erros[$chave];
unset($erros[$chave]);
}
}
return $erros;
}
and in the controller
if (!$form->isValid()) {
$erros = $filtro->convertErrorsArrayKeyToFriendlyNames($form->getMessages());
$resultado = new Resultado(Resultado::FLAG_WARNING, $erros);
$resultado->setaRetornoLayoutErro($this->getServiceLocator());
return $resultado->getJson();
}

Related

PHP form validation passes even though there is error

I am trying to develop a form validation system. But the problem is even though there is no data given by users as required the validation passes. Can't figure out where the problem is.
This is my form validation class
class Validation
{
private $_passed = false,
$_errors = array(),
$_db = null;
public function __construct() {
$this->_db = DB::getInstance();
}
public function check($source, $items= array()) {
foreach ($items as $item => $rules) {
foreach ($rules as $rule => $rule_value) {
$value = $source[$item];
if ($rule === 'required' && empty($value)) {
$this->addError("{$item} is required");
} else {
}
}
}
if (empty($this->_errors)) {
$this->_passed = true;
}
return $this;
}
private function addError($error) {
$this->errors[] = $error;
}
public function errors() {
return $this->_errors;
}
public function passed() {
return $this->_passed;
}
}
And this is the form page containing Html form.
require_once 'core/init.php';
if (Input::exists()) {
$validate = new Validation();
$validation = $validate->check($_POST, array(
'username' => array(
'required' => true,
'min' => 2,
'max' => 20,
'unique' => 'users'
),
'password' => array(
'required' => true,
'matches' => 'password'
),
'password_again' => array(
'required' => true,
'min' => 6
),
'name' => array(
'required' => true,
'min' => 2,
'max' => 60
),
));
if ($validation->passed()) {
//register new user
echo "passed"; //this passes even though users provides no data
} else {
print_r($validation->errors());
}
}
So, all i get is echo passed on the screen even though user provide no data at all. It should throw the errors instead. Please help. Thanks
addError writes in $this->errors, while the other methods use $this->_errors. (with underscore). The _errors array will remain empty, so _passed will be set to true in this statement:
if (empty($this->_errors)) {
$this->_passed = true;
}

Magento Admin Edit Form Fields - Custom Model Field(s)

Wanting to add a custom Model to be rendered in a custom Magento admin form. Just cant seem to get the source model to render any of the options. Couldn't really find anything on google as it was mostly to do with system/config source model examples. See code below
Model File (My/Module/Model/MyModel.php)
<?php
class My_Module_Model_MyModel extends Mage_Core_Model_Abstract
{
static public function getOptionArray()
{
$allow = array(
array('value' => '1', 'label' => 'Enable'),
array('value' => '0', 'label' => 'Disable'),
);
return $allow;
}
}
and my form tab file - Tab shows up with multiselect field, but its blank (My/Module/Block/Adminhtml/Module/Edit/Tab/Data.php)
<?php
class My_Module_Block_Adminhtml_Module_Edit_Tab_Data extends Mage_Adminhtml_Block_Widget_Form
{
protected function _prepareForm(){
$form = new Varien_Data_Form();
$this->setForm($form);
$fieldset = $form->addFieldset('module_form', array('legend'=>Mage::helper('module')->__('Module Information')));
$object = Mage::getModel('module/module')->load( $this->getRequest()->getParam('module_id') );
echo $object;
$fieldset->addField('module_enabled', 'multiselect', array(
'label' => Mage::helper('module')->__('Allowed Module'),
'class' => 'required-entry',
'required' => true,
'name' => 'module_enabled',
'source_model' => 'My_Module_Model_MyModel',
'after_element_html' => '<small>Select Enable to Allow</small>',
'tabindex' => 1
));
if ( Mage::getSingleton('adminhtml/session')->getModuleData() )
{
$form->setValues(Mage::getSingleton('adminhtml/session')->getModuleData());
Mage::getSingleton('adminhtml/session')->setModuleData(null);
} elseif ( Mage::registry('module_data') ) {
$form->setValues(Mage::registry('module_data')->getData());
}
return parent::_prepareForm();
}
}
So I have other fields, tabs that all save the data etc but just cant get the values to render using a custom model inside the multiselect field.
Looks like method name in the source model is incorrect. Also, you probably don't need to extend Mage_Core_Model_Abstract in source models.
Try this:
<?php
class My_Module_Model_MyModel
{
public function toOptionArray()
{
return array(
array('value' => '1', 'label' => Mage::helper('module')->__('Enable')),
array('value' => '0', 'label' => Mage::helper('module')->__('Disable')),
);
}
}
OP's solution migrated from the question to an answer:
updated the MyModel.php to get a foreach in a collection (CMS Pages
for example)
<?php
class My_Module_Model_MyModel
{
public function toOptionArray($withEmpty = false)
{
$options = array();
$cms_pages = Mage::getModel('cms/page')->getCollection();
foreach ($cms_pages as $value) {
$data = $value->getData();
$options[] = array(
'label' => ''.$data['title'].'('.$data['identifier'].')',
'value' => ''.$data['identifier'].''
);
}
if ($withEmpty) {
array_unshift($options, array('value'=>'', 'label'=>Mage::helper('module')->__('-- Please Select --')));
}
return $options;
}
and within My/Module/Block/Adminhtml/Module/Edit/Tab/Data.php I just
removed "source_model" and replaced it with
'values' => Mage::getModel('module/mymodel')->toOptionArray(),
Just to add, also had the issue of multiselect values not
saving/updating the multiselect field on refresh/save on the edit
page. To get this working, I edited the admin controller under the
saveAction (or the action name to save the form data). See below my
saveAction in the controller for the admin/backend located in
My/Module/controllers/Adminhtml/ModuleController.php
public function saveAction() {
$model = Mage::getModel('module/module');
if ($data = $this->getRequest()->getPost()) {
$model = Mage::getModel('module/module');
$model->setData($data)
->setModuleId($this->getRequest()->getParam('module_id'));
try {
if ($model->getCreatedTime() == NULL || $model->getUpdateTime() == NULL) {
$model->setCreatedTime(now())->setUpdateTime(now());
} else {
$model->setUpdateTime(now());
}
$ModuleEnabled = $this->getRequest()->getParam('module_enabled');
if (is_array($ModuleEnabled))
{
$ModuleEnabledSave = implode(',',$this->getRequest()->getParam('module_enabled'));
}
$model->setModuleEnabled($ModuleEnabledSave);
//save form data/values per field
$model->save();
Mage::getSingleton('adminhtml/session')->addSuccess(Mage::helper('module')->__('Item
was successfully saved'));
Mage::getSingleton('adminhtml/session')->setFormData(false);
if ($this->getRequest()->getParam('back')) {
$this->_redirect('*/*/edit', array('module_id' => $model->getModuleId()));
return;
}
$this->_redirect('*/*/');
return;
} catch (Exception $e) {
Mage::getSingleton('adminhtml/session')->addError($e->getMessage());
Mage::getSingleton('adminhtml/session')->setFormData($data);
$this->_redirect('*/*/edit', array('module_id' => $this->getRequest()->getParam('module_id')));
return;
}
}
Mage::getSingleton('adminhtml/session')->addError(Mage::helper('module')->__('Unable
to find item to save'));
$this->_redirect('*/*/');
}
This saves an imploded array (ie 2, 3 ,6, 23, 28,) into the database
value and renders the selected multiselect fields on the corresponding
tab on refresh/update/save

Select element from other table on the form zf2

i have 2 table with ManyToOne relation on the database between client and sale and i want to select the id_client on the Sale Form . for that o used that .
SaleForm :
public function __construct(ClientTable $table)
{
parent::__construct('vente');
$this->setAttribute('method', 'post');
$this->clientTable = $table;
$this->add(array(
'name' => 'id',
'attributes' => array(
'type' => 'hidden',
),
));
$this->add(
array(
'name' => 'id_client',
'type' => 'Select',
'attributes' => array(
'id' => 'id_client'
),
'options' => array(
'label' => 'Catégory',
'value_options' => $this->getClientOptions(),
'empty_option' => '--- Sélectionnez une categorie---'
),
)
);
public function getClientOptions()
{
$data = $this->clientTable->fetchAll()->toArray();
$selectData = array();
foreach ($data as $key => $selectOption) {
$selectData[$selectOption["id"]] = $selectOption["nom_client"];
}
return $selectData;
}
}
SaleController:
use Zend\Mvc\Controller\AbstractActionController;
use Zend\View\Model\ViewModel;
use Caisse\Model\Sale;
use Caisse\Form\SaleForm;
class SaleController extends AbstractActionController
{
protected $saleTable;
protected $clientTable;
public function addAction()
{
$form = new SaleForm($this->clientTable);
$form->get('submit')->setValue('Ajouter');
$request = $this->getRequest();
if ($request->isPost()) {
$vente = new Sale();
$form->setInputFilter($sale->getInputFilter());
$form->setData($request->getPost());
if ($form->isValid()) {
$vente->exchangeArray($form->getData());
$this->getSaleTable()->saveSale($sale);
return $this->redirect()->toRoute('sale');
}
}
return array('form' => $form);
}
}
But every Time i had this issue:
Catchable fatal error: Argument 1 passed to
Caisse\Form\SaleForm::__construct() must be an instance of
Admin\Model\ClientTable, null given.
Is this the good method to do it, any reference for same example will be welcome.
Thank you
Inside your controller, function addAction, you never set the variable clientTable maybe you forgot to initialize it.
Like this
public function addAction()
{
$this->clientTable = $this->getServiceLocator()->get('Client\Model\ClientTable');
$form = new SaleForm($this->clientTable);
// ...
}
About
public function getClientOptions()
{
$data = $this->clientTable->fetchAll();
$selectData = array();
foreach ($data as $row) {
$selectData[$row->id] = $row->nom_client;
}
return $selectData;
}

The Errors messages in edit actions, doesn't appear

I have my validation rules in model, and everything is fine. It validates like I want to, but in the Edit actions, although it not validates, don't show me de red error marks under textbox.
Any tip?
Thanks.
The Model Code(Model name is Safpercent):
var $validate = array(
'sequencia' => array(
'must_be_numeric' => array(
'rule' => 'Numeric',
'message' => 'Number Field: insert only numbers.'
)
),
);
View Text Box:
echo $form->input('Safpercent.sequence', array('id' => 'sequence', 'options' => $criteria, 'label' => false, 'div' => false, 'style' => 'width: 300px'));
Controller Code:
function edit($id = null) {
$criteria = $this->Safpercent->Safrequirement->find('list', array('fields' => array('Safrequirement.sequencia', 'Safrequirement.descricao'), 'conditions' => array('Safrequirement.tipo' => 'ILC')));
$this->set('criteria', $criteria);
if (!$id && empty($this->data)) {
$this->Session->setFlash(RecordNotValid, 'flash_failure');
$this->redirect(array('controller' => 'safpercents', 'action'=>'index'));
}
if (!empty($this->data)) {
$sequencia = $this->data['Safpercent']['sequencia'];
if($this->data['Safpercent']['tipo'] == ''){$tipo = 'ILC';}else{$tipo = $this->data['Safpercent']['tipo'];}
$encontro = $this->Safpercent->Safrequirement->find('all', array('conditions' => array('sequencia' => $sequencia, 'tipo' => $tipo)));
if($encontro <> array()){
if ($this->Safpercent->save($this->data)) {
$this->Session->setFlash(RecordSaved, 'flash_success');
$this->redirect(array('controller' => 'safpercents', 'action'=>'index'));
}else{
$this->Session->setFlash(RecordNotSaved, 'flash_failure');
}
}else{
$this->Session->setFlash('A Sequência que tentou Inserir não existe. Verifique a tabela de novo, por favor.');
}
}
if (empty($this->data)) {
$this->data = $this->Safpercent->read(null, $id);
$this->set('id', $id);
}
$this->set('cod_percent',$this->Safpercent->read(null, $id));
}
(Portuguese Variables and Text in some cases)
Try
debug($this->Safpercent->validationErrors)
and see if it shows any errors.
I see now. In your controller, you are using the sequencia field that you are validating, but not doing any validation at this stage. It passes a non-number to the find query, which then returns an error or something, and the save never gets called?
Before you do this:
$sequencia = $this->data['Safpercent']['sequencia'];
You should check that the data validates, by calling this:
$this->ModelName->set($this->data);
if ($this->ModelName->validates()) {
... //do your business here
So basically, change:
if (!empty($this->data)) {
to:
$this->Safpercent->set($this->data);
if (!empty($this->data) && $this->Safpercent->validates()) {

Zend_Validate: Db_NoRecordExists with Doctrine

Hey there, I'm trying to validate a form with Zend_Validate and Zend_Form.
My element:
$this->addElement('text', 'username', array(
'validators' => array(
array(
'validator' => 'Db_NoRecordExists',
'options' => array('user','username')
)
)
));
For I use Doctrine to handle my database, Zend_Validate misses a DbAdapter. I could pass an adapter in the options, but how do I combine Zend_Db_Adapter_Abstract and Doctrine?
Is there maybe an easyer way to get this done?
Thanks!
Solved it with an own Validator:
<?php
class Validator_NoRecordExists extends Zend_Validate_Abstract
{
private $_table;
private $_field;
const OK = '';
protected $_messageTemplates = array(
self::OK => "'%value%' ist bereits in der Datenbank"
);
public function __construct($table, $field) {
if(is_null(Doctrine::getTable($table)))
return null;
if(!Doctrine::getTable($table)->hasColumn($field))
return null;
$this->_table = Doctrine::getTable($table);
$this->_field = $field;
}
public function isValid($value)
{
$this->_setValue($value);
$funcName = 'findBy' . $this->_field;
if(count($this->_table->$funcName($value))>0) {
$this->_error();
return false;
}
return true;
}
}
Used like that:
$this->addElement('text', 'username', array(
'validators' => array(
array(
'validator' => new Validator_NoRecordExists('User','username')
)
)
));

Categories