What's the best way to control the output (view) based on database entry?

Hi everyone,

just learning CI and already excited about the speed of developing.

This is probably easy: I have some custom fields that take user input. Each custom field is stored in:

CREATE TABLE  'fields' (
        `category_id` int(12) unsigned NOT NULL REFERENCES categories(id),
        `name` VARCHAR(255) NOT NULL,
        `label` VARCHAR(255) NOT NULL,
        `desc` LONGTEXT NULL,
        `type` ENUM( 'textbox', 'textarea', 'dropdown', 'checkbox') NOT NULL,
        `required` bool NOT NULL default 1,
        `field_owner` VARCHAR(255) NOT NULL default '',
         PRIMARY KEY id  (`field_id`)
   ) TYPE=MyISAM;;

So I select all the fields that correspond to a certain category_id and generate a form. I want to be able to control the view based on the type of the fields (textbox, textarea, dropdown, checkbox).

Basically I could do this in the controller:
foreach ($allfields as $field){
if ($field['type']=textbox
$output  .= $this->load->view('form_textbox', 'some data', true);
elseif ($field['type']=checkbox
$output  .= $this->load->view('form_checkbox', 'some data', true);
elseif ......
else  ......

However, I'm feeling that I'm writing unnecessary code and there must be a more elegant way to achieve this. Any help?

You could do a helper function that accepts your data and return the expected form element using the form_helper. Something like this.

function form_magic($name, $type, $val, $attributes)
   //this is really basic you would add your conditionals here since form_helper arguments vary from
   //function to function

   $form_function = 'form_'.$type;
   return $form_function($name, $val);
$output = '';
foreach ($allfields as $field):
   $output .= form_magic($field['name'], $field['type']);
$data['output'] = $output;
//load your view file
$this->load->view('your_view_name', $data);

Keep in mind you will still have to determine where you want to start and end your form. In the controller or in your view. Hope this helps.

Edit: For this to work as I have shown, your enum values would have to corespond to the correcth form_helper functions. For example you would have to change the enum value of textbox to input.

Thanks for the help. Worked great!

Digg   Delicious   Reddit   Facebook   Twitter   StumbleUpon  

  Theme © 2014 iAndrew  
Powered By MyBB, © 2002-2021 MyBB Group.