CodeIgniter Forums

Full Version: Best way to populate an edit form from a database
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Pages: 1 2

El Forum

[eluser]dmorin[/eluser]
This may seem basic, but what is the best way to initially populate an 'edit' type from with values from the database?

Passing them in as a second parameter to set_value seems like one approach, but if you use the same view for both create and edit, you have to do checks and it gets really ugly. It's even worse for set_select function.

In the old validation library, I would have just forced the values into the validation library using $this->validation->field_name = value, but the new one stores these in an array and it seems really hacky to force the values into there. What is everyone doing for this?

El Forum

[eluser]cwt137[/eluser]
I've had this issue and here is my solution. You can still use the same view and still use set_value() for both editing and for creating new information. For the create page, you create a null variable and set_value() will put a blank value. I don't mess around with the set_select() function because on the edit page it is hard to select the entry from the database and have the re-population from form validation work. So, I use a combination of both the form_dropdown() and the set_value() functions. Here below is a snippet from a controller to demonstrate my point.
Code:
function create() {
  $data = array('title' => 'Add Page', 'form' => NULL);
  $this->load->view('form', $data);
}

function edit($id) {
  $sql  = 'SELECT id, first_name, last_name, shirt_size ';
  $sql .= '  FROM some_tbl WHERE id = ?';
  $sql_params = array($id);
  $query = $this->db->query($sql, $sql_params);
  $form = $query->row_array();

  $data = array('title' => 'Edit Page', 'form' => $form);
  $this->load->view('form', $data);
}

The view would look something like this:
Code:
<html>
<head>
<title><?php echo $title; ?></title>
</head>
<body>
<h1>&lt;?php echo $title; ?&gt;</h1>
<br />
&lt;form action="controler_name/save" method="post"&gt;
  First Name:
  &lt;input type="text" name="first_name" value="&lt;?php set_value('first_name', $form['first_name']); ?&gt;" /&gt;
  <br />
  Last Name:
  &lt;input type="text" name="last_name"  value="&lt;?php set_value('last_name', $form['last_name']); ?&gt;" /&gt;
  <br />
  Shirt Size:
  &lt;?php
    
    $options = array(
                  ''       => 'Select Shirt',
                  'small'  => 'Small Shirt',
                  'med'    => 'Medium Shirt',
                  'large'  => 'Large Shirt',
                  'xlarge' => 'Extra Large Shirt',
                );
        
    echo form_dropdown('shirt_size', $options, set_value('shirt_size', $form['shirt_size']));
    
     ?&gt;
  &lt;input type="submit" name="submit" value="Submit" /&gt;
  &lt;input type="hidden" name="id" value="&lt;?php set_value('id', $form['id']); ?&gt;" /&gt;
&lt;/form&gt;
&lt;/body&gt;
&lt;/html&gt;

I still have problems with check boxes and radio boxes. I still don't know the best way to have the right things pre-selected from the database and have the right stuff re-populated when the form validation comes back.

El Forum

[eluser]dmorin[/eluser]
Thanks for replying. That's a lot like my solution. The issue I see with yours is if you have php notices turned on, you're going to get a lot of errors because you're trying to reference array indexes that doesn't exist in the case of the new form. The work around is to do something like

Code:
&lt;?php set_value('first_name', (isset($form['first_name'])) ? $form['first_name'] : ''); ?&gt;

This starts to get really ugly though. It seems like we need some kind of validation defaults function that we can pass in an array and it can loop through an assign each field a "default" value.

El Forum

[eluser]Unknown[/eluser]
What I've done to solve this problem is use a method called getRecord() in my models. It will always return a "record" array and in the case of a new record, will simply populate empty field values. No complaints when the views are rendered.

The set_value() method of the form helper also appears to gracefully handle the problem of attempting to read/print unpopulated variables on your form. You just need to pass a default value to use if the variable you're attempting to access is not defined. It seems to work a lot like the sql function coalesce().

El Forum

[eluser]JulianM[/eluser]
Yes, set_value works nice for me, too.

You can pass the default value if you want to avoid to receive an error if the passed variable do not exist, or you can call it using @set_value, however I prefer the first option.

Good luck

Julian


[quote author="benajnim" date="1241211692"]What I've done to solve this problem is use a method called getRecord() in my models. It will always return a "record" array and in the case of a new record, will simply populate empty field values. No complaints when the views are rendered.

The set_value() method of the form helper also appears to gracefully handle the problem of attempting to read/print unpopulated variables on your form. You just need to pass a default value to use if the variable you're attempting to access is not defined. It seems to work a lot like the sql function coalesce().[/quote]

El Forum

[eluser]devbro[/eluser]
I did something similar to what I want to do.
I have my view files as thought they are ready for an "update" state. I end up with two situations:

1. Create: I simply populate and I happy with the rest, I simply make sure that something (URL or hidden field) says that it is a create.

2. update: before doing anything I find the data that I want to update. I make sure that form_validation or any other validation object is NOT loaded. Then I load all my data into $_POST. set_value takes care of the rest for me.

on the revisit i do a :
if($_POST)
{
$this->load->library('form_validation');
...
...

}

It is a bit hacky but is really easy to implement. let me know what you think of this way.

El Forum

[eluser]Thorpe Obazee[/eluser]
Code:
<select id="calendar_id" name="calendar_id" class="select small-column">
    &lt;?php foreach ($calendars as $calendar):?&gt;
    <option value="&lt;?php echo $calendar->calendars_id;?&gt;" &lt;?php echo ($calendar->calendars_id == $event->calendars_id) ? set_select('calendar_id', $event->calendars_id, TRUE) : set_select('calendar_id', $event->calendars_id); ?&gt; >&lt;?php echo $calendar->calendars_name;?&gt;</option>
    &lt;?php endforeach;?&gt;
</select>

This is what I do with simple selects. The logic works on check boxes and radio buttons.

El Forum

[eluser]Nexus Rex[/eluser]
[quote author="PDP" date="1243232347"]
Code:
<select id="calendar_id" name="calendar_id" class="select small-column">
    &lt;?php foreach ($calendars as $calendar):?&gt;
    <option value="&lt;?php echo $calendar->calendars_id;?&gt;" &lt;?php echo ($calendar->calendars_id == $event->calendars_id) ? set_select('calendar_id', $event->calendars_id, TRUE) : set_select('calendar_id', $event->calendars_id); ?&gt; >&lt;?php echo $calendar->calendars_name;?&gt;</option>
    &lt;?php endforeach;?&gt;
</select>

This is what I do with simple selects. The logic works on check boxes and radio buttons.[/quote]

Brilliant!

I used your method for two radio boxes:
Code:
&lt;?php echo form_radio('active', '1', FALSE, (1 == $member->active) ? set_radio('active', $member->active, TRUE) : set_radio('active', '1')); ?&gt; <label for="active">Active</label>
&lt;?php echo form_radio('active', '0', FALSE, (0 == $member->active) ? set_radio('active', $member->active, TRUE) : set_radio('active', '0')); ?&gt; <label for="active">Inactive</label>

El Forum

[eluser]JulianM[/eluser]
Thanks, I think this is a good approach, but still thinking that this code could be placed in a helper to avoid duplicating the logic each time.

Code:
(1 == $member->active) ? set_radio('active', $member->active, TRUE) : set_radio('active', '1'))

What do you think?

Julian


[quote author="Nexus Rex" date="1262761831"]
Brilliant!

I used your method for two radio boxes:
Code:
&lt;?php echo form_radio('active', '1', FALSE, (1 == $member->active) ? set_radio('active', $member->active, TRUE) : set_radio('active', '1')); ?&gt; <label for="active">Active</label>
&lt;?php echo form_radio('active', '0', FALSE, (0 == $member->active) ? set_radio('active', $member->active, TRUE) : set_radio('active', '0')); ?&gt; <label for="active">Inactive</label>
[/quote]

El Forum

[eluser]Nexus Rex[/eluser]
[quote author="JulianM" date="1262763235"]Thanks, I think this is a good approach, but still thinking that this code could be placed in a helper to avoid duplicating the logic each time.

Code:
(1 == $member->active) ? set_radio('active', $member->active, TRUE) : set_radio('active', '1'))

What do you think?

Julian
[/quote]

Great idea — and done!

Instructions for benefit of any who would like to use this helper to easily preset select boxes, checkbox fields, and radio buttons with values from database (or elsewhere) with one simple call while retaining the ability of the form to remember submitted values from the POST.

1. Create a new file called "my_form_helper.php" in your /system/application/helpers/ directory.

2. Copy and paste this code into your new helper file:
Code:
&lt;?php  if (!defined('BASEPATH')) exit('No direct script access allowed');
/**
* Code Igniter
*
* An open source application development framework for PHP 4.3.2 or newer
*
* @package        CodeIgniter
* @author        Rick Ellis
* @copyright    Copyright (c) 2006, pMachine, Inc.
* @license        http://www.codeignitor.com/user_guide/license.html
* @link        http://www.codeigniter.com
* @since        Version 1.0
* @filesource
*/

// ------------------------------------------------------------------------

/**
* Code Igniter My Form Helpers
*
* @package        CodeIgniter
* @subpackage    Helpers
* @category    Helpers
* @author        Travis Cable aka Nexus Rex
* @link        
*/

// ------------------------------------------------------------------------

// ------------------------------------------------------------------------

// ------------------------------------------------------------------------

/**
* Preset Select
*
* Let's you preset the selected value of a checkbox field via info from a database
* and allows info the in the POST array to override.
*
* @access    public
* @param    string
* @param    string
* @param    string
* @return    string
*/
if ( ! function_exists('preset_select'))
{
    function preset_select($field = '', $value = '', $preset_value = '')
    {
        if ($value == $preset_value)
        {
            return set_select($field, $preset_value, TRUE);
        }
        else
        {
            return set_select($field, $value);
        }
    }
}

// ------------------------------------------------------------------------

/**
* Preset Checkbox
*
* Let's you preset the selected value of a checkbox field via info from a database
* and allows info the in the POST array to override.
*
* @access    public
* @param    string
* @param    string
* @param    string
* @return    string
*/
if ( ! function_exists('preset_checkbox'))
{
    function preset_checkbox($field = '', $value = '', $preset_value = '')
    {
        if ($value == $preset_value)
        {
            return set_checkbox($field, $preset_value, TRUE);
        }
        else
        {
            return set_checkbox($field, $value);
        }
    }
}

// ------------------------------------------------------------------------

/**
* Preset Radio
*
* Let's you preset the selected value of a radio field via info from a database
* and allows info the in the POST array to override.
* If Form Validation is active it retrieves the info from the validation class
*
* @access    public
* @param    string
* @param    string
* @param    string
* @return    string
*/
if ( ! function_exists('preset_radio'))
{
    function preset_radio($field = '', $value = '', $preset_value = '')
    {
        if ($value == $preset_value)
        {
            return set_radio($field, $preset_value, TRUE);
        }
        else
        {
            return set_radio($field, $value);
        }
    }
}

?&gt;


3. Load the new helper in your Controller:
Code:
$this->load->helper('my_form');


4. Call the new preset_radio($field_name, $field_value, $preset_value) function in your radio buttons instead of set_radio():
Code:
&lt;?php echo form_radio('active', '1', FALSE, preset_radio('active', '1', $member->active)); ?&gt; <label for="active">Active</label>
&lt;?php echo form_radio('active', '0', FALSE, preset_radio('active', '0', $member->active)); ?&gt; <label for="active">Inactive</label>


The helper includes functions for select boxes and checkboxes as well: preset_select() and preset_checkbox()
Pages: 1 2