1

我想从服务器输入元素中获取我存储在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我传递给post.insert来自服务器的验证要求: {topic: '<input attr>', category: '<input attr>'}

所以在服务器端我期望

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

很高兴得到一些帮助;)

4

1 回答 1

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) }}
于 2019-07-10T09:33:24.203 回答