Drupal 9 How to add pager with entityQuery - drupal

We've a Drupal 9 installation and are trying to add a pager using the pagerer module for articles entityQuery, the aim is to list tagged articles in a tag page, but it’s not working. It returns null.
When we dump the data without the pager, using default drupal query, it returns the data of all tagged articles properly.
The code is added in the theme file themeName_preprocess_page hook and being called in page--page.html.twig template file.
Here’s our code:
$query = \Drupal::entityQuery('node')
->condition('status', 1)
->condition('type', 'article');
->pager(2);
$nids = $query->sort('created', 'DESC')
->execute();
if($nids):
$nodesNews = \Drupal\node\Entity\Node::loadMultiple($nids);
$pathNews = base_path();
$pager = [
'articles_data' => $nodesNews,
'results' => [
'#theme' => 'news_pagination',
'#items' => $nodesNews,
'#path' => $pathNews,
'#tag' => $tag
],
'pager' => [
'#type' => 'pager',
'#quantity' => 5
],
];
return $pager;
endif;
And here is the code that calls the query:
<div>
{{ articles_data }}
{{ pager }}
</div>
The above code returns only one page in the navigation and we’ve 10 articles, so given that we set 2 articles per page, the output should be 5 pages instead of 1.
Also articles_data attribute returns null. Could you please help me to find what’s wrong with the code? Happy to share more information as needed, thank you.

Just reading the docs for this module here,
it would seem that you are missing at least the #theme and #style keys in your render array for the pager.
A more likely to succeed version of the above render array would be
$pager = [
'articles_data' => $nodesNews,
'results' => [
'#theme' => 'news_pagination',
'#items' => $nodesNews,
'#path' => $pathNews,
'#tag' => $tag
],
'pager' => [
'#type' => 'pager',
'#theme' => 'pagerer_base',
'#style' => 'standard',
'#config' => [
'display_restriction' => 0,
],
'#quantity' => 5
],
];

Related

Nested form elements in Drupal 8

I'm trying to wrap checkboxes element in details by doing something like this:
function pf_form_user_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state) {
$config = \Drupal::config('pf.settings.notifications');
$form['pf'] = [
'#type' => 'details',
'#title' => t('Notification for updates in specific languages'),
'#description' => t('Expect getting one to two emails weekly'),
'#open': true,
];
$form['pf']['pf.notifications.checkboxes'] = [
'#type' => 'checkboxes',
'#title' => t('Check the ones you\'d like to recieve!'),
'#options' => [
'de' => t('german'),
'en' => t('english'),
],
'#default_value' => [
'de' => $config->get('de'),
'en' => $config->get('en'),
],
];
$form['actions']['submit']['#submit'][] = 'pf_form_user_form_submit';
}
but on submit, I get constantly back $values = ['de'=>0, 'en'=>0]:
function pf_form_user_form_submit(&$form, \Drupal\Core\Form\FormStateInterface $form_state) {
$values = $form_state->getValue('pf.notifications.checkboxes');
$config = \Drupal::config('pf.settings.notifications');
$config
->set('de', $values['de'])
->set('en', $values['en'])
->save()
;
}
As soon as I don't use the wrapping details form element, data (value==key for checked elements) is there. Like this:
function pf_form_user_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state) {
....
// $form['pf'] = [ commented out
$form['pf.notifications.checkboxes'] = ...
....
Inspecting $form_state with debugger shows the same. Zeroes in first case, ok data in second.
Am I missing something? How does grouping of form elements work?
I inspected the $form_state through the debugger more thoroughly, and I noticed some of the keys were in original, with dots 'pf.notifications.checkboxes' while in other places, substitution for underscores took place and the key was 'pf_notifications_checkboxes'.
Works with underscores.

yii2 mpdf view displaying debug toolbar code

I'm using kartik mpdf extension to print a report. Problem is, in print view css code displaying and in footer debug toolbar code too. Please guide me how to remove that.
i'm using following code.
$content = $this->render('print', ['modelPatientTest' => $modelPatientTest]);
$pdf = new Pdf([
'mode' => Pdf::MODE_CORE, // leaner size using standard fonts
'content' => $content,
'format' => Pdf::FORMAT_A4,
'options' => [
'title' => 'Test Report',
],
'methods' => [
'SetHeader' => [''],
'SetFooter' => ['{PAGENO}|'],
]
]);
return $pdf->render();
As Debug toolbar should be active only in a development environment, put at the top of your controller's action this code:
if(YII_DEBUG === true || YII_ENV === "dev") {
Yii::$app->getModule('debug')->instance->allowedIPs = [];
}
(Edited thanks to #Gubberrr comment below)
Just change
'mode' => Pdf::MODE_CORE,
to
'mode' => Pdf::MODE_UTF8,

How to create products programmatically in Drupal 8 commerce

I'm using current commerce 2.x.dev for online store development. It's first project with Commerce 2 for me.
When i started to work on products import, i found that Feeds module does not stable, and i decided to write custom solution for data import (Batch/Queue API data import from CSV/XML sources).
So, at this moment i cannot find any information about correct product entities creation via code. I explored Drupal Commerce documentation section: http://docs.drupalcommerce.org/v2/product/products.html but it contains only UI instructions for manual products management.
I think that short instruction for working from code with products / orders entities will be very helpful for developers, especially for developers, who starts working with commerce 2 and have some experience with 7.x commerce.
To create a product programmatically with 3 product variations, use the following code in a custom module:
use Drupal\commerce_product\Entity\ProductVariation;
use Drupal\commerce_product\Entity\Product;
use Drupal\commerce_price\Price;
function my_module_install() {
// Create variations
$variation1 = ProductVariation::create([
'type' => 'default',
'sku' => 'var1',
'price' => new Price('24.00', 'EUR'),
]);
$variation1->save();
$variation2 = ProductVariation::create([
'type' => 'default',
'sku' => 'var2',
'price' => new Price('50.00', 'EUR'),
]);
$variation2->save();
$variation3 = ProductVariation::create([
'type' => 'default',
'sku' => 'var3',
'price' => new Price('115.00', 'EUR'),
]);
$variation3->save();
// Create product using variations previously saved
$product = Product::create([
'type' => 'default',
'title' => t('Your Product Name'),
'variations' => [$variation1, $variation2, $variation3],
]);
$product->save();
}
I hope that it answers your question. Feel free for more details.
Best regards
You need to read this documentation (Creating products) and do the same way.
Edited
$variation_blue_large = \Drupal\commerce_product\Entity\ProductVariation::create([
'type' => 'my_custom_variation_type',
'sku' => '001',
'price' => new \Drupal\commerce_price\Price('10.00', 'USD'),
'attribute_color' => $blue,
'attribute_size' => $large,
])->save();
$variations = [
$variation_blue_large,
];
$product = \Drupal\commerce_product\Entity\Product::create([
'uid' => 1,
'type' => 'my_custom_product_type',
'title' => 'My Custom Product',
'stores' => [$store],
'variations' => $variations,
]);
$product->save();
**Load product with Multi-pal variation **
use Drupal\commerce_product\Entity\ProductVariation;
use Drupal\commerce_product\Entity\Product;
use Drupal\commerce_price\Price;
// Load existing variations
$result = \Drupal::entityQuery('commerce_product_variation')
->condition('type', 'variation_type')
->execute();
$entity_manager = \Drupal::entityManager();
$product_variation = $entity_manager->getStorage('commerce_product_variation')->loadMultiple($result);
//Add variation to Product
$product = Product::create([
'type' => 'hakuro_plate',
'title' => t('Your Product Name custom New testing'),
'variations' =>$product_variation,
]);
$product->save();

How to disable HTML escaping of labels in KnpMenuBundle

I want to render an HTML label like:
$menu->addChild('Dashboard', array(
'route' => 'dashboard',
'label' => '<i class="fa-icon-bar-chart"></i><span class="hidden-tablet"> Dashboard</span></a>',
'extra' => array('safe_label' => true)
)
);
And I've pass the proper option while rendering:
{{ knp_menu_render('WshCmsHtmlBundle:Builder:mainMenu', {'allow_safe_labels': true} ) }}
But my label is still being escaped. What am I doing wrong?
Ok, the answer is!
You set up extra items on menu item not by 'extra' key but by 'extras' key.
So when you setup the item like this:
$menu->addChild('Dashboard', array(
'route' => 'dashboard',
'label' => '<i class="fa-icon-bar-chart"></i><span class="hidden-tablet"> Dashboard</span></a>',
'extras' => array('safe_label' => true)
)
);
it works fine!
There's two steps to achieve this.
1. MenuBuilder
You have to set safe_label to true in extras. Note that you can now write HTML in your label.
$menu->addChild('Home<i><b></b></i>', array(
'route' => 'homepage',
'extras' => array(
'safe_label' => true
),
));
2. Twig
You have to filter the output of knp_menu_render() so that it prints raw HTML (see documentation).
{{ knp_menu_render('main', {'allow_safe_labels': true}) | raw }}
Warning
Please be aware that this may be dangerous. From the documentation:
Use it with caution as it can create some XSS holes in your application if the label is coming from the user.
I used FyodorX's method to add a strong tag. It works like a charm but I must say that the raw filter is not necessary

Drupal Block not showing on the page

$blocks['onemore'] = array(
'info' => t('onemore'),
'status' => TRUE,
'region' => 'content',
'weight' => 0,
'cache' => DRUPAL_NO_CACHE,
'visibility' => BLOCK_VISIBILITY_LISTED,
'pages' => 'admin/structure/nodequeue/1/view/1',
);
Problem - The above block shows up and works perfectly and as expected at 'admin/structure/nodequeue/1/view/1'
My problem is that I need to declare dynamic amounts of blocks based on the users inputs. So I wrote a db fetch and for each loop.
If I do this then the block shows up in 'admin/modules' but the it is not in 'content' region for the seven theme. As I want to show it there.
I have double checked the values and even the admin/structure/block/manage/xdmp/onemore/configure has the value but the region is not selected.
I am assuming there is some conflict in the for each loop or the db query. Please advice your thoughts on it.
function xdmp_block_info() {
$blocks = array();
// Here we are going to do a db query so that I can get a list of
// block ids to declare
$resultxdmp = db_query("
SELECT * FROM xdmp_container_list ");
foreach($resultxdmp as $resultRecords)
{
$xdmp_nodeque_id_to_display =(int)$resultRecords->xdmp_nodequeue_id;
$xdmp_nodeque_id_to_display = intval($xdmp_nodeque_id_to_display);
$xdmp_path_to_show_block = 'admin/structure/nodequeue/'.$xdmp_nodeque_id_to_display.'
/view/'.$xdmp_nodeque_id_to_display.'';
$xdmp_machinenameofblock=(string)$resultRecords->xdmp_container_machine_name;
$xdmp_nameofblock=(string)$resultRecords->xdmp_container_name;
$blocks[$xdmp_machinenameofblock] = array(
'info' => t($xdmp_nameofblock),
'status' => TRUE,
'region' => 'content',
'weight' => 0,
'cache' => DRUPAL_NO_CACHE,
'visibility' => BLOCK_VISIBILITY_LISTED,
'pages' => $xdmp_path_to_show_block,
);
} // end for for each
return $blocks;
}
cheers,
Vishal
Are you sure the 'content' region is valid? If it's not, it of course can't show up :)

Resources