0

这是我通过 api 添加记录的基本操作

    public function createAction(Request $request){
      $data = array();
      $data['employeeCode'] = $request->request->get('employeeCode');
      $data['employeeDescription'] = $request->request->get('employeeDescription');
      $data['firstName'] = $request->request->get('firstName');
      $data['lastName'] = $request->request->get('lastName');
      $data['address'] = $request->request->get('address');
      $data['suburb'] = $request->request->get('suburb');
      $data['postcode'] = $request->request->get('postcode');
      $data['country'] = $request->request->get('country');
      $data['phone'] = $request->request->get('phone');
      $data['mobile'] = $request->request->get('mobile');

      $emp = new Employees();
      $emp->setEmployeeCode($data['employeeCode']);
      $emp->setEmployeeDescription($data['employeeDescription']);
      $emp->setFirstName($data['firstName'] );
      $emp->setLastName($data['lastName']);
      $emp->setAddress($data['address']);
      $emp->setSuburb($data['suburb']);
      $emp->setCountry($data['country']);
      $emp->setSuburb($data['phone']);
      $emp->setCountry($data['mobile']);

      $em = $this->get('doctrine')->getEntityManager();
      $em->persist($emp);
      $em->flush();
      $view = View::create();
      $view->setData($emp);

      return $view;

这对我有用,但我想将它与我的员工表单绑定,这样我就可以从我的表单验证器获得每一个验证,而且我是 symfony2 的新手,所以我不知道该怎么做......

4

2 回答 2

1

如果您想在 api 上验证您的实体,只需使用 validate 方法:http ://symfony.com/doc/current/book/validation.html

您不必使用表格!

这里有一个例子:

public function createAction(Request $request){

    // ...previous code...

    // We valide manually the employee without a form !
    $validator = $this->get('validator');
    $errors = $validator->validate($emp);

    // If there are errors....
    if (count($errors) > 0) {

        return new Response('Errors !');
    }

    // Otherwise we save it !

    $em = $this->get('doctrine')->getEntityManager();
    $em->persist($emp);
    $em->flush();
    $view = View::create();
    $view->setData($emp);

    return $view;
}

当然,它会调用在您的员工实体上定义的所有验证器。

您也可以只调用一组验证器:

$errors = $validator->validate($emp, array('api_creation'));

此外,这里有一个使用 symfony2 构建 API 的好教程:http ://williamdurand.fr/2012/08/02/rest-apis-with-symfony2-the-right-way/

于 2012-09-04T11:14:21.273 回答
0

这真的很容易:

$emp = new Employees();

$form = $this->createForm(new EmployeesType(), $emp);
$form->bindRequest($request);

if ($form->isValid()) {
    $emp = $form->getData();
    (...)
}
(...)
于 2012-09-04T10:43:06.513 回答