my problem is :
The data returned have \u0022 instead of "".
$em=$this->getDoctrine()->getManager();
$result = $em->getRepository('HomeBundle:Product')->findAll();
$encoders = array(new XmlEncoder(), new JsonEncoder());
$normalizers = array(new ObjectNormalizer());
$serializer = new Serializer($normalizers, $encoders);
$jsonContent = $serializer->serialize($result,'json');
$response = new JsonResponse($jsonContent);
$response->headers->set('Content-Type', 'application/json');
return $response;
and that's what i get
"[{\u0022id\u0022:1,\u0022name\u0022:\u0022opp\u0022,\u0022price\u0022:3},{\u0022id\u0022:2,\u0022name\u0022:\u0022opp\u0022,\u0022price\u0022:5},{\u0022id\u0022:3,\u0022name\u0022:\u0022oppv\u0022,\u0022price\u0022:16},{\u0022id\u0022:4,\u0022name\u0022:\u0022opp\u0022,\u0022price\u0022:6},{\u0022id\u0022:5,\u0022name\u0022:\u0022opp\u0022,\u0022price\u0022:7},{\u0022id\u0022:6,\u0022name\u0022:\u0022opp\u0022,\u0022price\u0022:34},{\u0022id\u0022:7,\u0022name\u0022:\u0022opp\u0022,\u0022price\u0022:56},{\u0022id\u0022:8,\u0022name\u0022:\u0022opp\u0022,\u0022price\u0022:30}]"
thanks in advance for your help
As your entities are already serialised, change your JsonResponse to a Response :
use Symfony\Component\HttpFoundation\Response;
// ...
$response = new Response($jsonContent);
$response->headers->set('Content-Type', 'application/json');
return $response;
Or decode your results before create your JsonResponse :
return new JsonResponse(json_decode($jsonContent));
Note that the Content-Type of a JsonResponse is automatically application/json, no need to set it.
Related
I am trying to remove this error message:
User Deprecated: The
"Symfony\Component\Serializer\Normalizer\AbstractNormalizer::setCircularReferenceHandler()"
method is deprecated since Symfony 4.2, use the
"circular_reference_handler" key of the context instead.
Here is my code:
$encoder = new JsonEncoder();
$normalizer = new ObjectNormalizer();
$normalizer->setCircularReferenceHandler(function ($object, string $format = null, array $context = []) {
return $object->getName();
});
I made a composer update and cache clear. But nothing helps.
The error message tells that you should give it in the defaultContext array you can give that as third parameter in the costructor.
public function __construct(ClassMetadataFactoryInterface
$classMetadataFactory = null, NameConverterInterface $nameConverter = null, array $defaultContext = array())
in your case it would be:
$encoders = array(new JsonEncoder());
$normalizer = new JsonSerializableNormalizer(null,null,array(JsonSerializableNormalizer::CIRCULAR_REFERENCE_HANDLER=>function ($object) {
return (string)$object;
}));
EDIT:
I was using a JsonSerializableNormalizer and you an ObjectNormalizer then the constructor definition is:
public function __construct(ClassMetadataFactoryInterface $classMetadataFactory = null, NameConverterInterface $nameConverter = null, PropertyAccessorInterface $propertyAccessor = null, PropertyTypeExtractorInterface $propertyTypeExtractor = null, ClassDiscriminatorResolverInterface $classDiscriminatorResolver = null, callable $objectClassResolver = null, array $defaultContext = array())
and used in your program it should be:
$normalizer = new ObjectNormalizer(null,null,null,null,null,null,array(ObjectNormalizer::CIRCULAR_REFERENCE_HANDLER=>function ($object) {
return (string)$object;
}));
you should use it (circular_reference_handler) as configuration key.
For example,
serializer:
circular_reference_handler: App\Service\YourHandlerService
I tried it in framework.yaml and it works.
When serializing Entity which has relations to another entiyty.
A circular reference has been detected when serializing the object of class happens, if you don't set setCircularReferenceLimit and setCircularReferenceHandler.
It sloveed the problem before symfony3.2 but now Symofony4.1.6,Error: Maximum execution time of 30 seconds exceeded happens and timeout.
Where should I check????
$encoders = array(new XmlEncoder(), new JsonEncoder());
$norm = new ObjectNormalizer();
//// it fixes the problem before Symfony 3.2, but no it causes timeout
$norm->setCircularReferenceLimit(0);
$norm->setCircularReferenceHandler(function ($object) {
return $object->getId();
});
//////////
$normalizers = array($norm);
$serializer = new Serializer($normalizers, $encoders);
/// get entity from doctorine2//
$myEntity = ....
$jsonContent = $serializer->serialize($myEntity, 'json');
my Error is
in vendor/symfony/property-access/PropertyAccessor.php (line 372)
$result = self::$resultProto;
$object = $zval[self::VALUE];
$access = $this->getReadAccessInfo(\get_class($object), $property);
if (self::ACCESS_TYPE_METHOD === $access[self::ACCESS_TYPE]) {
$result[self::VALUE] = $object->{$access[self::ACCESS_NAME]}();
} elseif (self::ACCESS_TYPE_PROPERTY === $access[self::ACCESS_TYPE]) {
$result[self::VALUE] = $object->{$access[self::ACCESS_NAME]};
if ($access[self::ACCESS_REF] && isset($zval[self::REF])) {
$result[self::REF] = &$object->{$access[self::ACCESS_NAME]};
I'm working on getting some google analytics api stats and am able to get metrics just fine using this...
$results = getResults($analytics, $profile->getId(), $value);
$rows = $results->getRows();
$myvalue = $rows[0][0];
echo "<b>$value:</b> ". round($myvalue, 0) ."</br>";
but the below code throws an error (see post title) when I call batchGet using same analytics object that works in above code. Unsure why or if there is an alternative way to get the dimension data I'm after.
$device = new Google_Service_AnalyticsReporting_Dimension();
$device->setName("ga:deviceCategory");
// Create the ReportRequest object.
$request = new Google_Service_AnalyticsReporting_ReportRequest();
$request->setDimensions(array($device));
$body = new Google_Service_AnalyticsReporting_GetReportsRequest();
$body->setReportRequests( array( $request) );
return $analytics->reports->batchGet( $body );
Here is how I instantiate the $analytics object
function getService()
{
// service account email, and relative location of your key file.
$service_account_email = 'email#gserviceaccount.com';
$key_file_location = 'pathto/file.p12';
// Create and configure a new client object.
$client = new Google_Client();
$client->setApplicationName("Analytics");
$analytics = new Google_Service_Analytics($client);
$key = file_get_contents($key_file_location);
$cred = new Google_Auth_AssertionCredentials(
$service_account_email,
array(Google_Service_Analytics::ANALYTICS_READONLY),
$key
);
$client->setAssertionCredentials($cred);
if($client->getAuth()->isAccessTokenExpired()) {
$client->getAuth()->refreshTokenWithAssertion($cred);
}
return $analytics;
}
Still don't know why batchGet throws an error, but the code below works and will return the deviceCategories.
$optParams = array(
'dimensions' => 'ga:deviceCategory',
'filters' => 'ga:medium==organic');
$devices = $analytics->data_ga->get(
'ga:'.$profile->getId(),
'2015-05-01',
'2015-05-15',
'ga:sessions',
$optParams);
print_r($devices);
I've looked at this question but it doesnt work for me.
my controller looks like:
/**
* #Route("/testing")
*/
public function trackingNewsletter() {
$filename = 'T:\wamp\www\trendytouristmx\web\uploads\establishments\1-37.jpg';
$response = new \Symfony\Component\HttpFoundation\Response();
$response->headers->set('Cache-Control', 'private');
$response->headers->set('Content-type', mime_content_type($filename));
$response->headers->set('Content-Disposition',
'attachment; filename="' . basename($filename) . '";');
$response->headers->set('Content-length', filesize($filename));
$response->sendHeaders();
$response->setContent(file_get_contents($filename));
return $response;
}
But in the browser code is displayed instead of the image displayed:
browser looks like this
Thank you.
There is a special class which is designed for binary file response. I would recommend to use it instead. More info BinaryFileResponse
//$filePath = ...
//$filename = ...
$response = new BinaryFileResponse($filePath);
$response->trustXSendfileTypeHeader();
$response->setContentDisposition(
ResponseHeaderBag::DISPOSITION_INLINE,
$filename,
iconv('UTF-8', 'ASCII//TRANSLIT', $filename)
);
return $response;
You have to do :
public function trackingNewsletter() {
$path = 'T:\wamp\www\trendytouristmx\web\uploads\establishments\1-37.jpg';
$response = new Symfony\Component\HttpFoundation\Response();
$response->headers->set('Content-type', mime_content_type($path));
$response->headers->set('Content-length', filesize($path));
$response->sendHeaders();
$response->setContent(readfile($path));
}
Thank you #chalasr, finally it works, here's a solution:
first, I removed $response->headers->set('Cache-Control', 'private');
second, I changed the value of Content-Disposition from attachment to inline.
/**
* #Route("/tracking")
*/
public function trackingnewsletterAction() {
$filename = '...\establishments\1-39.jpg';
$response = new \Symfony\Component\HttpFoundation\Response();
$response->headers->set('Content-type', mime_content_type($filename));
$response->headers->set('Content-Disposition',
'inline; filename="' . basename($filename) . '";');
$response->headers->set('Content-length', filesize($filename));
$response->sendHeaders();
$response->setContent(file_get_contents($filename));
return $response;
}
How do I return a response in Symfony to output a pdf? I'm currently using FPDF as I don't want to use any bundles. Here is my controller action:
public function pdfAction(Request $request) {
//grab from database
$pdf = new \FPDF;
for($i = 0; $i < count($entities); $i++) {
//manipulate data
$pdf->AddPage();
$pdf->SetFont("Helvetica","","14");
$pdf->SetTextColor(255, 255, 255);
}
$pdf->Output();
return new Response($pdf, 200, array(
'Content-Type' => 'pdf'));
}
With this all I'm getting is a page with gibberish characters. I'm quite new to I/O manipulations so any help would be great. Thank you..
You need to set proper Content-Type of your response. Also, don't send your FPDF object as a content of your response, but rather the PDF output. Try this:
public function pdfAction(Request $request) {
//................//
return new Response($pdf->Output(), 200, array(
'Content-Type' => 'application/pdf'));
}
UPDATE:
To get your generated PDF file downloaded instead of displayed, you need to set disposition to attachment:
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\ResponseHeaderBag;
public function pdfAction(Request $request) {
//................//
$response = new Response(
$pdf->Output(),
Response::HTTP_OK,
array('content-type' => 'application/pdf')
);
$d = $response->headers->makeDisposition(
ResponseHeaderBag::DISPOSITION_ATTACHMENT,
'foo.pdf'
);
$response->headers->set('Content-Disposition', $d);
return $response;
}
http://symfony.com/doc/current/components/http_foundation/introduction.html#serving-files
In symfony 2.7, I'm having a "Corrupted content" while trying to set the Content-Disposition. My fix is:
public function pdfAction(Request $request) {
//................//
$response = new Response(
$pdf->Output(),
Response::HTTP_OK,
array('content-type' => 'application/pdf')
);
return $response;
}