如何向客户发送验证要求?

How can I send validation requirements to client?

我想从服务器输入元素中获取我存储在 validation.yaml 文件中的验证要求。

哦,正如标签所示,我正在使用 symfony 4 进行操作。

当用户想要上传新的 post 时,他将拥有默认的 post 视图但带有输入元素 - 这就是我想要实现的。

服务器端: 我有 2 个想法,其中 none 个我知道如何执行

以某种方式获取验证并构建元素:

/**
 * 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);

我希望我传递给 post.insertresponse.data 符合服务器的验证要求: {topic: '<input attr>', category: '<input attr>'}

所以我希望在服务器端

    return new JsonResponse(['data' => [
        'topic': $topicHTMLInput,
        'category': $categoryHTMLSelection
    ]]);
}

很高兴得到一些帮助 ;)

我使用了构建器,结果发现你可以在 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) }}