Drupal StackExchange

Render Custom Menu Block from Menu Tree Array of Links Programmatically

1 day 15 hours ago

Here's what I have: A custom menu (side nav) that mimics the main/secondary menu tree which shows the entire subtree of the root menu item (Dine, Play, Stay) you're under.

This sidenav can be shortened with a checkbox field in the content type. If checked, the sidenav shows the checked page as the root and all children, recursively, but omits any parents of the checked page. I've successfully created that menu and this all works on the checked pages.

This yields:

This is done by creating both menus, then adding a "hide" css class to one of them in the template_preprocess_page() function, depending on the checkbox of the current node.

MY ISSUE: The final thing I need it to do is when you are on a CHILD page of a parent with the shortened nav checked, I need it to still show that shortened nav. So on the example above, when on the Visitor FAQ page, it needs to show the shortened menu from Visitor Tips (with the current page bolded or whatever). So it needs to grab the field from the parent node, and if it is true, grab the shortened submenu array, which I've done, but I haven't been able to render the menu tree array into html correctly.

Here's the current code for grabbing the submenu (from the full menu), and it saves the menu array in $alternateSecondaryMenu. I also tried saving in $vars['secondary_nav'], which is the key Drupal uses for the rendered menu array, but I think the menu has already rendered by the time it calls preprocess_page(). I just can't figure out how to render that menu tree. (The menu is 4 levels deep, level 0 being the root menu item, so this only happens on level 1 or level 2.)

In template.php:

function THEME_preprocess_page(&$vars) { // Follow active-trail and check if short/long menu is toggled // *********************************************************** if(!empty($vars['secondary_nav'])) { // Level 1 foreach($vars['secondary_nav'] as &$topmenuitem) { // for each top level item if(!empty($topmenuitem['#title'])) { if(in_array('active-trail', $topmenuitem['#attributes']['class'])) { // check if in active-trail (parent) // load the node of the parent menu item $firstnid = str_replace('node/','',$topmenuitem['#href']); $firstnode = node_load($firstnid); // check for shortened menu checkbox if (array_key_exists('field_show_menu_as_parent',$firstnode) && $firstnode->field_show_menu_as_parent && $firstnode->field_show_menu_as_parent['und'][0]['value']) { dsm("1. YES, shortened menu."); // Saving this submenu in these variables $vars['secondary_nav'] = $topmenuitem; // this is the drupal-made array that shows the menu in question $alternateSecondaryMenu = $topmenuitem; // just saving to some other variable, too. } else { dsm("1. NO shortened Menu for you!"); } // Level 2 (same as level one) foreach($topmenuitem['#below'] as &$secondmenuitem) { if(!empty($secondmenuitem['#title'])) { if(in_array('active-trail', $secondmenuitem['#attributes']['class'])) { $secondnid = str_replace('node/','',$secondmenuitem['#href']); $secondnode = node_load($secondnid); if (array_key_exists('field_show_menu_as_parent',$secondnode) && $secondnode->field_show_menu_as_parent && $secondnode->field_show_menu_as_parent['und'][0]['value']) { dsm("2. YES, shortened menu."); $vars['secondary_nav'] = $secondmenuitem; $alternateSecondaryMenu = $secondmenuitem; } else { dsm("2. NO shortened menu for you!"); } } } } } } } } dsm(drupal_render($alternateSecondaryMenu)); // Only renders an <li> of the current node, not the <ul> or the children <li>, even though it has the whole menu tree. dsm($vars['secondary_nav']); // doesn't render anything because this preprocess_page() is called after the elements of the page have already rendered, right? }

I am using Panelizer to display and Menu Block to create the menu (only modules that ones that might be relevant).

Do I need to call the theme_menu_tree() and theme_menu_link() functions on this array again to render it, somehow? I wasn't able to get render() or drupal_render() to work. Also tried doing this with menu_preprocessing/tree functions but was having difficulty getting the checkbox value in the nodes. Any ideas or help would be GREATLY appreciated.

Thanks!

ProGrammar

Theme video-embed-iframe.html.twig by content type

1 day 16 hours ago

I am using Drupal 8 and trying to theme video-embed-iframe.html.twig by content type. with the current naming suggestions this is not possible.

I am using Media with video embed field containing in a field called video

This is what I did so far. in the fields template named above in the templates folder of my theme

{% if logged_in %} <iframe{{ attributes }}{% if url is not empty %} src="{{ url }}{% if query is not empty %}?{{ query | url_encode }}{% endif %}"{% endif %}></iframe> {% else %} <div id="promotion"> <div id="promotion-image"> <div id ="promotion-bg"> <div id ="promotion-text"> <H1>Eine brilliante Überschrift</H1> </div> </div> </div> <span id="promotion-attribution"> <a href="http://somesite.com">Credit author of the background image</a></span> </div> {% endif %}

I have no clue how to access the field by content type to separate the code deepening if you have a content type eg page and article Any Ideas?

Is there a way to populate a global var like logged in containing the mashine name of the content type without needing a custom module. I other words is there a way to populate a var like

contenttype=anycotenttypehere in the mytheme.theme file by writing a function? to be able to display the video depending on with contetnt type has been used and if the user is logged in or not

Josh

How to quickly delete many entities programmatically?

1 day 16 hours ago

This appears to be the prescribed way of deleting multiple node entities:

$nids = \Drupal::entityQuery('node') ->accessCheck(FALSE) ->condition('field_my_field', 'something') ->execute(); $storage_handler = \Drupal::entityTypeManager()->getStorage('node'); $entities = $storage_handler->loadMultiple($nids); $storage_handler->delete($entities);

However, this takes a long time to execute. On my machine, the above code takes about 15 minutes to delete 100 entities. The same machine can programmatically create 100 entities in about 40 seconds -- not blazingly fast, but acceptable.

I also tried looping through the $nids to load and delete them one at a time. That runs about 10% faster, perhaps because the memory is released after each load. Still, it's too slow.

The relevant content type has about 30 fields. Perhaps this is a factor.

What if my application requires regularly deleting hundreds of entities, and it isn't practical to wait over an hour for the script to execute? Is there some other option for deleting large numbers of entities?

Drupal 10.2.3. PHP 8.1.16. MariaDB 10.4.28.

arnoldbird

Inline Editing Weight Field on admin view

1 day 16 hours ago

I am working on a Drupal 10 site and and I have a built an admin view that has 2 fields. Node title and Weight. I would like to be able to on that view edit the weight inline on each node and save it. It looks like the modules that could do this in previous versions of Drupal are no longer supported in Drupal 10.

Does anyone know of a way to do this?

ThankYouNeco

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

1 day 18 hours 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 day 18 hours 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 day 18 hours 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 day 19 hours 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 day 19 hours 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