我想从服务器输入元素中获取他们的验证要求,并将其存储在validation.yaml文件中。
哦,正如标签所示,我正在使用symfony 4。
当用户要上传新帖子时,他将具有默认的帖子视图,但带有输入元素-这就是我想要实现的。
服务器端: 我有2个想法,没有一个我知道该如何执行
以某种方式获取验证并构建元素:
/**
* 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??
或通过表单生成器进行构建:
/**
* Builder function
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('category', EntityType::class, [
'class' => Category::class
])
->add('topic', TextType::class);
}
并这样做:
/**
* Controller function
*/
public function getPostFields(): JsonResponse
{
$post = new Post();
$form = $this->createForm(Builder::class, $post);
$HTMLInput = $form->renderHTMLInput();
$topicHTMLInput = $HTMLInput['topic'];
$categoryHTMLSelection = $HTMLInput['category'];
客户:
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);
我希望传递给response.data
的{{1}}符合服务器的验证要求:
post.insert
所以我希望在服务器端
{topic: '<input attr>', category: '<input attr>'}
很高兴收到一些帮助;)
答案 0 :(得分:0)
我接受了构建器的东西,结果发现您可以在Twig form_widget中进行渲染,而无需使用我做过的形式。这似乎不是最优化的答案,但它可以按我的意愿工作:
/**
* 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) }}