Welcome Guest, Not a member yet? Register   Sign In
update from best practice
#1

[eluser]dmitri1[/eluser]
Hi,

I'm codeigniter newbie. I'm trying to create update form. It works like this (standard): then user visits page it shows values from database, then user submits form it should show values entered by user + error message. As far as i understand from tutorial i should use form helper for this, and write something like this in my view:
Code:
<input type="text" name="name" value="<?php echo set_value('name', isset($data['name'])?$data['name']:'') ?>">

$data['name'] - is value read from db. I need to use construction
Code:
isset($data['name'])?$data['name']:''
because if form is rendered after user submit, then we don't read data from database and variable $data is not defined. On my mind it is annoying to write something like this each time.
So my question is: is there better solution for views that contain update/edit forms? I'm sure there should be nice solution, but unfortunately all tutorials and examples i've found were about add/create forms. What good/standard practice for this?
--
Thanks, Dmitri
#2

[eluser]PhilTem[/eluser]
That's a short form of how I usually do this stuff:

In your controller:
Code:
function edit($id)
{
  $data['details'] = $this->some_model->get_details_by_id($id);
  
  $this->load->view('edit', $data);
}
Let's assume method get_details_by_id returns a single row from the database as an array.


The view contains something like this for every item editable:
Code:
$data = array(
    'name'  => 'input_name',
    'value' => set_value('input_name', $details['input_name']),
    'class' => 'text'
  );

echo form_input($data);

assuming we have a column input_name within our model/table. The first parameter to set_value refers to the input-field's name, the second to a default value.
Of course, if there is no field within the table called input_name it will create ugly errors, but I'm always checking the data returned from the model to be valid before I output any view. Just for simplification I haven't put it into the code Wink

If the user submits the form and has any errors on then the updated data will be displayed. Once he submits the form and it's validated successfully, then I'm usually redirecting to another page and show a nice flash-message saying

Code:
Every data updated

Don't know if this is global best practice but it's at least my best practice ;D
#3

[eluser]dmitri1[/eluser]
Thank you for your answer. But my question was about other thing. I try to explain better. Controller code looks like this:

Code:
function edit()
{
    // if form submitted
    if($this->input->post('submit'))
    {
        // validate form
        if ($this->form_validation->run() == FALSE)
        {
            // here we don't read from db and variable 'data' is not defined in view
            $this->load->view('controller/edit');
        }
        else
        {
            // form validated successfully
            // save data
            $this->model->saveFromPost($this->input);
            // redirect to success page
            redirect('/controller/editsuccess');
        }
    }
    else
    {
        // read data from db and show to user
        $data = $this->model->getData();
        // variable 'data' defined in view
        $this->load->view('controller/edit', array('data'=>$data));
    }
}

So in case if validation fails variable 'data' that is used to set values from db is not defined in view.
Due this it is necessary to write code like:
Code:
set_value('name', isset($data['name'])?$data['name']:'')
in view. Is there there way to avoid it?
#4

[eluser]dmitri1[/eluser]
Noboy created edit action in CI?
#5

[eluser]PhilTem[/eluser]
I think I now got your point (hopefully). Try to run the form-validation within the same if-branch as you do the check for post-values like so

Code:
function edit()
{
    // if form submitted and validated
    if( $this->input->post('submit') && ( $this->form_validation->run() == TRUE ) )
    {
        // save data
        $this->model->saveFromPost($this->input);
        // redirect to success page
        redirect('/controller/editsuccess');
    }
    else
    {
        // read data from db and show to user
        $data = $this->model->getData();
        // variable 'data' defined in view
        $this->load->view('controller/edit', array('data'=>$data));
    }
}

This way you will always have variable $data within your edit-view no matter if the form was submitted or not. If this didn't solve your question maybe I'll have to read your posts more precisely Tongue
#6

[eluser]aquary[/eluser]
PhilTem, that'd be the same for him since he still have to put a code that annoy him in the view:

Code:
isset($data['name'])?$data['name']:''

From the topic, I'm assuming you are trying to use one form for both editting and creating. Although a little bit different, I've been using the same method and didn't found it to be that much annoying, compare to having to maintain 2 copy of form for editting and creating....

However, I'd suggest you to create a dummy $data before sending to the edit view... but this will add some code to your controller or model any way.

Code:
// Controller
function save($id=NULL){
   // assume this return a row of data from DB
   if(!empty($id))
      $data['data']=$this->the_model->get_data($id);
   else{
      // do whatever to get an empty data with the same structure
      // In this case, do a lazy way right here.
      $data['data']['input_name']='';
      $data['data']['input_name2']='';
      // or modify your get_data() function to return a structure of the data. in that case, you could even remove thw whole IF, and use only the get_data() row.
   }
   if($this->input->post() && $this->form_validation->run()){
      // do save command
      redirect('somewhere');
   }
   $this->load->view('edit', $data);
}

This way, since the data is always exists, you don't have to check if the data exist or not. However, IMO, there might be more annoyance since you'll have to keep track of the data structure in the controller as well, instead of focusing on one view file, and put the checking while you are adding fields...

btw, you could use empty() instead of isset().
Code:
<input type="text" name="name" value="<?php echo set_value('name', empty($data)?'':$data['name']); ?>">
#7

[eluser]dmitri1[/eluser]
Thank you for your answers. I think best solution here is to fork form helper. And make it checking some conventional variable lets say $formData. $formData is associative array with values for form fields. Similiar as it is done in cakephp. But it looks there is no way to get access to view variables from helper function.




Theme © iAndrew 2016 - Forum software by © MyBB