I am trying to send by ajax a property (color) of an entity (product). If I send it this way, it sends me the product id correctly:
public function source(Request $request): Response
{
$producto=$request->request->get('color');
if ($request->isXMLHttpRequest())
{
return new JsonResponse($producto);
}
return new Response('This is not ajax!', 400);
}
but if I try to send the color directly like this:
public function source(Request $request): Response
{
$producto=$request->request->get('color');
if ($request->isXMLHttpRequest())
{
return new JsonResponse($producto->getColor());
}
return new Response('This is not ajax!', 400);
}
It gives me the following error: Call to a member function getColor() on string
in this line of code: return new JsonResponse($producto->getColor());
I've been thinking about it for a day and I don't know why the error could be. By the way, indicate that the color property is a string. All the best.
When you are doing:
You're retrieving the value of a POST parameter called color, so the value of the variable
$producto
is the color, not the entityProducto
. What you are returning in the first example is not the product ID, but the color value. So as not to confuse me, I am going to call that variable$idColor
.If what you want is to obtain the entity
Producto
from the color property, you must go to look for it:And there you would already have the object to obtain the data you want.
For example, if what you want is to return the product ID, it would be:
And if what you want to return is the color, it would be to return
$producto->getColor()
I hope I can serve you