Is there an easy solution to export a filtered backendlist - list

I have a list with products and locations. I've created a filterdefinition and can filter products based on a location.
Now I want to export te filtered selection to print it to an pdf.
I've tried to acces the filtered items with the ajax framework, but can't find any information on how to retrieve the filtered id's.
My printhandler works fine, I only need to get the ID's of selected items in the filter.
scopes:
location:
label: Location
modelClass: XXX\xxxx\Models\Location
conditions: location_id in (:filtered)
nameFrom: location

As always, found a solution after asking for one;
Found a piece of code:
function getCurrentFilters() {
$filters = [];
foreach (\Session::get('widget', []) as $name => $item) {
if (str_contains($name, 'Filter')) {
$filter = #unserialize(#base64_decode($item));
if ($filter) {
//$filters[] = $filter;
array_push($filters, $filter);
}
}
}
return $filters;
}

Related

How to update local data after mutation?

I want to find a better way to update local component state after executing mutation. I'm using svelte-apollo but my question is about basic principles. I have watchQuery which get list of items and returns ObservableQuery in component.
query GetItems($sort: String, $search: String!) {
items(
sort: $sort
where: { name_contains: $search }
) {
id
name
item_picture{
pictures{
url
previewUrl
}
}
description
created_at
}
}
In component I call it:
<script>
$: query = GetItems({
variables: {
sort: 'created_at:DESC',
search
}
});
</script>
...
{#each $query.data?.items || [] as item, key (item.id)}
<div>
<Item
deleteItem={dropItem}
item={item}
setActiveItem={setActiveItem}
/>
</div>
{/each}
...
And I have addItem mutation.
mutation addItem($name: String!, $description: String) {
createItem(
input: { data: { name: $name, description: $description } }
) {
item {
name
description
}
}
}
I just simply want to update local state and add new item to an observable query result after addItem mutation, without using refetchQueries (because I don't want to get all list by network when I just added one item).
I seen this item in cache but my view is not updated.
P.S. If you have similar problems and some ways to solve it, be glad to see some cases from you.
I believe in this case, you could use the cache.modify function to modify the cache directly if you’re looking to skip the network request from refetchQueries. Would that work for your use case? https://www.apollographql.com/docs/react/data/mutations/#making-all-other-cache-updates
If you don’t mind the network request, I like using cache.evict to evict the data in the cache that I know changed personally. I prefer that to refetchQueries in most cases because it refetches all queries that used that piece of data, not just the queries I specify.

hook_form_FORM_ID_alter: Pre select a checkbox from an exposed filter in a drupal 8 view

I have a view that lists blog articles. The blog content type has a taxonomy reference field to the 'tags' vocabulary, authors can select 1 or multiple tags. The view exposes the 'Has taxonomy terms (with depth) (exposed)' filter (as a list of checkboxes) so that users can search for blog articles containing 1 or more tags.
Now, i'm trying to pre-select 1 of the checkboxes that are exposed to the user in the hook_form_FORM_ID_alter() hook. It should be a simple as the code below but it just doesn't work. The tag i'm trying to pre-select has the ID 288.
What am i doing wrong? Thx...
function xtheme_form_views_exposed_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id)
{
if($form['#id'] == 'views-exposed-form-vcon-finder-page-1'){
$form['tags']['#default_value'] = [288 => 288];
}
}
You have to set user input like this:
function xtheme_form_views_exposed_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {
if($form['#id'] == 'views-exposed-form-vcon-finder-page-1'){
if (is_null(\Drupal::request()->get('tags'))) {
// Avoid overriding the filter values selected by user
$input = $form_state->getUserInput();
$input['tags'] = [288 => 288];
$form_state->setUserInput($input);
}
}
}

Hide empty group in Ag-grid after row update

How to remove empty groups from ag-grid after updateRowData. In the plnkr example, I am modifying country value for the row, I expect group name to be changed but instead a new group is created.
Code for modifying country name:
let toBeUpdate = [];
this.gridApi.forEachNode((rowNode, index) => {
if(rowNode.data && rowNode.data.athlete == 'Sadiq Khoja'){
var data = rowNode.data;
data.country = 'AAA Unknown X';
toBeUpdate.push(data);
}
});
this.gridApi.updateRowData({update:toBeUpdate});
https://plnkr.co/edit/PTuwR5zejS2xiLIg
(Press 'Add' button to change the country name)
UpdateRowData works when there is no row group.
In this case, instead of using updateRowData try using setRowData -
this.gridApi.setRowData(toBeUpdate);
This will also refresh the grid to reflect the changes in the row.
For more information you can read here - https://www.ag-grid.com/documentation/javascript/data-update/
The correct way to update your data would be to use the setDataValue on rowNode (see here).
Once you update your data, you need to refresh your view for grouping via the api by calling refreshClientSideRowModel.
So your update funciton should be as follows:
this.gridApi.forEachNode((rowNode, index) => {
if(rowNode.data && rowNode.data.athlete == 'Sadiq Khoja'){
rowNode.setDataValue('country', 'AAA Unknown X');
}
});
this.gridApi.refreshClientSideRowModel('group');
Demo

Filter in multiple parameters in query string

I've got a django app that has a filter as one of it's features.
The filter values are decided from a checkbox which is sent to the django backend using ajax as follows:
$('input.type-check').on('click', function(){
var a = $(this).prop('checked');
if(a == true){
elem.push($(this).attr('data-role'));
}else{
elem.splice($(this).attr('data-role'));
}
var cats = '';
$.each(elem, function(i){
cats += elem[i];
});
var xurl ='/filter?category='+cats;
$.ajax({
type: 'GET',
url: xurl,
success: function(data){
$('div.products').html(data);
}
})
});
The /filter$' url is mapped to thefitlered` view which is:
def filtered(request):
if 'category' in request.GET and request.GET['category']:
cat = request.GET['category']
ct = Product.objects.filter(category__in=cat)
diction = {'prods': ct}
return render(request, 'filter.html', diction)
It works when only one category is sent as parameter. However, when I send multiple, it gives no results.
Eg:
filter?category=Dairy will return the product that's associated with that category. However, filter?category=Dairy,Plastics or filter?category=DairyPlastics (which is from the above mentioned Javascript snippet) returns no result.
I've tried putting the category inside brackets in the view as follows [cat] but that doesn't help either. What should I do to make it return results?
The issue is, you are neither specifying a delimiter to demarcate the categories, not are you separating the categories in the view.
Try this:
In JQuery,
var cats = elem.join(', ')
var xurl ='/filter?category='+cats;
And in the view:
def filtered(request):
if request.GET.get('category'):
cat = request.GET.get'category')
cat_list = [c.strip() for c in cat.split(',')]
ct = Product.objects.filter(category__in=cat_list).distinct()
#You might need a distinct clause too, to remove duplicates
diction = {'prods': ct}
return render(request, 'filter.html', diction)
This would work for a single category v/s a list of categories

Getting current cart ID in prestashop

I am busy with a site built on Code Igniter that needs integration with Prestashop. In the site, when creating a user account, I save a "shop_id" to the database, which is then retrieved as a session variable when logging in.
I am using the Prestashop API to retrieve the customer successfully (using above "shop_id")
$xml = $this->PSWebService->get(
array('resource' => 'customers', 'id' => (int)$this->user['shop_id'])
);
This successfully returns the user in question, but there is no Cart IDs in this result.
Logging in to the back-end of my shop, I see that there are multiple carts associated with the logged in user.
My question is: How to I retrieve the LATEST cart ID using the API?
$userId = (int) $this->user['shop_id'];
$opt['resource'] = 'carts';
$xml = $this->PSWebService->get($opt);
$carts = $xml->carts->children();
foreach ($carts as $cart) {
$cartIds[] = $cart['id'];
}
for ($i = count($cartIds) - 1; $i > -1; $i--) {
$opt['id'] = $cartIds[$i];
$xml = $this->PSWebService->get($opt);
//since cart ids are descending the first found will be the latest
if ($xml->cart->id_customer == $userId) {
$latestCartId = $cartIds[$i];
break;
}
}
Kind of late, but I struggled a bit with this same problem and found a way to do it just from query, based on yenshirak's tip (since cart ids are descending the first found will be the latest).
I query the API directly using postman like this:
get all carts:
GET webserver/api/carts
get cart for customer:
GET webserver/api/carts?filter[id_customer]=1
get the most recent:
GET webserver/api/carts?filter[id_customer]=1&sort=[id_DESC]&limit=1
for a pretty print, you can also add params:
display=full&output_format=JSON
You can do this in php, I have not tested if the syntax is correct, but based on documentation it looks something like this:
$opt = array(
'resource' => 'carts',
'filter[id_customer]' => '[1]',
'sort' => '[id_DESC]',
'limit' => '1'
);
$xml = $webService->get($opt);