Samson
Samson

Reputation: 2821

CodeIgniter MVC data manipulation best approach

I'm developing a website in CodeIgniter. It's kind of basic, except it has some enormous forms (150 fields) some dynamically created/locked/predefined/removed etc..

I'm having trouble doing the transition between the form and the database, which of course is very complicated. What I mean is that the submit of the form inserts more than one line in some tables and some data is not even saved. (some radio buttons etc..)

I have created a very large object with as many properties as possible named after the form input names in order to fill with the $_POST data using:

foreach ($largeObj as $key=>$value)
{
  if (isset($_POST[$key])){
    $largeObj[$key]=$value; //mind the data escaping 
  }
}

Of course this only works for half the inputs, for the others I need to do something like this:

$largeObj['tanks']=Array();
for ($i=0;$i<$_POST['nbrTanks'];$i++){
    $tank=new Tank();
    // some if's in order to set some properties
    $largeObj['tanks'][]=$tank;
}

Then I do all the calculations and prepare my DTO's to insert in each table the corresponding data. Btw I used PHPDAO to map the database tables as they were a bit too large to write the entire CRUD operations.

Is there a better approach? something annotation-driven or a more efficient way because I also need to fill the entire forms with the data from my DB. Any suggestions are welcome.

Upvotes: 1

Views: 700

Answers (1)

David
David

Reputation: 3821

If you have a list of the inputs that go to either method, you can do something like this:

##Array of items to be checked with `isset()`
$array_isset = array('field1', 'field2', 'field3');
foreach ($array_isset as $line) {
   #.... same thing you did before
}

$array_tank = array('field4', 'field5', 'field6'); 
foreach ($array_tank as $line) {
   $tank = new Tank()
}

If I understand your question, the above method would allow you to sort the fields by the operations that need to be performed on them.

That being said, I've had multiple projects where I've had to deal with large amounts of information. What I found, every single time, was that the best approach is to find a way to put the raw data in to the database, and perform your calculations at a later date.

This also makes it easy, because in CodeIgniter, you can just do this:

$array = $this->input->post(NULL, True);
$this->db->insert('table', $array);

If your form fields match up with your database column names.

If you have a list of data, then you can store the data as a comma-separted list like this:

$array = array('value1', 'value2', 'value3');
$insert_string = implode(',', $array);

And explode it when you select it.

This may not work in your situation, but it does have value in certain situations.

Good luck with your application; I hope I helped!

Upvotes: 1

Related Questions