Pregunta

I'm using Silex FormBuilder in my application. The structure of a builder is like this:

$form = $app['form.factory']->createBuilder('form')
->add('name', 'text', array(
        'constraints' => array(new Assert\NotBlank(), new Assert\Length(array('min' => 5)))
))
->add('email', 'text', array(
    'constraints' => new Assert\Email()
))
->add('gender', 'choice', array(
    'choices' => array(1 => 'male', 2 => 'female'),
    'expanded' => true,
    'constraints' => new Assert\Choice(array(1, 2)),
))
->getForm();

Let's say I would build such builder from blocks, which would be stored in a database as a whole. Always, in any form I would create I know, that e-mail field will always be defined the same. So I would get definitions from database and foreach them to create form.

->add('email', 'text', array(
'constraints' => new Assert\Email()))

When i get this from a database (posgresql in my case) this would be a string (because the database field is text type).
My question: is there any possibility to convert this to a valid code?

I thought of something like this:

$form = $app['form.factory']->createBuilder('form')
foreach ($definitions as $definition) {
  something to do with the $definition;
}
->getForm();

But instead of foreach createBuilder expects ->add... method, and this is where im stuck.

Best Regards,
Kamil

¿Fue útil?

Solución

/*Concidering $definitions = array("$form->add('email', 'text', array(
        'constraints' => new Assert\Email()
    ));"); 
*/
$form = $app['form.factory']->createBuilder('form');
foreach($definitions as $definition){
    eval($definition);
}
$form->getForm();

I would not recommend you use eval like so... You'd better store the parameters to pass to the function to make it work... You could also create a function or class to handle typical elements such as your email, so you would only need to reference the kind of input in the database, a bit like so:

function addFormElement(&$form,$type){
    switch($type){
        case 'email':$form->add('email', 'text', array(
                    'constraints' => new Assert\Email()
                ));
        break;
    }
}
/*Concidering $definitions = array("email"); 
*/
$form = $app['form.factory']->createBuilder('form');
foreach($definitions as $definition){
    addFormElement($form,$definition);
}
$form->getForm();
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top