-3

I am sending data from a controller to a service, but Symfony is not able to use data.

The controller receives the data from a fetch POST within the React app, then sends it to the service via $this->updateUser->updateUser($gUpdateUser); :

 /**
 * @Route("/update-user", name="update_user")
 */
public function updateUser(Request $request)
{
    $gCreds = json_decode('[' . $request->getContent() . ']');
    $gFirstName = $gCreds[0]->firstname;
    $gLastName = $gCreds[0]->lastname;
    $gAddress1 = $gCreds[0]->address1;
    $gAddress2 = $gCreds[0]->address2;
    $gCity = $gCreds[0]->city;
    $gState = $gCreds[0]->state;
    $gPostalCode = $gCreds[0]->postal_code;

    $username = $this->getUser()->getUsername();

    $gUpdateUser = $this->json([
        'username' => $username,
        'firstname' => $gFirstName,
        'lastname' => $gLastName,
        'address1' => $gAddress1,
        'address2' => $gAddress2,
        'city' => $gCity,
        'state' => $gState,
        'postal_code' => $gPostalCode
    ]);

    return $this->updateUser->updateUser($gUpdateUser);
}

The service that has the updateUser function is the following:

  public function updateUser($usr) {
    $cnvrtJsonUsr = json_decode($usr, false);
    // dd($cnvrtJsonUsr);
    $updateQry = $this->em->createQueryBuilder('u')
        ->update(
            'u.firstname = "' . $cnvrtJsonUsr[0]->firstname . '", 
            u.lastname = "' . $cnvrtJsonUsr[0]->lastname . '",
            u.address1 = "' . $cnvrtJsonUsr[0]->address1 . '",
            u.address2 = "' . $cnvrtJsonUsr[0]->address2 . '",
            u.city = "' . $cnvrtJsonUsr[0]->city . '",
            u.state = "' . $cnvrtJsonUsr[0]->state . '",
            u.postal_code = "' . $cnvrtJsonUsr[0]->postal_code . '"'
        )
        ->where('u.username = "' . $cnvrtJsonUsr[0]->username . '"')
        ->getQuery();
    $retour = $updateQry->execute();
    return new Response($retour);
}

When I dd($cnvrtJsonUsr) - var_dump();die(); - it returns null:

When I dd($usr) the following is what I see in the response tab:

    UpdateUser.php on line 20:
Symfony\Component\HttpFoundation\JsonResponse {#972
    #data: "{"username":"test1@test.com","firstname":"testing","lastname":"taslkj","address1":"alkdjf","address2":"alkdsj","city":"adsfa","state":"ca","postal_code":"19823"}"
    #callback: null
    #encodingOptions: 15
    +headers: Symfony\Component\HttpFoundation\ResponseHeaderBag {#973
        #computedCacheControl: array:2 [
            "no-cache" => true
        "private" => true
    ]
        #cookies: []
        #headerNames: array:3 [
            "cache-control" => "Cache-Control"
        "date" => "Date"
        "content-type" => "Content-Type"
    ]
        #headers: array:3 [
            "cache-control" => array:1 [
            0 => "no-cache, private"
    ]
        "date" => array:1 [
            0 => "Mon, 18 May 2020 22:53:51 GMT"
    ]
        "content-type" => array:1 [
            0 => "application/json"
    ]
    ]
        #cacheControl: []
    }
    #content: "{"username":"test1@test.com","firstname":"testing","lastname":"taslkj","address1":"alkdjf","address2":"alkdsj","city":"adsfa","state":"ca","postal_code":"19823"}"
    #version: "1.0"
    #statusCode: 200
    #statusText: "OK"
    #charset: null
}

If I do not use dd, then I receive a 500 error

detail: Notice: Trying to get property 'firstname' of non-object

I have used json_decode before to turn JSON into an associated array, but that was Ajax posted to PHP.

Why is it different to send the following and have Symfony not see the JSON. More importantly, how do I get around this issue?

        $gUpdateUser = $this->json([
        'username' => $username,
        'firstname' => $gFirstName,
        'lastname' => $gLastName,
        'address1' => $gAddress1,
        'address2' => $gAddress2,
        'city' => $gCity,
        'state' => $gState,
        'postal_code' => $gPostalCode
    ]);

    return $this->updateUser->updateUser($gUpdateUser);
kronus
  • 902
  • 2
  • 16
  • 34

1 Answers1

-1

My solution was to pass an array from the controller to the services

public function updateUser(Request $request)
{
    $array = [];
    if ($content = $request->getContent()) {
        $array = json_decode($content, true);
    }

    $attemptUpdate = $this->updateUser->updateUser($array);
    $decodeJ = json_decode($attemptUpdate);

    if ($decodeJ->{'message'} == 'Success') {
        return new Response(json_encode(['username' => $this->getUser()->getUsername()]));
    } else {
        return new Response(json_encode(['message' => 'wtf']));
    }
}

From the custom service, I return JSON for the React component, which I treat as a service for the React app:

public function updateUser($usr) {
    $conn = $this->em->getConnection();

    $sql = "update user set first_name = '" . $usr["firstname"] . "'," .
            " last_name = '" . $usr["lastname"] . "'," .
            " address1 = '" . $usr["address1"] . "'," .
            " address2 = '" . $usr["address2"] . "'," .
            " city = '" . $usr["city"] . "'," .
            " state = '" . $usr["state"] . "'," .
            " postal_code = '" . $usr["postal_code"] . "'" .
            " where email = '" . $this->security->getUser()->getUsername() . "'";

    $stmt = $conn->prepare($sql);
    $stmt->execute();
    if ($stmt) {
        return json_encode(['message' => 'Success']);
    } else {
        return json_encode(['message' => 'wtf']);
    }
}

The React component which acts as a service:

import React, {Component} from 'react';
import Notifications from './Notifications';


export class UpdateServices extends Component {
    static getInstanceUpdate() {
        return new UpdateServices();
    }

    constructor(props) {
        super(props);
        this.state={
            errMsg: ''
        }
    }

    async updateService(url, fname, lname, ad1, ad2, city, st, zip) {

        const requestOptions = {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'Accept': 'application/json',
                'credentials': "same-origin",
                'Authorization': 'Basic ' + btoa('gold:sold')
            },
            body: JSON.stringify({
                'firstname' : fname,
                'lastname' : lname,
                'address1' : ad1,
                'address2' : ad2,
                'city': city,
                'state': st,
                'postal_code': zip
            })
        };
        await fetch(url, requestOptions)
            .then( response => response.json())
            .then( response => Notifications.getInstance().messages(response))
            .catch((response) => {
                Notifications.getInstance().messages200('', usrn);
            });
    }
}

export default UpdateServices;
kronus
  • 902
  • 2
  • 16
  • 34