Welcome Guest, Not a member yet? Register   Sign In
example add / edit / delete app
#1

[eluser]Future Webs[/eluser]
Hi Folks,

Been toying with CI for a few weeks and getting on fairly well. As an of how all the form side of things works I thought it best to build an example to test each option. As you may have guessed Ive come across a few issues.

Ive had a good look though the user guide, screen casts, example aps and the forums and although there are lots of good examples nothing quite covered where I came unstuck.

Heres my demo and an explanation of the issues i found.

Controller

Code:
<?php

class Example extends Controller {

    function Example()
    {
        parent::Controller();    
        $this->load->model('Mdl_example');
        $this->load->library('form_validation');
        $this->load->helper('form');
    }
    
    function index()
    {
        $data['rs_examples'] = $this->Mdl_example->get_list() ;    
        $this->load->view('example_list', $data);
    }

    function form()
    {
        $example_id        = $this->uri->segment(3);

        $data['drop_menu_example_cats'] = $this->Mdl_example->drop_menu_example_cats() ;

        if ($example_id != "") { // edit so populate the form from database
        $data['rs_example']                = $this->Mdl_example->get_example_by_id($example_id) ;
        }
        
        if(isset($_POST) && count($_POST) > 0)    { // check if form has been submitted

        $this->form_validation->set_rules('example_text', 'Text Field', 'required');
        $this->form_validation->set_rules('example_radio', 'Radio Button', '');
        $this->form_validation->set_rules('example_checkbox', 'Checkbox', '');
        $this->form_validation->set_rules('example_dropmenu', 'Drop Menu', '');
        
        $this->form_validation->set_error_delimiters('<div class="Errors">', '</div>');
        
            if ($this->form_validation->run() == FALSE) // check if validation failed
            {
                // failed validation, back to form
            }
            else
            {
                // grab post info and add it to the database
                $form = array(
                        'example_text' =>             $this->input->post('example_text'),
                        'example_radio' =>            $this->input->post('example_radio'),
                        'example_checkbox' =>         $this->input->post('example_checkbox'),
                        'example_dropmenu' =>       $this->input->post('example_dropmenu')
                    );
                // set some form fields dependaing on insert or update
                if ($example_id == '' ) { // Insert
                    $form['example_date_added'] =        date("Y-m-d H:i:s") ;
                } else { // edit
                    $form['example_date_updated'] =        date("Y-m-d H:i:s") ;
                }
        
                        if ($example_id != '') {
                            // id passed so update
                            $this->db->where('example_id', $example_id);
                            $this->db->update('examples', $form);
                        } else {
                            // no id so insert
                            $this->db->insert('examples', $form);
                        }
    
                        // all went ok back to list
                        redirect('/example');                              
            
            } // check if validation failed
            
        } // check if form has been submitted

            // Not submitted load an empty view
            $this->load->view('example_form', $data);    
    }

    function delete_example()
    {
        $example_id        = $this->uri->segment(3);
        $this->db->where("example_id", $example_id);
        $this->db->delete("examples");
        redirect('example');    
    }
    
    
}

/* End of file example.php */
/* Location: ./system/application/controllers/example.php */

Continued in next post ....
#2

[eluser]Future Webs[/eluser]
Model

Code:
&lt;?php
class Mdl_example extends Model {

// ASSIGN SOME VARS TO USE

    var $example_id ;
    var $example_text ;
    var $example_radio ;
    var $example_checkbox ;
    var $example_dropmenu ;
    var $example_date_added ;
    var $example_date_updated ;


function Mdl_example()
    {
        // Call the Model constructor
        parent::Model();
    }
    
    function get_list()
    {
        $query = $this->db->get('examples');
        return $query->result();
    }
    function get_example_by_id($id='0')
    {
        $this->db->where('example_id', $id);
        $query = $this->db->get('examples');
        return $query->row();
    }
    function drop_menu_example_cats()
    {
        $this->db->select('example_cat_id,example_cat_name');
          $this->db->order_by('example_cat_id', 'ASC');
      $query=$this->db->get('example_cats');
      $result = $query->result();
      $drop_menu_example_cats = array();
          $options[''] = 'Select A Cat' ;
      foreach($result as $item){
        $options[$item->example_cat_id] = $item->example_cat_name;
      }
      return $options;
    }

    // FORM STUFF
    
    // CREATE OR UPDATE
    function save() {

        $dbArray['example_id']                =    $this->example_id ;
        $dbArray['example_text']            =    $this->example_text ;
        $dbArray['example_radio']            =    $this->example_radio ;
        $dbArray['example_checkbox']        =    $this->example_checkbox ;
        $dbArray['example_dropmenu']        =    $this->example_dropmenu ;
        $dbArray['example_date_added']        =    $this->example_date_added ;
        $dbArray['example_date_updated']    =    $this->example_date_updated ;
        
        if ($this->example_id != '') {
            $this->db->where("example_id", $this->example_id);
            $this->db->update("examples", $dbArray);
        }
        else {
            $this->db->insert("examples", $dbArray);
        }

    }
    // DELETE
    function delete_example() {

        $this->db->where("example_id", $this->example_id);
        $this->db->delete("examples");
    }

}
?&gt;

View - Form

Code:
&lt;?php

        echo anchor('/example/' , 'Back To List');

        echo form_open_multipart('/example/form/'.$this->uri->segment(3) );

        echo form_label('Text Field', 'example_text' ).'&nbsp;&nbsp;';
        $data = array(
                  'name'        => 'example_text',
                  'id'          => 'example_text',
                  'value'       => set_value('example_text', (isset($rs_example->example_text)) ? $rs_example->example_text : ''),
                  'maxlength'   => '25',
                  'size'        => '25',
                  'style'       => ''
                );
        echo form_input($data).'<br />' ;
        echo form_error('example_text').'<br /> '  ;
        
        echo form_label('Radio', 'example_radio' ).'&nbsp;&nbsp;';
        $data = array(
                  'name'        => 'example_radio',
                  'id'          => 'example_radio',
                  'value'       => '1',
                  'checked'       => TRUE,
                  'style'       => ''
                );
        echo form_radio($data, 0, set_value('example_radio', ($rs_example->example_text==1 ) ? TRUE:FALSE )).'<br />' ;
        echo form_error('example_radio').'<br /> ' ;

        echo form_label('Checkbox', 'example_checkbox' ).'&nbsp;&nbsp;';
        echo form_checkbox('example_checkbox', '1', set_value('example_checkbox', (isset($rs_example->example_checkbox) ? $rs_example->example_checkbox : 0 )) ).'<br />' ;
        echo form_error('example_checkbox').'<br />' ;

        echo form_label('Drop Menu', 'example_dropmenu' ).'&nbsp;&nbsp;';
        echo $rs_example->example_dropmenu.'<br />' ;
           echo form_dropdown('example_dropmenu', $drop_menu_example_cats, set_value('example_dropmenu', (isset($rs_example->example_dropmenu)) ? $rs_example->example_dropmenu : '')).'<br />' ;
        echo form_error('example_dropmenu').'<br />' ;

        echo form_submit('submit','Submit');

        echo form_close();

?&gt;


<br style="clear:both" />
<pre>
&lt;?php print_r($rs_example) ; ?&gt;
</pre>

Continued in next post ...
#3

[eluser]Future Webs[/eluser]
View - List

Code:
<p>&lt;?php echo anchor('/example/form/' , 'Add New Example'); ?&gt;</p>
<table width="100%" border="1" cellspacing="2" cellpadding="4" class="AdminTable">
  <tr class="AdminTableHeader">
    <td>&nbsp;</td>
    <td>&nbsp;</td>
    <td>Id</td>
    <td>Text</td>
    <td>Radio</td>
    <td>Checkbox</td>
    <td>Drop menu</td>
    <td>Date Added</td>
    <td>Date Updated</td>
  </tr>
&lt;?php foreach ($rs_examples as $row_rs_examples) : ?&gt;  
  <tr>
    <td>&lt;?php echo anchor('/example/form/'.$row_rs_examples->example_id , 'Edit'); ?&gt;</td>
    <td>&lt;?php echo anchor('/example/delete_example/'.$row_rs_examples->example_id, 'Delete' );  ?&gt;</td>
    <td>&lt;?php echo $row_rs_examples->example_id ; ?&gt;</td>
    <td>&lt;?php echo $row_rs_examples->example_text ; ?&gt;</td>
    <td>&lt;?php echo $row_rs_examples->example_radio ; ?&gt;</td>
    <td>&lt;?php echo $row_rs_examples->example_checkbox ; ?&gt;</td>
    <td>&lt;?php echo $row_rs_examples->example_dropmenu ; ?&gt;</td>
    <td>&lt;?php echo $row_rs_examples->example_date_added ; ?&gt;</td>
    <td>&lt;?php echo $row_rs_examples->example_date_updated ; ?&gt;</td>
  </tr>
&lt;?php endforeach ; ?&gt;
</table>

<pre>
&lt;?php print_r($rs_examples) ; ?&gt;
</pre>

Demo Sql

Code:
--
-- Table structure for table `examples`
--

CREATE TABLE IF NOT EXISTS `examples` (
  `example_id` int(10) NOT NULL auto_increment,
  `example_text` varchar(50) NOT NULL,
  `example_radio` int(5) NOT NULL,
  `example_checkbox` int(5) NOT NULL,
  `example_dropmenu` varchar(25) NOT NULL,
  `example_date_added` datetime NOT NULL,
  `example_date_updated` datetime NOT NULL,
  KEY `example_id` (`example_id`)
) ENGINE=MyISAM  DEFAULT CHARSET=latin1 AUTO_INCREMENT=10 ;

--
-- Dumping data for table `examples`
--

INSERT INTO `examples` (`example_id`, `example_text`, `example_radio`, `example_checkbox`, `example_dropmenu`, `example_date_added`, `example_date_updated`) VALUES
(1, 'First Example', 1, 0, '1', '2008-11-18 00:00:00', '2008-11-19 01:20:13'),
(2, 'Second Example', 0, 1, '2', '2008-11-18 00:00:00', '2008-11-19 01:22:47'),
(3, 'Third Example', 1, 0, '3', '2008-11-18 00:00:00', '2008-11-19 01:20:17'),
(4, 'Fourth Example', 1, 1, '4', '2008-12-10 00:00:00', '2008-11-19 01:26:05');

-- --------------------------------------------------------

--
-- Table structure for table `example_cats`
--

CREATE TABLE IF NOT EXISTS `example_cats` (
  `example_cat_id` int(10) NOT NULL auto_increment,
  `example_cat_name` varchar(25) NOT NULL,
  PRIMARY KEY  (`example_cat_id`)
) ENGINE=MyISAM  DEFAULT CHARSET=latin1 AUTO_INCREMENT=5 ;

--
-- Dumping data for table `example_cats`
--

INSERT INTO `example_cats` (`example_cat_id`, `example_cat_name`) VALUES
(1, 'First Category'),
(2, 'Second Category'),
(3, 'Third Category'),
(4, 'Fourth Category');

Continued in next post ...
#4

[eluser]Future Webs[/eluser]
So ..

Onto where I came unstuck ..

#########################
## EDIT 11th Dec 2008 ###
#########################

Ive updated some of the code above to fix some of the errors I mention here

#########################

If i go to the form to add a new record rather then edit I have a problem like

Code:
A PHP Error was encountered
Severity: Notice
Message: Undefined variable: rs_example
Filename: views/example_form.php
Line Number: 11

A PHP Error was encountered
Severity: Notice
Message: Trying to get property of non-object
Filename: views/example_form.php
Line Number: 11

Now I guess that the first one is due to the fact that in the set_value part i set a default value that comes from the database but as an add type form we dont have anything there to show. How do I make it so that it ignores the default if its not needed.

FIXED

The next thing that I had a problem with was to do with drop menus, radio groups and checkboxs and how you would set which option was chosen during an update form but also having it so that it catches any changes if there is a validation problem

FIXED

I know there were a few other things too that I cant remember now so Ill just focus on the two mentioned.

In my example Im not using the model properly for the insert and edit etc and there is no mention of using an upload field.

After using this I also switched to splitting the insert and edit within the controller as I was having problems assigning different validation or post data depending on what the form was doing.

Ill update this code as i go along to try and come up with a good all round solution
#5

[eluser]dmorin[/eluser]
Try
Code:
'value'       => set_value('example_text', (isset($rs_example)) ? $rs_example->example_text : ''),
#6

[eluser]Future Webs[/eluser]
thanks, I had seen code like that but wasnt sure of exactly how it needed to be.

are we basically saying

if the array is set then show the variable after the ? otherwise : show nothing.

That little snippet should keep me going for a bit. Ill post back when i hit the next hurdle
#7

[eluser]dmorin[/eluser]
Yeah, it's called a Ternary Operator. More info at http://www.tech-evangelist.com/2007/11/1...-operator/
#8

[eluser]Future Webs[/eluser]
excellent, very useful to know

very much appreciate your help
#9

[eluser]Andrew Gunstone[/eluser]
Hi guys...I am new to CI (am a big fan of EE thought!!). The code above is pretty much exactly what I needed as a good example of how to build an add/edit form... particularly around best practice of the function placement (i.e. should it go in the controller, the model, etc). I am still trying to get my head around it all, but thanks for posting ALL your code.

No question here...just a big thumbs up to both w3bm and dmorin.

:-)
#10

[eluser]Future Webs[/eluser]
my code could do with a few fixes and ill do that tomorrow




Theme © iAndrew 2016 - Forum software by © MyBB