Forge - populate a form from database
- Posted by dlib on March 15th, 2008 filed in Code examples, Forge
With some regularity I see people running into the problem of loading database values into a Forge form. A while ago I wrote an addition to Forge to help me doing that amongst other things. Anyway, the issue can be solved quite easily.
application/libraries/MY_Forge.php
class Forge extends Forge_Core{ public function load_values($data) //you could call it populate_form as well { foreach($data as $field=>$value) { if(array_key_exists($field,$this->inputs)) { $this->$field->set_value($value); } } } }
$data is an array of data whose keys match the names of the Forge elements.
Note that a similar method is available in Formation.
March 16th, 2008 at 1:01 am
Pretty much useless. Nobody calls the field “name” as “input”. Even more, to change the $key $value of the array and then change the $value to $input_type is more difficult that populate the form “by hands”.’
K. R.
Xobb
March 16th, 2008 at 9:27 am
It’s not like that or my logic is wrong, it worked back then. You pass an array
To this method and the Forge field with the name ‘username’, and ‘email’ will receive the appropriate values.
I was able to pass an ORM::as_array() to this method and it would show me a filled in form with values from the db. Only thing was that db fields and form fields had to match.
March 17th, 2008 at 11:06 pm
Oh, now I see. I was sleepy that day and didn’t take a proper look at the code. You’re right, it’s loading only the values, not the whole form.
How about dropdowns? Is set_value() an alias to options()? It would be cool to pass all these arrays as a single multidimensional one.
March 17th, 2008 at 11:41 pm
I haven’t tested it for dropdowns, I hope to look into it sometime
March 18th, 2008 at 7:21 pm
Is it valid for this file to be in application/MY_Forge.php or should it be saved to application/libraries/MY_Forge.php?
March 18th, 2008 at 11:03 pm
You’re right neovive, it should be saved to application/libraries/MY_Forge.php I fixed the post, thanks.
March 19th, 2008 at 12:45 am
No problem. I was starting to get confused with the rules for extending core and module resources.
With modules, it appears that the class names need to have _Core appended in order to allow them to be extended with a MY_ version. Otherwise they can only be replaced with a local version in the “application” folder. Lots of little undocumented rules, I guess.
April 29th, 2008 at 2:50 am
I have a problem to populate hidden fields with this example.
I fix it changing the line:
if(array_key_exists($field,$this->inputs))
to:
if(array_key_exists($field,$this->inputs) OR array_key_exists($field,$this->hidden))
April 29th, 2008 at 7:28 am
You’re right, I didn’t cover for this. I’ll change the example soon.