FosRestBundle post/put [создать новый/обновить объект] неправильно читает запрос

Короче говоря: используя FOSRestBundle, я пытаюсь создать некоторые сущности с помощью вызова POST или изменить существующие с помощью PUT.

вот код:

/**
 * Put action
 * @var Request $request
 * @var integer $id Id of the entity
 * @return View|array
 */
public function putCountriesAction(Request $request, $id)
{
    $entity = $this->getEntity($id);
    $form = $this->createForm(new CountriesType(), $entity, array('method' => 'PUT'));
    $form->bind($request);

    if ($form->isValid()) {
        $em = $this->getDoctrine()->getManager();
        $em->persist($entity);
        $em->flush();
        return $this->view(null, Codes::HTTP_NO_CONTENT);
    }

    return array(
        'form' => $form,
    );
} //[PUT] /countries/{id}

Если я вызываю /countries/{id} с PUT, передавая json, например {"description":"Japan"}, он меняет мою страну с id=1, добавляя пустое описание.

Если вместо этого я попытаюсь создать НОВЫЙ объект с помощью этого метода:

/**
 * Create new Countries (in batch)
 * @param  Request $request json request
 * @return array           redirect to get_coutry, will show the newly created entities
 */
public function postCountriesAction(Request $request)
{
    $entity = new Countries();
    $form = $this->createForm(new CountriesType(), $entity);
    $form->bind($request);

    if ($form->isValid()) {
        $em = $this->getDoctrine()->getManager();
        $em->persist($entity);
        $em->flush();

        return $this->redirectView(
            $this->generateUrl(
                'get_country',
                array('id' => $entity->getId())
            ),
            Codes::HTTP_CREATED
        );
    }

    return array(
        'form' => $form,
    );
} //[PUT {"description":"a_description"}] /countries

это дает мне сообщение об ошибке:

exception occurred while executing 'INSERT INTO countries (description) VALUES (?)' with params [null]:
SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'description' cannot be null

поэтому кажется, что я не могу правильно передать запрос на привязку к форме.

Обратите внимание, что если я json_decode запрос, как предложено, rest-api">здесь он отвечает

{
    "code":400,
    "message":"Validation Failed",
    "errors":{
        "errors":[
            "This value is not valid."
        ],
        "children":{
            "description":[
            ]
        }
    }
}

Любой совет?

Спасибо, Роллс


person rollsappletree    schedule 13.12.2013    source источник


Ответы (2)


Я решил :)

это причина, почему это не работало раньше:

В моем определении формы имя было «zanzibar_backendbundle_countries».

public function getName()
{
    return 'zanzibar_backendbundle_countries';
}

Итак, чтобы привязать запрос к этой форме, json должен был выглядеть так:

{"zanzibar_backendbundle_countries": [{"description": "Japan"}]}

Так как я хотел, чтобы это было что-то вроде

{"id":1,"description":"Italy"}

Мне пришлось удалить имя из формы:

public function getName()
{
    return '';
}

В общем, если вы хотите опубликовать json с заполнителем, например

"something":{"key":"value"}

имя вашей формы должно быть в точности "что-то"

person rollsappletree    schedule 14.12.2013

Попробуй это :

if ($form->isValid()) {
    $entity = $form->getData();       //   <------ you didn't bind entity to the form
    $em = $this->getDoctrine()->getManager();
    $em->persist($entity);
    $em->flush();
person BENARD Patrick    schedule 13.12.2013
comment
к сожалению, это не помогает... Кажется, я не могу привязать запрос к форме... что у меня есть [из отладки]: request: PUT request: Array ([description] => Japan) entity from db: Countries Object ([id:protected] => 1; [description:protected] => Italy) from form->getData()form: Countries Object <- ([id:protected] => 1; [description:protected] => ) what it save: entity: Countries Object([id:protected] => 1; [description:protected] => ) - person rollsappletree; 13.12.2013