MrYamous
MrYamous

Reputation: 21

Use JSON in Symfony controller

I'm looking for a way to execute a little bit of JSON from my Symfony (2.6 btw) controller, moreover than an other action (post data into database)

In fact, there is an register page with a controller which put data into database and then, redirect user to another page. But i need that my controller execute too a little bit of JSON to use Mailchimp API.

I've found a lot of docs about how to render JSON response, but, it seems to me that it's not what i want to be.

There is my controller

public function registerAction(Request $request)
{
    /** @var $formFactory \FOS\UserBundle\Form\Factory\FactoryInterface */
    $formFactory = $this->get('fos_user.registration.form.factory');
    /** @var $userManager \FOS\UserBundle\Model\UserManagerInterface */
    $userManager = $this->get('fos_user.user_manager');
    /** @var $dispatcher \Symfony\Component\EventDispatcher\EventDispatcherInterface */
    $dispatcher = $this->get('event_dispatcher');

    $user = $userManager->createUser();
    $user->setEnabled(true);

    $event = new GetResponseUserEvent($user, $request);
    $dispatcher->dispatch(FOSUserEvents::REGISTRATION_INITIALIZE, $event);

    if (null !== $event->getResponse()) {
        return $event->getResponse();
    }

    $form = $formFactory->createForm();
    $form->setData($user);

    $form->handleRequest($request);

    if ($form->isValid()) {

        // Gestion du type d'utilisateur et ajout du role
        $user_type = $form->get('user_profile')->get('type')->getData();
        $new_role = $this->roles[$user_type];          

        $event = new FormEvent($form, $request);
        $user = $event->getForm()->getData();
        $user->addRole($new_role);

        $user->getUserProfile()->setEmail($user->getEmail());

        $dispatcher->dispatch(FOSUserEvents::REGISTRATION_SUCCESS, $event);

        $userManager->updateUser($user);

        if (null === $response = $event->getResponse()) {
            $url = $this->generateUrl('fos_user_registration_confirmed');
            $response = new RedirectResponse($url);
        }

        $dispatcher->dispatch(FOSUserEvents::REGISTRATION_COMPLETED, new FilterUserResponseEvent($user, $request, $response));

        return $response;
    }

    return $this->render('FOSUserBundle:Registration:register.html.twig', array(
        'form' => $form->createView(),
    ));
}

There is my JSON request

{
"email_address": "$email",
"status": "subscribed",
"merge_fields": {
    "FNAME": "$name",
    "LNAME": "$lastname",
    "DATE": "$date"

} }

So, how can i do to execute this JSON with this controller ?

Thank you in advance for your help (and sorry for my excellent english)

Upvotes: 1

Views: 1028

Answers (2)

Carca
Carca

Reputation: 594

You can achieve this also using JsonResponse (Symfony\Component\HttpFoundation\JsonResponse)

   use Symfony\Component\HttpFoundation\JsonResponse;
    ...
// if you know the data to send when creating the response
$data = [
    'email_address' => $email,
    'status' => 'subscribed',
    'merge_fields' => [
        'FNAME' => $name,
        'LNAME' => $lastname,
        'DATE' => $date,
    ]
];
$response = new JsonResponse($data);
return $response;

More details here https://symfony.com/doc/current/components/http_foundation.html

Upvotes: 0

OK sure
OK sure

Reputation: 2646

You probably want to create the JSON from an array rather than try to pass variables. Try:

$data = [
    'email_address' => $email,
    'status' => 'subscribed',
    'merge_fields' => [
        'FNAME' => $name,
        'LNAME' => $lastname,
        'DATE' => $date,
    ],
];
$json = json_encode($data);

Then I'm assuming this data gets sent to MailChimp in a POST request? If so, you could use Guzzle to send the data to MailChimp:

First add the guzzle dependency in composer by running:

composer require guzzlehttp/guzzle

Then send the data:

$client = new \GuzzleHttp\Client();
$response = $client->request('POST', 'https://MAILCHIMP_URL', ['body' => $data]);

To send JSON instead of raw data, do the following:

$client = new \GuzzleHttp\Client();
$response = $client->request('POST', 'https://MAILCHIMP_URL', ['json' => $data]);

Depending on the response status, you can then handle the logic afterwards.

Upvotes: 1

Related Questions