Drupal StackExchange

Create a View of Books

2 days 1 hour ago

I'm using the core Book module for organizing meeting notes and documentation. How do I create a list of books with the views module? That is, I'd like a list of only the top-level Books, not all the book pages.

An example of what I want in core is at admin/content/book which looks like this:

Thus far, all I've been able to get is a hierarchical list of books and all book pages. Current view:

rocketeerbkw

Adding HTML class attributes to Entity Reference field links in View

2 days 2 hours ago

I have a view ("Tasks") that pulls in Task nodes, complete with sorting and filtering. Each Task can have multiple nodes attached via the "Related Articles" field (field_related_articles). I am trying to loop through each node (which can be a Video, Document, Article, etc.) and assign each link a class name depending on the type.

For example, a "Document" node attached to a Task would display a hyperlink with the document class. Video nodes will be video, and so on.

Here is my preprocess that is targeting the specific field:

function mytheme_preprocess_field__node__field_related_articles(&$variables) { $items = $variables['items']; foreach ($items as $index => $item) { $content_type = $item['content']['#options']['entity']->type->entity->label(); $class_name = slugify($content_type); // custom function $variables['items'][$index]['attributes']['class'] = [$class_name]; } }

When I inspect the $variables array, I see the following, which looks okay to me (but I can't be sure):

As you can see, the attributes object now has a class value for each items value (I have two). However, in the HTML, the classes do not show up:

Is there something I'm doing wrong?

TerranRich

Migration lookup and no stubbing

2 days 3 hours ago

I have a problem with languages and no stubbing regarding migration_lookup plugin in Drupal 8. I have a different json data, each of them is different languages for example json with de:

data:{ id: 12345, name: 'Product 1 de', id: 123456, name: 'Product 2 de'}

json with en

data:{ id: 12345, name: 'Product 1 en'}

of course this json is only example not validate.

I have a 2 migration yaml file called: migrate_plus.migration.data.yml and migrate_plus.migration.data_de.yml

English version is default version in drupal.

To join de version with en I use process:

nid: - plugin: migration_lookup source: id migration: data no_stub: true stub_id: data

I use no_stub: true because i don't want to create stub nodes for not existing en version. Everything works well but only for first time but if I want to update migration I got errors

[error] Drupal\Core\Database\IntegrityConstraintViolationException: SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry '9424706c-e536-4a59-be13-ebb91367a1a9' for key 'node_field__uuid__value': INSERT INTO {node} (vid, type, uuid, langcode) VALUES (:db_insert_placeholder_0, :db_insert_placeholder_1, :db_insert_placeholder_2, :db_insert_placeholder_3); Array

for de version item. In my case I don't want to create new stub item for english version for product 2 de so I though that no_stub option will be ok. Even if I do migrate:rollback I noticed that this migration from de still exist.

crafter

Why this code doesn't send an email with drupal_email()?

2 days 4 hours ago

I am developing a Drupal 6 module that should send an email after a form is submitted. So far, I wrote the following code.

function mailform_mail($key, &$message, $params) { $headers = array( 'MIME-Version' => '1.0', 'Content-Type' => 'text/html; charset=UTF-8; format=flowed', 'Content-Transfer-Encoding' => '8Bit', 'X-Mailer' => 'Drupal' ); foreach ($headers as $key => $value) { $message['headers'][$key] = $value; } $message['subject'] = $params['subject']; $message['body'] = $params['body']; } /** * Form submission handler. */ function mailform_form_submit($form, &$form_state) { $valid_email = $form_state['values']['email']; $subject = $form_state['values']['Subject']; $body = $form_state['values']['body']; $params = array( 'email'=> $valid_email, 'body' => $body, 'subject' => $subject, ); // The first argument of drupal_mail() function must match the first part of the hook_mail function. // Therefore the first argument is 'mailform_form' and the the mail hook is 'mailform_form_mail' // For more infoormation see: // - http://api.drupal.org/api/function/drupal_mail/6 // - http://api.drupal.org/api/function/hook_mail/6 if (drupal_mail('mailform','reply', $valid_email, language_default(), $params, $from, TRUE) { drupal_set_message('An email has been sent to ' . $valid_email); } else { drupal_set_message('There was an error sending your email'); } }

Using this code, I can get the values after a form is submitted, but the mail is not sent out.

Is there anything wrong with the code? The module machine name is mailform.

Rahman

How can I fix the "Predis\Client not found" error?

2 days 5 hours ago

I have a project based on Drupal 7. I installed PHP 7.4, Redis, and php-redis on Ubuntu. I get a Class 'Predis\Client' not found error.

The values in the setting.php file for the module are the following.

$conf['redis_client_interface'] = 'Predis'; $conf['cache_backends'][] = 'sites/all/modules/redis/redis.autoload.inc'; $conf['cache_class_cache'] = 'Redis_Cache'; $conf['cache_class_cache_menu'] = 'Redis_Cache'; $conf['cache_class_cache_drupal_get_filename'] = 'Redis_Cache'; $conf['cache_class_cache_bootstrap'] = 'Redis_Cache'; $conf['cache_class_cache_path'] = 'Redis_Cache'; $conf['cache_class_cache_field'] = 'Redis_Cache'; $conf['cache_class_cache_views'] = 'Redis_Cache'; $conf['cache_class_cache_admin_menu'] = 'Redis_Cache'; $conf['lock_inc'] = 'sites/all/modules/redis/redis.lock.inc';

When I run drush cc the same error is show. For solving that, I re-installed Redis and php-redis, but that hasn't fixed the error.

mohammad nabipour

How to configure a Slideshow with thumbnails in modal window

2 days 6 hours ago

I have tried to get the following scenario to work, with no success. I have 3 images. They are displayed in thumbnail form, in the bottom of a div. A main, preferred image, is displayed in a larger size above the thumbnails. I need that, when clicking on the thumbnail, the main image will change. So, in the image included, if I click on the green image, the main image will change from red to green.

Also I need that when clicking on the larger image, a modal window will appear, with a Slideshow of all the images, starting from the one clicked.

I have managed to make it work very easily with PHP-Javascript alone (10 minutes of programming) but I am not able to do it with none of the following modules: Colorbox, FlexSlider, Lightbox2.

Even when launching a View with FlexSlider content using Lightbox2, it works but it takes ages to load the content, even if I have disabled all extra HTML stuff by making a template tpl suggestion.

Sincerely, I don't think it is so complicated behaviour. Also there is the approach of FlexSlider with thumbnails, but I cannot manage to include the lightbox (modal window) effect.

Cesar

How to build multivalue form elements using Form API

2 days 7 hours ago

With the 'field collections' module at the form level, you can create a fieldset (or 'field group') that will accept multiple sets of values.

Is there a way to do this with the Form API directly (or with the help 'field collections' or 'field group' module) programmatically. I can make the form fieldset easy enough, but I'm not sure how to set multiple values for this set. In fact, I'm not really sure how you define multiple values for any field with the Form API.

UPDATE: Just to be clear I want to create the form, not the entity itself (at least not yet). I want to use the Form API to accomplish this to make my own $form – just the form.

Joe

Webform mail formatting broken after moving to symfony-mailer-lite from swiftmailer

2 days 7 hours ago

In march 2024 we left swiftmailer and switched to symfony-mailer-lite.

Everything looked well until we found that the font for mails which had no template specified in our theme had a default font like times new roman instead of arial.

We then took the mail template from the old swiftmailer and put it in our theme thought this will fix it.

It did fix it for the font but not for the formatting. Before any Element title was bold and styled in the mails now only plain text.

So now I wonder if there is something else we missed.

Here are two mails, the first is from february and contains all the style info. The second is from now.

<html><head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"><style type="text/css"> table tr td { font-family: Arial; font-size: 12px; } </style> </head> <body> <div> <table width="800px" cellpadding="0" cellspacing="0"> <tr> <td> <div style="padding: 0px 0px 0px 0px;"> <p>Gesendet am: Fr., 26.04.2024 - 19:35</p> <p>Gesendet von: admin</p> <p>Gesendete Eingaben:</p> <b>Anrede</b><br>Familie<br><br><b>Vorname</b><br>Dixisset<br><br><b>Nachname</b><br>Loremipsum<br><br><b>Straße</b><br>Dixisset<br><br><b>Hausnummer</b><br>Oratione<br><br><b>PLZ</b><br>Loremipsum<br><br><b>Ort</b><br>Loremipsum<br><br><b>E-Mail</b><br><a href="mailto:test@test.com">test@test.com</a><br><br><b>Telefonnummer</b><br>Oratione<br><br><b>Betreff</b><br>Loremipsum<br><br><b>Ihr Anliegen</b><br>Quae cum dixisset, finem ille. Quamquam non negatis nos intellegere quid sit voluptas, sed quid ille dicat. Progredientibus autem aetatibus sensim tardeve potius quasi nosmet ipsos cognoscimus. Gloriosa ostentatio in constituendo summo bono. Qui-vere falsone, quaerere mittimus-dicitur oculis se privasse; Duarum enim vitarum nobis erunt instituta capienda. Comprehensum, quod cognitum non habet? Qui enim existimabit posse se miserum esse beatus non erit. Causa autem fuit huc veniendi ut quosdam hinc libros promerem. Nunc omni virtuti vitium contrario nomine opponitur.<br><br><b>Weitergabe von personenbezogenen Daten</b><br>Ich bin nicht damit einverstanden, dass meine in diesem Formular erhobenen personenbezogenen Daten zum Zweck der Beantwortung meiner Anfrage an andere Behörden der Landesverwaltung, Bundes- oder kommunale Behörden weitergeleitet werden. Wir weisen vorsorglich darauf hin, dass Ihre Anfrage u. U. nicht beantwortet werden kann, wenn Sie hiermit nicht einverstanden sind.<br><br> </div> </td> </tr> </table> </div> </body> </html>

The current one:

<!-- THEME DEBUG --><!-- THEME HOOK: 'symfony_mailer_lite_email' --><!-- FILE NAME SUGGESTIONS: * symfony-mailer-lite-email--webform--kontakt-e-mail.html.twig * symfony-mailer-lite-email--webform.html.twig x symfony-mailer-lite-email.html.twig --><!-- BEGIN OUTPUT from 'themes/custom/hw_radix_standard/templates/mail/symfony-mailer-lite-email.html.twig' --><html><head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"><style type="text/css"> table tr td { font-family: Arial; font-size: 12px; } </style> </head> <body> <div flags="63"> <table width="800px" cellpadding="0" cellspacing="0"> <tr> <td> <div style="padding: 0px 0px 0px 0px;"> <b>symfony-mailer-lite-email</b> <!-- THEME DEBUG --> <!-- THEME HOOK: 'webform_email_message_html' --> <!-- FILE NAME SUGGESTIONS: * webform-email-message-html--kontakt--email--e-mail.html.twig * webform-email-message-html--kontakt--email.html.twig * webform-email-message-html--kontakt.html.twig x webform-email-message-html.html.twig --> <!-- BEGIN OUTPUT from 'modules/contrib/webform/templates/webform-email-message-html.html.twig' --> <b>webform-email-message-html</b> <p>Gesendet am: Fr., 26.04.2024 - 13:44</p> <p>Gesendet von: admin</p> <p>Gesendete Eingaben:</p> <p> Anrede<br>Frau</p> <p> Vorname<br>Dixisset</p> <p> Nachname<br>Dixisset</p> <p> Straße<br>Oratione</p> <p> Hausnummer<br>Oratione</p> <p> PLZ<br>Oratione</p> <p> Ort<br>Loremipsum</p> <p> E-Mail<br><a href="mailto:test@test.com">test@test.com</a></p> <p> Telefonnummer<br>Oratione</p> <p> Betreff<br>Loremipsum</p> <p> Ihr Anliegen<br>Quae cum dixisset, finem ille. Quamquam non negatis nos intellegere quid sit voluptas, sed quid ille dicat. Progredientibus autem aetatibus sensim tardeve potius quasi nosmet ipsos cognoscimus. Gloriosa ostentatio in constituendo summo bono. Qui-vere falsone, quaerere mittimus-dicitur oculis se privasse; Duarum enim vitarum nobis erunt instituta capienda. Comprehensum, quod cognitum non habet? Qui enim existimabit posse se miserum esse beatus non erit. Causa autem fuit huc veniendi ut quosdam hinc libros promerem. Nunc omni virtuti vitium contrario nomine opponitur.</p> <p> Weitergabe von personenbezogenen Daten<br>Ich bin damit einverstanden, dass meine in diesem Formular erhobenen personenbezogenen Daten zum Zweck der Beantwortung meiner Anfrage an andere Behörden der Landesverwaltung, Bundes- oder kommunale Behörden weitergeleitet werden. </p> <!-- END OUTPUT from 'modules/contrib/webform/templates/webform-email-message-html.html.twig' --> </div> </td> </tr> </table> </div> </body> </html> <!-- END OUTPUT from 'themes/custom/hw_radix_standard/templates/mail/symfony-mailer-lite-email.html.twig' -->

We did not have any special template with all the styles for the mail body.
So I wonder where this information did come from before. Any changes in webform module, core or is symfony-mailer just dropping it?

Found this issue in symfony-mailer-lite https://git.drupalcode.org/project/symfony_mailer_lite/-/commit/623c53acc21bd1d82fad41bec7cfd8eacd1e7546 and changed the config to not use the default content in the message settings of symfony-mailer-lite - but no change to the behaviour. Somehow the HTML of message.body from webform gehts stripped.

macbert

PHPUnit Test run Error with ConfigFactory

2 days 8 hours ago

I'm running an error with the following test I wrote including some config. I don't know if my test is even properly written so any advice in improving that code is welcomed. Since my test is not finish yet, dont mind the self::assertTrue(TRUE);

Here is my Test :

namespace Drupal\mymodule\Tests\Service; use Drupal\Component\Serialization\Json; use Drupal\Core\DependencyInjection\ContainerBuilder; use Drupal\Core\Url; use Drupal\Tests\UnitTestCase; use Drupal\mymodule\Service\MyClass; /** * MyClass Test. * * @group mymodule */ class MyClassTest extends UnitTestCase { private $params; protected $configFactory; protected $loggerFactory; protected $container; protected $myClass; /** * Set Up. */ public function setUp() { parent::setUp(); $this->configFactory = $this ->getConfigFactoryStub([ 'mymodule.settings' => [ 'api' => [ 'hostname' => 'https://example.com', 'periodbars_uri' => '/api/v2.0/articles', 'api_key' => 'aaabbbcccdddeeefffzzz', ], ], ]); $this->container = new ContainerBuilder(); $this->container ->set('config.factory', $this->configFactory); \Drupal::setContainer($this->container); $this->loggerFactory = $this ->getMockBuilder('Drupal\Core\Logger\LoggerChannelFactoryInterface') ->disableOriginalConstructor() ->getMock(); $this->params = [ 'criteria' => [ 'id' => '1', ], ]; $this->myClass = new MyClass($this->configFactory, $this->loggerFactory); } /** * Test API Accor Fetcher. */ public function testMyClass() { $params = Json::encode($this->params); $url = 'https://example.com/api/v2.0/articles'; $this->myClass->myClassRequest($url, $params, 'FR'); self::assertTrue(TRUE); } }

And here is the class I test :

namespace Drupal\mymodule\Service; use Drupal\Core\Config\ConfigFactoryInterface; use Drupal\Core\Logger\LoggerChannelFactoryInterface; use Psr\Http\Message\ResponseInterface; use GuzzleHttp\Client; use GuzzleHttp\Psr7\Request; use GuzzleHttp\Pool; use GuzzleHttp\Exception\ClientException; use GuzzleHttp\Exception\ServerException; use Drupal\Core\Url; /** * Provides all the functions to call MyClass Webservices. */ class MyClass { protected $configFactory; protected $loggerFactory; /** * AccorWebService constructor. * * @param \Drupal\Core\Config\ConfigFactoryInterface $config_factory * Config Factory. * @param \Drupal\Core\Logger\LoggerChannelFactoryInterface $logger_factory * Logger Factory. */ public function __construct(ConfigFactoryInterface $config_factory, LoggerChannelFactoryInterface $logger_factory) { $this->configFactory = $config_factory; $this->loggerFactory = $logger_factory; } /** * The Guzzle Request. * * @param string $url * The url of the webservice to call. * @param string $params * The params to be sent to the webservice formatted in JSON. * @param string $langcode * The langcode to call the webservice. * * @return \Psr\Http\Message\StreamInterface|null * The response from the webservice. */ public function myClassRequest($url, $params, $langcode = 'FR') { $api_key = $this->configFactory->get('mymodule.settings')->get('api.api_key'); $headers = [ 'apikey' => $api_key, 'Content-Type' => 'application/json', 'Accept-Language' => $langcode, ]; $client = new Client(); $response = NULL; try { $request = $client->request('POST', $url, [ 'headers' => $headers, 'body' => $params, ]); $response = $request->getBody(); } catch (ClientException $e) { $this->loggerFactory->get('mymodule') ->error($e->getMessage()); } catch (ServerException $se) { $this->loggerFactory->get('mymodule') ->error($se->getMessage()); } return $response; }

When I run the Test in PHPStorm, I get Call to a member function get() on null on the line where the code is : $api_key = $this->configFactory->get('mymodule.settings')->get('api.api_key');

pbonnefoi

Drupal Planet

Drupal Core News: Drupal 11.0.0-alpha 1 will be released on the week of April 29, 2024

2 days 7 hours ago

Last month, we announced that depending on readiness of the codebase to 11.0.0 beta requirements today on April 26, 2024, Drupal 11 would be released either on the week of July 29, 2024 or the week of December 9, 2024.

The Drupal 11 codebase progressed a lot since then, it is based on Symfony 7 and jQuery 4, and the deprecated APIs have been removed. However, while we are making rapid progress on PHPUnit 10 support, we need to fully complete that update to PHPUnit 10 before a beta release, which will not quite be ready for next week.

To help the community prepare for Drupal 11, we decided to make Drupal 11.0.0-alpha1 available next week (on the week of April 29, 2024), alongside Drupal 10.3.0-beta1. This also means that those attending DrupalCon Portland 2024 the week after can already try out the first tagged version of Drupal 11, and modules can add Drupal 11 compatibility confident that all runtime APIs are stable.

We are giving ourselves an additional couple of weeks to run down the last PHPUnit 10 issues and any other remaining beta blockers ready for a stable Drupal 11.0.0 release on the week of July 29, 2024. Assuming all goes well, we'll make a final decision by May 10th and release a beta shortly afterwards.