Unable to sort in FOSElasticaBundle - php

I use FOSElasticaBundle in my project to search a list of ads. I can get all the result but I can't order it in "asc" or "desc". I have seen different tutorial speaking about Filtering. But it's not working.
if (!empty($cati)) {
$query = new \Elastica\Query\Bool();
if((!empty($cati)) && $cati!='1')
{
$query1 = new \Elastica\Query\Match();
$query1->setFieldQuery('post.cat_id', $cati);
$query->addMust($query1);
}
}
else {
$query = new \Elastica\Query\MatchAll();
}
$elasticaQuery = new \Elastica\Query();
$elasticaQuery->setQuery($query);
$elasticaQuery->setSize($nbPerPage);
$elasticaQuery->setFrom(($page - 1) * $nbPerPage);
$elasticaQuery->addSort(array('date', array("desc"));
$repistoryManager = $this->container->get('fos_elastica.manager');
$repistory = $repistoryManager->getRepository('AdsManagerBundle:Post');
$eq = new \Elastica\Query();
$eq->setQuery($query);
$finder = $this->container->get('fos_elastica.index.ads.post');
$elasticaResultSet = $finder->search($eq);
$ed = $elasticaResultSet->getResults();
I can't get where the problem is!

You did in a mistake in your code (parse error + bad construction of the JSON syntax):
$elasticaQuery->addSort(array('date' => 'desc'));

Related

PHP NetSuite - Advanced Search with criterion

I have PHP code for Advanced Search items in NetSuite,
but I don't know how I can combine to my search - filtering by item name.
My code is:
$service = new NetSuiteService($config);
$service->setSearchPreferences(true, $page_size, true);
$savedSearchId = '###';
$searchAdvanced = new ItemSearchAdvanced();
setFields($searchAdvanced, array('savedSearchScriptId'=>$savedSearchId));
$request = new SearchRequest();
$request->searchRecord = $searchAdvanced;
$results = $service->search($request);
I want to combine a criteria
Here's sample code I found to get inventory details using Item internal id as a filter. You can reference Suite Answer 90401, 37585, and 25066.
<?php
require_once '../PHPToolkit/NetSuiteService.php';
$service = new NetSuiteService();
// formulate the criteria
$itemRecord = new RecordRef();
$itemRecord--->internalId = 140;
$itemMultiSelect = new SearchMultiSelectField();
$itemMultiSelect->operator = 'anyOf';
$itemMultiSelect->searchValue = $itemRecord;
$itemSearchBasic = new ItemSearchBasic();
$itemSearchBasic->internalId = $itemMultiSelect;
$criteria = new ItemSearch();
$criteria->basic = $itemSearchBasic;
// formulate the resulting columns
$searchRowBasic = new ItemSearchRowBasic();
$searchRowBasic->itemId = new SearchColumnStringField(); // Item Name/Number in UI
$searchRowBasic->internalId = new SearchColumnSelectField(); // Internal ID in UI
$searchRowBasic->location = new SearchColumnSelectField(); // Location (Main section of Inventory Item) in UI
$searchRowBasic->inventoryLocation = new SearchColumnSelectField(); // Location column in Locations tab (Inventory Item) in UI
$searchRowBasic->locationQuantityOnHand = new SearchColumnDoubleField();// Quantity on Hand column in Locations tab (Inventory Item) in UI
$columns = new ItemSearchRow();
$columns->basic = $searchRowBasic;
// item search advanced
$search = new ItemSearchAdvanced();
$search->criteria = $criteria;
$search->columns = $columns;
$request = new SearchRequest();
$request->searchRecord = $search;
$searchResponse = $service->search($request);
if (!$searchResponse->searchResult->status->isSuccess) {
echo "SEARCH ERROR";
} else {
echo "SEARCH SUCCESS, records found: " . $searchResponse->searchResult->totalRecords ;
}
?>

How to get AdSchedule object with Google Ads API

I am trying to get all Ad Schedules placed in Google Ads through the Google Ads API and obtain the start and end times (hour and minute) to compare it with some existing values and depending on whether they differ update accordingly.
Here is my code showing where I am iterating over returned Ad Schedules.
foreach($campaigns as $camp) {
// Get restaurant and details
$res = RestaurantsService::getRestaurantByName($camp->getName());
$hours =$res->getHours()->dequeue();
$start = explode("-",$hours)[0];
$end = explode("-",$hours)[1];
// Get current ad schedules as they are now
$campaignAdSchedules = self::getCampaignAdSchedule($campaignCriterionService,$camp->getId());
if ($campaignAdSchedules == null){
$operations = [];
$schedule = new AdSchedule();
$schedule->setDayOfWeek(self::DAYS[date("N")-1]);
$schedule->setStartHour((int)substr($start,0,2));
$schedule->setStartMinute(MinuteOfHour::ZERO);
$schedule->setEndHour((int)substr($end,0,2));
$schedule->setEndMinute(MinuteOfHour::ZERO);
$operation = new CampaignCriterionOperation();
$criterion = new CampaignCriterion();
$criterion->setCampaignId($camp->getId());
$criterion->setCriterion($schedule);
$operation->setOperand($criterion);
$operation->setOperator(Operator::ADD);
$operations[] = $operation;
$campaignCriterionService->mutate($operations);
} else {
foreach($campaignAdSchedules as $adSchedule){
---> $schedule = $adSchedule->getCriterion(); <---
}
}
}
Here the line marked with arrows is the line I am having problems with. The getCriterion() function returns a Criterion object which does not have the methods getStartHour() etc. I have tried casting it but haven't found the correct way.
Help is much appreciated!
Try check the instance:
$result = $campaignCriterionService->get($serviceSelector);
$campaignAdSchedules = $result->getEntries();
foreach ($campaignAdSchedules as $criterion) {
$adSchedule = $criterion->getCriterion();
if ($adSchedule instanceof AdSchedule) {
$adSchedule->getStartHour();
}
}

PHP solr atomic update

I'm new in solr and I've been using this thread to do a atomic update
How do I update a document in Solr PHP?
Basically im doing an mysql query then update a document on solr
Question: How to do an atomic update where a specific field matches a field should be matched inside an if statement like this:
if(solr(username.field) == 'john'))
{
//execute atomic update
}
so far my code is messy like these:
$query = "SELECT * from User";
$options = array
(
'hostname' => SOLR_SERVER_HOSTNAME,
'login' => SOLR_SERVER_USERNAME,
'password' => SOLR_SERVER_PASSWORD,
'port' => SOLR_SERVER_PORT,
'path' => SOLR_SERVER_PATH,
);
$result = $mysqli->query($query);
if($result->num_rows > 0)
{
while($row=mysqli_fetch_assoc($result))
{
$querySearch = '+username:*'; //query all user that is on solr
$query = new SolrQuery();
$query->setQuery($querySearch);
$query->setStart(0);
$query->setRows(10000);
$client = new SolrClient($options);
$query_response = $client->query($query);
$query_response->setParseMode(SolrQueryResponse::PARSE_SOLR_DOC);
$response = $query_response->getResponse();
$doc = new SolrInputDocument();
$counter = $response->response->numFound;
for($x = 0; $x < $counter; $x++)
{
$doc = $response->response->docs[$x]->getInputDocument(); //this gets the old value (refer to thread)
$docs = $query_response->getResponse()->response->docs[$x]->username->values; //how I get the value of users
$second_doc = new SolrInputDocument();
if($docs == get_product($row['USERNAME']))
{
$second_doc->addField('points', $row['POINTS']); //this suppose to update my solr document with those username found
}
else
{
$second_doc->addField('points', "0");
}
$second_doc->merge($doc);
$updateResponse = $client->addDocument($second_doc);
$client->commit();
}
}
It should have been
if(!empty($response->response->docs[$x]->username->values[$x]) == get_product($row['USERNAME']))
{
$doc = $response->response->docs[$x]->getInputDocument();
$second_doc->addField('point', $row['POINT']);
}
else
{
//do other update here
}
//$response->response->docs[$x]->username->values[$x] => get the usernames in the document

Sending WooCommerce order to NetSuite

I'm attempting to take an order from WooCommerce using the Rest API, and add that information into NetSuite as a Sales Order. I can successfully grab the order information from WooCommerce, but I am unsuccessful when adding the order into NetSuite using the PHPToolkit. Here is what I have so far:
<?php
/*
* Add a customer to Netsuite.
*
* paramtypesmap
*
*/
require_once 'includes/functions.php';
// create array of fields
$itemArr = array();
$i = 0;
$service = new NetSuiteService();
$salesOrder = new SalesOrder();
$salesOrder->entity = new RecordRef();
$salesOrder->entity->internalId = 512;
$salesOrder->entity->type = 'customer';
$salesOrder->shipDate = formatDate('2014-10-06T07:12:57.000-07:00');
$service = new NetSuiteService();
$service->setSearchPreferences(false, 1000);
$siteCategory = new SearchMultiSelectField();
$siteCategory->operator = "anyOf";
$siteCategory->searchValue = array('internalId' => 512);
$search = new ItemSearchBasic();
$search->internalId = $siteCategory;
$request = new SearchRequest();
$request->searchRecord = $search;
$searchResponse = $service->search($request);
$products = $searchResponse->searchResult->recordList->record;
$salesOrder->itemList = new SalesOrderItemList();
$item = new SalesOrderItem();
$item->item = new RecordRef();
$item->item->internalId = 531;
$item->quantity = 1;
//removeEmpty($item->item);
//removeEmpty($item);
$item->price = new RecordRef();
$item->price->internalId = 1;
$item->amount = 55.3;
$salesOrder->itemList->item=array(0=>$item);
//Equivalent too print_r
pr($item);
//Equivalent too print_r
pr($salesOrder);
removeEmpty($salesOrder);
$request = new AddRequest();
$request->record = $salesOrder;
//$service->setFields($purchaseOrderFields);
$response = $service->add($request);
if (!$response->writeResponse->status->isSuccess) {
echo getErrors($response->writeResponse);
} else {
echo success($response->writeResponse->baseRef->internalId);
}
?>
I'm just trying to work from the ground up to see what fields are required and how to build them, however I keep getting this error when ran:
Please choose a child matrix item
I have spent the last couple of days attempting to try some Google Fu on the problem, but with my luck found nothing. Can anyone help me with this?
Based from the error message, you are trying to submit a Parent Matrix Item instead of the child. Verify it by checking the Item Record with internal id 531.
The best way to achieve correct internal ids is to import Matrix Items directly from NetSuite into WooCommerce as variable products. Assigning the internal id to each variation.

Google Calendar EventId issues (PHP Api)

I've been working with the PHP api for google Calendar, and have been getting quite frustrated.
I downloaded the zend package with all the libraries from google's page, and have been working off the provided code to make sure it can meet my requirements.
The issue I'm running into involves getting an event back from the system. The provided code includes a demo with function getEvent($clientId, $eventId), which based on the documentation and reading the code, i would expect to return an event that is in my calendar that matches the provided Id.
So in my tests, I create a new event, and then I try to retrieve it. However, whenever I retrieve the event, Zend_data_Gdata_App_HttpException is:
function processPageLoad()
{
global $_SESSION, $_GET;
if (!isset($_SESSION['sessionToken']) && !isset($_GET['token'])) {
requestUserLogin('Please login to your Google Account.');
} else {
$client = getAuthSubHttpClient();
$id = createEvent ($client, 'Tennis with Beth',
'Meet for a quick lesson', 'On the courts',
'2010-10-20', '10:00',
'2010-10-20', '11:00', '-08');
$newEvent = getEvent($client, $id);
}
}
the code for createEvent( ) is :
function createEvent ($client, $title = 'Tennis with Beth',
$desc='Meet for a quick lesson', $where = 'On the courts',
$startDate = '2008-01-20', $startTime = '10:00',
$endDate = '2008-01-20', $endTime = '11:00', $tzOffset = '-08')
{
$gc = new Zend_Gdata_Calendar($client);
$newEntry = $gc->newEventEntry();
$newEntry->title = $gc->newTitle(trim($title));
$newEntry->where = array($gc->newWhere($where));
$newEntry->content = $gc->newContent($desc);
$newEntry->content->type = 'text';
$when = $gc->newWhen();
$when->startTime = "{$startDate}T{$startTime}:00.000{$tzOffset}:00";
$when->endTime = "{$endDate}T{$endTime}:00.000{$tzOffset}:00";
$newEntry->when = array($when);
$createdEntry = $gc->insertEvent($newEntry);
return $createdEntry->id->text;
}
And finally the code for getEvent() is:
function getEvent($client, $eventId)
{
$gdataCal = new Zend_Gdata_Calendar($client);
$query = $gdataCal->newEventQuery();
$query->setUser('default');
$query->setVisibility('private');
$query->setProjection('full');
$query->setEvent($eventId);
try {
$eventEntry = $gdataCal->getCalendarEventEntry($query);
return $eventEntry;
} catch (Zend_Gdata_App_Exception $e) {
var_dump($e);
return null;
}
}
we have the same problem, just share my solution. since you assign $id = createEvent()
$id will have a URL values. then you use $id getEvent($client, $id);
the solution is that getCalendarEventEntry() can have a $query or just a URL.
function getEvent($client, $eventId)
{
$gdataCal = new Zend_Gdata_Calendar($client);
try {
$eventEntry = $gdataCal->getCalendarEventEntry($eventId);
return $eventEntry;
} catch (Zend_Gdata_App_Exception $e) {
var_dump($e);
return null;
}
Hope it helps!!

Categories