I want to get from server input elements with theirs validation requirements that I store in validation.yaml file.
oh, and as tags shows I'm doing it with symfony 4.
When user will want to upload new post he will have default post view but with input elements - that's what I want to achieve.
Server-side: I've got 2 ideas, none of them that I know what to execute with
Get validation and build elements somehow:
/**
* Controller function
*/
public function getPostFields(): JsonResponse
{
$topicRequirements = getThemFromSomewhere('topic');
$categoryRequirements = getThemFromSomewhere('category');
# How do I get those?
$topicHTMLInput = buildItSomehow('input', $topicRequirements);
$categoryHTMLSelection = buildItSomehow('selection', $categoryRequirements);
# Or build those??
or build it via form builder:
/**
* Builder function
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('category', EntityType::class, [
'class' => Category::class
])
->add('topic', TextType::class);
}
and do it like so:
/**
* Controller function
*/
public function getPostFields(): JsonResponse
{
$post = new Post();
$form = $this->createForm(Builder::class, $post);
$HTMLInput = $form->renderHTMLInput();
$topicHTMLInput = $HTMLInput['topic'];
$categoryHTMLSelection = $HTMLInput['category'];
Client:
var post = {
topic: someHTMLElement,
category: someOtherHTMLElement,
insert: function(data) {
for (let key in this)
if (this[key] instanceof Element && data.hasOwnProperty(key))
this[key].innerHTML = data[key];
}
}
response = someXMLHttpRequestResponse;
post.insert(response.data);
I want response.data
that I pass to post.insert
to be with validation requirements from server as:
{topic: '<input attr>', category: '<input attr>'}
so on the server-side I expect
return new JsonResponse(['data' => [
'topic': $topicHTMLInput,
'category': $categoryHTMLSelection
]]);
}
Glad to recieve some help ;)
I went with builder thing and turns out you can render in Twig form_widget without form which I did. It doesn't seem like the most optimized answer but it works as I wanted it to:
/**
* Controller function
*/
public function getPostFields(): JsonResponse
{
$post = new Post();
$form = $this->createForm(PostFormBuilder::class, $post);
$form = $form->createView();
return new JsonResponse([
'data' => [
'category' => $this->renderView('elements/form/category.twig', ['post' => $form]),
'topic' => $this->renderView('elements/form/topic.twig', ['post' => $form]),
]
]);
}
/**
* templates/elements/form/category.twig
*/
{{ form_widget(post.category) }}
/**
* templates/elements/form/topic.twig
*/
{{ form_widget(post.topic) }}