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'
Related
I am trying to create a wordpress plugin that exports or sends out (through an API) bulk data resource by resource (such as products, orders, customers, etc) of a woocommerce site without affecting the performance of the site.
But I am new to php and finding it difficult.
Also, I was planning to use WP-Cron to build the bulk data on certain time interval in order to avoid the hit in performance. But, from some research, I got to know that WP-Cron is not a reliable solution to my goal as it is not a regular cron and also, it can be disabled easily.
As my idea requires a regular bulk data building approach, I am now looking out for different options such as recursive calling.
I have exposed an endpoint where I will be receiving some required details and will call the class that will take care of the bulk data building.
public function getCCBulkSync( $request )
{
$entity = $_GET['entity'];
$startDate = $_GET['start_date'];
$endDate = $_GET['end_date'];
$delivery_url = $_GET['delivery_url'];
$limit = $_GET['limit'];
if(!$delivery_url) return 'Delivery Url cannot be null';
include 'class-wc-cc-bulk-data-builder.php';
$bulkBuilder = WC_CC_Bulk_Data_Builder::getInstance();
$bulkBuilder = ($bulkBuilder === NULL || $bulkBuilder->getObjectDetails()['entity'] === NULL) ? $bulkBuilder->setObjectDetails($entity, $delivery_url, $startDate, $endDate, $limit) : $bulkBuilder;
return 'Bulk sync initiated! Check later for the completion!!!';
}
The bulk data builder class code is given below
class WC_Bulk_Data_Builder
{
private static $instance = NULL;
protected $entity = NULL;
protected $startDate = NULL;
protected $endDate = NULL;
protected $delivery_url = NULL;
protected $dataCount = 0;
protected $limit = 0;
static public function getInstance()
{
if (self::$instance === NULL)
self::$instance = new WC_Bulk_Data_Builder();
return self::$instance;
}
protected function __construct($entity = NULL, $delivery_url = NULL, $startDate = NULL, $endDate = NULL, $limit = 1000)
{
$this->entity = $entity;
$this->delivery_url = $delivery_url;
$this->startDate = $startDate;
$this->endDate = $endDate;
$this->limit = $limit;
}
public function getObjectDetails() {
$objData = array();
$objData['entity'] = $this->entity;
$objData['startDate'] = $this->startDate;
$objData['endDate'] = $this->endDate;
$objData['deliveryUrl'] = $this->delivery_url;
$objData['dataCount'] = $this->dataCount;
$objData['limit'] = $this->limit;
return $objData;
}
public function setObjectDetails($entity = NULL, $delivery_url = NULL, $startDate = NULL, $endDate = NULL, $limit = 1000) {
$this->entity = $entity;
$this->delivery_url = $delivery_url;
$this->startDate = $startDate;
$this->endDate = $endDate;
$this->limit = $limit;
$this->bulk_data_builder();
return self::$instance;
}
function bulk_data_builder()
{
$entity = $this->entity;
if($entity === 'order') {
$this->build_order_data();
}
sleep(20);
$this->bulk_data_builder();
}
protected function build_order_data()
{
$ordersArray = wc_get_orders( array(
'limit' => 250,
'offset' => $this->dataCount,
'orderby' => 'ID',
'order' => 'ASC',
) );
$this->dataCount += count($ordersArray);
$orders = array();
foreach($ordersArray as $order_index=>$order) {
$orders[$order_index]=$order->get_data();
$orders[$order_index]['refunds'] = $order->get_refunds();
}
$header_args = array_keys($orders[0]);
$output = fopen( 'order_csv_export.csv', 'a+' );
fputcsv($output, $header_args);
foreach($orders AS $order_item){
foreach($header_args AS $ind=>$key) {
if('array' === gettype($order_item[$key])) $order_item[$key] = json_encode($order_item[$key]);
}
fputcsv($output, $order_item);
}
if($dataCount>=$limit)
{
$dataCount = 0;
$req_headers = array();
$req_headers[] = 'Content-Type: text/csv; charset=utf-8';
$req_headers[] = 'Content-Disposition: attachment; filename=order_csv_export.csv';
$cURL = curl_init();
$setopt_array = array(CURLOPT_URL => $delivery_url, CURLOPT_RETURNTRANSFER => true, CURLOPT_HTTPHEADER => $req_headers);
curl_setopt_array($cURL, $setopt_array);
$json_response_data = curl_exec($cURL);
curl_close($cURL);
exit;
}
fclose($output);
}
}
Now, what I am expecting is the recursive calling on same bulk_data_builder() method which should build the data continuously on a 20 seconds interval or any other way to do the same until the record count reaches the limit, so that I can send the bulk data built, to the delivery_url.
But, the mentioned method is not getting called recursively. Only for the first time the method is called and giving back 250 records.
As I am new to php, I am not sure about the async functionality also.
Can someone help me to understand what I am doing wrong or what I am missing?
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();
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);
}
...
}
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.
how to do a facet query with elasticsearch on symfony2 ?
i can do query, and got result, it works!
now on this query, i would like to facets the results.
public function facetAction()
{
// index
$search = $this->get('fos_elastica.index.appellations.appellation');
$query = new \Elastica\Query\MatchAll();
$elasticaQuery = new \Elastica\Query();
$elasticaQuery->setQuery($query);
$elasticaQuery->setSize(550);
$elasticaFacet = new \Elastica\Facet\Terms('regions');
$elasticaFacet->setField('regions');
$elasticaFacet->setSize(550);
$elasticaFacet->setOrder('reverse_count');
$elasticaQuery->addFacet($elasticaFacet);
// ResultSet
$elasticaResultSet = $search->search($elasticaQuery);
// Get Facets
$elasticaFacets = $elasticaResultSet->getFacets();
foreach ($elasticaFacets['regions']['terms'] as $elasticaFacet) {
$results[] = $elasticaFacet;
}
return $this->container->get('templating')->renderResponse
('ApplicationGhvAppellationsBundle:Default:indexFacets.html.twig', array(
'appellations' => $results
));
}
Since Facets are going to be deprecated here is the updated code with aggregations
public function aggregationAction()
{
// index
$search = $this->get('fos_elastica.index.appellations.appellation');
$query = new \Elastica\Query\MatchAll();
$elasticaQuery = new \Elastica\Query();
$elasticaQuery->setQuery($query);
$elasticaQuery->setSize(550);
$elasticaAggreg= new \Elastica\Aggregation\Terms('regions');
$elasticaAggreg->setField('regions');
$elasticaAggreg->setSize(550);
$elasticaAggreg->setOrder('_count', 'desc');
$elasticaQuery->addAggregation($elasticaAggreg);
// ResultSet
$elasticaResultSet = $search->search($elasticaQuery);
// Get Aggregations
$elasticaAggregs = $elasticaResultSet->getAggregations();
foreach ($elasticaAggregs['regions']['buckets'] as $elasticaAggreg) {
$results[] = $elasticaAggreg;
}
return $this->container->get('templating')->renderResponse
('ApplicationGhvAppellationsBundle:Default:indexFacets.html.twig', array(
'appellations' => $results
));
}