Created
March 26, 2016 15:42
-
-
Save davidDuymelinck/52362cd7dc3e5c411bd9 to your computer and use it in GitHub Desktop.
POC dynamic form in symfony 3
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace DppBundle\Controller; | |
use Symfony\Bundle\FrameworkBundle\Controller\Controller; | |
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route; | |
use Symfony\Component\Form\Extension\Core\Type\SubmitType; | |
use Symfony\Component\Form\Extension\Core\Type\TextType; | |
use Symfony\Component\HttpFoundation\Request; | |
use Symfony\Component\Validator\Constraints\NotBlank; | |
class DefaultController extends Controller | |
{ | |
/** | |
* @Route("/", name="home") | |
*/ | |
public function indexAction(Request $request) | |
{ | |
$form = $this->getDynamicForm(); | |
$form->handleRequest($request); | |
if ($form->isSubmitted() && $form->isValid()) { | |
// ... perform some action, such as saving the task to the database | |
return $this->redirectToRoute('home'); | |
} | |
return $this->render('DppBundle:default:index.html.twig', array( | |
'form' => $form->createView(), | |
)); | |
} | |
protected function getDynamicForm() { | |
$formBuilder = $this->createFormBuilder(); | |
$fields = $this->getFormFields(); | |
foreach($fields as $field) { | |
$formBuilder->add($field['name'], $field['class'], $field['options']); | |
} | |
return $formBuilder->getForm(); | |
} | |
public function getFormFields() { | |
$fieldsDefault = [ | |
'firstName' => [ | |
'name' =>'firstName', | |
'class' => TextType::class, | |
'options' => [] | |
], | |
'lastName' => [ | |
'name' => 'lastName', | |
'class' => TextType::class, | |
'options' => [], | |
], | |
'save' => [ | |
'name' => 'save', | |
'class' => SubmitType::class, | |
'options' => [], | |
] | |
]; | |
// get if form somewhere else | |
$fieldsOverWrite = [ | |
'firstName' => [ | |
'options' => [ | |
'constraints' => array( | |
new NotBlank(), | |
), | |
] | |
], | |
'save' => [ | |
'options' => [ | |
'label' => 'Save overwrite' | |
] | |
] | |
]; | |
$fields = array_merge_recursive($fieldsDefault, $fieldsOverWrite); | |
foreach($fieldsDefault as $fieldName => $metaData) { | |
if(!isset($fieldsOverWrite[$fieldName])) { | |
unset($fields[$fieldName]); | |
} | |
} | |
return $fields; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment