how to stop saving data in associated tables in cakephp 3 - cakephp-3.2

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

Related

Entity misbehaving whilst rendering PDF with twig, symfony2 and doctrine

I'm facing a funny issue here, I will do my best to explain it:
I have an Order entity and an orderProducts with a one to many relation.
Now I'm trying to generate a PDF invoice.
So I built my invoice using twig, then I use Knp\Snappy\Pdf; then it's just the following
$snappy = new Pdf($myProjectDirectory . 'vendor/h4cc/wkhtmltopdf-i386/bin/wkhtmltopdf-i386');
$renderedView = $this->renderView(
'ERPBundle:Orders:invoicepdf.html.twig', array(
'order' => $order,
'invoice' => $invoice
)
);
$snappy->generateFromHtml($renderedView, $invoicePath);
In the generated PDF, the orderProducts are duplicated, meaning I get the same row displayed twice.
I've rendered the template separately to view it in the browser and the orderProdcuts displays correctly, I used the same code to retrieve the data.
So I'm guessing this has got to be an issue between Snappy rendering of the html output + doctrine's lazy load. But I don't have the skills to debug this.
The issue is irrelevant to this code or the relative bundles.
The invoice PDF was generated after a form update, and in assigning my sub entity values I did this:
$orderProducts = $order->getOrderProducts();
foreach ($orderProducts as $orderProduct) {
$order->addOrderProduct($orderProduct);
}
This generated the duplicate value for orderProducts, I didn't catch this before, because doctrine recognizes the duplication and ignores it.
The fix is to properly handle the update like this
$orderProducts = $order->getOrderProducts();
foreach ($orderProducts as $orderProduct) {
$order->addOrderProduct($orderProduct);
if (empty($orderProduct->getId())) {
$order->addOrderProduct($orderProduct);
}
}
link to fix

Strange Doctrine 2 behaviour

I am using a Symfony command to retrieve member details from an API afor updating in a local database.
I query my local database and then loop through each member to retrieve data and update individually. However, doctrine is not updating these member details.
I have tried to use persist and merge but none of them seems to be working which is really baffling. Below is the code I am using, hopefully an extra pair of eyes will spot what I am not:
$members = $em->getRepository('AppBundle:Member')->findByNot(array('pin' => "'NULL'"),array('updated_at' => 'ASC'),4,0);
foreach($members as $member)
{
$details = json_decode($api_url->apiConnect(array('login' => $member->getId(), 'password' => $member->getPassword())), true);
$member->setFirstName($details['firstName']);
$member->setLastName($details['lastName']);
$member->setCard($details['card']);
//$em->merge($member);
$em->persist($member);
$em->flush();
}
When I check the mysql query log, none of the update queries are run.

SonataAdminBundle Exporter issue with many to many

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.

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

how to customise search results of apachesolr (drupal 6)

can somebody help me how to customize the search result of a apache solr search. i was only able to access these variables [comment_count] => [created] => [id] => [name] => [nid] => [title] => [type] => [uid] => [url] => [score] => [body].
how can i access other variable like status, vote .... from the index ( i don't want to access the database for retrieving these values, i want to get it from the index itself)
i need to display no of votes for that specific node in the result snippet
i need to understand
1. how to index votes field
2. how to show the vote, status... in result snippet.
Votes are a poor choice for indexing for a couple of reasons:
Votes can change quickly
When a vote is made, the node is not updated. As such, apachesolr won't know to re-index the node to pick up the change.
If by 'status' you mean the node->status value, then the answer is that it will always be 1. Unpublished nodes are never indexed.
Now, if you want to add something else to the index, you want hook_apachesolr_update_index(&$document, $node) - this hook gets called as each node is being indexed, and you can add fields to $document from $node to get the values into the solr index. However, you want to use the pre-defined field prefixes - look at schema.xml to find the list.
Below is example of code to add fields for sorting, and for output.
/**
* Implementation of hook_apachesolr_update_index()
* Here we're adding custom fields to index, so that they available for sorting. To make this work, it's required to re-index content.
*/
function somemodule_apachesolr_update_index(&$document, $node) {
if ($node->type == 'product') {
$document->addField('sm_default_qty', $node->default_qty);
$document->addField('sm_sell_price', $node->sell_price);
$document->addField('sm_model', $node->model);
foreach ($node->field_images AS $image) {
//$imagecached_filepath = imagecache_create_path('product', $image['filepath']);
$document->addField('sm_field_images', $image['filepath']);
}
}
}
/**
* Implementation of hook_apachesolr_modify_query()
* Here we point what additional fields we need to get from solr
*/
function somemodule_apachesolr_modify_query(&$query, &$params, $caller) {
$params['fl'] .= ',sm_default_qty,sm_field_images,sm_sell_price,sm_model';
}
If you want to totally customize output, you should do following:
1) Copy search-results.tpl.php and search-result.tpl.php from /modules/search to your theme's folder.
2) Use the $result object as needed within search-result.tpl.php
3) Don't forget to clear the theme registry by visiting admin/build/themes
Or as mentioned about, you can override using preprocessor hooks.
Regards, Slava
Another option is to create a view(s) of your liking with input argument nid, then create the following preprocess in your template.php file:
function MYTHEME_preprocess_search_result(&$vars) {
$vars['myView'] = views_embed_view('myView', 'default', $vars['result']['node']->nid);
}
Matching the view name 'myView' with the variable name makes sense to me. Then you can use the variable $myView in your search-results.tpl.php file.
Here's a video by the makers of the Solr Search Integration module with an overview on how to customise what nodes and fields are indexed, and what Solr spits out as a search result...
For Drupal 6:
http://sf2010.drupal.org/conference/sessions/apache-solr-search-mastery.html
And Drupal 7:
http://www.acquia.com/resources/acquia-tv/conference/apache-solr-search-mastery
It all looks very customisable!

Resources