Forge - populate a form from database

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.


9 Responses to “Forge - populate a form from database”

  1. Xobb Says:

    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

  2. admin Says:

    It’s not like that or my logic is wrong, it worked back then. You pass an array

    array('username'=>'some name','email'=>'some email');

    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.

  3. Xobb Says:

    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.

  4. admin Says:

    I haven’t tested it for dropdowns, I hope to look into it sometime

  5. neovive Says:

    Is it valid for this file to be in application/MY_Forge.php or should it be saved to application/libraries/MY_Forge.php?

  6. admin Says:

    You’re right neovive, it should be saved to application/libraries/MY_Forge.php I fixed the post, thanks.

  7. neovive Says:

    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.

  8. Edinho Says:

    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))

  9. dlib Says:

    You’re right, I didn’t cover for this. I’ll change the example soon.