Does anyone know how to limit the autocomplete suggestions of Link Fields to only language of the current node?

1 month 3 weeks ago

Currently, I limit the content types using hook_form_alter with:

$form['field_standard_link']['widget'][0]['uri']['#selection_handler']="default:node"; $form['field_standard_link']['widget'][0]['uri']['#selection_settings']=[ 'target_bundles'=>['article'=>'article'], //etc

I would like to add a restriction that the internal nodes reference are in the same language as the current node.

kmharrell

Cookies for anonymous users aren't read nor checked

1 month 3 weeks ago

I currently have a module on http://hitechwolf.com that creates a welcome overlay upon a user's first visit, This should work by utilizing a jquery created cookie and showing the overlay based on its existence. The jquery works, the cookie is created, but for anonymous users the cookie is ignored and the overlay shows on every page. I've implemented jquery.cookie but it still completely ignores the cookie for anonymous users. I'm at the end of my rope, any help or alternatives would really be appreciated.

welcome-overlay.js /** * @file * Toggles Welcome Overlay, upon first button * clicks toggles different content, second toggles overlay */ (function ($, Drupal) { Drupal.behaviors.welcomeOverlay = { attach: function () { var cookieName = 'firstWelcome'; cookieValue = 'returning'; cookieDays = 60; /** Create Cookie Creation Function **/ function createCookie(name, value, days) { if (days) { var date = new Date(); date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000)); expires = "; expires=" + date.toGMTString(); } else { var expires = ""; } document.cookie = name + "=" + value + expires + "; path=/"; } /** Check for Specfic Cookie **/ function readCookie(name) { var nameEQ = name + "="; ca = document.cookie.split(';'); for (var i = 0; i < ca.length; i++) { var c = ca[i]; while (c.charAt(0) == ' ') { c = c.substring(1, c.length); if (c.indexOf(nameEQ) === 0) { return c.substring(nameEQ.length, c.length); } } } return null; } /** Sets value corresponding to cookie existance **/ var visited = readCookie(cookieName); visited2 = document.cookie.search(cookieName); /** If Non-existant Create Cookie and Show Content **/ if (visited === null || visited2 < 0) { // $(document).ready(function () { // Seconds Before Overlay Slides Over Content setTimeout(function () { overlay.slideToggle('800', 'linear', function () { appearFirst.fadeTo('800', 1, 'linear'); }); }, 1500); createCookie(cookieName, cookieValue, cookieDays); } } } })(jQuery, Drupal); welcome-overlay.module function welcome_overlay_preprocess_page(&$variables) { /** Include the jquery.cookie plugin **/ drupal_add_library('system', 'jquery.cookie'); /** Attach jquery/css to module **/ $path = drupal_get_path('module', 'welcome_overlay'); drupal_add_css($path . '/welcome_overlay.css'); drupal_add_js($path . '/welcome_overlay.js'); }
Bakajuice

Field of type media with two values display inline

1 month 3 weeks ago

I have two entities 1-is a media field (of type image) with 2 allowed values. 2-is a date field (date only) with 2 allowed values When I uses these fields in a view (Table Format) the media fields are always one over the other regardless of the multiple field setting checkbox 'display all values in the same row', while the date field is either in line when display all values in same row is checked or one over the other if unchecked.

How can I make the media fields display in the same row?

Cliff

Assign textfield to each checked option in a checkboxes field

1 month 3 weeks ago

Lets say I have a checkboxes field and when I check one of the options, I would like a textfield to appear so I can assign a number (quantity) to it. Every option I check would have its own textfield.

For example, I have a "Fruits" field and I want to be able to say how many of each fruit I have. So it would be something like that:

[x] Apple (3) [] Grape [x] Orange (2)

Is there any module that does something similar to that?

Edit:

Another thing that would do the work for me would be a select list of numbers for each option. So by default the options are like that:

[0] Apple [0] Grape [0] Orange

So I can simply change the number of fruits in each option by selecting in the dropdown.

vitorsdcs

I cant get the session

1 month 3 weeks ago

I m beginner on drupal, and i have a problem with session.

I created a custom form submission inside the clubs module.

namespace Drupal\idan_login\Form; // Form submission handler. public function submitForm(array &$form, FormStateInterface $form_state) { // Get the submitted values. $values = $form_state->getValues(); $username = $values['username']; $password = $values['password']; // Tentez d'authentifier l'utilisateur. // Attempt to check infos the user. $uid = \Drupal::service('user.auth')->authenticate($username, $password); // Check if authentication was successful. if ($uid) { // User authenticated successfully. // Load the user entity. $user = User::load($uid); // Check if the user has the "club idan" role. if ($user->hasRole('club_idan')) { $_SESSION['has_subscribed'] = TRUE; // User authenticated successfully and has the "club idan" role. \Drupal::messenger()->addStatus(t("Vous avez été connecté avec succès")); // Redirect to "/fr/clubs". $response = new RedirectResponse('/fr/clubs'); $response->send(); } else { unset($_SESSION['has_subscribed']); // User authentication failed due to missing role. \Drupal::messenger()->addError(t("Vous n'avez pas le rôle requis pour accéder à ce site")); // Redirect to a different page. $form_state->setRedirectUrl(Url::fromUri('internal:/fr/club-idan')); } } else { // Authentication failed. unset($_SESSION['has_subscribed']); // Display an error message. \Drupal::messenger()->addError(t("Nom d'utilisateur ou mot de passe invalide. Veuillez réessayer")); // Redirect back to the same page. $form_state->setRedirectUrl(Url::fromUri('internal:/fr/club-idan')); } // Rebuild the form to display any updated messages. //$form_state->setRebuild(TRUE); }

And i create a new custom module named "custom_access_check" to grant access to a page when the "has_subscribed" value has been set for the current session.

// custom_access_check.module use Drupal\Core\Url; use Drupal\Core\Session\SessionManagerInterface; /** * Implements hook_node_view_alter(). */ function custom_access_check_node_view_alter(&$build) { // Start the session if it's not already started. \Drupal::service('session')->start(); // Check if the node being viewed is of type 'your_content_type'. if (!empty($build['#node']->getType()) && $build['#node']->getType() == 'page') { if ($alias_path == '/clubs') { // Check if the session variable "has_subscribed" is set. if (!isset($_SESSION['has_subscribed']) || !$_SESSION['has_subscribed']) { // If user has not subscribed, deny access to the content. throw new \Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException(); } } } }

$_SESSION['has_subscribed'] contains NULL.

If someone has the some situation or has any idea for this problem?

Mohamed Ouhammou

Compatibility of Bioinformatics modules: Should I downgrade for the unsupported modules?

1 month 3 weeks ago

As part of college course work, I am required to make a genomic database for a local website with basic features (like gene search, sequence alignment). I have installed Drupal 10.2.3 with PostgreSQL 14.11, PHP 8.3.4 and Tripal 4.0.0-alpha2.

Problem arises when I try to install essential modules like Tripal BLAST UI and Jbrowse. These are some of the main features I have to implement, but both documentations only show Drupal 7.x compatibility.

My main doubt is, considering the time frame I have to finish this course (1 month), can I afford to wait for module upgradation to support Drupal 10 (Tripal 4), or should I redo the whole project with Drupal 7? Or is there anything else I am missing? I am looking to create this as part of my course project that can be converted to a full-fledged website beyond that (so cannot redo the whole thing after Drupal 7 end-of-support in just a few months).

Note: I am new to Drupal and website development in general. Would appreciate clear instructions or redirection if I am in the wrong forum.

s-135

Use Tokens and/or Replacement Patterns in Shortcodes

1 month 3 weeks ago

Looking for a way to add a token/replacement pattern into shortcode.

For example, creating a button where different text and link is required depending on other factors - something like the following:

[button link="mysite/[url replacement pattern]" text="[label replacement pattern]"][/button]

The main reason I need to do this is that I'm using view field views and want to replace an empty field with a custom button, contained in the 'sub view' when the view is empty, which needs to be different depending on what should be in the 'sub view' - I'm using shortcodes in with Global: Text Area in the No Results Behaviour (if that makes sense)

Unless, of course, anyone knows another way to achieve the same result.

Simo

How can I set up an a SQLite memory database to improve PHPUnit test speeds?

1 month 3 weeks ago

I'm trying to speed up a functional Drupal test. Given a test...

... public function the_front_page_loads_for_anonymous_users() { $this->config('system.site') ->set('page.front', '/node') ->save(TRUE); $this->drupalGet('<front>'); $assert = $this->assertSession(); $assert->pageTextContains('Welcome to Drupal'); $assert->pageTextContains('No front page content has been created yet.'); }

This test runs really slow against my database ... 2+ mins.

If I use a test sqlite database, it drops to around 1.6 mins <env name="SIMPLETEST_DB" value="sqlite://localhost/logs/test.sqlite"/>

If I use a in-memory database, <env name="SIMPLETEST_DB" value="sqlite://localhost/:memory:"/>, Drupal detects no database and runs install.php

How can I set up an sqlite memory database to improve test speeds?

tyler36

Error with Chado module installation

1 month 3 weeks ago

As part of college course work, I am required to make a genomic database with a local website with basic features. I have installed Drupal 10.2.3 with PostgreSQL 14.11, PHP 8.3.4 and Tripal 4.0.0-alpha2.

I am facing error during Chado module installation via Home > Administration > Tripal > Data Storage > Chado > Install Chado. I have already enabled it from the 'Extend' tab. I am new to Drupal as well as website development in general. From my limited understanding, it has something to do with missing "drupal_chado_installations" table but it seems to exist when I give command

SELECT * FROM information_schema.tables WHERE table_name = 'drupal_chado_installations'

Below is the Chado installation error when I try installing through my local server's website @http://localhost/admin/tripal/storage/chado/install

The website encountered an unexpected error. Try again later.

Drupal\Core\Database\DatabaseExceptionWrapper: SQLSTATE[42P01]: Undefined table: 7 ERROR: relation "drupal_chado_installations" does not exist

LINE 3: "drupal_chado_installations" "i" ^: SELECT "i"."install_id" AS "install_id", "i"."schema_name" AS "schema_name", "i"."version" AS "version", "i"."created" AS "created", "i"."updated" AS "updated" FROM "drupal_chado_installations" "i"; Array ( ) in Drupal\tripal_chado\Database\ChadoConnection->getAvailableInstances() (line 279 of modules/contrib/tripal/tripal_chado/src/Database/ChadoConnection.php).

Drupal\Core\Database\StatementWrapperIterator->execute() (Line: 851) Drupal\Core\Database\Connection->query() (Line: 239)

Drupal\pgsql\Driver\Database\pgsql\Connection->query() (Line: 525) Drupal\Core\Database\Query\Select->execute() (Line: 155) Drupal\pgsql\Driver\Database\pgsql\Select->execute() (Line: 279) Drupal\tripal_chado\Database\ChadoConnection->getAvailableInstances() (Line: 47) Drupal\tripal_chado\Form\ChadoInstallForm->buildForm() call_user_func_array() (Line: 536) Drupal\Core\Form\FormBuilder->retrieveForm() (Line: 283) Drupal\Core\Form\FormBuilder->buildForm() (Line: 73) Drupal\Core\Controller\FormController->getContentResult() call_user_func_array() (Line: 123) Drupal\Core\EventSubscriber\EarlyRenderingControllerWrapperSubscriber->Drupal\Core\EventSubscriber{closure}() (Line: 627) Drupal\Core\Render\Renderer->executeInRenderContext() (Line: 121) Drupal\Core\EventSubscriber\EarlyRenderingControllerWrapperSubscriber->wrapControllerExecutionInRenderContext() (Line: 97) Drupal\Core\EventSubscriber\EarlyRenderingControllerWrapperSubscriber->Drupal\Core\EventSubscriber{closure}() (Line: 181) Symfony\Component\HttpKernel\HttpKernel->handleRaw() (Line: 76) Symfony\Component\HttpKernel\HttpKernel->handle() (Line: 58) Drupal\Core\StackMiddleware\Session->handle() (Line: 48) Drupal\Core\StackMiddleware\KernelPreHandle->handle() (Line: 28) Drupal\Core\StackMiddleware\ContentLength->handle() (Line: 32) Drupal\big_pipe\StackMiddleware\ContentLength->handle() (Line: 106) Drupal\page_cache\StackMiddleware\PageCache->pass() (Line: 85) Drupal\page_cache\StackMiddleware\PageCache->handle() (Line: 50) Drupal\ban\BanMiddleware->handle() (Line: 48) Drupal\Core\StackMiddleware\ReverseProxyMiddleware->handle() (Line: 51) Drupal\Core\StackMiddleware\NegotiationMiddleware->handle() (Line: 36) Drupal\Core\StackMiddleware\AjaxPageState->handle() (Line: 51) Drupal\Core\StackMiddleware\StackedHttpKernel->handle() (Line: 704) Drupal\Core\DrupalKernel->handle() (Line: 19)

My settings.php file already contains the database connection details so online solutions mentioning that are not working

$databases['default']['default'] = array ( 'database' => 'teak_wood_genes_db', 'username' => 'postgres_molecular', 'password' => '**********', 'prefix' => 'drupal_', 'host' => 'localhost', 'port' => '5432', 'driver' => 'pgsql', 'namespace' => 'Drupal\\pgsql\\Driver\\Database\\pgsql', 'autoload' => 'core/modules/pgsql/src/Driver/Database/pgsql/', );
s-135

How to manage reservations with a 2 hours duration without duplicate bookings?

1 month 3 weeks ago

I want to make a calendar view that will show when music teachers are available, so that students can register online and attend a lesson. The courses have all the same duration which is 2 hours. For this, I created a content type called "Lessons" (Fields: title, description, teacher name, teacher email, date/time) and a content type using node reference module for registrations to each specific lesson. In that way students can register online for music lessons.

There are 2 problems with this:

  1. How can I have a fixed 2 hour duration in the day of the calendar view that won't let students register for more or less time than the two hours? I can not just hide the time fileds because the system must show them the time that the lesson takes place?

  2. I want to allow just one user register for each lesson and then the system must show that lesson as booked. To be more specific, I want the calendar to show the whole day seperated in 2-hour periods and which periods are free. When a user registers for a lesson, the lesson changes color (I can do this with css) and is marked as reserved so that the "next" user can only register for another of the open lessons and so on.

Any ideas?

Pan Adams

Custom module update with project status url

1 month 3 weeks ago

My .info file is the following.

name = {some_name} description = This will contain all {some_name} related information package = {Package_name} core = 7.x ; Information added by Drupal.org packaging script on 2014-10-03 version = "7.x-1.1" core = "7.x" project = "{project_name}" project status url=http://domain.com/{project_name}/7.0/sub_module datestamp = "1432104957"

I uploaded the sub_module.zip and the sub_module.tar.gz files, as well as the sub_module folder to the above project status URL, with .info version set to 7.x.2.1.

Still I'm not getting any updates for my custom module. Can anyone help me with this?

Ashish

How to render formatted text field from paragraphs as is in twig?

1 month 3 weeks ago

I need to render a text (formatted long) field using twig. At this time i am doing the following below. However, i am finding that if i were to add a line break in the text field or apply adding spacing or a horizontal line, the twig filter "raw" removes those attributes. I need assistance to see what I am missing.

I have already set the view mode for field on the content type to default

Twig template (filter used)

{% for item in items %} {{ item.field_body.value|raw }} {% endfor %}

Expecting

Actual result

usernameabc

Define a normalizer just for a specific use case

1 month 3 weeks ago

I try to create a custom API with custom endpoints where API users can receive entity data from our page. We want to have flat arrays for most of the fields and some additional custom data added so I tried to implement some custom normalizer classes. I found out that supportsNormalization() is the place where the decision is made if my normalizer is used, but I have no context. I just have the object which needs normalization and the format on which I can say Yes, please use my normalizer. As I don't want to force all my entities everywhere in the project be normalized with flat array this is too restrictive for us. I want to use my normalizer only when the entities should be normalized for delivering it in a specific API. Is there a way to achieve this?

Tobias Krause

Views, Taxonomy, multiple parameters using contextual filters

1 month 3 weeks ago

A view has been created to display related content types via their taxonomy terms, using contextual filters. Currently the view is able to display content based on the first param eg. about The goal is to abe to display content based on the second param, being the child term and hide the parent eg. about/meet-the-team.

Here is a break down

Url : page/parent term

parent term Content item referenced to parent term Content item referenced to parent term Content item referenced to parent term Content item referenced to parent term

Url: page/parent term/child term

child term Content item referenced to child term Content item referenced to child term Content item referenced to child term Content item referenced to child term Content item referenced to child term

Url: page/parent term/child term/child child term

Content item referenced to child child term Content item referenced to child child term Content item referenced to child child term Content item referenced to child child term Content item referenced to child child term Content item referenced to child child term Content item referenced to child child term

And this will continue on

Eg Url: page/parent term/child term/child child term/child child child term/child child child child term.

Chris

How do you use hook_query_alter to get inside a query's creation?

1 month 3 weeks ago

I'm getting no love from hook_query_alter. I have a simple query to which I want to add a tag, while also adding a node_access tag. Thus the whole query looks like this:

$the_nodes = db_select('node', 'n') ->condition('n.type', 'some_node_type') ->fields('n', array('nid', 'title')) ->addTag('node_access') ->addTag('my_custom_tag') ->execute()->fetchAll();

I then define a handler in one of my modules and litter it with debugging statements, hoping something will happen:

function mymodule_query_alter(QueryAlterableInterface $the_query) { dsm("inside mymodule_query_alter"); dsm($the_query); if ($the_query->hasTag('my_custom_tag')) { dsm('Found it!'); // do real work here } }

I then clear the system cache. Once I've done this, the following things happen:

  • My handler is running, and reports a number of invocations from various system calls.
  • The objects being dumped by the dsm calls are all very much alike -- they contain only an alterTags array, which typically has entries for either node_load_multiple or file_load_multiple, but nothing else -- certainly nothing like a full Query object.
  • None of the alterTags arrays have an entry for my_custom_tag.
  • The inner "Found it!" message never fires.

Arggh. This is my first encounter with hook_query_alter(), and I'm probably just missing something basic about its use. Can anybody clue me in? (BTW, based on some browsing around, I've also tried defining handlers for my_module_query_my_custom_tag_alter and my_module_query_node_access_alter, but never see anything from them.)

Jim Miller

Accessing Content: Path field within views_view_unformatted TWIG template

1 month 3 weeks ago

I have a view that has the fields: Content: ID, Content: Title and Content: Path.

In my views-view-module.html.twig file I can access the fields via the following:

{{ item['#row']._entity.id }} {{ item['#row']._entity.title[0].value }}

But I cannot seem to retrieve the path field using:

{{ item['#row']._entity.path[0].value }}

Do I do this the same way or am I missing a trick? I've tried to use dump/kint but I keep getting the WSOD.

Can anyone offer me a solution?

Thanks in advance

cwiggo

Pass custom variable to an entity reference templete

1 month 3 weeks ago

i have the following problem in Drupal 8.

In custom content type there is a field, which is a multiple entity reference to the same content type. The field is set to use custom view mode, where only title and body fields are displayed. Kind of sub-pages structure. Also the content type has a boolean field, which determines whether the body field of sub pages (entity reference) should be displayed or not. So in my theme_preprocess_field() hook i can get the boolean value, but i don't know how to pass it to the entity references, so in my node--mypage--grid-item.html.twig i could check for that flag and determine should be content.body be rendered or not.

Thank for any hints.

user1112057

How to get text from radio option value

1 month 3 weeks ago

How do I get the option text from the submitted value of the radio field in Drupal 8 webform submission? I have written a rule action condition on webform submission where I am storing data in a middle table.

Based on screen I am looking for Option Text from webform field. Current version: Drupal 8.6.15 & webform 8.x-5.2

kirtivaland

Check if form already failed validation

1 month 3 weeks ago

I added a validation hook to a node creation form.

For my project, i need this validation only ONE time: basically i just check if a value already exists in the DB and i notify it to the user. If the user still submits the form, i must add it anyway.

i would like to do something like that:

if (form_did_not_fail_validation_before) { $form['#validate'][] = 'my_module_validation_hook'; }

in my hook_form_alter, so that validation hook is only called the first time.

I can't find a way to check if the form already failed validation, any ideas?

gbalduzzi
Checked
11 hours 2 minutes ago
most recent 30 from drupal.stackexchange.com
Subscribe to Drupal StackExchange feed