Как я могу отправить требования проверки клиенту? - PullRequest
1 голос
/ 04 июля 2019

Я хочу получить от сервера входные элементы с их требованиями к валидации, которые я храню в файле 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
    ]]);
}

Рад получить некоторую помощь;)

1 Ответ

0 голосов
/ 10 июля 2019

Я пошел с конструктором и оказалось, что вы можете рендерить в 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) }}
...