Загрузка TWIG формы на стороне клиента

0

У меня есть приложение Symfony2, которое я пытаюсь сделать RESTful.

Моя самая большая проблема, что я не могу понять, как (если это возможно)

  1. Создайте форму, используя $form = $form->createView();
  2. Сериализовать его
  3. Передайте его клиенту
  4. Разберите его на стороне клиента.

Я использую FOS REST Bundle.

Все, что я мог найти в документации здесь, - это то, как справляться с ошибками или делать это.

Если это актуально, я сериализую с использованием набора JMS Serializer Bundle

Ниже приведен JSON, который я передаю клиенту:

{
"info": {
    "ContactName": "Zane Zorn ",
    "BusinessName": "Business 164",
    "JobCategory": "House Sitting",
    "MajorIntersection": "John St and Jane St",
    "JobDescription": "A job that needs being done"
},
"form": {
    "vars": {
        "value": {},
        "attr": [],
        "id": "LeadResponseForm",
        "name": "LeadResponseForm",
        "full_name": "LeadResponseForm",
        "disabled": false,
        "multipart": false,
        "block_prefixes": ["form", "LeadResponseForm", "_LeadResponseForm"],
        "unique_block_prefix": "_LeadResponseForm",
        "translation_domain": "messages",
        "cache_key": "_LeadResponseForm_LeadResponseForm",
        "read_only": false,
        "errors": [],
        "valid": true,
        "data": {},
        "required": true,
        "label_attr": [],
        "compound": true,
        "method": "POST",
        "action": "",
        "sonata_admin_enabled": false,
        "sonata_admin": {
            "edit": "standard",
            "inline": "natural",
            "block_name": false
        }
    },
    "children": {
        "ContactName": {
            "vars": {
                "value": "",
                "attr": {
                    "value": "Zane Zorn "
                },
                "id": "LeadResponseForm_ContactName",
                "name": "ContactName",
                "full_name": "LeadResponseForm[ContactName]",
                "disabled": false,
                "label": "Contact Name",
                "multipart": false,
                "block_prefixes": ["form", "text", "_LeadResponseForm_ContactName"],
                "unique_block_prefix": "_LeadResponseForm_ContactName",
                "translation_domain": "messages",
                "cache_key": "_LeadResponseForm_ContactName_text",
                "read_only": false,
                "errors": [],
                "valid": true,
                "required": true,
                "label_attr": [],
                "compound": false,
                "method": "POST",
                "action": "",
                "sonata_admin_enabled": false,
                "sonata_admin": {
                    "edit": "standard",
                    "inline": "natural",
                    "block_name": false
                }
            },
            "children": [],
            "rendered": false
        },
        "Email": {
            "vars": {
                "value": "",
                "attr": {
                    "value": "[email protected]"
                },
                "id": "LeadResponseForm_Email",
                "name": "Email",
                "full_name": "LeadResponseForm[Email]",
                "disabled": false,
                "label": "Your Email",
                "multipart": false,
                "block_prefixes": ["form", "text", "email", "_LeadResponseForm_Email"],
                "unique_block_prefix": "_LeadResponseForm_Email",
                "translation_domain": "messages",
                "cache_key": "_LeadResponseForm_Email_email",
                "read_only": false,
                "errors": [],
                "valid": true,
                "required": true,
                "label_attr": [],
                "compound": false,
                "method": "POST",
                "action": "",
                "sonata_admin_enabled": false,
                "sonata_admin": {
                    "edit": "standard",
                    "inline": "natural",
                    "block_name": false
                }
            },
            "children": [],
            "rendered": false
        },
        "Phone": {
            "vars": {
                "value": "",
                "attr": {
                    "value": "(416)877-3344"
                },
                "id": "LeadResponseForm_Phone",
                "name": "Phone",
                "full_name": "LeadResponseForm[Phone]",
                "disabled": false,
                "label": "Your Phone",
                "multipart": false,
                "block_prefixes": ["form", "text", "_LeadResponseForm_Phone"],
                "unique_block_prefix": "_LeadResponseForm_Phone",
                "translation_domain": "messages",
                "cache_key": "_LeadResponseForm_Phone_text",
                "read_only": false,
                "errors": [],
                "valid": true,
                "required": true,
                "label_attr": [],
                "compound": false,
                "method": "POST",
                "action": "",
                "sonata_admin_enabled": false,
                "sonata_admin": {
                    "edit": "standard",
                    "inline": "natural",
                    "block_name": false
                }
            },
            "children": [],
            "rendered": false
        },
        "Message": {
            "vars": {
                "value": "",
                "attr": {
                    "value": "It looks like your gonna need a new Johnson Rod. That going to be 500$",
                    "style": "width:500px"
                },
                "id": "LeadResponseForm_Message",
                "name": "Message",
                "full_name": "LeadResponseForm[Message]",
                "disabled": false,
                "label": "The Message",
                "multipart": false,
                "block_prefixes": ["form", "text", "textarea", "_LeadResponseForm_Message"],
                "unique_block_prefix": "_LeadResponseForm_Message",
                "translation_domain": "messages",
                "cache_key": "_LeadResponseForm_Message_textarea",
                "read_only": false,
                "errors": [],
                "valid": true,
                "required": true,
                "label_attr": [],
                "compound": false,
                "method": "POST",
                "action": "",
                "sonata_admin_enabled": false,
                "sonata_admin": {
                    "edit": "standard",
                    "inline": "natural",
                    "block_name": false
                }
            },
            "children": [],
            "rendered": false
        },
        "Send to the Customer": {
            "vars": {
                "attr": [],
                "id": "LeadResponseForm_Send to the Customer",
                "name": "Send to the Customer",
                "full_name": "LeadResponseForm[Send to the Customer]",
                "disabled": false,
                "multipart": false,
                "block_prefixes": ["button", "submit", "_LeadResponseForm_Send to the Customer"],
                "unique_block_prefix": "_LeadResponseForm_Send to the Customer",
                "translation_domain": "messages",
                "cache_key": "_LeadResponseForm_Send to the Customer_submit",
                "clicked": false
            },
            "children": [],
            "rendered": false
        },
        "_token": {
            "vars": {
                "value": "b54d228db0acb06ed5686a6e3dbd7a231ec027e2",
                "attr": [],
                "id": "LeadResponseForm__token",
                "name": "_token",
                "full_name": "LeadResponseForm[_token]",
                "disabled": false,
                "multipart": false,
                "block_prefixes": ["form", "hidden", "_LeadResponseForm__token"],
                "unique_block_prefix": "_LeadResponseForm__token",
                "translation_domain": "messages",
                "cache_key": "_LeadResponseForm__token_hidden",
                "read_only": false,
                "errors": [],
                "valid": true,
                "data": "b54d228db0acb06ed5686a6e3dbd7a231ec027e2",
                "required": false,
                "label_attr": [],
                "compound": false,
                "method": "POST",
                "action": "",
                "sonata_admin_enabled": false,
                "sonata_admin": {
                    "edit": "standard",
                    "inline": "natural",
                    "block_name": false
                }
            },
            "children": [],
            "rendered": false
        }
    },
    "rendered": false
}

}

Теги:
rest
twig

1 ответ

1
Лучший ответ

Я использовал FosRestbundle для создания спокойного api. Взгляните на сообщение в блоге: http://williamdurand.fr/2012/08/02/rest-apis-with-symfony2-the-right-way/

Вам необходимо создать форму при обработке действий put/post. для списка (getResouces action) и получения одного ресурса по его id (getResource Action) вы просто используете поиск репозитория, но вы должны иметь аннотацию Rest на действия контроллера:

 @Rest\View(serializerGroups={"self.link"})

И на маршрутизацию yml пакета:

status:
 type: rest
 resource: Radsphere\RecruitmentBundle\Controller\StatusController
 prefix: /api
 name_prefix: api_recruitment_

Затем у меня есть метод централизованной формы процесса, который обрабатывает все действия post и put

  /**
 * Process update or create request from a resource
 * @param $apiResource
 * @return View|Response
 */
protected function processForm($apiResource)
{
    $form = null;
    try {
        $resourceData = $apiResource->getData();
        $statusCode = $resourceData->getId() ? 204 : 201;
        $formMethod = "POST";
        if ($statusCode === 204) {
            $formMethod = "PUT";
        }

        $request = $this->getRequest();

        $form = $this->createForm(
            $apiResource->getResourceFormName(),
            $resourceData,
            array('method' => $formMethod)
        );
        $request = $this->get('api_resource.factory')->formatRequestWithForm(
            $request,
            $apiResource->getResourceFormName(),$content
        );

        $form->handleRequest($request);


        if ($form->isValid()) {


            $this->get($apiResource->getResourceHandlerName())->update($resourceData);

            $response = new Response();
            $response->setStatusCode($statusCode);

            // set the 'Location' header only when creating new resources
            if ($statusCode === 201 || $statusCode === 204) {

                        $serializedObject = $this->get('jms_serializer')->serialize($resourceData, 'json');

                }
                $response->setContent($serializedObject);


            }

            return $response;
        }
        return View::create($form, 400);
    } catch (\Exception $e) {
        $this->get('logger')->error("Exception raised during post a resource " . $e->getMessage());
        return View::create($e->getMessage(), 400);
    }


}

Ещё вопросы

Сообщество Overcoder
Наверх
Меню