DaanBuit
DaanBuit

Reputation: 74

API Platform custom operation with custom parameter

I just started using the dunglas api platform. Im using v2.0.0-rc1 and i added an custom operation to enabled/disable an user.

This is my custom action for the user

<?php

namespace Zoef\UserBundle\Action;

use Zoef\UserBundle\Entity\User;
use Doctrine\Common\Persistence\ManagerRegistry;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
use Symfony\Component\Routing\Annotation\Route;

class UserAction
{
    /**
     * @Route(
     *     name="enabled_user",
     *     path="/users/{id}/enabled",
     *     defaults={"_api_resource_class"=User::class, "_api_item_operation_name"="enabled"}
     * )
     * @Method("PUT")
     */
    public function __invoke(User $user)
    {
        if($user->isEnabled()) {
            $user->setEnabled(false);
        } else {
            $user->setEnabled(true);
        }

        return $user;
    }
}

When i go to my docs the custom operation is added and functional but to use this action i need to send 4 parameters: email, fullname, username, enabled. but i only want to send the enabled parameter and the id of the user is given in the route but i cant find in the doc how to change the parameters.

Can someone help me with this?

Upvotes: 3

Views: 6576

Answers (1)

Joel Mora
Joel Mora

Reputation: 21

I was trying to make the same enable/disabled and I did it this way:

I created a custom controller in AppBundle\Controller\AddressController

use Symfony\Bundle\FrameworkBundle\Controller\Controller;

class AddressController extends Controller
{
    public function enableAction($data)
    {
        $data->setActive(true);

        $em = $this->getDoctrine()->getManager();
        $em->persist($data);
        $em->flush();

        return $data;
    }
}

In my routing.yml I have:

address_enable:
    path:     '/addresses/{id}/enable'
    methods:  ['PUT']
    defaults:
            _controller: 'AppBundle:Address:enable'
            _api_resource_class: 'AppBundle\Entity\Address'
            _api_item_operation_name: 'enable'

In my entity, I have:

 * @ApiResource(
 *     itemOperations={
 *          "enable"={"route_name"="address_enable"},
 *     }
 * )

And after that I just send it as URL/addresses/123/enable no need to send more parameters, just the id.

Upvotes: 2

Related Questions