SonataAdminBundle Exporter issue with many to many - symfony

currently I'm using sonata admin bundle to export a "order" data, how can I export the data with manytomany relationship? I saw a post, it helps a bit, but I still not sure how to get the data in many to many relationship.
Here is my code:
public function getExportFields() {
return [
$this->getTranslator()->trans('Order Number') => 'id',
$this->getTranslator()->trans('First Name') => 'customer.First_name',
$this->getTranslator()->trans('Last Name') => 'customer.Last_name',
...]
Here is fine, but when I try to get 'OrderToProduct' or 'product.name' it failed or only output empty string. I spent to much time on this already, hope someone can give a clue. Thank you.

Well, you can't use product.name, because product is a collection.
Export action iterates through objects and get properties with path defined and tries to stringify them.
What you need to do is a workaround - define some method in Order class - i.e. getProductsAsString(), make it return string you need, and then add
$this->getTranslator()->trans('Products') => 'productsAsString'
But still - it will put whole string in single cell of xls, csv, xml you are trying to export.

Related

Getting values of a POST multi-dimensional array with doctrine

I have a Symfony3 CRM that implements a form to create an invoice. In this form there is a list of different costs, such as labour, service and materials. I have coded this so it's in a multidimensional array since the user can create any number of fields with whatever they want.
An example of the post array:
[costings] => Array
(
[labour] => 80.30
[materials] => 75.00
[service] => 43.50
....
)
I want to use Doctrine to get the data. To retrieve the costings array, I use this:
$request->request->get('costings');
But I do not know how to get the values within that array. I tried:
$costings->get('labour');
But I get a warning saying I'm trying to call get() on an array. Is there a way to do this or do I need to revert back to just using $_POST?
Simply use this, since you POST costings as normal array.
$costings = $request->request->get('costings');
$labourCostings = $costings['labour'];
Did you try:
$labour = $request->request->get('costings')['labour'];
?
If it doesn't work, try to dump the result of $request->request->get('costings')

how to stop saving data in associated tables in cakephp 3

i have a table(user table) which is associated to many tables. While saving data, it is getting saved in all associated table. But in some scenario i need to save only in base table (User) not in assoicatied table.
In cakephp 2 we have option callback => false, but how can we achive this in cake php 3?
You may specify the associated tables in which you want to save (cf: CakePHP ORM Documentation).
You could then do :
$this->Users->save($user, ['associated' => false]);
To disable the save in associated tables. (I have not tested as I'm at work, I will edit my message if it does not work for me !)
following code worked for me
$entity = $this->Users->newEntity($this->request->data, ['ignoreCallbacks' => true,'associated' => []]);
$result = $this->Users->save($entity);

Return a value from entity to view file in symfony

I want to return a value from entity to view file. Below is my entity function
public function getVisitorName($id)
{
$repository = $this->getDoctrine()->getRepository('SystemVmsBundle:VisitorsDetails');
$product = $repository->findOneBy(array('id' =>$id));
$name=$product->getFirstname();
return $name;
}
This is the line in my view file which calls that function
{{ entity.visitorName(entity.visitorId) }}
Its not giving me any error. But only a blank page. How can i fix this?
This is my controller code
public function indexAction()
{
$em = $this->getDoctrine()->getManager();
$entities = $em->getRepository('SystemVmsBundle:EntryDetails')->findAll();
return array(
'entities' => $entities,
);
}
I am trying to fetch the visitors name(from visitors table) corresponding to the visitor id(in entry table).How will i do it then?
you have two ways of doing it:
1) Map your SystemVmsBundle:EntryDetails entity, to SystemVmsBundle:VisitorsDetails as OntToOne by adding field details to your EntryDetails; , and then in twig template just call it via
{{ entity.details.name }}
2) instead of creating getVisitorName(), it is better to create twig function for this, with same functionality.
Your indexAction() is not returning a response object, it is just returning an array of entities. Controller actions should return a Response containing the html to be displayed (unless they are for e.g. ajax calls from javascript). If you are using twig templates you can use the controller render() method to create your response, something like this:
return $this->render('<YourBundle>:<YourViewsFolder>:<YourView>.html.twig', array(
'entities' => $entities,
));
When you've corrected that I suspect you'll get an error because $this->getDoctrine() won't work from an entity class. The code you have in the getVisitorName() method just shouldn't be in an entity class.
As #pomaxa has already suggested, I believe there should be a relationship between your EntryDetails and VisitorsDetails entities although I don't know enough about your data from the question to know what type of relationship it should be (OneToOne / ManyToOne). If your EntryDetails entity had a relationship to VisitorsDetails, the EntryDetails class would then contain a $visitorsDetails attribute and methods to get/set it. Then the line in your twig file would look like this:
{{ entity.visitorsDetails.firstName }}
There is a section on Entity Relationships / Associations in the Symfony Manual.
Also, I hope you don't mind me giving you a little advice:
Be careful when you copy and paste code as it appears you have done in getVisitorName(). You have kept the variable name '$product' although there are no products in your system. This sort of thing can cause bugs and make the code more difficult to maintain.
I recommend you avoid tacking 'Details' onto the end of entity names unless you genuinely have two separate and related entities such as Visitor + VisitorDetails and a good reason for doing so. I think the entities in your example are actually 'Visitor' and 'VistorEntry'.
Unless you are writing a re-usable component, I recommend you use specific variable names like '$visitorEntries' rather than '$entities' in your controller and twig.
In general, the more meaningful your variable names, the more readable, maintainable and bug-free your code is likely to be. Subsequently, it will also be much easier for people on SO to understand your code and give you help when you need it.

How to create a unique form using multiple entities fields in symfony2

I want to create a form using some fields from multiple entities. I have all the distinct entites needed already created and i am not using form classes. I need to know how to do to render a form and handle its data so i can save them to the correct tables in my database.
Here is a part of my controller in charge of doing that
public function createPublicSpaceAction() {
//My entities
$Room = new Room();
$GuestList = new GuestList();
$Guest = new Guest();
//I need to know what to do from here
return $this -> render('AcmeUserBundle:Default:Forms/createPublicSpace.html.twig', array());
}
I kept trying to find a solution and i came up with the idea that one form needs one entity. So maybe the solution would be to merge those entities in one so i can build the form easily. I would then have to persist data to corresponding tables. But i can't think of how to merge entities.
I figured out a temporary solution. For those who want to know, I manually created an entity that looks like a merge of all the entity I need. This new entity has no link with Doctrine therefore it cannot create a table. Its goal is simply to allow me to build up a form and be able to manipulate data through that form. I then assign all data submitted to corresponding entities fields and persist them to the database.
Once again i know this is not the best solution. But for some reasons I won't tell, it is for me at this moment. I hope this can help some that are in the same situation than me and do not hesitate to post links that could help or better ways to do that.
It is highly recommended to use form classes http://symfony.com/doc/current/book/forms.html#creating-form-classes
They are designed to save time and make a lot of things just easier.
However to answer your question consider the following. Your action needs to handel a post request. So catch the request object with the post data:
use Symfony\Component\HttpFoundation\Request;
public function createPublicSpaceAction(Request $request)
Then get a form builder intance and create the form:
$builder = $this->createFormBuilder();
$builder->add('floor', 'text', array(
'label' => 'Room floor',
'data' => $room->getFloor()
));
add as much form fields as you need. There are several built-in field types: http://symfony.com/doc/current/book/forms.html#built-in-field-types
Create the form:
$form = $builder->getForm();
Pass the form to your template:
return $this -> render('AcmeUserBundle:Default:Forms/
createPublicSpace.html.twig', array(
'roomForm' = $form
));
To get posted data within your action:
if ('POST' == $request->getMethod()) {
$data = $request->request->get("form");
}
And in your template you can render the form by yourself or let twig do the job:
{{ form_widget(form.floor)}}
So this are the most importend things to mention. However you should go through http://symfony.com/doc/current/book/forms.html They actually tell you everything I wrote down.
Good luck ;)

Symfony2: How do i export the SonataAdminBundle listing data to excel sheet?

I need to export sonata admin data via excel or pdf. How can i be able to achieve this? Is there any bundle that helps me do that?
Any ideas!?
Thanks.
You have to override the admin getExportFields() method.
If the entity has some (X)-to-many or many-to-(X) relations you have to override all the fields
public function getExportFields()
{
$exportFields = parent::getExportFields(); //It's not working in case of *-to many relation, so remove it, but it's ok for small customisation
$exportFields["Date"] = 'date'; //if your date is an instance of DateTime, you have to format it
$exportFields["User name"] = 'user.name'; // in case of *-to-many relations
$exportFields["Status"] = 'statusAsString'; //for customise format implement getStatusAsString() in you entity
return $exportFields;
}
To customise the type of report to download you have to override, removing the default one:
public function getExportFormats()
{
return array(
'json', 'xml', 'csv', 'xls'
);
}
I've implemented Bundle for Symfony and Sonata to export lists to PDF. You could get it here: https://github.com/whyte624/sonata-admin-extra-export-bundle. It is based on solution suggested here: http://cristian-radulescu.ro/article/add-pdf-export-functionality-in-sonataadminbundle.html.
I know that the question is quite old, but hopefully it helps someone else.

Resources