Symfony2 outputting pdf using FPDF - symfony

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;
}

Related

How to set locale in controller

In my SilverStripe project I have a controller which I call by a cronjob. But in this controller I want to use the translations from the yaml language files. So I want to set the locale to use the right translations. I tried to do something like this, but this doesn't work:
class CronController extends Controller {
public function opendataform() {
i18n::set_locale('it_IT');
$Params = $this->getURLParams();
self::$ad = $Params['ID'];
$selectMemberSelectionField = new DropdownField('SelectionName', _t('General.CHOOSE_SELECTION', "Choose selection"), MemberSelection::get()->map('ID', 'Name'));
$fields = new FieldList($selectMemberSelectionField);
$actions = new FieldList(
FormAction::create("doOpen")->setTitle(_t('General.Open', "Open"))
);
$form = new Form($this, 'OpenForm', $fields, $actions);
return $form;
}
}
Also tried with: Translatable::set_current_locale('it_IT');
Any suggestions? Thanks in advance!

Call to a member function batchGet() on a non-object

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);

FOSRestBundle: just trying to return an empty form for new elements

I have this code to response with a form to create new customers:
public function getNewAction()
{
$form = new CustomerType();
$view = $this->view($form, 200)
->setTemplate("PlacasFrontendBundle:Customer:newCustomer.html.twig")
;
return $this->handleView($view);
}
but when I request http://crm/app_dev.php/new the only I get rendered on browser is this:
{}
NOTE: I don't have any problems with this function below. I mean it returns a jsoned list of customers correctly:
public function getCustomersAction()
{
$repository = $this->getDoctrine()->getRepository('PlacasFrontendBundle:Customer');
$data = $repository->findAll();
$view = $this->view($data, 200)
->setTemplate("PlacasFrontendBundle:Customer:getUsers.html.twig")
->setTemplateVar('users')
;
return $this->handleView($view);
}
public function getNewAction()
{
$form = new CustomerType();
$view = $this->view($form, 200)
->setTemplate("PlacasFrontendBundle:Customer:newCustomer.html.twig")
->setHeader('Content-Type', 'text/html')
;
return $this->handleView($view);
...
You need to set the proper Content-Type header.

Symfony2 form validation without createFormBuilder

I am trying to validate the form that I have made myself in .twig file.I am not creating form using createFormBuilder. This is my Controller Code that is call for both case 1) for view 2) after submitting the form.
public function cart_newAction(Request $request)
{
$entity = new Product();
$errors = '';
if ($request->getMethod() == 'POST')
{
$validator = $this->get('validator');
$errors = $validator->validate($entity);
if (count($errors) > 0) {
echo 'Error';
}
else {
echo 'Success';
}
}
return $this->render('CartCartBundle:Cart:Add.html.twig', array('errors' => $errors ));
}
this is view file and I am showing errors like this
Add.html.twig
{% for error in errors %}
{{error}}
{% endfor %}
I have set the error in validation.yml file for name that cannot be blank.
So now when I run the view page it every times show the error after I submit the form.
If no error it should not display me the error just show the blank error.
Note:Is there any better way that I can do this so please share it.Remember that I am doing it without createFormBuilder
UPDATE
It always show me Error.Even if my form is valid and don't missing any field.
If you want to make the form yourself then you can't validate it using the Syfmony form validator. You need to use a simple PHP validation Server-side. Something like this
if ($request->getMethod() == 'POST')
{
$username = $_POST['username'];
if ($username == '')
{
// set error message here
}
}
Ok let me be clear. I gonna give you tow solutions, the first is the best and the most proper way:
1) Generate your EntityForm Type: bin/console make:form or d:g:form command.
2) Then just add some few lines to submit and get the errors.
public function cart_newAction(Request $request)
{
$entity = new Product();
$form = $this->createForm(EntityType::class, $entity);
$form->submitForm($request->request->all(), false);
if ($request->getMethod()->isPost())
{
if ($form->isValid()) {
echo 'Error';
}
else {
echo 'Success';
}
}
return $this->render('CartCartBundle:Cart:Add.html.twig', [
'errors' => $form->getErrors(),
]);
}
The second solution is bind your data into your entity object because we need to set the data into our object.
1) First step create a private fonction in your current class to bind all the submited data:
private function bindEntityValues(Product $entity, array $data) {
foreach ($data as $key => $value){
$funcName = 'set'+ucwords($key);
if(method_exists($entity, $funcName)) $entity->$funcName($value);
}
}
Then your cart_newAction should be like this:
public function cart_newAction(Request $request)
{
$entity = new Product();
$this->bindEntityValues(entity, $request->request->all());
$errors= $this->get('validator')->validate($entity)
if (count($errors) > 0) {
echo 'Error';
}
else {
echo 'Success';
}
}
return $this->render('CartCartBundle:Cart:Add.html.twig', ['errors' => $errors]);
}
Wish this helped you to have a clear vision.
You must check if $errors is empty or not :
if (count($errors) > 0) {
return $this->render('CartCartBundle:Cart:Add.html.twig', array('errors' => $errors ));
} else {
return $this->render('CartCartBundle:Cart:Add.html.twig');
}
See the doc here.

How to attach files with metaWeblog to a blog post?

I'm trying to post to my blog with images.
Yes, I can upload images and I can see that images in the content of post
but it's not in a attached file list.
How can I put the images that I upload in the attached file list?
When I'm posting with MS word 2010 to my blog, images that I put on the word are always updated in a attached file list. But my php source doesn't.
Is there any way to attach files to a blog post?
$cBlog = new blog;
$title = "This is a article's title";
$desc = "IT will be the content";
$return = $cBlog->writePost($title, $desc);
class blog
{
public $g_blog_url;
public $user_id;
public $blogid;
public $password;
public $publish;
function __construct()
{
$this->g_blog_url = "https://api.blog.naver.com/xmlrpc";
$this->user_id = "globeseen";
$this->blogid = "globeseen";
$this->password = "password";
$this->publish = true;
}
function writePost($title, $description, $category="")
{
$client = new xmlrpc_client($this->g_blog_url);
$client->setSSLVerifyPeer(false);
$GLOBALS['xmlrpc_internalencoding']='UTF-8';
$img = $this->upload_image("D:\\1.jpg");
$struct = array(
'title' => new xmlrpcval($title, "string"),
'description' => new xmlrpcval($description."<img src=$img>", "string"),
'categories' => new xmlrpcval($category, "string"),
'tags' => new xmlrpcval('clothing', "string")
);
$f = new xmlrpcmsg("metaWeblog.newPost",
array(
new xmlrpcval($this->blogid, "string"),
new xmlrpcval($this->user_id, "string"),
new xmlrpcval($this->password, "string"),
new xmlrpcval($struct , "struct"),
new xmlrpcval($this->publish, "boolean")
));
$f->request_charset_encoding = 'UTF-8';
return $response = $client->send($f);
}
function upload_image($fpath) {
global $api_url, $blog_user, $blog_passwd;
$api_url = $this->g_blog_url;
$blog_user = $this->user_id;
$blog_passwd = $this->password;
$imgbit = file_get_contents($fpath, FILE_BINARY);
$img = new xmlrpcval(
array (
'bits' => new xmlrpcval($imgbit, 'base64'),
'type' => new xmlrpcval('image/jpeg', 'string'),
'name' => new xmlrpcval(basename($fpath), 'string')
), 'struct');
$c = new xmlrpc_client($api_url);
$c->setSSLVerifyPeer(false);
$x = new xmlrpcmsg("metaWeblog.newMediaObject");
$x->addParam(new xmlrpcval($blog_user, 'string'));
$x->addParam(new xmlrpcval($blog_user, 'string'));
$x->addParam(new xmlrpcval($blog_passwd, 'string'));
$x->addParam($img);
$c->return_type = 'phpvals';
$r =$c->send($x);
if ($r->errno=="0") {
return $r->val['url'];
} else {
echo "There was an error<pre>";
print_r($r);
echo "</pre>";
return null;
}
}
}

Resources