Welcome Guest, Not a member yet? Register   Sign In
Best way to populate an edit form from a database
#11

[eluser]jakeone[/eluser]
Thanks for this Travis, it's a great help.
#12

[eluser]123wesweat[/eluser]
@Travis, could you help me with a preselect select menu

$profile_data->bike returns a no or yes from the db
Code:
<select name="bike" id="bike">
<option value="no" &lt;?php echo preset_select('bike', 'no', FALSE, preset_select('bike', 'no', $profile_data->bike)); ?&gt; >no</option>
<option value="yes" &lt;?php echo preset_select('bike', 'yes', FALSE, preset_select('bike', 'yes', $profile_data->bike)); ?&gt; >yes</option>
</select>

but it doesn't preselect the right value??
#13

[eluser]Nexus Rex[/eluser]
@123wesweat - My example is using the Form Helper calls to create the form fields.

See here:
http://ellislab.com/codeigniter/user-gui...elper.html

Try this:
Code:
<select name="bike" id="bike">
<option value="no" &lt;?php echo preset_select('bike', 'no', $profile_data->bike); ?&gt; >no</option>
<option value="yes" &lt;?php echo preset_select('bike', 'yes', $profile_data->bike); ?&gt; >yes</option>
</select>
#14

[eluser]adamp1[/eluser]
Why not just do this:

Code:
form_dropdown('bike', array('no'=>'no','yes'=>'yes'), $profile_data->bike);
#15

[eluser]Unknown[/eluser]
Here's a very simple solution. I put this in a helper file. In my controller, my "new" function submits the would-be database object "$person" as a null value:

Code:
function new_person()
{
   $data['person'] = null;
   ...
   $this->load->view('person_edit', $data);

}


Whereas it submits the person values from the database if it is the edit request
Code:
function edit_person()
{
   ...
   $data['person'] = $this->person_model->fetch_person( $kPerson );
   ...
   $this->load->view('person_edit', $data);
}

The helper function is this:

Code:
function getValue($object, $item){
    $output = "";
    if($object){
        $output = $object->$item;
    }
    return $output;
}

In the form, then the print out would be something like this:

Code:
...
echo form_input('firstName', getValue($person, 'firstName'));
...

The one catch, which I think could be resolved, is if you type a non-existent property as the "item" parameter for the getValue function. It seems best to have this remain error-producing because you'd want the feedback. If you really wanted to prevent errors from being displayed, you could use:
Code:
$var_list = get_object_vars($object);
$var_keys = array_keys($var_list);
//produces an associative array of object properties
if (in_array($item, $var_keys)){
    $output = $object->$item;
}

I just whipped that one off. It works, but seems inelegant. You could just work with the $var_list array using the larger number of array-manipulation and validation tools available for php to extract the data you want.

You could also add a third function parameter to getValue that allows a default return value
#16

[eluser]satanuzo[/eluser]
Mi metodo

CONTROLLERS

Para cargar la vista

Code:
public function add_ciudad(){

        $data['data_form']          = $this->session->flashdata('data_form');
        $data['insertar_otro']      = $this->session->flashdata('insertar_otro');
        
        $data['opt_region']         = $this->localidad_model->opt_region();
        
        $data['url_navegacion']     = anchor('localidad/list_ciudad/listar/'.$this->session->userdata('offset').'',$this->titulo_nav_2).' > '.'Nueva ciudad';
        $data['url_accion']         = site_url('localidad/insert_ciudad');

        $this->load->view('head');
        $this->load->view('localidad_ciudad_insert', $data);
        $this->load->view('foot');
    }


Para insertar

Code:
public function insert_ciudad(){

        $data_form          = $this->input->post('data_form');
        $insertar_otro      = $this->input->post('insertar_otro');

        $msg = '';
        $this->form_validation->set_rules('data_form[id_region]', 'Regi&oacute;n', 'trim|required|xss_clean');
        $this->form_validation->set_rules('data_form[nombre_ciudad]', 'Nombre', 'trim|required|min_length[3]|xss_clean|callback_ciudad_check');
        

        // run validation
        if ($this->form_validation->run() == FALSE){
            $msg['error'] = 'No se pudo ingresar la ciudad, intentelo nuevamente.<br />'.validation_errors();
            $this->session->set_flashdata('msg', $msg);
            $this->session->set_flashdata('data_form', $data_form);
            $this->session->set_flashdata('insertar_otro', $insertar_otro);
            redirect('localidad/add_ciudad','location', 301);
        }else{
            $id_region = $this->localidad_model->insert_ciudad($data_form);
            $msg['ok'] = 'La ciudad ha sido ingresada.';
            $this->session->set_flashdata('msg', $msg);
            if ($insertar_otro == 'on'){
                $this->session->set_flashdata('insertar_otro', $insertar_otro);
                redirect('localidad/add_ciudad','location', 301);
            }else{
                redirect('localidad/list_ciudad/listar/'.$this->session->userdata('offset').'','location', 301);
            }
        }
    }

VIEWS

Code:
<div class="content">
    <div class='tible'>&lt;?=$url_navegacion;?&gt;</div>
    &lt;?=form_open($url_accion)?&gt;
        <div class="data_form">
            <table>
                <tr>
                    <th width="30%">Regi&oacute;n<span class="requerido">&nbsp;*</span></th>
                    <td>&lt;?=form_dropdown('data_form[id_region]', $opt_region, $data_form['id_region'])?&gt;</td>
                </tr>
                <tr>
                    <th width="30%">Nombre<span class="requerido">&nbsp;*</span></th>
                    <td>&lt;?=form_input('data_form[nombre_ciudad]', $data_form['nombre_ciudad'])?&gt;</td>
                </tr>
                <tr>
                    <th>&nbsp;</th>
                    <td>&lt;?=form_submit('guardar','Guardar')?&gt;&nbsp;&lt;?=form_checkbox('insertar_otro','on', ($insertar_otro == 'on' ? TRUE : FALSE))?&gt;INSERTAR OTRO</td>
                </tr>
            </table>
        </div>
    &lt;?=form_close()?&gt;
    <br />
</div>
#17

[eluser]satanuzo[/eluser]
PARA EDITAR

CONTROLLERS

Code:
public function edit_ciudad($id_ciudad){

        if ($this->session->flashdata('data_form')){
            $data['data_form']          = $this->session->flashdata('data_form');
        }else{
            $data['data_form']          = $this->localidad_model->ciudad_por_id($id_ciudad);
        }
        
        $data['opt_st_ciudad']      = $this->estado;
        $data['id_ciudad']          = $id_ciudad;
        $data['opt_region']         = $this->localidad_model->opt_region();

        $data['url_navegacion']     = anchor('localidad/list_ciudad/listar/'.$this->session->userdata('offset').'',$this->titulo_nav_2).' > '.'Actualizar ciudad';
        $data['url_accion']         = site_url('localidad/update_ciudad/'.$id_ciudad);
        // load view

        $this->load->view('head');
        $this->load->view('localidad_ciudad_edit', $data);
        $this->load->view('foot');
    }

    public function update_ciudad($id_ciudad){
        $this->session->set_userdata('id_ciudad', $id_ciudad);
        $data_form      = $this->input->post('data_form');

        $msg = '';

        $this->form_validation->set_rules('data_form[id_region]', 'Regi&oacute;n', 'trim|required|xss_clean');
        $this->form_validation->set_rules('data_form[nombre_ciudad]', 'Nombre', 'trim|required|min_length[3]|xss_clean|callback_ciudad_check');
        
        $this->form_validation->set_rules('data_form[st_ciudad]', 'Estado', 'trim|required|xss_clean');
        // run validation
        if ($this->form_validation->run() == FALSE){
            $msg['error'] = 'No se pudo actualizar la ciudad, intentelo nuevamente.<br />'.validation_errors();
            $this->session->set_flashdata('msg', $msg);
            $this->session->set_flashdata('data_form', $data_form);
            redirect('localidad/edit_ciudad/'.$id_ciudad,'location', 301);
        }else{
            $num_filas_afectadas = $this->localidad_model->update_ciudad($id_ciudad, $data_form);
            $msg['ok'] = 'La ciudad ha sido actualizada.';
            $this->session->set_flashdata('msg', $msg);
            redirect('localidad/list_ciudad/listar/'.$this->session->userdata('offset').'','location', 301);
        }
    }

VIEW

Code:
<div class="content">
    <div class='tible'>&lt;?=$url_navegacion;?&gt;</div>
    &lt;?=form_open($url_accion)?&gt;
        <div class="data_form">
            <table>
                <tr>
                    <th width="30%">Id</th>
                    <td>&lt;?=form_input('data_form[id_region]', $id_region, 'disabled')?&gt;</td>
                </tr>
                <tr>
                    <th width="30%">Nombre<span class="requerido">&nbsp;*</span></th>
                    <td>&lt;?=form_input('data_form[nombre_region]', $data_form['nombre_region'])?&gt;</td>
                </tr>
                <tr>
                    <th>Estado<span class="requerido">&nbsp;*</span></th>
                    <td>&lt;?=form_dropdown('data_form[st_region]', $opt_st_region, $data_form['st_region'])?&gt;</td>
                </tr>
                <tr>
                    <th>&nbsp;</th>
                    <td>&lt;?=form_submit('actualizar','Actualizar')?&gt;</td>
                </tr>
            </table>
        </div>
    &lt;?=form_close()?&gt;
    <br />
</div>


la idea es que los campos del form se llamen igual a los campos de la db



CREATE TABLE IF NOT EXISTS `tbl_ciudad` (
`id_ciudad` smallint(3) unsigned NOT NULL AUTO_INCREMENT,
`nombre_ciudad` tinytext,
`id_region` tinyint(2) unsigned NOT NULL DEFAULT '0',
`st_ciudad` enum('activo','inactivo') NOT NULL DEFAULT 'activo',
PRIMARY KEY (`id_ciudad`),
KEY `id_region` (`id_region`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 ROW_FORMAT=COMPACT AUTO_INCREMENT=349 ;

en el formulario
&lt;input type="test" name="data_form[nombre_ciudad]"

MODELS

Code:
function insert_ciudad($data_form)
    {
        $this-&gt;db->insert('tbl_ciudad', $data_form);
        return $this->db->insert_id();
    }

    function update_ciudad($id_ciudad, $data_form)
    {
        $this->db->update('tbl_ciudad', $data_form, array('id_ciudad' => $id_ciudad));
        return $this->db->affected_rows();
    }

    function ciudad_por_id($id_ciudad)
    {
        $sql="
            SELECT
                    tbl_ciudad.id_ciudad,
                    tbl_ciudad.nombre_ciudad,
                    tbl_region.nombre_region,
                    tbl_region.id_region,
                    tbl_ciudad.st_ciudad

            FROM    tbl_ciudad, tbl_region
            WHERE   tbl_ciudad.id_ciudad = $id_ciudad
            AND     tbl_ciudad.id_region = tbl_region.id_region";
        $result = $this->db->query($sql);
        return $result->row_array();
    }
#18

[eluser]cyberjunkie[/eluser]
Not sure if this is what you're looking for.. I use the following for the input value.

Code:
(set_value('some_value')) ? set_value('some_value') : $row->some_value

(You might want to add an isset to that)

In the Model class I'm using

Code:
return $query->row();

and in Controller sending it to my view as $row

Code:
$data['row'] = $this->My_model->populate_form();
$this->load->view('my_view', $data);

It's a very straight-forward technique.




Theme © iAndrew 2016 - Forum software by © MyBB