CodeIgniter Forums
Problem with set_value() of Form Validation - Printable Version

+- CodeIgniter Forums (https://forum.codeigniter.com)
+-- Forum: Archived Discussions (https://forum.codeigniter.com/forum-20.html)
+--- Forum: Archived Development & Programming (https://forum.codeigniter.com/forum-23.html)
+--- Thread: Problem with set_value() of Form Validation (/thread-17197.html)



Problem with set_value() of Form Validation - El Forum - 03-28-2009

[eluser]Italo Domingues[/eluser]
Good evening, I wish to inform a problem in the method set_Value () the library form_validation. I have the following form. And I got the script for the validation of some required fields (scripts below). The problem that occurs is, if I fill out the form and leave a required field not filled, it makes the validation perfectly, but when he return to form, the set_Value () returns only the data that are in the script validation, for example, if I enter something in the specification of the product, so it makes the validation of the fields, and return again to the form stating that there is a mandatory field not filled, the field specification of the product does not return what was entered, even though the set_Value () in the attribute value of the input. This is normal?

Form
Code:
<?php echo form_open('admin/produtos/cadastrar', array('id' => 'form_cadastro_produto', 'onSubmit' => 'cadastrarProduto(); return false;')); ?>
<p>
<label>Categoria</label>
&lt;?php echo form_dropdown('cod_categorias', $selectCategorias, set_value('cod_categorias'), 'onchange="selectSubcategoria(this.value);"'); ?&gt;
</p>
<p>
<label>Subcategoria</label>
<select name="cod_subcategorias" id="cod_subcategorias">                    
</select>
</p>
<p>
<label>Nome do Produto </label>
&lt;input name="nome_produtos" type="text" id="nome_produtos" value="&lt;?php echo set_value('nome_produtos'); ?&gt;" maxlength="200" /&gt;
</p>
<p>
<label>Url-Amigável </label>
&lt;input name="nome_amigavel_produtos" type="text" id="nome_amigavel_produtos" value="&lt;?php echo set_value('nome_amigavel_produtos'); ?&gt;" maxlength="250" /&gt;
</p>
<p>

<label>Cód. Interno </label>
&lt;input name="cod_interno_produtos" type="text" id="cod_interno_produtos" value="&lt;?php echo set_value('cod_interno_produtos'); ?&gt;" maxlength="150" /&gt;
</p>
<p>
<label>Descrição do Produto </label>
&lt;textarea name="descricao_produtos" id="descricao_produtos"&gt;&lt;?php echo set_value('descricao_produtos'); ?&gt;&lt;/textarea&gt;
</p>
<p>
<label>Especificação do Produto </label>
&lt;textarea name="especificacao_produtos" id="especificacao_produtos"&gt;&lt;?php echo set_value('especificacao_produtos'); ?&gt;&lt;/textarea&gt;
</p>                                                        
<p class="pbotoes">
&lt;input name="btnSalvar" class="botoes" type="submit" value="Salvar" /&gt;
</p>
<p>
<div id="msg">&lt;?php echo !empty($msg) ? utf8_encode($msg) : NULL; echo utf8_encode(validation_errors()); ?&gt;</div>
</p>                        
&lt;/form&gt;

Script
Code:
function _verificar_campos()
{
    $rules = array(
        array(
            'field' => 'cod_categorias',
            'label' => 'Categoria',
            'rules' => 'required'
        ),
       array(
            'field' => 'cod_subcategorias',
            'label' => 'Subcategoria',
            'rules' => 'required'
        ),
       array(
            'field' => 'nome_produtos',
            'label' => 'Nome do Produto',
            'rules' => 'required'
        ),
        array(
            'field' => 'nome_amigavel_produtos',
            'label' => 'Url-Amigável',
            'rules' => 'required'
        ),
        array(
            'field' => 'descricao_produtos',
            'label' => 'Descrição do Produto',
            'rules' => 'required'
        ),
        array(
            'field' => 'peso_produtos',
            'label' => 'Peso do Produto',
            'rules' => 'required|numeric'
        ),
        array(
            'field' => 'preco_produtos',
            'label' => 'Preço do Produto',
            'rules' => 'required|numeric'
        ),
        array(
            'field' => 'mostrar_preco_produtos',
            'label' => 'Mostrar Preço',
            'rules' => 'required'
        ),
        array(
            'field' => 'imagem_principal_produtos',
            'label' => 'Imagem Principal',
            'rules' => 'required'
        ),
        array(
            'field' => 'ativo_produtos',
            'label' => 'Status',
            'rules' => 'required'
        )
    );

    $this->form_validation->set_rules($rules);

    if ($this->form_validation->run() === FALSE)
    {
        return FALSE;
    }
    else
    {
        return TRUE;
    }
}


PS: I had to draw some lines of form because it does not fit in the post!


Problem with set_value() of Form Validation - El Forum - 03-31-2009

[eluser]Aaron Wallentine[/eluser]
I had this exact same problem.

Basically, if you use set_value, and you use the Form_validation class, set_value() only actually returns the prepopulated value for fields that have validation rules set for them.

I looked into the source code of set_value and found this:

If you're not using the form_validation class, it just returns your $_POST data (after processing it through form_prep() ).
If you are using the form_validation class, it calls the set_value function from the form_validation object, which looks in its internal $_field_data array for the value. If it doesn't find it, it returns default.
I did a print_r on the _field_data array from there, and it appears that it only contains data of fields that have had validation rules defined on them,

So, if you want set_value to work for all your fields, it looks like you either:
1. Set up a validation rule for the field(s) in question
2. patch set_value() in form_validation.php to also check $_POST if it doesn't find the value in _field_data
3. don't load the form validation class

Should I file a bug report for this?

Or is this expected behavior? IE, if I'm using the form validation class, it's assumed that I have at least one rule set for all fields?


Problem with set_value() of Form Validation - El Forum - 05-19-2009

[eluser]Unknown[/eluser]
just do the trick with set a blank rule, ie :
Code:
$this->form_validation->set_rules('field_name', '', '');
it will repopulated the value


Problem with set_value() of Form Validation - El Forum - 02-07-2010

[eluser]lolmann[/eluser]
[quote author="Agus Tri Mulyanto" date="1242756686"]just do the trick with set a blank rule, ie :
Code:
$this->form_validation->set_rules('field_name', '', '');
it will repopulated the value[/quote]

It is an ugly workaround but it works.

Took me some time to find this.

Would be cool if this bug got fixed.


Problem with set_value() of Form Validation - El Forum - 05-30-2011

[eluser]pam81[/eluser]
Hi, i have the same problem and I wanna know if was this bug fixed?


Problem with set_value() of Form Validation - El Forum - 08-03-2011

[eluser]Pieter[/eluser]
I created a My_Form_validation library to solve this problem. It should work with arrays as fieldnames, like profile[name] and colors[] as well. Locate it in your 'application/libraries/My_Form_validation.php'. Hope it helps.

Code:
&lt;?php if (!defined('BASEPATH')) exit('No direct script access allowed.');

class MY_Form_validation extends CI_Form_validation
{
    

   /**
    * ----------------------------------------------------------
    * Set Value: Get the value from a form
    * Extends method to return posted data for fields with no rules
    * ----------------------------------------------------------
    *
    * @param string $field
    * @param string $default
    * @return string
    */    
    
    function set_value($field = '', $default = '')
    {
        // no post?
        if (count($_POST) == 0){
            return $default;
        }
        
        // no rules for this field?
        if ( ! isset($this->_field_data[$field]))
        {
            $this->set_rules($field, '', '');
            
            // fieldname is an array
            if ($this->_field_data[$field]['is_array']){
                $keys = $this->_field_data[$field]['keys'];
                $value = $this->_traverse_array($_POST, $keys);
            }
            
            // fieldname is a key
            else{
                $value = isset($_POST[$field])? $_POST[$field] : FALSE;
            }
            
            // field was not in the post
            if($value === FALSE){
                return $default;
            }
            
            // add field value to postdata
            else{
                $this->_field_data[$field]['postdata'] = form_prep($value, $field);
            }
        }

        return parent::set_value($field, $default);
    }
    


   /**
    * ----------------------------------------------------------
    * Traverse Array: traverse array with given keys and return value or false if not set
    * ----------------------------------------------------------
    *
    * @param array $array
    * @param array $keys
    * @return mixed
    */
    public function _traverse_array($array, $keys)
    {
        foreach($keys as $key)
        {    
            if( ! isset($array[$key]))
            {
                return FALSE;
            }
            
            $array = $array[$key];
        }
        
        return $array;
    }


}

/* End of file MY_Form_validation.php */



Problem with set_value() of Form Validation - El Forum - 08-03-2011

[eluser]Unknown[/eluser]
Pieter, thank you for the post on this. It was exactly what I was looking for and solved a couple of issues that I was having with both set_value and form_validation!