Welcome Guest, Not a member yet? Register   Sign In
Best practice for templates for updating an item
#1

[eluser]mortenfrisi[/eluser]
I'm building a site where a user can add an item, which consist of title (item_title), description (item_desc) and size (item_size).

The user should be able to update this information, but I have a hard time figuring out what to do when the user update an item that doesn't go through the validation.

I have made the script below, but it's there an easier way?

Code:
// check if there is an validation error (it will output an set_value
if (   set_value('title')  
        OR set_value('description')
OR set_value('size')
    ){
            $value_title = set_value('title');
            $value_desc = set_value('description');
     $value_size = set_value('size');
        }
else {
// there is no validation error, so we show what we got from the database
            $value_title = $db_result[0]->title;  
            $value_description = $db_result[0]->description;
     $value_size = $db_result[0]->size;
        }
        
// creating the array for the form        
$title = array(
'name' => 'title',
    'value' => $value_title,    
);

$description = array(
'name' => 'description',
    'value' => $value_desc,    
);

$size = array(
'name' => 'size',
    'value' => $value_size,    
);

<!-- show the form -->
<p>&lt;?php echo form_label('Description', $description['id']); ?&gt;</p>
<p>&lt;?php echo form_textarea( $description); ?&gt;</p>
<div class="error">&lt;?php echo form_error( $description['name']); ?&gt;&lt;?php echo isset($errors[$description['name']])?$errors[$description['name']]:''; ?&gt;</div>

&lt;!-- etc --&gt;

Maybe there is a better way?
#2

[eluser]PhilTem[/eluser]
That's much easier

view (assume $item holds the data for the item to edit from the database (as an object))
Code:
$input = array(
    'name' => 'your_name',
    'value' => set_value('your_name', $item->your_name),
    'class' => 'text'
);
echo form_input($input);
echo form_error('your_name', 'pre_wrapper', 'post_wrapper');

You can use that code for each form-input you want. Read through the form-helper to all extent Wink


controller method 'edit'
Code:
function edit($id = FALSE)
{
    if ( ! $id OR ! $this->your_model->valid_id($id) )
    {
        // Do something when the provided ID isn't valid (wrong format, not in DB, ...)
    }
    
    if ( $this->input->post('smt_submit') )
    {
        if ( $this->form_validation->run() == TRUE )
        {
            // Do the update logic
            // and maybe redirect to list-page
        }
        // Maybe set some message here that the form wasn't completed without errors
    }
    
    $data['item'] = $this->your_model->get($id);
    
    $this->load->view('path/to/edit/view', $data);
}
#3

[eluser]mortenfrisi[/eluser]
Cheers, that saved me a lot of time ;-)
#4

[eluser]PhilTem[/eluser]
I thought so, that's why I replied/shared it Wink




Theme © iAndrew 2016 - Forum software by © MyBB