Yii2: Assign sum of textfields to another field in form - forms

Im new to Yii and I'm trying to assign the sum of 3 different fields in my _form.php into a total field. I've tried assigning it directly in the controller but the total field stays null. I'm basically trying to achieve this:
$model->cuerdas= $model->propia + $model->usofructo + $model->arrendada;
This is the actionCreate code of the Controller where I tried making the assignment:
public function actionCreate()
{
$model = new AsdaPa0025();
$modelosfacilidades = [new FacilidadesARealizar0025()];
if ($model->load(Yii::$app->request->post())) {
$model->file = UploadedFile::getInstance($model, 'file');
$modelosfacilidades = Model::createMultiple(FacilidadesARealizar0025::classname());
Model::loadMultiple($modelosfacilidades, Yii::$app->request->post());
//valida los modelos
$valid = $model->validate();
$valid = Model::validateMultiple($modelosfacilidades) && $valid;
if ($valid) {
$transaction = \Yii::$app->db->beginTransaction();
try {
if ($flag = $model->save(false)) {
foreach ($modelosfacilidades as $modelofacilidades) {
//Aqui le digo al controlador que id_0025 es igual al id de la instancia de la forma 0025
$modelofacilidades->id_0025 = $model->id_asda_pa_0025;
if (! ($flag = $modelofacilidades->save(false))) {
$transaction->rollBack();
break;
}
}
}
if ($flag) {
$transaction->commit();
$model->cuerdas= $model->propia + $model->usofructo + $model->arrendada;
$model->file->saveAs('uploads/' . $model->file->baseName . '.' . $model->file->extension);
return $this->redirect(['view', 'id' => $model->id_asda_pa_0025]);
}
} catch (Exception $e) {
$transaction->rollBack();
}
}
// $model->file = 'uploads/' . $model->imageFile->baseName . '.' . $model->imageFile->extension;
// if ($model->save()) {
// $model->file->saveAs('uploads/' . $model->file->baseName . '.' . $model->file->extension);
// return $this->redirect(['view', 'id' => $model->id_asda_pa_0025]);
}
else{
// return $this->redirect(['view', 'id' => $model->id_asda_pa_0025]);
return $this->render('create', [
'model' => $model,
'modelosfacilidades' => (empty($modelosfacilidades)) ? [new FacilidadesARealizar0025] : $modelosfacilidades
]);
}
}
I also tried calling this function from model in the controller instead of the manual assignment but I get a using this->() when not in object context error
/**
* #return \yii\db\ActiveQuery
*/
public static function getSuma()
{
return $this->find()->sum('propia + arrendada + usofructo');
}
This is my _form.php where the fields are:
<div class="col-sm-6">
Cuerdas
<?= $form->field($model, 'propia')->textInput()->label('7.Propia') ?>
<?= $form->field($model, 'arrendada')->textInput()->label('8.Arrendada') ?>
<?= $form->field($model, 'usofructo')->textInput()->label('9.Usufructo') ?>
<?= $form->field($model, 'cuerdas')->textInput(['readOnly'=> true])->label('10. Total Cuerdas')?>
</div>
I turned the cuerdas field input as readonly since it is going to be the one that will receive the sum of the other 3 values.
I would appreciate any help on how would the correct approach be to achieve this.

Assuming you have properly assigned the value in form once your model is loaded the values you have assigned are available so
if ($model->load(Yii::$app->request->post())) {
$model->cuerdas= $model->propia + $model->usofructo + $model->arrendada;
......
should work

Related

CodeIgniter 4: Call to member function on null where post request is valid in var_dump()

** Very new to CodeIgniter so please be kind! **
I have an issue with my two user authentication forms: users/register.php and users/login.php where I cannot pass the post input to functions in my model.
As of now, I'm getting the error Call to member function addUser() on null on the registration form and a validation error on the login form that states the username/password don't match any credentials in the database. Both seem to stem from post being null although it is not.
I have done a var_dump on $login which is defined as $login = $this->request->getPost() as well as inspected the request in Firefox Developers Browser to find all the post data correctly displayed. I am stumped. Why can't I pass this array to my model?
Here is a screenshot of the post request for login.php (the same can be said for registration.php and is not included).
These are my routes:
// Login and Registration
$routes->match(['get', 'post'], 'users/register', 'Users::register');
$routes->match(['get', 'post'], 'users/login', 'Users::login', ["filter" => "noauth"]);
Here is my model UserModel.php in its entirety:
class UserModel extends Model
{
protected $DBGroup = 'default';
protected $table = 'users';
protected $primaryKey = 'username';
protected $useAutoIncrement = false;
protected $insertID = 0;
protected $returnType = 'object';
protected $useSoftDelete = false;
protected $allowedFields = [
'username',
'password',
'id',
'role',
'profile_image',
'profile_views',
'last_login',
'about_me',
'age',
'gender',
'occupation',
'hometown',
'country',
'fav_shape',
'fav_color',
'created',
'modified',
];
// Dates
protected $useTimestamps = true;
protected $dateFormat = 'datetime';
protected $createdField = 'created';
protected $modifiedField = 'modified';
// Callbacks
protected $allowCallbacks = true;
protected $beforeInsert = ['beforeInsert'];
public function __construct()
{
parent::__construct();
}
protected function beforeInsert(array $data)
{
$data = $this->passwordHash($data);
return $data;
}
protected function passwordHash(array $data)
{
if (isset($data['password'])) {
$data['password'] = password_hash($data['password'], PASSWORD_DEFAULT);
}
return $data;
}
public function lastLogin($username)
{
$this->builder()
->where('username', $username)
->update('last_login', date('Y-m-d H:i:s'));
}
public function addUser($newUser)
{
$builder = $this->builder()
->set($newUser)
->insert();
if ($builder->affected_rows() == 1) {
return TRUE;
} else {
return FALSE;
}
}
public function getUser($username)
{
$builder = $this->builder()
->where(['username' => $username])
->limit(1);
if ($builder->countAllResults() === 1) {
return $builder->get()->getRow();
} else {
return FALSE;
}
}
}
Here are excerpts from my controller Users.php:
class Users extends BaseController
{
protected $userModel;
public function __construct()
{
$userModel = new UserModel();
}
public function login()
{
$validation = \Config\Services::validation();
// Set session variable
$session = session();
if ($this->request->getMethod() === 'post' && ! empty($_POST)) {
$validation->getRuleGroup('login');
$validation->setRuleGroup('login');
$validation->withRequest($this->request)->run();
$recaptchaResponse = trim($this->request->getVar('g-recaptcha-response'));
$userIp = $this->request->getIPAddress();
$secret = env('recaptcha2_secretkey');
$credential = [
'secret' => $secret,
'response' => $recaptchaResponse,
'remoteip' => $userIp,
];
$verify = curl_init();
curl_setopt($verify, CURLOPT_URL, 'https://www.google.com/recaptcha/api/siteverify');
curl_setopt($verify, CURLOPT_POST, TRUE);
curl_setopt($verify, CURLOPT_POSTFIELDS, http_build_query($credential));
curl_setopt($verify, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($verify, CURLOPT_RETURNTRANSFER, TRUE);
$response = curl_exec($verify);
$status = json_decode($response, TRUE);
curl_close($verify);
if (empty($validation->getErrors()) && $status['success']) {
$login = $this->request->getPost();
$user = $this->userModel->getUser($login['username']);
// Storing session values
$this->setUserSession($user);
// Storing success message
$session->setFlashdata('success', 'You have successfully logged in!');
// Update last login datetime
$this->userModel->lastLogin($login['username']);
// Redirecting to dashboard after login
if ($user['role'] == 1) {
return redirect()->to('admin/dashboard');
} elseif ($user['role'] == 0) {
return redirect()->to('members/dashboard');
}
} else {
$data = [
'title' => 'Login',
'errors' => $validation->getErrors(),
];
echo view('templates/index_header', $data);
echo view('users/login');
echo view('templates/footer', $data);
}
} else {
$data = [
'title' => 'Login',
];
echo view('templates/index_header', $data);
echo view('users/login');
echo view('templates/footer', $data);
}
}
/**
* Sets session with user id, username, isLoggedIn, and role for use in member/admin site
* #param model user data
* #return boole if session was set successfully
*/
private function setUserSession($user)
{
$data = [
'id' => $user->id,
'username' => $user->username,
'profile_image' => $user->profile_image,
'isLoggedIn' => true,
'role' => $user->role,
];
if (session()->set($data)) {
return true;
} else {
return false;
}
}
public function register()
{
$validation = \Config\Services::validation();
if ($this->request->getMethod() == 'post' && ! empty($_POST)) {
$validation->getRuleGroup('registration');
$validation->setRuleGroup('registration');
$validation->withRequest($this->request)->run();
if (empty($validation->getErrors())) {
$newUser = $this->request->getPost();
if ($this->userModel->addUser($newUser)) {
$this->session->setFlashdata('success', 'Successful Registration');
$data['title'] = 'Login';
echo view('templates/index_header', $data);
echo view('users/login');
echo view('templates/footer', $data);
} else {
$this->session->setFlashdata('error', 'Something went wrong with your registration! Please try again.');
}
} else {
$data = [];
$data = [
'title' => 'Register',
'script' => 'js/click_link',
'errors' => $validation->getErrors(),
];
echo view('templates/index_header', $data);
echo view('users/register', $data);
echo view('templates/footer', $data);
}
} else {
$data = [
'title' => 'Register',
'script' => 'js/click_link',
];
echo view('templates/index_header', $data);
echo view('users/register', $data);
echo view('templates/footer', $data);
}
}
}
These are my validation rules in Config\Validation:
/**
* Registration
*/
public $registration = [
'username' => 'required|is_unique[users.username,username]|min_length[5]|max_length[25]|alpha_dash|badWordsFilter[username]',
'password' => 'required|min_length[8]|max_length[255]|regex_match[/^(?=.*[!##$%^&*-])(?=.*[0-9])(?=.*[A-Z]).{8,255}$/]',
'pass_confirm' => 'required|matches[password]',
'about_me' => 'permit_empty|max_length[250]|alpha_numeric_punct|badWordsFilter[about_me]',
'occupation' => 'permit_empty|max_length[50]|alpha_space|badWordsFilter[occupation]',
'hometown' => 'permit_empty|max_length[50]|alpha_space|badWordsFilter[hometown]',
'age' => 'permit_empty|less_than[100]|greater_than[0]|numeric',
'country' => 'permit_empty',
];
/**
* Password Verification
*/
public $login = [
'password' => 'required|validateUser[username,password]',
];
This is my custom rule to authenticate username and password credentials User_rules:
class User_rules
{
/**
* Checks if input username exists in database and then checks whether the input password matches the hash for that username
* #param string $str is the input password
* #param string $fields are the associated form fields that are being used
* #param array $data is an array containing the values for the fields indexed by field names
* #return boolean true or false depending on if the user exists and the password matches the hashed password stored in the database
*/
public function validateUser(string $str, string $fields, array $data)
{
$userModel = new UserModel();
$user = $userModel->getUser($data['username']);
if(!$user) {
return FALSE;
}
return password_verify($data['password'], $user->password);
}
Lastly, my view for login.php:
<div class='form-container'>
<?= form_open('users/login',['autocomplete' => FALSE]); ?>
<div class='form-header'>
<h2>Login</h2>
</div>
<div class='form-body'>
<div class='form-row'>
<div class='input-container'>
<i class='fas fa-user'></i>
<?php $attributes = [
'type' => 'text',
'name' => 'username',
'class' => 'input-field',
'id' => 'username',
'placeholder' => 'Username',
'required' => TRUE,
]; ?>
<?= form_input($attributes); ?>
</div>
</div>
<div class='form-row'>
<div class='input-container'>
<i class='fas fa-lock'></i>
<?php $attributes = [
'type' => 'password',
'name' => 'password',
'class' => 'input-field',
'placeholder' => 'Password',
'required' => TRUE,
]; ?>
<?= form_input($attributes); ?>
</div`>
</div>
</div>
<div class='captcha-container'>
<div class='g-recaptcha' data-sitekey='<?= env('recaptcha2_sitekey'); ?>'></div>
</div>
<div class='form-footer'>
<?php $submit = [
'name' => 'loginSubmit',
'value' => 'Login',
'class' => 'submit-btn',
];?>
<?= form_submit($submit); ?>
</div>
<h4 style='text-align: center'>Not a member yet? Register
<a href= <?= site_url('users/register'); ?> title = 'Register'> HERE</a>
</h4>
<?= form_close(); ?>
</div>
It was a stupid mistake. Someone on the codeigniter forum answered my question here: CodeIgniter Forum
basically in my constructor I needed $this->userModel = new UserModel(); instead of $userModel = new UserModel();.

yii2 blank page issue in all crud create and update actions

Please help me.
I have problem as follow:
At the localhost everything ok.
But, at hosting after model save method, controller redirect method return blank page without any error.
my code here:
public function actionCreate()
{
$model = new Project();
$file = UploadedFile::getInstance($model, 'file');
if ($model->load(Yii::$app->request->post()) && $model->save()) {
if($file) {
$path = 'uploads/projects/' . $file->baseName . '.' . $file->extension;
$file->saveAs($path);
$model->image = $path;
$model->save(false);
}
return $this->redirect(['view', 'id' => $model->id]);
} else {
return $this->render('create', [
'model' => $model,
]);
}
}
But redirect method works normally outside model save() method.
Thanks
Try this.
Edited:
public function actionCreate()
{
$model = new Project();
if ($model->load(Yii::$app->request->post())) {
$model->file = UploadedFile::getInstance($model, 'file');
if($file) {
$path = 'uploads/projects/' . $file->baseName . '.' . $file->extension;
$file->saveAs($path);
$model->image = $path;
$model->save(false);
}
return $this->redirect(['view', 'id' => $model->id]);
} else {
return $this->render('create', [
'model' => $model,
]);
}
}

How to improve admin controllers used for crud

I use Zend Framework and in my application admin is mostly used for CRUD operations.
I don't use zend form, and I want to keep it that way if possible, but I think that my code is not good at all, and that it can be improved allot so I am asking nicely you how to organize better this class (since all my classes look prety much the same)...
Here is the code:
http://pastie.org/2422147
honestly the improvement would be to use Zend_Form. What is you reasoning for not using Zend_Form? If it is that you cannot get the custom look and feel you require using decorators, there are ways to leverage zend_Form without mucking with that stuff.
Sample Admin CRUD Controller (for hierarchical categories)
class StoreAdmin_CategoryController extends Zend_Controller_Action
{
protected $_flashMessenger = null;
public function init()
{
$this->_flashMessenger = $this->_helper->getHelper('FlashMessenger');
$this->initView();
}
public function indexAction()
{
$this->_forward('list');
}
public function listAction()
{
$table_category = new Store_Model_DbTable_Category();
$obj_select = $table_category->build_select(array(), array('order_by' => 'ASC'));
$arr_categories = $table_category->fetch_all_objects($obj_select);
$table_category = new Store_Model_DbTable_Category();
$hierarchy = $table_category->get_hierarchy(NULL);
$this->view->assign('arr_categories', $arr_categories);
$this->view->assign('hierarchy', $hierarchy);
}
public function createAction()
{
$form = new StoreAdmin_Form_Category();
if($this->getRequest()->isPost())
{
if($form->isValid($this->getRequest()->getPost()))
{
$table_category = new Store_Model_DbTable_Category();
$category = $table_category->get();
$category->set_name($form->getValue('name'));
$category->set_slug($form->getValue('slug'));
$category->set_description($form->getValue('description'));
$category->set_order_by($form->getValue('order_by'));
$category->set_id_parent($form->getValue('id_parent'));
$category->set_date_created(time());
$category->set_date_modified(time());
$table_category->save($category);
$this->_helper->FlashMessenger(array('success' => sprintf("Category: %s was successfully created!", $category->get_name())));
$this->_redirect('/store-admin/category/list');
}
else
{
$this->_helper->FlashMessenger(array('error' => "Errors! Correct the errors in the form below"));
}
}
$this->view->assign('form_category', $form);
}
public function updateAction()
{
$id_category = $this->getRequest()->getParam('id_category');
if(empty($id_category))
{
throw new Zend_Exception('Error: Category ID Missing from request');
}
$form = new StoreAdmin_Form_Category();
$form->removeOption($id_category);
$table_category = new Store_Model_DbTable_Category();
$category = $table_category->get($id_category);
if($this->getRequest()->isPost())
{
if($form->isValid($this->getRequest()->getPost()))
{
$category->set_name($form->getValue('name'));
$category->set_slug($form->getValue('slug'));
$category->set_description($form->getValue('description'));
$category->set_order_by($form->getValue('order_by'));
$category->set_id_parent($form->getValue('id_parent') ? $form->getValue('id_parent') : NULL);
$category->set_date_modified(time());
$table_category->save($category);
$this->_helper->FlashMessenger(array('success' => sprintf("Category: %s was successfully updated!", $category->get_name())));
$this->_redirect('/store-admin/category/list');
}
else
{
$this->_helper->FlashMessenger(array('error' => "Errors! Correct the errors in the form below"));
}
}
else
{
$form->populate($category->to_array());
}
$this->view->assign('form_category', $form);
$this->view->assign('category', $category);
}
public function deleteAction()
{
$id_category = $this->getRequest()->getParam('id_category');
if(empty($id_category))
{
throw new Zend_Exception('Error: Category ID Missing from request');
}
$table_category = new Store_Model_DbTable_Category();
$category = $table_category->get($id_category);
$table_category->destroy($category);
$this->_helper->FlashMessenger(array('success' => "Category was successfully deleted!"));
$this->_redirect('/store-admin/category/list');
}
}
Sample create view
<div class="span-24">
List
<form action="<?php echo $this->form_category->getAction(); ?>" method="<?php echo $this->form_category->getMethod(); ?>">
<h2>Create a Category</h2>
<p>
<?php echo $this->form_category->getElement('name')->renderLabel(); ?>
<br>
<?php echo $this->form_category->getElement('name')->renderViewHelper(); ?>
<?php echo (NULL != ($errors = $this->form_category->getElement('name')->getMessages()) ? $this->formErrors($errors) : ''); ?>
</p>
<p>
<?php echo $this->form_category->getElement('slug')->renderLabel(); ?>
<br>
<?php echo $this->form_category->getElement('slug')->renderViewHelper(); ?>
<?php echo (NULL != ($errors = $this->form_category->getElement('slug')->getMessages()) ? $this->formErrors($errors) : ''); ?>
</p>
<p>
<?php echo $this->form_category->getElement('id_parent')->renderLabel(); ?>
<br>
<?php echo $this->form_category->getElement('id_parent')->renderViewHelper(); ?>
<?php echo (NULL != ($errors = $this->form_category->getElement('id_parent')->getMessages()) ? $this->formErrors($errors) : ''); ?>
</p>
<p>
<?php echo $this->form_category->getElement('description')->renderLabel(); ?>
<br>
<?php echo $this->form_category->getElement('description')->renderViewHelper(); ?>
<?php echo (NULL != ($errors = $this->form_category->getElement('description')->getMessages()) ? $this->formErrors($errors) : ''); ?>
</p>
<p>
<?php echo $this->form_category->getElement('order_by')->renderLabel(); ?>
<br>
<?php echo $this->form_category->getElement('order_by')->renderViewHelper(); ?>
<?php echo (NULL != ($errors = $this->form_category->getElement('order_by')->getMessages()) ? $this->formErrors($errors) : ''); ?>
</p>
<p>
<?php echo $this->form_category->getElement('submit_category')->renderViewHelper(); ?>
</p>
</form>
</div>
<script type="text/javascript">
$(document).ready(
function()
{
$('#name').change( slugify ).keyup( slugify );
}
);
function slugify()
{
text = $(this).val().toLowerCase();
text = text.replace(/[^-a-zA-Z0-9,&\s]+/ig, '');
text = text.replace(/-/gi, "_");
text = text.replace(/\s/gi, "-");
$('#slug').val(text);
}
</script>
Sample Category Form
<?php
class StoreAdmin_Form_Category extends Zend_Form
{
public function init()
{
$this->setMethod(self::METHOD_POST);
$element = $this->createElement('hidden', 'id_category');
$element->removeDecorator('DtDdWrapper');
$element->removeDecorator('label');
$this->addElement($element);
$element = $this->createElement('text', 'name');
$element->setLabel('Name');
$element->setRequired(TRUE);
$element->removeDecorator('DtDdWrapper');
$element->setAttrib('class', 'text');
$this->addElement($element);
$element = $this->createElement('text', 'slug');
$element->setLabel('Slug');
$element->setRequired(TRUE);
$element->removeDecorator('DtDdWrapper');
$element->setAttrib('class', 'text');
$this->addElement($element);
$element = $this->createElement('textarea', 'description');
$element->setLabel('Description');
$element->removeDecorator('DtDdWrapper');
$element->setAttrib('class', '');
$this->addElement($element);
$table_category = new Store_Model_DbTable_Category();
$options = $table_category->get_tree_options(NULL, '', array(NULL => ''));
$element = $this->createElement('select', 'id_parent');
$element->setLabel('Parent Category');
$element->setRequired(FALSE);
$element->removeDecorator('DtDdWrapper');
$element->addMultiOptions($options);
$this->addElement($element);
$element = $this->createElement('text', 'order_by');
$element->setLabel('Display Order');
$element->setRequired(TRUE);
$element->removeDecorator('DtDdWrapper');
$element->setAttrib('class', 'text');
$this->addElement($element);
$element = $this->createElement('submit', 'submit_category');
$element->setLabel('Submit');
$element->setRequired(TRUE);
$element->removeDecorator('DtDdWrapper');
$element->removeDecorator('label');
$this->addElement($element);
}
/**
* Makes sure that a Category cannot become its own parent (causing a rescursion error)
*/
public function removeOption($id_category)
{
$this->removeElement('id_parent');
$table_category = new Store_Model_DbTable_Category();
$options = $table_category->get_tree_options(NULL, '', array(NULL => ''));
if(array_key_exists($id_category, $options))
{
unset($options[$id_category]);
}
$element = $this->createElement('select', 'id_parent');
$element->setLabel('Parent Category');
$element->setRequired(FALSE);
$element->removeDecorator('DtDdWrapper');
$element->addMultiOptions($options);
$this->addElement($element);
}
}
Zend_Form greatly simplifies crud controllers. More importantly, it is the accepted practice to use them if you are going to be building apps on ZF.

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

ZEND, Edit form

I have a Zend form to add something to database. And then I want to use this form to edit what I added to the databese. Is any possibility to use this form (fill it from database and display it???)
I have this in my controller:
public function editAction() {
if (Zend_Auth::getInstance()->hasIdentity()) {
try {
$form = new Application_Form_NewStory();
$request = $this->getRequest();
$story = new Application_Model_DbTable_Story();
$result = $story->find($request->getParam('id'));
// $values = array(
// 'title' => $result->title,
// 'story' => $result->story,
// );
if ($this->getRequest()->isPost()) {
if ($form->isValid($request->getPost())) {
$data = array(
'title' => $form->getValue("title"),
'story' => $form->getValue("story"),
);
$where = array(
'id' => $request->getParam('id'),
);
$story->update($data, $where);
}
}
$this->view->form = $form;
$this->view->titleS= $result->title;
$this->view->storyS= $result->story;
} catch (Exception $e) {
echo $e;
}
} else {
$this->_helper->redirector->goToRoute(array(
'controller' => 'auth',
'action' => 'index'
));
}
}
In my view:
<?php
try
{
$tmp = $this->form->setAction($this->url());
//$tmp->titleS=$this->title;
//$tmp->storyS=$this->story;
//echo $tmp->title = "aaaaa";
}
catch(Exception $e)
{
echo $e;
}
And when I try to change something in this view I mean give any value different then NULL I have error that I can not do it so is any possibility to reuse this form? Or not?
Thanks!
Zend_Form has method populate(), which sets values of the form based on array data. So just do:
$form->populate($result->current()->toArray());
and form will be populated based on keys from array.