How do I create reports in Symfony2? - symfony

Im creating an application un Symfony2.7 and I want to start creating reports, I have been reading for a couple of days and cant find a solution.
Ive tried ps pdfbundle, but I cant generate reports. Cant find more Documentation.
Please help
My Code:
public function formatoOcAction($id)
{
$facade = $this->get('ps_pdf.facade');
$response = new Response();
$em = $this->getDoctrine()->getManager();
$InOc = $em->getRepository('NivalInventarioBundle:InOrdenCompra')->findById($id);
$InOcDet = $em->getRepository('NivalInventarioBundle:InOrdenCompraDetalle')->findBy(array(
'idOrdenCompra' => $id));
$stylesheetXml = $this->renderView('NivalInventarioBundle:InOrdenCompra:ordencompra.xml.twig', array());
$this->render('NivalInventarioBundle:InOrdenCompra:ordencompra.pdf.twig', array(
"entities1" => $InOc,
"entities2" => $InOcDet,
"id" => $id),
$response);
$xml = $response->getContent();
$content = $facade->render($xml, $stylesheetXml);
$filename = $this->getParameter('upload_directory').'orden_compra_'.$id.'.pdf';
file_put_contents($filename, $content);
return new Response($content, 200, array('content-type' => 'application/pdf'));
}
Where $id is the Id of the purchase order.
This renders a xml file to PDF but without sylesheet.
This is the twig:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE pdf SYSTEM "%resources%/dtd/doctype.dtd">
{% set empresa = app.session.get('empresa') %}
<pdf>
<page>
<div>
<div>
<table>
<tr>
<td>
<h3>{{ empresa }}</h3>
</td>
<td id="s1">
<h2>NĂºmero: <b>{{ id }}</b></h2>
</td>
</tr>
<tr>
<td></td>
<td>
<h3>Orden de compra</h3>
</td>
</tr>
<tr>
<td></td>
<td>
Departamento de Finanzas
</td>
</tr>
</table>
</div>
<div>
{% for entity1 in entities1 %}
Fecha: {{ entity1.fecha|date('d-m-Y') }}
{% endfor %}
</div>
</div>
<div>
<div>
<table width="100%">
<tr>
<td width="60%">Producto</td>
<td width="20%">Unidad</td>
<td>Cantidad</td>
<td>Precio</td>
<td>Total</td>
</tr>
{% set gran_total = 0 %}
{% for entity2 in entities2 %}
<tr>
<td>{{ entity2.productoOc.nombre }}</td>
<td>{{ entity2.productoOc.unidadMedida.nombre }}</td>
<td class="text-right">{{ entity2.cantidad }}</td>
<td class="text-right">{{ entity2.precioCompra }}</td>
<td class="text-right">{{ entity2.total }}</td>
</tr>
{% set gran_total = gran_total + entity2.total %}
{% endfor %}
<tr>
<td></td><td></td><td></td><td></td>
<td class="text-right" >{{ gran_total|number_format(2) }}</td>
</tr>
</table>
</div>
</div>
</page>
</pdf>

Maybe look at the KnpSnappyBundle which allow you to generate PDF file from many sources, including twig templates : http://knpbundles.com/KnpLabs/KnpSnappyBundle

You have at least two options to choose from. I found easiest to work with:
Github KnpLabs/snappy as mentioned by Cyrille Hejl
PDF creator from html content, but in your report controller you would have to do all the work of creating:
header html from twig template
footer html from twig template
cover page html from twig template
toc XML from twig template
base document html from twig template
adding all mentioned html docs to object $pdf = $this->get('knp_snappy.pdf');
PROS:
easy to work with Twig html
no memory exhaust if entity object with relations is supplied to Twig (on longer documents)
CONS:
have to supply html files from Twig template for each joined page (cover, toc, header, footer, base doc)
needed tinkering with right wkhtmltopdf binary version
Github mbence/OpenTBSBundle
This is template merger. In your report controller you will have to supply office template and all the variables, that are replaced with TBS at e.g. word template:
it supports OpenOffice and MSOffice templates
PROS:
customer supplies template, you just replace dynamic content with variables (customer takes care of document design)
CONS:
it could run to memory exhaust problems, since PHP script holds all input variables or arrays in memory.
harder to understand than Twig html (longer learning curve)

I recommend to use: WhiteOctoberTCPDFBundle, it's a bundle to facilitate using TCPDF for PDF generation in Symfony2 applications, great to make the reports we need. Please go to: https://github.com/whiteoctober/WhiteOctoberTCPDFBundle

Related

How should i use if else and for loop with .hbs file (Handlebars.js)?

I know how can i use if else statement or for loop using .ejs file but i need to change code in .hbs file and i am new with this.Please help me with below example in which i have used .ejs file i need to convert it in .hbs file but don't know how to change if else and for loop
<!DOCTYPE html>
<html lang="en">
<head>
<title>Fetch using MySQL and Node.js</title>
</head>
<body>
<div class="table-data">
<h2>Display Data using Node.js & MySQL</h2>
<table border="1">
<tr>
<th>S.N</th>
<th>Full Name</th>
<th>Email Address</th>
<th>City</th>
<th>Country</th>
<th>Edit</th>
<th>Delete</th>
</tr>
<%
if(userData.length!=0){
var i=1;
userData.forEach(function(data){
%>
<tr>
<td><%=i; %></td>
<td><%=data.fullName %></td>
<td><%=data.emailAddress %></td>
<td><%=data.city %></td>
<td><%=data.country %></td>
<td>Edit</td>
<td>Delete</td>
</tr>
<% i++; }) %>
<% } else{ %>
<tr>
<td colspan="7">No Data Found</td>
</tr>
<% } %>
</table>
</div>
</body>
</html>
I have used below code but it is not working as i am new i need your guidence
#76484 i have used this ``` {{#if userData.length != 0 }}
{{var i =1;}}
{{userData.forEach(function(data))}}
<tr>
<td>{{=i;}}</td>
<td>{{= data.fullName}}</td>
<td>{{= data.emailAddress}}</td>
<td>{{= data.city}}</td>
<td>{{= data.country}}</td>
<td>{{= data.Dimension_4_Score}}</td>
<td>{{= data.Total_Score_Persentage}}</td>
</tr>
{{i++; })}}
{{else{} }
<tr>
<td colspan="7">No Data Found</td>
</tr>
{{}}}
</table>
</div>
</body> ``` but it is not working
The primary difference between your embedded JS example and Handlebars is that Handlebars does not execute arbitrary JavaScript, like your .forEach loop. Instead, Handlebars provides helpers to allow you to do things like conditionals and iteration.
First, we will tackle your condition, if (userData.length != 0). Handlebars has a #if helper which we could use to check if userData has a truth (greater than 0) length. The result would be:
{{#if userData.length}}
{{! TODO: output each user data}}
{{else}}
<tr>
<td colspan="7">No Data Found</td>
</tr>
{{/if}}
Secondly, Handlebars has an #each helper which is used for looping over collections as you are doing with your userData.forEach(function(data) { /*...*/ } code. For your purposes, the syntax would be:
{{#each userData}}
<tr>
<td>{{ #index }}</td>
<td>{{ fullName }}</td>
<td>{{ emailAddress }}</td>
<td>{{ city }}</td>
<td>{{ country }}</td>
<td>Edit</td>
<td>Delete</td>
</tr>
{{/each}}
Notice how we are evaluating the properties of each object in our userData array. There is no =. We just wrap the property name in double-handlebars, like {{ fullName }}. Handlebars handles the execution context within the #each so that we are always referring to the current iteration of our array.
Also notice the {{ #index }}. This is a special variable provided by Handlebars to give us the current iteration index within our #each loop. It is zero-index, so our output will be slightly different from your ejs example because you initialized your counter at 1.
Unfortunately, if we want our indexes to be one-based, we will have to write a custom helper to this. Our helper would just need to take a number, #index, and increment it by 1. It would look like:
Handlebars.registerHelper('increment', function (num) {
return num + 1;
});
And we would update our template to make use of it:
{{increment #index }}
I have created a fiddle with the final example for your reference.

Update only a single property of a given object

I have an entity called worker and each worker has a property called active which is boolean.
My twig is an index that shows the list of workers with active=true.
I have a button in front of each worker, when I press this button I want it to change that worker's active property to false.
The problem: I couldn't figure out how to change that value in the controller without making a form since I'm still an amateur when it comes to Symfony
Here's my twig:
<table id="file_export" class="table table-striped table-bordered">
<thead>
<tr>
<th>ID</th>
<th>First Name</th>
<th>Last name</th>
<th>Active</th>
<th>edit</th>
</tr>
</thead>
<tbody>
{% for worker in workers %}
<tr>
<td>{{ worker.id }}</td>
<td>{{ worker.Firstname }}</td>
<td>{{ woker.Lastname }}</td>
<td>{{ worker.active ? 'active' : 'inactive' }}</td>
<td>
<i class="fa fa-pencil"></i>
</td>
</tr>
{% endfor %}
</tbody>
</table>
and my controller (which doesn't work):
/**
* #Route("/{id}/edit", name="worker_edit", methods={"GET","POST"})
*/
public function edit(Request $request, Worker $worker): Response
{
if ($this->isCsrfTokenValid('edit'.$worker->getId(), $request->request->get('_token'))) {
$worker->setActive(false);
$entityManager = $this->getDoctrine()->getManager();
$entityManager->persist($worker);
$entityManager->flush();
}
return $this->redirectToRoute('index');
}
you actually have to add a csrf token to your path call:
path('worker_edit', {'id': worker.id, '_token': csrf_token('worker'~worker.id)})
or otherwise your check for the csrf token obviously cannot succeed.
however, since a link will trigger a GET request, you have to look into
$request->query->get('_token')
in the isCsrfTokenValid call.
As a hint: give your routes and actions semantically better names. Like ... "worker_deactivate", if it is used to deactivate a worker (which it apparently is). it's also quite common, to call the routed methods of a controller actionAction, so that would be deactivateAction.
If you want to make HTTP requests without reloading the web page, then you've to go for AJAX calls. A very simple implementation using fetch that doesn't require any additional packages (like jQuery) would look like this:
<script>
(function() {
document.getElementById({{worker.id}}).addEventListener('click', function(e) {
e.preventDefault();
fetch({{path('worker_edit', {'id': worker.id})}}, {method: 'POST'})
.then(function(response) {
// you can catch eventual errors here, and of course refresh your button or display a nice message..
});
});
})()
</script>
<table id="file_export" class="table table-striped table-bordered">
<thead>
<tr>
<th>ID</th>
<th>First Name</th>
<th>Last name</th>
<th>Active</th>
<th>edit</th>
</tr>
</thead>
<tbody>
{% for worker in workers %}
<tr>
<td>{{ worker.id }}</td>
<td>{{ worker.Firstname }}</td>
<td>{{ woker.Lastname }}</td>
<td>{{ worker.active ? 'active' : 'inactive' }}</td>
<td>
<i class="fa fa-pencil"></i>
</td>
</tr>
{% endfor %}
</tbody>
</table>
p.s: The javascript code above is not tested as I have to reproduce the twig and controller, but it could give you an idea on how to achieve the task.

Which is best paginator for in doctrine symfony2?

I have written custom queries in my repository class and they returns arrays then I do some processing on those arrays then displays to twig.
So please suggest the best pagination method to apply paging on this custom queries resulting in arrays.
I am new to symfony2, does default paging will work and how? I mean what syntax, please provide example.
You should try Knp Paginator. It is simple and customizable.
Simple code example (Doctrine MongoDB ODM):
// Pay attention: query, not result.
$query = $this->getRepositoryOfferKind()->createQueryBuilder()
->field('is_private')->equals(false)
->field('is_deleted')->notEqual(true)
->sort('updated_at', 'DESC')->getQuery();
$paginator = $this->get('knp_paginator');
$pagination = $paginator->paginate($query, $request->get('page', 1), 20);
/* #var $pagination SlidingPagination */
$pagination->setUsedRoute('admin_offer_kind_index');
$pagination->setPageRange(10);
return array(
'objects' => $pagination,
);
And twig:
<table>
<thead>
<tr>
<th>Title</th>
</tr>
</thead>
<tbody>
{% for object in objects %}
<tr>
<td>
{{ object.title }}
</td>
</tr>
{% else %}
<tr>
<td>No data</td>
</tr>
{% endfor %}
</tbody>
<tfoot>
<tr>
<td>
{{ knp_pagination_render(objects) }}
</td>
</tr>
</tfoot>
</table>
You can try this native solution
public function getPagination($someValue, int $page = 1, $limit = 20, $sort = "createdAt", $sortOrder = 'DESC')
{
$qb = $this->createQueryBuilder();
$qb->field('some_filed')->equals($someValue);
// and so on
return $qb->sort($sort, $sortOrder)
->skip(($page - 1) * $limit)
->limit($limit)
->getQuery()->toArray();
}

Laravel 4 email template styling

I'm trying to give a style to my email template using bootstrap but every time what laravel is doing is, it parses the template and adds a '3D' where ever there is '=' in the template, which results in style=3D"table" instead of style="table", here is a snippet of the mail source code
<div class=3D"well">
<table class=3D"table table-bordered table-striped" id=3D'table'>
<thead>
<th>Group Name</th>
<th>Kpi Name</th>
<th>User Name</th>
</thead>
<tbody>
</tbody>
</table>
</div>
here is my code for template
<html lang="en-US">
<head>
<meta charset="utf-8">
{{ HTML::style('app\\client\\css\\bootstrap.css') }}
{{ HTML::script('app\\javascripts\\js\\jquery-1.8.3.min.js') }}
{{ HTML::script('app\\client\\js\\bootstrap.min.js') }}
<style>
#table {
border: 2px solid #ccc;
border-radius: 5px;
}
</style>
</head>
<body>
<div class="well">
<table class="table table-bordered table-striped" id='table'>
<thead>
<th>Group Name</th>
<th>Kpi Name</th>
<th>User Name</th>
</thead>
<tbody>
#foreach ($groups as $group)
<tr>
<td>{{ $group['name'] }}</td>
<td>
<ul>
#if (array_key_exists('kpis', $group))
#foreach ($group['kpis'] as $kpi)
<li>{{ Kpi::find($kpi['kpi'])->title }}</li>
#endforeach
#endif
</ul>
</td>
<td>
<ul>
#if (array_key_exists('users', $group))
#foreach ($group['users'] as $user)
<li>{{ User::find($user['user'])->fName.' '.User::find($user['user'])->lName }}</li>
#endforeach
#endif
</ul>
</td>
</tr>
#endforeach
</tbody>
</table>
</div>
<footer>
<br>
<br>
Regards,<br>
<strong>Yogesh Joshi</strong><br>
Group Leader
</footer>
</body>
</html>
is there something I'm missing or there is some problem in laravel or mail-server (gmail or hotmail), and yeah I've cross checked the script and style files, they do exists in public folder.
please help or provide any alternate method for it.
For the =3D items, see this post: What's a 3D doing in this HTML?
And I see that you are trying to load javascript in your email, that's not a good idea. see: Is JavaScript supported in an email message?
And I am not sure about loading a stylesheet into a html email, so I will leave that one open.
Using Bootstrap in emails sounds a little bit overkill, but there's old project called Bootstrap Template for HTML Email. Not sure if this helps.
Also this question seems to be partially about the same subject as SO question "Has anyone gotten HTML emails working with Twitter Bootstrap?"
Probably easier to use HTML Email Boilerplate with just copied mini style sheet from your actual project.
Or if you're lazy, use the Mailchimp wysiwyg -editor and export it out of MC. They have really nice wysiwyg-editor and responsive templates. I've been using it and it saves some time and effort.

symfony2 multidelte records delete

i have a file called index which shows list of customer inquiry.
i want to put multiple delete in the that.
the code of my index file list is bellow.
{% block body -%}
<h1>Enquiry list</h1>
<table class="records_list" id="rounded-corner">
<thead>
<tr>
<th>Option</th>
<th>Id</th>
<th>Name</th>
<th>Email</th>
<th>Subject</th>
<th>Body</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
{% for entity in entities %}
<tr>
<td><input type="checkbox" name="multiSelect" id="multiSelect[]" value="{{ entity.id }}"></td>
<td>{{ entity.id }}</td>
<td>{{ entity.name }}</td>
<td>{{ entity.email }}</td>
<td>{{ entity.subject }}</td>
<td>{{ entity.body }}</td>
<td>
<img src="http://test//bundles/blogger/image/view.png" style="width:30px; height:30px">
<img src="http://test//bundles/blogger/image/edit.png" style="width:30px; height:30px" >
</td>
</tr>
{% endfor %}
</tbody>
<tfooter>
</tfooter>
</table>
<ul>
<li>
<a href="{{ path('enquiry_new') }}">
Create a new entry
</a>
</li>
</ul>
{% endblock %}
I have put the checkbox inside it.
and what i want is the array value of the "multiSelect[]" which store all id.
and i am passing this to my controller.
i donot know how to pass this array value as my controller argument. so please help me
i want to pass it here.
<tfooter>
MultiDelete
</tfooter>
You need to use a form for that. Using input fields without a form is always a sloppy way.
I got the answer.
I have created the form and pass the request to the controller deleteAction .
in deleteAction method
i get the request parameters using $request->get('multiSelect'); "multiSelect" the name of the input box.
and using the repositoryclass object i have completed the task.
Thanks for your response.
I think the most secure way to do this is with a link that onclick generates a form and send it by post. For example:
<a href="{{ path('your_delete_action', { 'id': object.id }) }}"
token="{{ token }}"
data-method="POST"
object-id ="{{ object.id }}">
<span class="red"><i class="icon-remove"></i></span>
</a>
And onClick on this links you generate a form and send it to your deleteAction
// Every link with an attribute data-method
$("#container").on("click", "a[data-method]", function(event){
event.preventDefault();
var target = $(event.currentTarget);
var method = target.attr('data-method');
var action = target.attr('href');
var token = target.attr('token');
var objectId = target.attr('object-id');
// Create a form on click
var formulario = $('<form/>', {
style: 'display:none;',
method: method,
action: action
});
formulario.appendTo(target);
formulario.append("<input name='token' value='" + token + "' type='hidden'/>");
formulario.append("<input name='id' value='" + objectId + "' type='hidden'/>");
// Do submit
formulario.submit();
});

Resources