0
votes

I would like to write my own controller in the api-platform for symfony 4. There is an error with the GET operation:  

NotFoundHttpException HTTP 404 Not Found Not Found

And with the post operation I have an error:

An exception has been set up for the application of the application. (Either a route). config / routes / api_platform.yaml). Make sure there is a loader supporting the api_platform type.

here's the code:

    @ApiResource(itemOperations={
 *     "post",
 *     "special"={"route_name"="user_method_special"}
 *     })
 */
class Users

UserController:

class UserController extends Controller implements AuthenticatedController
{

    public function userMethod(Request $request)
    {
        $userId = $request->get('user_id');
        $method = $request->get('method');

        $em = $this->getDoctrine()->getManager();
        $userRepository = $em->getRepository(Users::class);
        $user = $userRepository->findOneBy(['userId' => $userId]);

        $userModel = new UserModel($em);

        if (!$method) {

            if (!$user) {
                return new JsonResponse(['message' => 'Brak oraz userId: ' . $userId], Response::HTTP_NOT_FOUND, ['content-type'=>'application/json']);
            }
            $account = $userModel->getMethod($userId);
        }

            $method = str_replace(' ', '', $method);
            $acclen = strlen($method);

            $account = $userModel->parseMethod($method, $acclen, $userId, $replaceZeros);

            //return new JsonResponse([ 'data' => FormatModel::formatMethod($method, $format)], Response::HTTP_OK, ['content-type'=>'application/json']);
            return FormatModel::formatMethod($method, $format);
        }
}

and routes.yaml:

user_method:
  path: '/user-method'
  methods: ['POST']
  defaults:
    _controller: '\App\Controller\UserController::userMethod'
    _api_resource_class: 'App\Entity\Users'
    _api_item_operation_name: 'special'

what am I doing wrong?

I would like to return one value taken from doctrine.

Edit: When I changed the definition route_name = user_method, I have an error with the POST method:

Exception thrown when handling an exception (Symfony\Component\Config\Exception\FileLoaderLoadException: Either a "route_name" or a "method" operation attribute must exist for the operation "post" of the resource "App\Entity\Users" in . (which is being imported from "D:\xampp\htdocs\api\config/routes/api_platform.yaml"). Make sure there is a loader supporting the "api_platform" type.)

2

2 Answers

1
votes

The name of the route in your operation definition and in your routing definition doesn't match:

user_method_special vs user_method

Btw, the method you use to create custom operations is not the recommended way: https://api-platform.com/docs/core/operations/#recommended-method

0
votes

The code above is variable $ account. Instead of it, there should be a $ method and the $replaceZeros variable should not be at all.