Welcome Guest, Not a member yet? Register   Sign In
How to preset my form fields and use the Validation class
#11

[eluser]InsiteFX[/eluser]
Read this article

I just found.

InsiteFX
#12

[eluser]TWP Marketing[/eluser]
@InsiteFX, no good, only difference in your line was the position of the size= attribute,
@toopay, Yes, that works, set_value DOES return the correct text 'Charley Smith' as the default value.

I think this is a fix, but I don't know why it works... I'll have do do some major re-write of my code to move all the set_value usage the controller, but if it works, it works. Thank you both for your input.
#13

[eluser]TWP Marketing[/eluser]
@InsiteFX, I'll have to read the whole thread, but it may be a clue. I do have rules set for the name field and I'll experiment with that.
More later.
#14

[eluser]TWP Marketing[/eluser]
Well, it gets interesting...
Between the two forms of set_value('field','default value'), one from the form_validation.php library and the other from the form_helper.php library, the returned result may or may not use the default value. Which is why I could not pass an existing db value as the default, in some cases.

There have been fixes posted by various forum members, but I don't think these have made their way into the current version (2.0.1).

I'm wondering why this hasn't resulted in more failures of the form_validation process. Is everybody just assuming forms are ONLY used for new data input and not for data editing? That's a rhetorical question, no reply needed...

Anyway, my current understanding is that if you have invoked the form_validation class (creating an instance of that object), you will be using the set_value('field','default value') function found in form_validation.php , which simply determines whether the field has been set and returns the default value if not. It does NOT check the POSTed array.

On the other hand, if you invoke the set_value() function from the form_helper.php library, it checks whether the set_value() function already exists (it might have been invoked in the form_validation object already) and does not execute. If it DID NOT find a prior invocation, it would check for POSTed values and use them or return the default.

Neither case works for all situations...

I DON"T want to make changes/fixes to my system files. I'll wait for the next version where it has hopefully been resolved, or use the fix that [toopay] pointed out above (declare the field attributes in the controller and pass them to the view as part of the data array), OR I'll do what I was doing in the first place, which was to write my own validation code, a messy process with lots of wasted code.

I'll revisit this if I find any changes have been made in the system code.
Thanks to both InsiteFX and toopay for their help on this.
#15

[eluser]toopay[/eluser]
I think there's nothing wrong with Form_validation library. Its working as is designed by CI Team and their expectation, (unfortunately) not like your expectation.

If you want it works as your needs, without make a huge changes in your code, you can do it by modify 'Form_validation.php', under 'system/libraries', find 'set_value' function on line 726, make some little change...
Code:
...
function set_value($field = '', $default = '')
    {
                // Add more validation, and it should give what you want :)
        if ( ! isset($this->_field_data[$field]) OR $this->_field_data[$field] != '')
...
#16

[eluser]osci[/eluser]
try
Code:
<input type="text" name="name" id="name" value="<?php echo set_value('name', "$name");?>" size="50" />
#17

[eluser]louisl[/eluser]
Here's an example of how I typically do it, using one form, controller does add / update and passes the form view to a template view. I pre-populate the form variables from the model. I've slimmed this down a fair bit to (hopefully) make it easy to unserstand.

Model
Code:
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class tags_model extends CI_Model {

    public $TagID;     //:int
    public $Tag;     //:str
    public $Active; //:bool

    public function __construct() {
        
        parent::__construct();
        
        $this->TagID = 0;
        $this->Tag = 'hi this is a default';
        $this->Active = false;
        
    }
    
    
    /**
    * This function gets a tag sets the object variables and returns the query result.
    * @return object (query result)
    */
    public function getTag() {
    
        $sql = 'SELECT '
            .'* '
                .'FROM '.$this->db->dbprefix.'Tags WHERE '
            .'(TagID = ?)';
        
        $params[] = $this->TagID;
        
        $query = $this->db->query($sql, $params);
        
        if ($query->num_rows() > 0) {
            
            $row = $query->row_array();
            
            $this->Tag = $row['Tag'];
            $this->Active = $row['Active'];
        
        }
        
        return $query;
        
    }
    
    
    /**
    * This function inserts a tag and returns the id.
    * @return mixed - int, false
    */
    public function insertTag() {
    
    
        $sql = 'INSERT INTO '.$this->db->dbprefix.'Tags ('
            .'Tag, '
            .'Active '
            .') '
                .'VALUES '
            .'(?,?)';
        
        $params[] =    $this->Tag;
        $params[] = $this->Active;
        
        $query = $this->db->query($sql, $params);
        
        if ($query) {
        
            return $this->db->insert_id();
            
        } else {
        
            return false;
            
        }
        
    
        
    }
    
  
    /**
    * This function updates a tag and returns the query result.
    * @return object (query result)
    */
    public function updateTag() {
    
        $sql = 'UPDATE '.$this->db->dbprefix.'Tags SET '
            .'Tag = ?, '
            .'Active = ? '
                .'WHERE '
            .'TagID = ?';
        
        $params = array(
            $this->Tag,
            $this->Active,
            $this->TagID
        );
        
        $query = $this->db->query($sql, $params);
        
        return $query;
        
    }

}
/* End of file tags_model.php */
/* Location: ./application/models/tags_model.php */



View (template)
Code:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">&lt;html &gt;
    &lt;head&gt;
        &lt;meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /&gt;
        &lt;title&gt;Manage tags&lt;/title&gt;
    &lt;/head&gt;
    &lt;body&gt;
        &lt;?php echo($content); ?&gt;
    &lt;/body&gt;
&lt;/html&gt;


View (form)
Code:
&lt;?php
if (strlen( validation_errors() ) > 0) {
    echo('<div class="form_error_msg"><p>Please fill in all of the required fields below.</p></div>');
}

if ( isset($updated) ) {
    echo('<div class="form_ok_msg"><p>Tag "'.$Tag.'" updated.</p></div>');
}

if ( isset($inserted) ) {
    echo('<div class="form_ok_msg"><p>Tag "'.$Tag.'" added.</p></div>');
}
?&gt;

&lt;?php

    $data = array(
            'name'        => 'tag_form',
            'class'       => 'default_form'
    );

    echo form_open_multipart( site_url(uri_string()), $data );
?&gt;

    <fieldset>
    
        <legend>Tag Details</legend>
            
            <p>
                &lt;?php
                echo form_label('Tag *', 'Tag');
                $data = array(
                          'name'        => 'Tag',
                          'id'          => 'Tag',
                          'value'       => set_value('Tag', $Tag),
                          'maxlength'   => '255',
                          'size'        => '50'
                );
                echo form_input($data);
                echo form_error('Tag', '<span class="form_error">', '</span>');
                ?&gt;
            </p>

            <p>
                &lt;?php
                    echo form_label('Active', 'Active');
                    $data = array(
                        'name'             => 'Active',
                        'id'              => 'Active',
                        'value'         => '1',
                        'checked'         => set_checkbox('Active', '1', $Active == '1')
                    );
                    echo form_checkbox($data);
                ?&gt;
            </p>

    </fieldset>
    
    &lt;?php
        echo form_submit('submit', 'Save');
    ?&gt;

&lt;?php
    echo form_close();
?&gt;
#18

[eluser]louisl[/eluser]
Controller
Code:
&lt;?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class manage_tags extends CI_Controller {

    public function __construct() {
        
        parent::__construct();
        
        //$this->output->enable_profiler(true);
        
        $this->load->model('tags_model');
        $this->load->library('session');
        $this->load->helper('url');
        $this->load->helper('form');
        $this->load->library('form_validation');
        
        
    }
    
    public function index() {
    
        //removed search function for this example
    
    }

    public function add_tag() {

        $data['Tag'] =                 $this->tags_model->Tag;
        $data['Active'] =             $this->tags_model->Active;
    
        $this->form_validation->set_rules('Tag', 'Tag', 'trim|required|max_length[255]|xss_clean');
        $this->form_validation->set_rules('Active', 'Active', 'trim');
                    
        if ($this->form_validation->run() == FALSE) {
                    
            $admin_template['content'] = $this->load->view('admin/tags/tag_form_view', $data, true);
    
        } else {
        
            $this->tags_model->Tag =             $this->input->post('Tag');
            $this->tags_model->Active =         $this->input->post('Active');
            
            $this->tags_model->TagID =             $this->tags_model->insertTag();
    
            $redirect = '/admin/manage-tags/edit-tag/'.$this->tags_model->TagID;
            
            $this->session->set_flashdata('inserted', 'true');
            
            redirect($redirect, 'refresh');
    
        }
    
        
        $this->load->view('admin_template', $admin_template, false);
    
    }


    public function edit_tag() {
        
        $this->tags_model->TagID = $this->uri->segment(4);
        $this->tags_model->getTag();
        
        $data['Tag'] =                 $this->tags_model->Tag;
        $data['Active'] =             $this->tags_model->Active;
        
        if ($this->session->flashdata('inserted') == 'true') {
            $data['inserted'] = true;
        }
        
        if ($this->session->flashdata('updated') == 'true') {
            $data['updated'] = true;
        }
    
        $this->form_validation->set_rules('Tag', 'Tag', 'trim|required|max_length[255]|xss_clean');
        $this->form_validation->set_rules('Active', 'Active', 'trim');
                    
        if ($this->form_validation->run() == FALSE) {
                    
            $admin_template['content'] = $this->load->view('admin/tags/tag_form_view', $data, true);
    
        } else {
        
            $this->tags_model->Tag =             $this->input->post('Tag');
            $this->tags_model->Active =         $this->input->post('Active');
            
            $this->tags_model->updateTag();
    
            $redirect = '/admin/manage-tags/edit-tag/'.$this->tags_model->TagID;
            
            $this->session->set_flashdata('updated', 'true');
            
            redirect($redirect, 'refresh');
    
        }
    
        $this->load->view('admin_template', $admin_template, false);
    
    }

}

/* End of file manage_tags.php */
/* Location: ./application/controllers/manage_tags.php */
#19

[eluser]TWP Marketing[/eluser]
@osci, I'll try the quoted string and report back.

@toopay, as I said, I don't want to mod my system files.
I'd have to maintain that mod until at least the next version release and perhaps longer.
If I make a new validation library, I'll post it here, but I don't have the time to do that now.

@louis, thanks for the suggestion, your code is essentially the same as mine with the exception of
using session vars to pass flags. I did not post my entire code since the point was to identify
why the set_value() function was not behaving the same after invoking the validation library. As I noted, I now see that there are two versions of set_value(), which behave differently, hence my confusion.

To all, I've got a medium size site that I wrote without using the CI form_validation library. I discovered this problem while testing the validation library on that site and I don't see an easy (quick) solution.
Yes, I can re-write the site to use only the CI validation library and it will work, but the time factor is too large for this job.

Again, thanks to all for your feedback, it was an immense help and I hope to return the favor, here, as opportunity arises.
#20

[eluser]TWP Marketing[/eluser]
[quote author="osci" date="1302528301"]try
Code:
&lt;input type="text" name="name" id="name" value="&lt;?php echo set_value('name', "$name");?&gt;" size="50" /&gt;
[/quote]


@osci, This works UNLESS the form_validation library is instantiated AND a rule is set for the 'name' field. In that case, the set_value() function, defined in form_validation.php is used (see below) and it does not allow the default value to be displayed. NOTE: this is CI 2.0.1

Code:
...
    /**
     * Get the value from a form
     *
     * Permits you to repopulate a form field with the value it was submitted
     * with, or, if that value doesn't exist, with the default
     *
     * @access    public
     * @param    string    the field name
     * @param    string
     * @return    void
     */
    function set_value($field = '', $default = '')
    {
        if ( ! isset($this->_field_data[$field]))
        {
            return $default;
        }

        // If the data is an array output them one at a time.
        //     E.g: form_input('name[]', set_value('name[]');
        if (is_array($this->_field_data[$field]['postdata']))
        {
            return array_shift($this->_field_data[$field]['postdata']);
        }

        return $this->_field_data[$field]['postdata'];
    }
...
It relates to having a validation rule set on that field. Set the rule and the function cannot return the default value, because the field is in the _field_data[] array. Don't set the rule and the field will not be validated... I want a default value to be displayed in the field when the form is first displayed, not an empty field.




Theme © iAndrew 2016 - Forum software by © MyBB