Doctrine not getting newly added record - symfony

I have a function that does 2 things.
Saves an existing or a new item/record
Query and re-order items
The code algorithm is like this
public function doSomething($id = 0)
{
$em = $this->getEntityManagerFromSomewhere();
$service = $this->getSomeServiceFromSomewhere();
$repo = $em->getRepository(Item::class);
$conn = $em->getConnection();
$conn->beginTransaction();
if ($id) {
$item = new Item();
} else {
$item = $repo->find($id);
}
$em->persist($item);
$em->flush();
$items = $repo->getAllItems();
// changes are saved to the database
$service->rearrangeItems($items);
$conn->commit();
}
Now the issue I'm having with this is that, if it is a new Item, when we try to get all items, that new item is not included for some odd reason.
I've tried stuff on my own and the one that works for me is to insert
$em->clear(); // after flush
I am not sure if this is the best way to approach this or if I'm misusing this functionality. It works though, when I tested it.

public function doSomething($id = 0)
There is $id is default 0, Actually, your are creating item every time.
if ($id) {
$item = new Item();
$em->persist($item);
} else {
$item = $repo->find($id);
}
also, you don't need to persist if you don't update or create new Item.
Or the way that I understood.
if($id)
{
$item = $em->getRepository(Item::class)->find($id)
}
else
{
$item = new Item();
$em->persist($item);
}
$em->flush();

Related

Symfony - doctrine - change encoding - all entities and rows

I need to change an encoding in symfony. Problem is that there is a production which contains some data. Is there any way to list of all entitites, all rows and do on string / text column change encoding?
I didn't found any better solution, so I did in a migration:
$entityManager = $this->container->get('doctrine.orm.entity_manager');
$entities = $entityManager->getConfiguration()->getMetadataDriverImpl()->getAllClassNames();
foreach ($entities as $className) {
if ((strpos($className, "AppBundle") !== false) && (strpos($className, "Abstract") === false)) { //only my classes and no abstract class
$records = $entityManager->getRepository($className)->findAll();
$metadata = $entityManager->getClassMetadata($className);
$entity_fields = $metadata->getFieldNames();
foreach ($entity_fields as $field) {
$type = $metadata->getTypeOfField($field);
if ($type === "string") {
foreach ($records as $record) {
$oldValue = $metadata->getReflectionProperty($field)->getValue($record);
$metadata->getReflectionProperty($field)->setValue($record, " ");
$entityManager->persist($record);
$entityManager->flush();
$metadata->getReflectionProperty($field)->setValue($record, trim($oldValue));
$entityManager->persist($record);
$entityManager->flush();
}
}
}
}
}

Access session variable from different controller in symfony

i want to create an array as a session table to put it empty in the beggining for my cart shop to display nothing as an empty cart and when i press AddtoCart i want get that array and do an array_push with the new items but i didn't know how to do it
This is the first controller when i create the array empty
public function FrontAction()
{
$pro=new Produit();
$pro->setNom('');
$pro->setQuantite(0);
$pro->setPrix(0);
$em = $this->getDoctrine()->getManager();
$sess=new Session();
$sess->setName('PANIER');
$sess=array('');
array_push($sess,$pro->getNom(),$pro->getQuantite(),$pro->getPrix());
$paniers = $em->getRepository(Panier::class)->findByUserId(1);
$produits = $this->getDoctrine()->getRepository(Produit::class)->findAll();
$boutiques = $this->getDoctrine()->getRepository(Boutique::class)->GetBestShopsDQL();
if ($paniers != null)
{
$prixTotal = 0;
foreach ($paniers as $panier) {
$prixTotal += $panier->getPrixTotal();
}
$resultCount = count($paniers);
return $this->render('BoutiqueBundle:FrontViews:ListBoutique.html.twig', array('produits' => $produits, 'boutiques' => $boutiques,'paniers' => $paniers, 'prixTotal' => $prixTotal,'resultCount' => $resultCount));
}
return $this->render('BoutiqueBundle:FrontViews:ListBoutique.html.twig', array('produits' => $produits, 'boutiques' => $boutiques,'sess'=>$sess));
}
and this is the second controller where i want to fill that empty array with new items
public function ajouterauPanierAction($id)
{
$ses=new Session();
$ses->getName('PANIER');
$test=array('');
$test=$ses;
// $user_id = $this->getUser()->getId(); //à modifier!!!!!
$em = $this->getDoctrine()->getManager();
$produit = $em->getRepository(Produit::class)->find($id);
$test = $em->getRepository(Panier::class)->findExistant($id, 1);
// $session->replace(array_push($produit,));
if(($produit != null)&&(empty($test)))
{
array_push($test,$produit->getNom(),$produit->getQuantite(),$produit->getPrix());
/* $panier = new Panier();
$panier->setProduitId($produit->getId());
$panier->setUserId(1); //à changer avec le fos
$panier->setDate(new \DateTime("now"));
$panier->setPrixTotal($produit->getPrix());
$em->persist($panier);
*/ $em->flush();
$msg = "success";
// return $this->redirectToRoute('Dashboard');
}
else
{
//return $this->render('BoutiqueBundle:FrontViews:404.html.twig');
$msg = "failure";
}
return new JsonResponse(array('msg' => $msg));
}
i didn't know how to do it correctly or if my idea is wrong so hope u guys got what i need to do
Here is how I am doing it in Symfony 4, (I think this part is unchanged). First I have declared my session keys as class constants on the entities to avoid collisions.
class Appointment
{
const SESSION_KEY = 'confirmed_app_entity_appointment';
...
}
Then in the controller use the SessionInterface and it will get autowired into your controller method with a typehinted parameter (SessionInterface $session). Symfony will handle starting the session, just set, get, and/or remove the key as needed.
use Symfony\Component\HttpFoundation\Session\SessionInterface;
...
public function confirmAppointment($first_name, $last_name, $time, SessionInterface $session)
{
...
$session->set(Appointment::SESSION_KEY, $appointment);
$session->set(StaffMember::SESSION_KEY_SELECTED_STAFF, $member);
...
if ($this->isConflict($appointment)) {
$session->remove(Appointment::SESSION_KEY);
$session->remove(StaffMember::SESSION_KEY_AUTH);
$this->addFlash('error', 'Failed to create Appointment, conflict found');
return $this->redirectToRoute('customer');
}
...
}
public function saveAppointment(SessionInterface $session)
{
if (!empty($session->get(Appointment::SESSION_KEY))) {
$appointment = $session->get(Appointment::SESSION_KEY);
}
...
}

Pagerfanta symfony Pagination

I have a mysql database blog with 21 posts in it.
I set $maxPerPage = '3'; So I get 7 pages, but from page 4 I get the following error:
OutOfRangeCurrentPageException: Page "4" does not exist. The currentPage must be inferior to "3"
Here's my code:
public function indexAction($page)
{
$maxPerPage = '3';
$currentPage = $page;
$entityManager = $this->getDoctrine()->getManager();
$queryBuilder = $entityManager->createQueryBuilder()
->select(array('u')) // string 'u' is converted to array internally
->from('AppBundle:Blog', 'u');
$adapter = new DoctrineORMAdapter($queryBuilder);
$pagerfanta = new Pagerfanta($adapter);
if (!$page) $currentPage = '1';
try {
$pagerfanta->setCurrentPage($currentPage);
}
catch(NotValidCurrentPageException $e) {
throw new NotFoundHttpException('Illegal page');
}
$pagerfanta->setMaxPerPage($maxPerPage); // 10 by default
//$textblog = $this->getDoctrine()
//->getRepository('AppBundle:Blog')
//->find($page);
return $this->render('textblog/blog.html.twig',array('pagerfanta' => $pagerfanta));
}
Can anyone help please?
Stupid me...
$pagerfanta->setMaxPerPage($maxPerPage);
This code should be before the 'if'

Symfony doctrine batch processing not working

Maybe anyone can have a look:
I have a function and using batch to process bulk data to doctrine, but it not seems working, because nothing is inserted to database, but if i flush() every element, everything is working
any ideas why?
private function insertData($linesInFile, $output)
{
$google = $this->getContainer()->get('google.books');
$amazon = $this->getContainer()->get('amazon.books');
$em = $this->getContainer()->get('doctrine.orm.entity_manager');
$number = 1;
$batchSize = 5;
foreach ($linesInFile as $string) {
$string = preg_split('/isbn_13/', $string);
$book = new Book();
$isbn = new Isbn();
if (isset($string[1])) {
$value = str_split($string[1], 23);
$isbnValue = preg_replace('/\D/', '', $value[0]);
$isbn->setIsbn($isbnValue);
$book = $google->getBookByIsbn($isbn);
if (null == $book->getIsbn()) {
$book = $amazon->getBookByIsbn($isbn);
}
$pages = $book->getPages();
$image = $book->getCover();
$about = $book->getAbout();
if ($about !== "") {
if ($image !=="") {
$em->persist($book);
if (($number % $batchSize) === 0) {
$em->flush();
$em->clear();
}
$output->writeln($isbnValue);
$number++;
}
}
}
}
$em->flush();
$em->clear();
return $number;
}
}
So, my code is good, it was some bug in google API and items were not persisted properly.

wordpress wp_list_categories problem

I need to make something like wp_list_categories that shows categories that are empty but only if they have children categories that have posts in them. Anyone have any ideas?
Thanks
You can probably do this with a Walker, but I tried it the old-fashioned way.
$categories = get_categories();
// First index all categories by parent id, for easy lookup later
$cats_by_parent = array();
foreach ($categories as $cat) {
$parent_id = $cat->category_parent;
if (!array_key_exists($parent_id, $cats_by_parent)) {
$cats_by_parent[$parent_id] = array();
}
$cats_by_parent[$parent_id][] = $cat;
}
// Then build a hierarchical tree
$cat_tree = array();
function add_cats_to_bag(&$child_bag, &$children)
{
global $cats_by_parent;
foreach ($children as $child_cat) {
$child_id = $child_cat->cat_ID;
if (array_key_exists($child_id, $cats_by_parent)) {
$child_cat->children = array();
add_cats_to_bag($child_cat->children, $cats_by_parent[$child_id]);
}
$child_bag[$child_id] = $child_cat;
}
}
add_cats_to_bag($cat_tree, $cats_by_parent[0]);
// With this real tree, this recursive function can check for the cats you need
function has_children_with_posts(&$children)
{
$has_child_with_posts = false;
foreach ($children as $child_cat) {
$has_grandchildren_with_posts = false;
if (isset($child_cat->children)) {
// Here is our recursive call so we don't miss any subcats
if (has_children_with_posts($child_cat->children)) {
$has_grandchildren_with_posts = true;
}
}
if (0 < intval($child_cat->category_count)) {
$has_child_with_posts = true;
} else if ($has_grandchildren_with_posts) {
// This is a category that has no posts, but does have children that do
$child_cat->is_empty_with_children = true;
var_dump($child_cat->name);
}
}
return $has_child_with_posts;
}
has_children_with_posts($cat_tree);

Resources