Welcome Guest, Not a member yet? Register   Sign In
form_validation on forms that handle add+edit
#1

[eluser]chrisco23[/eluser]
Hi all,

I've been rebuilding my largest CI app.

In the old (currently live, working) version, I have a number of forms that serve the dual purpose of adding and editing records.

In my view files, I have code like the following:

Code:
<input type="text" name="username" value="<?php echo
isset($this->validation->name) ? $this->validation->name : NULL?>" />

In the case of "Edit" functionality, I would assign, for example, some existing database value to $this->validation->name before displaying my form. I was never very happy with the way the code read because I have a lot of lines of code with "validation" in the syntax before any validation is taking place.

With the new form_validation class though, it seems even more awkward due to the extent of abstraction.

How are people going about this? I can think of a few ways but I don't like any of them:

1. When reading fields from the db (edit mode), assign them to $_POST before calling the view file. The HTML looks like:
Code:
<input type="text" name="myVar" value="<?php echo set_value('myVar',
$_POST['myVar']);?>" />
2. When reading fields from the db (edit mode), assign each to $this->myVar in my controller, then the view file HTML looks like:
Code:
<input type="text" name="myVar" value="<?php echo set_value('myVar', $this->myVar)?>" />
3. When reading fields from the db (edit mode), assign them directly to $this->_field_data[fieldname]['postdata']. This is kinda similar to #1 but it's ugly to access "private" vars in this way.

Maybe it's from being up all night then running into this new library. Anybody see a better way?

I'm thinking Option #2 is probably the best I can come up with right now but even that is a pita because I have many optional fields and I have to either set a lot of fields to '' (empty quotes) to avoid error, or put a bunch of isset()'s in my view file...

Somebody see a cleaner way?


Thanks,
Chris
#2

[eluser]Huan[/eluser]
Hi. This is the way I'm using, and I find it better than other ways I've tried (using form_validation in CI 1.7.0):

In my Controller:

Code:
function add_or_edit_var() {
  $this->load->library('form_validation');
  // validation rules here

  $mode = $somevalue; // add or edit here
  if ($mode == 'add') {
    $data['myVar'] = '';
  } else {
    $q = $this->db->query('SELECT myvar FROM tablename LIMIT 1');
    $data['myVar'] = $q->row()->myvar;
  }

  if (count($_POST)==0) return $data; // Do nothing if we have no $_POST value

  if ($this->form_validation->run() === false) {
    // return and show error
    return $data;
  }

  // if no error : save it
  if ($mode == 'add') {
    // add to database
  } else {
    // update database record
  }

  redirect('somewhere'); // after successfully updating DB
}

In my View:

Code:
<input type="text" name="myVar" value="<?php echo set_value('myVar', $myVar) ?>" />

So $myVar always has a default value no matter I'm doing "ADD" or "EDIT"

The same can be applied to other types of form input fields:

Code:
<input type="radio" name="name" value="value" <?=set_radio('name', 'value', $myVar=='value')?> />

<select name="name">
<option value="value1" &lt;?=set_select('name', 'value1', $myVar == 'value1')?&gt;></option>
<option value="value2" &lt;?=set_select('name', 'value2', $myVar == 'value2')?&gt;></option>
</select>

and so on
#3

[eluser]Rob Stefanussen[/eluser]
Hi chrisco, I just upgraded to 1.7.0. I had the exact same problem as you. My coworkers and I have been using CI for a long time and we were shocked that a bit of a hack (the method you were using in <= 1.6.3) was required to edit database records with the validation class.

After upgrading and also finding out that editing was even MORE awkward, I jumped back onto these boards because I was sure that the new Validation class had finally addressed this issue. I supposed I'll have to pick one of the hacks you suggest.

I do appreciate CodeIgniter and what it has done for my coding, and I hate to see it crash and burn like this on something as fundamental as CRUD. Isn't that like PHP 101??
#4

[eluser]JayTee[/eluser]
[Edit: I was wrong - the set_value property works just fine for an "edit" type of form - see below]

I gotta agree with you, @Rob Stefanussen! There were wiki entries that suggested changing the validation class so that you could assign a 'default' value for a given field. Then your form would display the data in the following order of precedence:
1. the data the person posted
2. the default value
3. nothing

It was a good 'hack' to the validation class because you could avoid writing code like this:
Code:
&lt;?PHP echo form_input('lastn',$this->validation->lastn ? $this->validation->lastn : $data->last_name,'class="inputText"'); ?&gt;
Kind of tough to look at when you're making an edit form!

I was also excited to see the new validation class - and simultaneously disappointed that this particular issue wasn't addressed.

I love the framework nonetheless - the validation class on forms for editing will still remain a thorn in my side for the time being, I guess Sad

Edit (please ignore last couple of sentences above):
I set up a test as follows:
controller(home.php):
Code:
function test() {
    $this->load->library('form_validation');
    $this->form_validation->set_rules('test1','Test Field','required|alpha');
    $data = array(
      'dat' => 'Test Data' //could come from DB
    );
    if ($this->form_validation->run()) {
      echo 'success';
    } else {
      $this->load->view('form_test',$data);
    }
  }
View (form_test.php):
Code:
&lt;form action='/home/test' method="POST"&gt;
  &lt;?= form_error('test1') ?&gt;
  &lt;input type="text" name="test1" value="&lt;?= set_value('test1',$dat) ?&gt;"&gt;
  &lt;input type="submit"&gt;
&lt;/form&gt;
When the form first loads, the 'Test Data' text is used. When I submit the form with incorrect data (in this case, some numbers), the field is populated with whatever I put in there when it comes back.

So I jumped the gun (sorry). The set_value function does exactly what I need for creating 'edit' types of forms.
#5

[eluser]chrisco23[/eluser]
Thanks folks for the feedback.

Huan I like what you have and it looks pretty analogous to my option #2 (except you have regular page variables instead of class properties, maybe a little less typing for your version, but similar otherwise). I'll give it a try.


Chris
#6

[eluser]treadsoftley[/eluser]
I have just spent no small amount of time translating a large form to the new validation .... why? Don't ask me ... I could perceive no real benefit at all in fact it was a monumental waste of time and indeed the validation which I had working fine now just doesn't. I only did it because it is a new site and I thought I would build its foundations on 1.7.

Validation has never been wonderful and now it seems less so.

Can someone explain exactly what the benefits of 'form_validation' are meant to be?
#7

[eluser]Unknown[/eluser]
@treadsoftley: it's the same mine opinion. I have a large application which I decided to convert from 1.6.3 to 1.7.1, because of the new 'form_validation' class. But reading on the forum and trying to change the code, I've seen that the new validation class is not handling in a smart way the classic add/edit pattern.
I mean: for what reason do I have to write such a code:
&lt;?= form_input('input_name',set_value('input_name',$default[input_name'])); ?&gt;
why "set_value" doesn't handle the obvious "default value" problem? why there is not a way _in the controller_ to set that default value, but we need to go to the view (which shoud be as simple and dumb as possible in MVC?)

Rant: my biggest concern is about the fact that nobody of CI official development team is giving any hint or reply to such new philosopy adopted with the new form_validation. So my doubt is: what do I have to think about CI? is it still a living project? Or do we need to think in advance and begin now to search an alternative PHP framework for our applications?
#8

[eluser]coldfire82[/eluser]
any solutions or CI Forum thread where its solution is discussed?
#9

[eluser]gtlitc[/eluser]
I am really pulling my hair out. What is the best way to achieve ADD+EDIT forms with CI?
Here is a slimed down example of what I am doing in my UPDATE method:
Code:
if ($this->form_validation->run() == FALSE)
        {
            // populate form fields
            $event                  = $this->event_model->get_by_id($id)->row();

            // set the form data
            $data['f_title']          = $event->title;
            $data['f_description']    = $event->description;
            $data['f_homepage']       = $event->homepage;

            // load view
            $this->load->view('admin/event/event_form_view', $data);
        }
        else
        {
            $event = array('title' => $this->input->post('title'),
                            'description' => $this->input->post('description'),
                            'homepage' => $this->input->post('homepage'));
            $this->event_model->update($id,$event);

            // set user message
            $data['message'] = '<p class="success">Successfully updated</p>';


            // load view
            $this->load->view('admin/event/event_view', $data);
        }

And then in my view I use:
Code:
&lt;input type="text" name="title" value="&lt;?= set_value('title', $f_title); ?&gt;" /&gt;
&lt;textarea name="description"&gt;&lt;?= set_value('description', $f_description); ?&gt;&lt;/textarea&gt;
&lt;input type="checkbox" name="homepage" value="1" &lt;?php echo set_checkbox('homepage', $f_homepage); ?&gt; /&gt;

set_value() is working fine. The problem I am having is with set_checkbox() not working as expected?
I have been all round trying to figure this one out and am sure that someone will have a better way of doing things?
Or will spot my mistake?
#10

[eluser]coffey[/eluser]
I haven't got a checkbox example to hand but this is what my view looks for radios

Code:
echo form_label('Publish Setting','publish');
    $radio="publish";
    $$radio=(isset($$radio))?$$radio:1;
    echo 'Yes-'.form_radio($radio, 1, ($$radio==1)?TRUE:FALSE);
    echo ' No (draft)- '.form_radio($radio, 2, ($$radio==2)?TRUE:FALSE);

ah just found a checkbox....

Code:
$box="checkbox";
echo form_checkbox($box, "1", set_value($box, (isset($$box)?$$box:0)));

With both examples, as long as the page is receiving $publish and $checkbox they should work. Hope this helps. Above examples good for long lists of checkboxes as they can be placed in a loop and populated from an array.....

Code:
$boxes = array('box1','box2','box3');

foreach ($boxes as $box){
    echo form_checkbox($box, "1", set_value($box, (isset($$box)?$$box:0)));
}

.....that sort of thing .... you could even add another dimension to the array that could carry the initial setting etc.




Theme © iAndrew 2016 - Forum software by © MyBB