explicit "switch to mobile theme" link with Theme Key I'm using Theme Key https://www.drupal.org/project/themekey to switch automatically between themes dependent on browser and/or OS id.
Now I would like to allow the user to explicitly switch to or from to one or the other theme by clicking a link too. ThePersistant URL https://www.drupal.org/project/purl module might be helpful for this but how exactly can I go about implementing this?

EDIT 1

I followed Answer 1, added drupal_add_library('system', 'jquery.cookie'); into the already existing function marinelli_preprocess_page(&$vars) in my template.php.

I setup two ThemeKey rules like:

system:cookie = "theme=marinelli" THEME [Marinelli]

and

system:cookie = "theme=skeleton" THEME [Skeleton]

and
added following html to my page:

Switch to Marinelli Switch to Skeleton

But clicking the links, doesn't do anything, seems like I might be missing something or it might not quite work this way because href="#" doesn't actually reload the page if that was the actual idea...?

One way would be to nest each theme switching rule inside another rule using

system:cookie = theme=theme1

     Theme switching rule here

system:cookie = theme=theme2

     Another theme switching rule here

You will need to set up your theme switching links to create a cookie using your method of choice, PHP or jquery.cookie

An example using jquery.cookie could be something like:

template.php:

function THEMENAME_preprocess_page(&$vars) {
  drupal_add_library('system', 'jquery.cookie');
}

Your theme switching links:

Switch to Theme1
Switch to Theme2

Keep in mind that this is not page caching friendly.  If you want this to work for anonymous users, you will need to disable page caching.


Remove "where" clause in views 3 I want to remove "where" clause for city and postal_code in the views query. I found an example online for D6. I tried to change it a bit but it's not working. The "where" clause is still there.
Below is my code. It was originally for D6.

function distsearch_views_query_alter(&$view, &$query) {
  if ($view->name == 'search' && $view->current_display == 'page_3') {
    // Remove the exposed filter conditions from the WHERE clause (WHERE city = MyCityInput)
    // and remove the corresponding args that were passed via the exposed filters
    // This effectively turns the city and zip code exposed filters into just text fields
    // that get used in distprox_mini_exposed_filter_proximity();

    $city = $view->exposed_raw_input['city'];
    $zip = $view->exposed_raw_input['postal_code'];

    // Remove the city or zip arguments (from the exposed filters)
    foreach ($query->where[0]['args'] as $key => $arg) {
      if ($arg == $city || $arg == $zip) {
        unset($query->where[0]['args'][$key]);
      }
    }

    // Remove the corresponding WHERE clause additions
    foreach ($query->where[0]['clauses'] as $key => $clause) {
      if (strpos($clause, 'postal_code') !== FALSE || strpos($clause, 'city') !== FALSE) {
        unset($query->where[0]['clauses'][$key]);
      }
    }
  }
}

It was a lot easier than I thought. I dsm the query and did it like below. Not sure it's the perfect way to do it but it's working.

function distprox_mini_views_query_alter(&$view, &$query) {
//dsm($query);
  if ($view->name == 'search' && $view->current_display == 'page_3')
    unset($query->where[1]['conditions'][0]);
    unset($query->where[1]['conditions'][1]);
  }
}


Don't show message on View display page I have some rules created and working fine. Some of them are made for messages, that are displaying after certain period of time. And that's alright, works.
But, it also displays the message when browsing the page created in Views, that is listing all the content of X type.

So, let's say I have a work content type; Every work node older than few weeks is getting the message shown to the user. I also have a view, but I don't want the rules to display the message in there.

Well, answering myself. Turns out pure Rules are rather not enough.
But together with Path Rules (https://drupal.org/project/pathrules) it works without a problem. So, question answered, issue solved. Maybe it will help someone.


Update existing 'paragraph' entity while changing the ID is not supported I'm trying to update a paragraph with this code:
$entityManager = \Drupal::entityTypeManager();
      $paragraph = $entityManager->getStorage('paragraph')->load('1');
      $paragraph->set('field_test','testValue');
      $paragraph->save();

But I received this error:
Drupal\Core\Entity\EntityStorageException: Update existing 'paragraph' entity while changing the ID is not supported. in Drupal\Core\Entity\Sql\SqlContentEntityStorage->save() (line 846 of core/lib/Drupal/Core/Entity/Sql/SqlContentEntityStorage.php).

Stack:
Drupal\Core\Entity\EntityStorageBase->save(Object) (Line: 837)
Drupal\Core\Entity\Sql\SqlContentEntityStorage->save(Object) (Line: 395)
Drupal\Core\Entity\EntityBase->save() (Line: 171)
jnjmdc_content_card_module_help('help.page.jnjmdc_content_card_module', Object)
call_user_func_array('jnjmdc_content_card_module_help', Array) (Line: 392)
Drupal\Core\Extension\ModuleHandler->invoke('jnjmdc_content_card_module', 'help', Array) (Line: 144)
Drupal\help\Controller\HelpController->helpPage('jnjmdc_content_card_module')
call_user_func_array(Array, Array) (Line: 123)
Drupal\Core\EventSubscriber\EarlyRenderingControllerWrapperSubscriber->Drupal\Core\EventSubscriber\{closure}() (Line: 573)
Drupal\Core\Render\Renderer->executeInRenderContext(Object, Object) (Line: 124)
Drupal\Core\EventSubscriber\EarlyRenderingControllerWrapperSubscriber->wrapControllerExecutionInRenderContext(Array, Array) (Line: 97)
Drupal\Core\EventSubscriber\EarlyRenderingControllerWrapperSubscriber->Drupal\Core\EventSubscriber\{closure}() (Line: 151)
Symfony\Component\HttpKernel\HttpKernel->handleRaw(Object, 1) (Line: 68)
Symfony\Component\HttpKernel\HttpKernel->handle(Object, 1, 1) (Line: 57)
Drupal\Core\StackMiddleware\Session->handle(Object, 1, 1) (Line: 47)
Drupal\Core\StackMiddleware\KernelPreHandle->handle(Object, 1, 1) (Line: 106)
Drupal\page_cache\StackMiddleware\PageCache->pass(Object, 1, 1) (Line: 85)
Drupal\page_cache\StackMiddleware\PageCache->handle(Object, 1, 1) (Line: 50)
Drupal\ban\BanMiddleware->handle(Object, 1, 1) (Line: 47)
Drupal\Core\StackMiddleware\ReverseProxyMiddleware->handle(Object, 1, 1) (Line: 52)
Drupal\Core\StackMiddleware\NegotiationMiddleware->handle(Object, 1, 1) (Line: 23)
Stack\StackedHttpKernel->handle(Object, 1, 1) (Line: 708)
Drupal\Core\DrupalKernel->handle(Object) (Line: 19)

Do you know why?
P.s. If I try to update with the last ID it works. It doesn't work only for old Paragraphs.

You could load the paragraphs through their parent entity to get the active revisions:
$nids = \Drupal::entityQuery('node')
  // load only nodes where this paragraph reference field exists and has content
  ->exists('field_paragraph')
  ->execute();
$nodes = \Drupal::entityTypeManager()->getStorage('node')->loadMultiple($nids);
foreach ($nodes as $node) {
  $paragraphs = $node->field_paragraph->referencedEntities();
  foreach ($paragraphs as $paragraph) {
    if ($paragraph->hasField('field_foo')) {
      $paragraph->field_foo->value = 'bar';
      $paragraph->save();
    }
  }
}


Where are the webform files in the D8 directory? I'm trying to manually update the D8 webform module but cannot find any directory, folder, or file named webform.  Where are the webform module files located?

We can install the modules in (root/modules/contrib) as webform is contributed module.

But by default, all contrib modules are in (root/core/modules/webform.)


View in views header still displaying when no result I tried this question:
Empty view is rendered even though there is no result

And it didn't work

I have a view of Judge nodes that displays using a contextual filter. Inside that view I have embedded a view block into the header that displays a Featured Judge, passing it the contextual filters and left 'Display even if no results' unchecked. In the Featured Judge view I have set it to not display empty fields. Also I have added a filter to a field as suggested in the question above.

Still I get the following output in the views header:

I have dpm'd the views array in preprocess view, and results is empty. I have set it to NULL and it still displays. At present the only solution appears to be to check if the results array is empty and if so add a class to display: none; which is frankly ludicrous.

Anyone have any ideas?

Looks like you have added the filter only for the Featured Judge View.

Try adding a filter in the View that lists the Judge Nodes. This will completely note render the whole view at all.


Is there any hook or event that is fired when user data is set/updated/deleted I am using the user.data service to store additional data for users. I would like to trigger some custom functionality each time the user.data is changed. I can't find any hook or event that I could use. Is there any way to achieve this?

hook_entity_presave (hook_ENTITY_TYPE_presave)

  Act on an entity before it is created or updated.

  You can get the original entity object from $entity->original when it
  is an update of the entity.

hook_entity_update (hook_ENTITY_TYPE_update)

  Respond to updates to an entity.

  This hook runs once the entity storage has been updated. Note that
  hook implementations may not alter the stored entity data. Get the
  original entity object from $entity->original.

Here's a sample implemented by system.module:

/**
 * Implements hook_ENTITY_TYPE_presave() for user entities.
 */
function system_user_presave(UserInterface $account) {
  $config = \Drupal::config('system.date');
  if ($config->get('timezone.user.configurable') && !$account->getTimeZone() && !$config->get('timezone.user.default')) {
    $account->timezone = $config->get('timezone.default');
  }
}


Remove fieldset from date field I am trying to remove the <fieldset> surrounding a date popup field, but I find that the label is also removed. This is my code:

function mymodule_profile_form_alter(&$form, $form_state, $form_id) {

  global $user;
  //print_r($form['field_last_name']);

  $form['field_birthdate']['und'][0]['#theme_wrappers']=$form['field_birthdate']['und'][0]['#theme_wrappers'][0];
}

Can anyone help me to solve this problem?

Typically there is a theme function associated with the different sort of output you can give data fields or indeed any fields If you want to change this you do so on the theme level by overriding the default theme function in your themes template.php file.

Date popup

function YOURTHEME_date_popup($vars) {
  $element = $vars['element'];
  $attributes = !empty($element['#wrapper_attributes']) ? $element['#wrapper_attributes'] : array('class' => array());
  $attributes['class'][] = 'container-inline-date';
  // If there is no description, the floating date elements need some extra padding below them.
  $wrapper_attributes = array('class' => array('date-padding'));
  if (empty($element['date']['#description'])) {
    $wrapper_attributes['class'][] = 'clearfix';
  }
  // Add an wrapper to mimic the way a single value field works, for ease in using #states.
  if (isset($element['#children'])) {
    $element['#children'] = '
' . $element['#children'] . '
';
  }
  return '
' . theme('form_element', $element) . '
';
}

Although it must be said this is being themed as a form_element so there is no fieldset.

Date combo is themed as a fieldset and again can be overriden...

function YOURTHEME_date_combo($variables) {
    $element = $variables['element'];
    $field = field_info_field($element['#field_name']);
    $instance = field_info_instance($element['#entity_type'], $element['#field_name'], $element['#bundle']);

    // Group start/end items together in fieldset.
    $fieldset = array(
            '#title' => t($element['#title']) . ' ' . ($element['#delta'] > 0 ? intval($element['#delta'] + 1) : ''),
            '#value' => '',
            '#description' => !empty($element['#fieldset_description']) ? $element['#fieldset_description'] : '',
            '#attributes' => array(),
            '#children' => $element['#children'],
    );

    // Fix required marker.
    if ($element['#required']) {
        $fieldset['#title'] .= " " . theme('form_required_marker');
    }
    return theme('fieldset', array('element' => $fieldset));
}

If you replaced 'fieldset' with 'form_element' this would work.


How do you deal with multiple locations? I'm sure this applies to offices with multiple locations, but I am trying to create a site for a charity that runs summer camps. I was wondering how would you suggest I present the different locations?

I looked at gmaps and open layers (they may do what I want but I couldn't figure out how so easily, I don't want to have to enter coordinates because locations are changing often and I want to make it easy for new staff to add/remove locations).  Ideally it would be good to either have a map with markers that users can click on to see details of the location or to list the locations and once they click on it it shows it in a map.

So I guess there's two questions: 1) What tool can help me present this data in drupal 7?; and: 2) What tool can be used to manage the data?

I've been using GMap + Location to accomplish this.  The site I've been working on involves Apartment Communities spread out all over the place.  I created a content type for apt_community which accepts location data (I only allowed an exact address but you can let the user pick a location on a map).  Then I have a view that puts all the points on a map which I attach to a page.

Check this DrupalTherapy screencast on GMap + Location (http://www.drupaltherapy.com/gmap) and this other screencast Drupal Aficionado did on using GMap and Views (http://blip.tv/drupal-aficionado/gmap-location-and-views-1773822).


Find matching fields between content types and create new nodes I'm working on a project that collects information about a corporate client and then based on the information provided, connects that client with other companies that can help them with a specific need.

I have worked through the first half of the project to collect data conditionally based on the type of industry/operations the company is involved with using rules.  Now i need to use the information collected and filter a view to find matching companies.

Essentially once a client submits their finalized application (a collection of different fields within a handful of content types), behind the scenes I need to figure out a way to filter a view of other companies with matching characteristics, then for each company that matches the filtered view, add a new  node within a separate content type and then entity reference that node back to the finalized application for further input/editing.  Here is a simplified visual:

Most of the fields being filtered are taxonomy references; however, some would be numeric inputs filtered by a less than, greater than, or equal to filter.

Financials Taxonomy: good financials; so so financials; challenged financials

Industry Taxonomy: technology, manufacturing, real estate, etc...

"Client A" node field answers in Clients content type:

good financials (financials taxonomy reference)
focused on technology (industry taxonomy reference)
50 employees (numerical field)

Companies content type contains the following nodes:

Company A: likes only challenged financials; focused on manufacturing; works with companies <100 employees
Company B: likes only good financials; focused on technology; works with companies <500 employees
Company C: likes only challenged financials; focused on manufacturing; works with companies <25 employees
Company D: likes only good or challenged financials; focused on manufacturing; works with companies <100 employees

Once client A selects a field indicating the answers are finalized and the content type Clients is saved, I need to find a way to have the matching companies filtered based on client A's answers, and a new node for a different content type (content type called Partner Details) should be created for each matching company.

That content type would be called Partner Details and would consist of the following fields for each matching company:

entity references the client content type
entity references the matching company to the client
custom blah blah blah entered by rules that indicates why the match makes sense
contact information from the company content type
etc., etc...

So to sum up, client A answers the questions noted above within the client content type, then based on that information, the data within the Companies content type would be filtered - and for this example - two new nodes of Partner Detail content type would be created because nodes in the Companies content type matched the fields that Client A answered in Clients content type. Company B and Company D matched the criteria so they would be entity referenced by the two new Partner Details nodes created. This way, Client A could log in and see their matches and edit the matching partner details and view information about Company B or D based on their entity referenced nodes.

I have an intermediate understanding of views, panels and rules, but can't seem to figure out how i would do this behind the scenes once a user indicates the application is finalized. I also have an understanding of how to use rules to create new nodes and entity reference them. Hoping for a step by step example as detailed as you can provide.  Any help is greatly appreciated. Thanks for bearing with my long winded explanation, hopefully that makes some sense.

(Finally, I had no idea what to title this question so if anyone has a better suggestion, let me know and I'll change it.)

You need the below rule to fire when the client's content type is saved.. And all relevant fields must exist in BOTH content types. It will talk your clients answers, feed them through a VBO, get the company NIDs that match and then loop through them to create Partner Details nodes.

First, you need to have Views Bulk Operations (VBO) which will give a new rule action.. "Load a list of entity IDs from a VBO View". In this action, you can specify a VBO view and a list of arguments (taxonomy tids etc.) to send to the view using replacement patterns. The list of returned IDs is what you will use to create your "partner details".
You need to create the VBO view by adding "Bulk operations: Content (Content)" as a field in a new view. The arguments sent from the rules action can be picked up by contextual filters using the "Provide Default: Raw Value from URL" setting. If I remember correctly, the first argument starts with path component 2.
The results of the VBO should be limited to those nodes that match the arguments. Now we have a list in rules that we can use Loop to go over.
Depending on needs, you can just create the new entities and reference the client and company nodes or do a two way reference so that the client and company nodes also reference each partner detail node.

The above is will do the taxonomy fine but for the integers, it's a bit more complicated since the contextual filter must match perfectly. For this, you can use the contextual filter: Global Null (which won't limit the results) and use Views Argument Substitutions to take the value from the contextual filter and use it in your views filters (the regular ones on the left). * *  *!2 * * * (no spaces) if your global: null is the second contextual filter.

This is pretty limited but it could work. If you need it to only be 50-100 employees for example,  on the company content type, have minimum and maximum integer fields and use "greater than" and "less than" filters in VBO view.

You should do quite a lot of testing on the VBO preview to make sure things work as expected. I really believe this is the only way to do this without writing a nasty amount of custom code. Good luck!


SymfonyTestsListener does not exist on PHP Unit Test When I try to run a unit test I get an error that SymfonyTestsListener does not exist.  Am I running this correctly?

../../vendor/bin/phpunit -c phpunit.xml ../modules/custom/my_module/

Class "Symfony\Bridge\PhpUnit\SymfonyTestsListener" does not exist

I am using PHPUnit 6.5.13.

Had a similar issue:
Solved it by adding the "symfony/phpunit-bridge": "^3.4.3" library.


Can access arguments only be specified once for all sub-routes? For example:

I would start off by setting this.

$items['admin'] = array(
 'access arguments' => array('administer users'),
 'type' => MENU_NORMAL_ITEM,
);

But the anytime after I use admin in my menu hook it would take on the same access arguments. So below would take on the same access argument as the above.

$items['admin/users'] = array(
 'page callback' => 'drupal_get_form',
 'page arguments' => array('get_users_page'),
 'title' => 'Users Listing',
 'type' => MENU_NORMAL_ITEM,
);

EDIT: To put in better words, thanks Jaypan. Can access arguments be inherited from their parent's access arguments?

Basing on the documentation for hook_menu() access arguments are inherited from the parent route only if the access callback is inherited, and that only happens for MENU_DEFAULT_LOCAL_TASK routes.

For the code shown in the question, this would happen only if it would be written as follows.

function mymodule_menu() {
  $items['admin'] = array(
    'page callback' => 'drupal_get_form',
    'page arguments' => array('get_users_page'),
    'access arguments' => array('administer users'),
    'type' => MENU_NORMAL_ITEM,
  );

  $items['admin/users'] = array(
    'title' => 'Users Listing',
    'type' => MENU_DEFAULT_LOCAL_TASK,
  );

  return $items;
}

I take the route names are used just as example. Since admin is already defined from system_menu(), it is better not to use route names containing admin or admin/.

As side note, the page callback is inherited from the parent route, in any case.


Different domain names to site languages I have a Multilingual Drupal 7 site. The site is in 3 languages Dutch (default), English and German. The multilingual setup is done based on the i18n module. All is setup and works great!

Dutch site: litebook.eu
German site: litebook.eu/de
English site: litebook.eu/en

But now i have 2 more Domain names i have to use: litebook.de and litebook.co.uk

I want:
- litebook.de to go to litebook.eu/de
- litebook.co.uk to go to litebook.eu/en

What is the best way to set this ups and what do i have to do exactly?

Thanks a lot!

the simple way will be to use .htaccess

<IfModule mod_rewrite.c>
  RewriteEngine On
  RewriteCond %{HTTP_HOST} ^litebook.de$ [OR]
  RewriteCond %{HTTP_HOST} ^www.litebook.de$
  RewriteRule (.*)$ http://litebook.de/de/$1 [R=301,L]
  RewriteCond %{HTTP_HOST} ^litebook.co.uk$ [OR]
  RewriteCond %{HTTP_HOST} ^www.litebook.co.uk$
  RewriteRule (.*)$ http://litebook.eu/en/$1 [R=301,L]
</IfModule>


How to get taxonomy translated when creating a new node in a different language than the interfaces? Configuration:
I set up a multilingual site with Multilingual support: Enabled, with translation so I'm creating a new node for each language.

The taxonomy term is set up with the Translation mode: Translate, so I have a new term for each language.

Creating a node with default language first is working fine:
If I create a new node in my default language using node/add/page I correctly see the taxonomy terms in the site language, then after the node is created, using the Translate tab and select the Spanish language will work correctly and display the terms in Spanish.

Creating a node in a different language:
Now if I want to create a Spanish node first and I go to node/add/page I will see the site default language for the terms, so my tid will be in English instead of Spanish even if the language switcher is correctly set to Spanish.
Then when I'll edit this node, my terms will switch back to Spanish and loose the default term I selected while creating the node.

Partial solution:
A way to avoid this problem is to go to es/node/add/page instead and now the terms are correctly in Spanish.

This solution isn't very convenient, so what is the correct way to handle this efficiently and avoid saving a Spanish node with English terms ?

Language Selecting

There are number of ways Drupal distinguishes which language the current user is in (yourself for example).

The admin page at '/admin/settings/language/configure' lists 4 methods.

None.
Path prefix only.
Path prefix with language fallback.
Domain name only.

As you can see, to determine the language, Drupal either uses a 'path prefix', 'language fallback' and 'domain'.

The path prefix is simply something like '/de/about-us-page'. Drupal sets the language to German. When I say set, I actually mean it sets it for that particular page request. Then visiting '/about-us-page' would NOT display the language in German but your default language (maybe English).

For Language Fallback, Drupal check if the currently logged in user has a language set in their $user account. If not, it will look for a language from the headers sent from the browser. If in any case the language cannot be determined, the default language is used; again may be English.

The Domain method is simply inspecting the domain and checking if it has been mapped to a language. e.g. German to domain.de.

Conclusion

From this, you can see that Drupal is simply reverting back to the default language. You setting the 'language' within the node edit form, is simply mapping this node to that language.
Usually when adding content for other languages, I switch into the native language. This ensure my taxonomy terms are mapped correctly.

Essentially, this is not a problem but the way this system works.

Possible Fix

If all the terms you are using are common to all languages, you can modify the Taxonomy translation mode to 'Localize' instead of 'Translate'. This should allow all the terms to be saved correctly even if you use the edit page without prefix 'node/add/page'.
Just ensure you translate the terms using the String translation module.

Hope this help.
Amarjit


search results page in custom layout using Display Suite I'm pretty new in drupal. I'm using Drupal's core search module for search functionality in my website. Now. I need to customize search results display page to my website theme.
For this I've googled and find that this can be done if you change tpl.php files, but I don't want to change any template files for this. I've also found that Display Suite is most appropriate for this so I go fot it. I found display suite search page under admin/structure/pages. (Image 1) I've edit this page layout and create variant as per my page layout requirement. search form and search results taken from widgets. (Image 2)

Now the problem is I cannot see search results in search results block. How can I display search results in that block. Or is there any other way to achieve this as per my theme layout. Any suggestions or tutorial links will be appreciate..

Thanks in advance...

In configuration search setting I "Active search modules" set display suite search and set Default search module as "display suite".


unable to delete a custom content type I just followed http://www.andypangus.com/drupal-7-adding-roles-to-users-dynamically to create a new content type. I am successfully able to create it, but when I uninstall the module, the content type is not getting deleted. I also cannot delete it from the admin interface; there is no delete option.

Why cannot I remove the content type? How should I remove it?

Make sure you actually uninstall the module as opposed to just disabling it.

Uninstall is an additional tab on Admin > Modules page.

If that doesn't work, you could try calling node_type_delete($type) from somewhere.


Hide breadcrumb from CMIS views We're running Drupal 7.65 and Alfresco 5.2.4. We've the ability to display CMIS content (hosted in Alfresco) by fetching a URI like: https://domain.com/cmis/browser?id=<node_ID>. Doing so allow users who doesn't have access to Alfresco to download a file (if node_ID refers to a file) or browse the content of a directory (if node_ID refers to a directory).
Issue: sharing a directory via this method allow users to navigate the whole content of Alfresco by navigating the breadcrumb.

We'd like to remove this breadcrumb, could you recommend ways to do it ?
Here's what we've been thiking at:

Ideally, find a Drupal/Alfresco setting that allow us to restrict display
Comment out the line(s) responsible of displaying this breadcrumb inside Drupal' source code
less ideally, filter the DOM through JS (document.getElementById('cmis-breadcrumb').innerHTML = '')

Apologies for my English and the lack of knowledge about CMIS and Drupal

edit 19/01/2021: I believe I've found the module & the function responsible for the breadcrumb: https://git.drupalcode.org/project/cmis/-/blob/7.x-1.x/cmis_browser/cmis_browser.theme.inc#L125

CMIS Browser, a submodule of CMIS API, handles CMIS links. We are using CMIS API v7.x.x.
Here's the function responsible for the breadcrumb:
# cmis/cmis_browser/cmis_browser.theme.inc #125

function theme_cmis_browser_browse_breadcrumb($variables) {

  $next_img = theme('image', array('path' => drupal_get_path('module', 'cmis_browser') .'/images/next.gif'));
  $contents = '';
  $currentpath = '';

  $contents .= '
';
  if (!empty($_GET['type']) && $_GET['type'] == 'popup') {
    $contents .= l('Root', 'cmis/browser'. $currentpath, array('query' => array('type' => 'popup', 'caller' => $_GET['caller'])));
  }
  else {
    $contents .= l('Root', 'cmis/browser'. $currentpath);
  }

  $currentpath = '';
  foreach ($variables['bcarray'] as $space) {
    $contents .= $next_img .' ';
    $currentpath .= '/'. $space;
    if (!empty($_GET['type']) && $_GET['type'] == 'popup') {
      $pagelink = l($space, 'cmis/browser'. $currentpath, array('query' => array('type' => 'popup', 'caller' => $_GET['caller'])));
    }
    else {
      $pagelink = l($space, 'cmis/browser'. $currentpath);
    }
    $contents .= $pagelink;
  }

  $contents .= '
';

  return $contents;
}

Our workaround is simply to return an empty
 earlier:

function theme_cmis_browser_browse_breadcrumb($variables) {
  return '

';

  .....
}

Be careful since it's not a persistent solution.


Why is Drupal Core not updating via composer? We realized that our Drupal core version is outdated by two versions. We are currently running 8.5.3, but 8.5.5 has been released. Rather than updating directly two versions, we wanted to upgrade from 8.5.3 to 8.5.4 and then eventually from 8.5.4 to 8.5.5.

We tried the following but it didn't get updated.

composer update drupal/core:8.5.4 --with-dependencies

Message after running composer command

  Nothing to install or update

I ran this command in the directory outside of docroot in C:\users\name\Sites\mysite\ which has the following folders

.git
config
docroot
drush
hooks
vendor

I also ran composer why-not drupal/core:8.5.4 and had the following message returned.

  There is no installed package depending on "drupal/core" in versions
  not matching 8.5.4

After running composer why-not drupal/core:8.5.4 and doing some more research on the error message, I came across Upgrading from 8.5.0 to 8.5.1 using composer

This command did the trick for me.

composer require drupal/core:8.5.4  webflo/drupal-core-require-dev --update-with-dependencies


Group content by taxonomy term, but then also list all terms in each row I'm looking for help with creating a view.

I have a content type, Thing. Thing has a field on it where you can select multiple terms in a taxonomy, Category. I want my view to look like this:

Category 1

Thing 1

Category 1
Category 2

Thing 2

Category 1
Category 3

Category 2

Thing 1

Category 1
Category 2

So basically, I want to group by the terms and then list out all terms underneath each Thing. I also don't want groups to end up with headers of "Category 1, Category 2," and I want to make sure each of the terms is listed under each instance of the Thing in the view.

Thanks for any help!

I figured it out!

Instead of just adding Category as a single field in the View and trying to figure out how to configure that to show each Category for a Thing row but only one Category header per group, I have the Category field on there twice - one that does not display multiple in one row (for the headers), and one that does display them all within one row (to list out all Categories for a Thing).

I hope this possibly helps someone else!


Put blocks, views, etc in git for other developers Keep in mind that I'm fairly inexperienced with drupal!

I use a docker based setup for my development environment for docker 7. I'm building a site that involves a front page that will be changed infrequently but I still want the key users to change what's necessary.

I'm firing up the drupal docker with my_theme mapped to /var/www/sites/all/themes/my_theme and the following is executed in the docker container:

# Install zen theme (needed for the sub-theme)
/usr/local/bin/drush -r /var/www en zen -y
# Install base modules
/usr/local/bin/drush -r /var/www en views, entity, pathauto, devel_node_access, backup_migrate, imce, link_css, jquery_update, ckeditor, farmmix -y
# Set our theme as default
/usr/local/bin/drush -r /var/www vset theme_default farmmix
# Disable old theme
/usr/local/bin/drush -r /var/www dis bartik -y
# Enable/Install permissions
/usr/local/bin/drush -r /var/www en views_ui, entity_token, views_content, admin_devel, color, contextual, dashboard, field_ui, file, image, list, locale, number, options, overlay, search, shortcut, taxonomy -y

This installs and enables the modules I need for development. What this does NOT do is create content types, blocks, views, etc that might be necessary for this site.

It would be ridiculous to recreate these essentials for the site each time a new instance is spun up (e.g: another developer starts to work on it). How can I put content types, blocks, views etc in git so if another developer checks it out, he can continue where I just left off?

Only backup and migrate helps?

You have several modules that allow to export configuration changes (like views, blocks, content types etc) into code. One is features and the other is configuration Features is much more heavily used and configuration isn't supported by the security team, so I tend to use Features. There are a number of good tutorials on using Features, like this one. Once you create a feature, it will exported into a code-based collection of files under custom modules, which you can then share with git.

The one caveat is that using Features (or any config changes module for that matter) in a collaborative environment can become tricky: team members have to be mindful of the branches and feature versions they are working with. For example, switching from a branch where feature was installed to a branch that does not have that feature can throw fatal errors because GIT will remove the feature files according to the branch but the database will still look for the feature. In such a case you can disable the feature before switching branches or install the feature in all the branches you are working in.


Cannot update checkbox with services I have been trying several configurations for trying to update a user account checkbox to uncheck it, with no success. I have been able to check it without issue.

updateCharType = function (token) {

    var obj = {
        "uid": "1",
        "name": "admin",
        "field_character_type": {"und": [{"value": 0}]}
    };
    return $.ajax({
        url: 'www.example.com/endpoint/1.json',
        crossDomain: true,
        type: 'PUT',
        data: obj,
        dataType: 'json',
        headers: {
            'X-CSRF-Token': token
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            console.log('user edit - failed to edit ' + textStatus);
            console.log(errorThrown);
        },
        success: function (data) {
            alert(success!);
        }
    });
}

Now, it always gets to the success portion of the code, and it seems like it is working correctly.

However the checkbox never gets unchecked. I've read a bunch of documentation, and tried a million different iterations of how the JSON should be formed - putting null, removing the [], removing the und - for some reason I am having absolutely zero luck updating this checkbox!

How do I update a checkbox on a user account with services?

EDIT:

I WAS able to get it working with a list of values for a different field:

 var fontSize = jQuery('#font-size').val();

    var obj = {
        "uid": "1",
        "name": "admin",
        "field_font_size": {"und": fontSize}
    };
    return $.ajax({
        url: 'http://example.com' + "/users/user/1.json",
        crossDomain: true,
        type: 'PUT',
        data: obj,
        dataType: 'application/json',
        headers: {
            'X-CSRF-Token': token
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            console.log('user edit - failed to edit ' + textStatus);
            console.log(errorThrown);
        },
        success: function (data) {
            alert("Success for user save!:) ");
        }
    });
};

Differences:

How to be a list of values, and I needed to set it to application/json

Boolean field still not working under any variations.

Also, whenever I try to uncheck the checkbox I get the following error:

Notice: Array to string conversion in DatabaseStatementBase->execute() (line 2227 of /Users/username/Desktop/Projects/example.com/includes/database/database.inc).

To un-check a check box with Services in Drupal 7 (aka setting false on a boolean field), try this:

"field_character_type": {"und": null}

I've just verified this works on my localhost (for both users and nodes), here's the payload for the PUT:

{
  uid: 1,
  name: "admin",
  field_character_type: { und: null }
}

And here's the path:

api/user/1.json

Make sure you include the [my-endpoint-path]/user/[uid].json for the call.

You only need to cast the data payload into a string if you're using vanilla .js and an xhr object, otherwise jQuery's ajax does it automatically for you.


Most maintainable way to make page with one top half and alternative bottom halves selected by tabs? I want to make a page which has one top part, a row of two or more horizontal tabs beneath it, and alternative bottom parts which appear beneath that and can be selected by clicking on the tabs.

For example, imagine a page that someone might write about their cat. The top half is a photo of the cat and some text. At the moment, it's static, but I might later add a Twitter feed. Under it are tabs labelled "Poem", "Photo", and "Blog". The bottom half that gets selected when the user clicks on "Poem" is a poem, static HTML. That which gets selected when clicking on "Photos" is also static HTML, another image. And that which gets selected when clicking on "Blog" is dynamic: a blogroll implemented as a View.

Just to make sure that’s unambiguous, there are pictures of the top half and the three bottom halves at http: //www.j-paine.org/dobbs/kitty_page_top_264.gif, http: //www.j-paine.org/dobbs/kitty_page_poem_257.gif, http: //www.j-paine.org/dobbs/kitty_page_photo_296.gif, and http: //www.j-paine.org/dobbs/kitty_page_blog_279.gif. Apologies for the deformed HTML, but this thing only lets me post two links.

I’ve found quite a lot of methods that on first sight, may do what I want. These include the modules Quick Tabs and Node Tab, as well as the trick with views menus that Ron Golan describes in "Views Menu Tabs Quick Guide" (see https://www.urbaninsight.com/2013/11/01/views-menu-tabs-quick-guide). There are also assorted PHP code hacks. But I can't find recommendations about which solution is best for reliability and maintainability. It does appear that some of the techniques were written for older versions of Drupal, and may have been superseded.

One thing is that unskilled site administrators should easily be able to find all the content (tops, tabbed menus, and alternative bottoms). That might rule out of some of the modules: I can’t find the reference again, but at least one of them is said to implement its own special interface for keeping track of tabbed content rather than extending the standard Drupal interface.

This problem raised another question. How should I think about Drupal when working out how to do this? It’s well known that programming needs three key concepts, used both in describing control and describing data: sequencing, alternation, and repetition. If I were programming the problem in Pascal, I would represent the page as a record. The first field would represent the top half of my page; the second would represent the bottom halves. Because these require alternation, I’d represent them as a discriminated union. I’d also need some pragmatic information saying that the union is to be displayed using tabs and giving the tabs’ labels.

Now, it’s clear that some of the built-in Drupal menus implement that kind of alternation. I get the impression, actually, that they’re more important than the content itself, because users on various discussion groups have wondered why they couldn’t see their content, then been told by an expert that this was because it’s not attached to a menu. But I don’t think the Drupal documentation says this anywhere. A formal semantics of Drupal would be good, but I can’t find one. So when designing a structure like my page with one top and multiple bottoms, where should I start? What’s the equivalent of C.A.R. Hoare's famous essay "Notes on Data Structuring" that every computer scientist will know from the classic Structured Programming?

Looks like you need to look at some of the typical "page layout" modules, such as these ones (excerpts from their project pages):

Display Suite.

... allows you to take full control over how your content is displayed using a drag and drop interface. Arrange your nodes, views, comments, user data etc. the way you want without having to work your way through dozens of template files. A predefined list of layouts (D7 only) is available for even more drag and drop fun!

Panels.

... allows a site administrator to create customized layouts for multiple uses. At its core it is a drag and drop content manager that lets you visually design a layout and place content within that layout. Integration with other systems allows you to create nodes that use this, landing pages that use this, and even override system pages such as taxonomy and the node page so that you can customize the layout of your site with very fine grained permissions.

Not sure if Display Suite will be sufficient for all your needs, but Panels will pretty sure be helpfull. Possibly also with 'mini-panels' added to that.
Be prepared however to invest some time in learning about these amazing modules. A great resource for learning about Panels is the (free) video training about Learn Page manager. Panels uses 'Page manager', which is one of the sub-modules of Chaos tool suite (ctools)).


How is the user logout process supposed to work? I’ve built a complete private site. Everything seems to work. When users wants to  log out, they are redirect from /user/logout /user/login?destination=/, which seems the normal behavior, for what I understand.

A client told me he is not redirected to /user/login?destination=/ but stays on /user/logout, getting an Access Denied error.

I can’t reproduce this issue.

How is the logout supposed to work? Is the redirect from /user/logout to /user/login?destination=/ the normal behavior?

Is the redirect from /user/logout to /user/login?destination=/

No, the normal behavior is to redirect to the frontpage. You probably have a module installed which issues a second redirect when the logged out user doesn't have access to the frontpage.

  How is the user logout process supposed to work?

This is the core controller as example:

UserController::logout

  /**
   * Logs the current user out.
   *
   * @return \Symfony\Component\HttpFoundation\RedirectResponse
   *   A redirection to home page.
   */
  public function logout() {
    user_logout();
    return $this->redirect('<front>');
  }

So you only need to call user_logout() in custom code to implement your own logout.


How to render set of Form API elements? I have an array like the following.

$form["something"]["something"] = array(
  0 => array( "#markup" => "line 0" ),
  1 => array( "#markup" => "line 1" ),
  2 => array( "#markup" => "line 2" ),
);

When rendering it in the theme function with drupal_render($form["something"]["something"]), I get only the first line.

  line 0

When I try to use foreach, this somehow does not return anything.

So what am I doing wrong? Should I modify an array itself and add some wrapper element? I would prefer to render it all with one line, without foreach.

Instead of drupal_render(), you should use drupal_render_children().

print drupal_render_children($form["something"]["something"]);


Can we add a new column to field collection in edit form? I created a topic before with this question, but i write another to be more exact on what i want to do. I have an entity with several field collections and in this field collections, several fields (text, checkbox, entity ref...). When i open the form in EDIT mode, i want to add a new column to my field collection and in this column i would add a simple link to go to another page. So in my other topic we told me to use "link" module but it's not working on EDIT form but just in VIEW mode. So i searched how to add a column programmatically in drupal. I tried in my HOOK_form_alter to alter the form but i can't...

I can add a new column with jQuery i think but that won't be the best solution.

Someone got an idea ?

Thanks

It sounds like hook_form_alter is the way to go.

See this for more information

See both answers because i think that waht you want to do is just add another tab at the end of the node edit form for just a link to another page.

You can always check the form api for more information


Restore hacked website from database without source I have a database backup from a hacked drupal site. The source code of the hacked website has been lost. When I try to make another installation of the site working using the old database, I have the following error:

Fatal error: require_once(): Failed opening required 'C:\ampps\www\drupal.fox\drupal/sites/all/modules/date/date_api/date_api.module' (include_path='.;C:\php\pear') in C:\ampps\www\drupal.fox\drupal\includes\bootstrap.inc on line 3168

How could I avoid such errors? is there any way to make drupal runs temporarly without missing modules or even is there a tool that able to download and install missing modules?

You can set status to '0' in table 'system' for missing modules
P. S. 'drush cc all' is a must-run command after the manipulation like this or manually empty cache tables


Can't access to password input on registration form I have a problem. I can't access through module to password field on registration page.

function customization_form_user_register_form_alter(&$form, &$form_state, $form_id) {
$form['account']['pass']['#id'] = 'userRegInput';
}

It wont change id of input. I don't know why...

Thank you!

EDIT: Btw. i have installed user_registrationpassword module, maybe is because of that...

You can access the password form field in the registration form, but the ID you are setting is not used.

When a password_confirm form field is being added to a form, Drupal is really adding two password form field with a process function (form_process_password_confirm()); that function doesn't use the ID set for the password_confirm field for the new fields.
There isn't a theme function for the password_confirm form field, which means that the following code (executed from theme_password(), and theme functions for other form fields) is not executed.

element_set_attributes($element, array('id', 'name', 'size', 'maxlength'));
_form_set_class($element, array('form-text'));

What you can do is to wrap the password_confirm form field with a
 tag to which you assign your ID.

$form['account']['pass']['#prefix'] = '
';
$form['account']['pass']['#suffix'] = '
';

If you are using the CSS ID to execute JavaScript code, or to style the field, keep in mind that the default output for the password_confirm field (for the form field you are interested) is the following one.

Password strength:

    Password *
    <input class="password-field form-text required password-processed" type="password" id="edit-pass-pass1" name="pass[pass1]" size="25" maxlength="128">

Passwords match:

    Confirm password *
    <input class="password-confirm form-text required" type="password" id="edit-pass-pass2" name="pass[pass2]" size="25" maxlength="128">

Provide a password for the new account in both fields.

The HTML output includes also the output from the JavaScript code that outputs the password strength.

As alternative, you can add a process function that is executed after the process functions normally used by Drupal.

$form['account']['pass']['#process'] = array('form_process_password_confirm', 'mymodule_process_password_confirm', 'user_form_process_password_confirm');

Use form_process_password_confirm() as guideline for the code you should write.

function form_process_password_confirm($element) {
  $element['pass1'] =  array(
    '#type' => 'password',
    '#title' => t('Password'),
    '#value' => empty($element['#value']) ? NULL : $element['#value']['pass1'],
    '#required' => $element['#required'],
    '#attributes' => array('class' => array('password-field')),
  );
  $element['pass2'] =  array(
    '#type' => 'password',
    '#title' => t('Confirm password'),
    '#value' => empty($element['#value']) ? NULL : $element['#value']['pass2'],
    '#required' => $element['#required'],
    '#attributes' => array('class' => array('password-confirm')),
  );
  $element['#element_validate'] = array('password_confirm_validate');
  $element['#tree'] = TRUE;

  if (isset($element['#size'])) {
    $element['pass1']['#size'] = $element['pass2']['#size'] = $element['#size'];
  }

  return $element;
}

user_form_process_password_confirm() just adds the JavaScript code to handle the password strength, and any messages about the used password (e.g. Make it at least 6 characters, Make it different from your username).

I tried using the following code in my test site, and the output for the password field didn't change.

function code_testing_form_user_register_form_alter(&$form, &$form_state, $form_id) {
  $form['account']['pass']['#attributes'] = array('id' => array('userRegInput'));
}

The ID is not being added to the form field.

Password strength:

    Password *
    <input class="password-field form-text required password-processed" type="password" id="edit-pass-pass1" name="pass[pass1]" size="25" maxlength="128">

Passwords match:

    Confirm password *
    <input class="password-confirm form-text required" type="password" id="edit-pass-pass2" name="pass[pass2]" size="25" maxlength="128">

Provide a password for the new account in both fields.


How can I generate similar sets of fields in views quickly from within the views ui? I have several views that I have made of the users on my site.  Each view has different contextual filters, pages, and fields.  However, certain "groups" of fields are the same.

In particular, I have a series of four checkboxes on the user profile that I use the views module's rewriting ability to display, and this "group" of four fields is the same among all views.

Is there a way to somehow save this as a reusable unit within the views UI so I don't have to input it manually all the time?

The easiest thing to do it to add all of the common fields to the Master display, and then a few displays to the view that get customized for the individual uses using overrides.


What is causing Views to consistently but intermittently not find a view provided by the Advanced Forum module? I'm getting a frequent, intermittent error from the Advanced Forum module that causes a 500 error when it occurs (WSOD). On production, it's happening about 20 times per hour, on probably 2-3% of all forum page loads per hour. It is consistently intermittent. Locally, I cannot consistently reproduce the error, but it does occur.
The error is on

Line 232 o f sites/all/modules/contrib/advanced_forum/includes/core-overrides.inc`:
Call to undefined method stdClass::preview()

The problem lies with the advanced_forum_get_topics() function:
function advanced_forum_get_topics($tid, $sortby, $forum_per_page, $sort_form = TRUE) {
  $term = taxonomy_term_load($tid);
  drupal_add_feed('taxonomy/term/' . $tid . '/feed', 'RSS - ' . check_plain($term->name));

  // Views handles this page
  $view = views_get_view('advanced_forum_topic_list');
  $view->sort_form = $sort_form;

  return $view->preview('default', array($tid));

}

Essentially views_get_view() fails to find the view and the object isn't created as expected on the return line. So the problem seems to lie with Views occasionally not knowing the view exists. This makes me think it's a hook problem.
Where it starts to get odd are the implementations of hook_views_default_views() and hook_views_plugins(). According to views.api.php hook_views_default_views() should be in a file called MODULENAME.views_default.inc and hook_views_plugins() should be in a file called MODULENAME.views.inc. However, both files are in the MODULENAME.views.inc file.
From views.api.php:

hook_views_plugins()
This hook should be placed in MODULENAME.views.inc and it will be auto-loaded.
MODULENAME.views.inc must be in the directory specified by the 'path' key returned by MODULENAME_views_api(), or the same directory as the .module file, if 'path' is unspecified.

hook_views_default_views()
This hook should be placed in MODULENAME.views_default.inc and it will be auto-loaded.   MODULENAME.views_default.inc must be in the directory specified by the 'path' key returned by MODULENAME_views_api(), or the same directory as the .module file, if 'path' is unspecified.

I tried splitting up these routines into the seemingly correct files. This caused Views to consistently find the Advanced Forum view (as indicated that it appeared in the Views GUI list) but not see the plug-in. The pages in Advanced Forum ran fine, but the views were blank because they referenced a style plugin provided by Advanced Forum that Views was no longer seeing.
I assume I'm missing something about Views hooks, but I'm totally stumped.

Stack: Drupal 7, Views (7.x-3.3), CTools (7.x-1.0), Advanced Forum (7.x-2.0)
PHP FPM, APC, nginx, Redis
I didn't find anything helpful in this d.o issue

UPDATE 1: While I have not solved the root cause, it does appear that disabling Redis and reverting to Drupal's default database-based cache storage mechanism stops the problem from occuring.
UPDATE 2: I can reliably replicate the issue on local by doing a flushall in Redis. The first page load of looking at a forum listing will fatal out. The second page load (and all subsequent) work fine. UPDATE: I have to hit the admin Views listing page to clear the error.
UPDATE 3: On further troubleshooting the issue appears to be caused by the Views cache not properly being rebuilt after a cache clear, only when using Redis. The issue does not occur when reverting to standard Drupal cache. When the issue occurs only 2-4 cache entries exists for Views, as opposed 100+ when the cache is properly built. Visiting the admin views list page causes the cache to be fully built and the issue does not occur. I need to verify if hitting any View view page causing the issue, or just the advanced forum view.
UPDATE 4: A helpful user on IRC has suggested this might be a problem related to Views cache race condition issues: 853864, 1102252

It sounds like you found the right answer from the IRC.  "Consistently intermittent" in my experience is when there are two sources filling the cache.  Most common is when you have a development site and a staging/production site on different code bases but same database.  The drupal-provided caches that I have read code for connect to the database, so routing/function information that is cached will cross contaminate.  Hitting the admin/modules page will refresh the module cache and locations, hitting the admin/views listing page clears your error because it refreshes the site's understanding of views from the perspective of your site instead of the perspective of whatever is conflicting with you.

If you have server admin ability, change the password to your site's database and the password in your settings.php, and see what breaks.  Your listings should stop being corrupted and what is tampering with them should break ... unless it is directly connected to your site and using your settings.php file.

Also, check to make sure there are not multiple installations of the views module in your docroot.


Why is the content of existing blocks not editable? I have inherited the Administration of a Drupal 6 site with major funkiness going on. In this case I can't even figure out where to look.

There are a few dozen blocks configured and for the most part they are displaying what they are supposed to. However, a few of them are either blank or need tweaking. When I go to the block admin page, I am able to configure the blocks and bring up the Block specific settings tab, however the normal fields are all missing. Only Block Title shows up and that appears to be blank across the board.

Strangely enough, if I go to add a new block of my own, the form shows up correctly with all the fields.

What could cause these fields to not be displayed for existing blocks or where would I find the content of these blocks to be edited?

I suspect that the blocks that are doing this are made via hook_block and not with the block UI (ie, admin/build/block/add).  I just checked a Drupal 6 site that I did a while ago, and all of my custom blocks have this behavior.

The Configure link for each custom block should contain the module name that defined it, along with the delta.  For example the "Who's online" block has this for the configure link:

  admin/build/block/configure/user/3

It is defined in user.module and if you look at user_block you will see that the $delta for this is 3.


Where are valid password reset tokens stored? When one submits the form on user/password or executes drush uli, a password token is generated. Where does Drupal store these?

I do not think Drupal stores password tokens. I have used drush uli many times and it generates a one time login link, similar to link generated by user_pass_reset_url(). You should see the functions coding


Unknown top and bottom padding in panels I'm using the panels module in drupal 7. I'm having some problem with the css in panels. I've removed the top and bottom padding in my custom css but there still appears to be some padding. How can I remove it?
I have give the id "leftpane" and made the following CSS

#leftpane {
    margin: 0px;
    padding:0px 20px;
    background:#17532E;
    border-radius:17px;
    float: left;
    }

How do I remove the unknown top and bottom padding?

leftpane {
margin: 0px;
padding:0px 20px !important;
background:#17532E;
border-radius:17px;
float: left;
}

Add !important rule to override existing padding


Altering Views Exposed Form Elements and their Associated Labels I have a series of Views Exposed Forms across a Drupal 8 website. My goal is to generate unique template suggestions so I can theme each individual input and their labels differently as needed.

Here is my current approach. Placed into theme.theme.   I've hit a brick wall.

function HOOK_form_views_exposed_form_alter(array &$form, FormStateInterface $form_state, $form_id) {
    $form['#attributes']['twig-suggestion'] = $form['#id'];
}

function HOOK_theme_suggestions_input_alter(&$suggestions, array $variables) {
    $element = $variables['element'];

    if (isset($element['#attributes']['twig-suggestion'])) {
      $suggestions[] = 'input__' . $element['#type'] . '__' . $element['#attributes']['twig-suggestion'];
    }
}

function HOOK_theme_suggestions_form_element_label_alter(&$suggestions, &$variables, $hook) {
    $element = $variables['element'];

    if (isset($element['#attributes']['twig-suggestion'])) {
      $suggestions[] = 'label__' . $element['#attributes']['twig-suggestion'];
    }
}

All input and label [#attributes] are null via Kint.
Here are the URLs I have referenced for background:

1) http://kevinquillen.com/drupal/2017/01/28/adding-twig-template-suggestions-for-form-elements

2) https://www.chapterthree.com/blog/how-to-create-custom-theme-suggestions-drupal-8

3) https://yellowpencil.com/blog/getting-granular-with-drupal-eight-forms/

Should add #attributes to your element form so the form alter should be like:

function HOOK_form_views_exposed_form_alter(array &$form, FormStateInterface $form_state, $form_id) {
    $form['name_of_element']['#attributes']['twig-suggestion'] = $form['#id'];
}

HOOK_theme_suggestions_input_alter will works only with input elements textfield.


How to use a tag as a header in Views? I have a view page where the sort criteria are tag names.

I want to have the appropriate tag-name appear as a h2 above the content of that type.

Is there an easy way to do this? Or do I have to mess with Twig templates?

You can add the <h2> tag under Style Settings of your field.

Example:


Homepage accessible to non-members though title of the page says : "Access Denied" Since i upgraded to 7.8 i noticed that the homepage of my site now displays a title of "Access denied" as it used to be "Welcome to my site". Though it remains perfectly accessible to non-members.

I'don t recall modifying any permission so far so i doubt this is because of my code. Have anyone experienced that ? How could it be fixed ? Do i need to override menu title for that page ?

I have no idea what caused that though i solve it by creating a custom menu item with HOOK_menu giving it full permissions, then i added that new menu item in the homepage field in site configuration .


Detect 403 or 404 in page.tpl.php I'm looking for a working solution, to detect a current 403 or 404 state from within a template (page.tpl.php) in Drupal 7.

Unfortunately, Drupal seems to be unable to handle error pages.

If my assumption is correct, then you are looking for the way to handle 404 and 403 pages.

If that is the case,

  Goto configuration->Site information, there you can specify your own page for handling 404 or
  403 pages.

For that particular page, you can write tpl file like node--type--nid.tpl.php


Use default installation profile? I've written a custom installation profile.  When running install.php for the first time to install it, I have to select the installation profile I want to use.  I then select mine and run the install profile, no problem.  However, my client wants to be able to use the profile I put together as the default installation profile and skip that first step entirely (selecting an install profile).  How can this be accomplished?  Simply setting it as the default selected profile is not enough.

This part of your original question isn't quite clear:

  Simply setting it as the default selected profile is not enough.

However, all you have to do is to add exclusive = TRUE in the .info file of your installation profile.
This will automatically select your installation profile, and the user will proceed to the language selection screen.

Note 1: the setting above will be ignored if there are 2 or more installation profiles marked as exclusive. This might happen only if you downloaded another installation profile and are keeping it in the /profiles folder (e.g. Commerce Kickstart).

Note 2: this has been committed to Drupal 7.22 and is based on this issue/discussion.


What is the use of @db_query? I have used db_query to retrieve table rows from database. Recently I noticed, some people use @db_query instead of db_query.

I dont see any difference with the two. Is it doing any special functionality that normal db_query doesn't?

@ is the error control operator, what it does is suppress notices/warnings and even script halting errors. You see it most commonly used with variable comparisons where the person coding didn't bother to check if a variable is set first.

if (@$unsetVar != $var) {
  @$unsetVar .= $non_existent_variable';
}

Suppresses the warning that $unsetVar is not initialised.

The proper way of doing this though would be using isset($unsetVar) to check that this variable is in fact initialized first, if not don't do anything with it, or assign it a default of some kind. Then neither the comparison or the concatenate will throw errors. Keeping this in mind can prevent some show stopping bugs later down the line as your applications become more complicated.

I'd personally advise against using @ wherever possible, if there's a notice/warning/error it's usually for a reason, using @ is a lazy fix and can make debugging a pain if something does go wrong.

Tl;dr, I'd avoid using @ where possible.


How do I remove the tab provided by a third-party module? I'm using the Guestbook module version 6x-2.0. How do I remove the "My Guestbook" tab on user profile pages?

I solved this with the Tab Tamer module.

  Tab Tamer is an administration utility that provides easy re-ordering, hiding, and deactivation of tabs and subtabs.

  Tab Tamer makes use of Drupal's drag ordering, but degrades gracefully when javascript is disabled.


How to have a field displayed depending on user's role in Views? I use Views module to display the content of a custom entity with Page view (not Block view).
I'd like to have one field displayed only if the user has a certain role.
What is the best way to do that?

If this is a custom entity you may consider overriding the checkFieldAccess method of Drupal\Core\Entity\EntityAccessControlHandler.

Then assign your own handler as handlers/access in @ContentEntityType.

But it's only me who prefers being in coding hell instead of configuration hell :-)


Function to check for value prior to using getValue? I'm trying to write a function that takes into account both regular text fields and entity references and checks for a value prior to using getValue() to assign it to a variable.

   function checkUserFieldAvailability($fieldName, $assignedName){
      if (!$user->get($fieldName)->isEmpty()) {
        ${$assignedName} = $user->get($fieldName)->first()->getValue()['target_id'];
      }
      else {
        ${$assignedName} = "";
      }
    }

Something like this... Is there an easy way to make it account for both entity references that are assigned like this...

$name = $user->get('field_firstname')->first()->getValue()['target_id'];

and regular text fields which are assigned like this.

$email = $user->get('mail')->getValue();

Basically i'm trying to confirm all the fields I'm making assignments too in fact first have a value (to avoid errors) and if not assing  an empty string.

I think you are looking for the main property of the field:

if ($item = $user->get($fieldName)->first()) {
  $string = $item->{$item->mainPropertyName()};
}
else {
  $string = '';
}


I want my LinkItem to get target="_blank" if my node has the checkbox checked I'm not sure if hook_preprocess_node is the right hook. But I cant find the setting for target in the LinkItem. Can you help me?

A different approach I failed is to extended the FieldWidget of Link and add a checkbox to toggle the target setting. I wasn't able to save this setting though...

class TargetLinkWidget extends LinkWidget {
  public static function defaultSettings() {
    return ['target' => ''] + parent::defaultSettings();
  }

  public function formElement(FieldItemListInterface $items, $delta, array $element, array &$form, FormStateInterface $form_state) {
    $element = parent::formElement($items, $delta, $element, $form, $form_state);

    $element['target'] = [
      '#type' => 'checkbox',
      '#title' => t('Open link in new window'),
      '#value' => '_blank',
      '#default_value' => $this->getSetting('target'),
    ];
    return $element;
  }
}

According to your answer to my comment on the question, you are using a view. To have my solution work, it needs to display fields, not teasers.

First off, you do not need to add an additional field to the node type/content type.

All you need to do is to add the already displayed link field in views a second time. All fields get a views internal machine name which is often identical to the field's machine name. However, if you add a field twice, you will end up with two machine names, thus you can determine which version of the rendered field to use at some point.

So, you end up having the same field (Link - field_link) showing up twice in your view's field list. The one added first will be accessible through the token [field_link], the second one by using [field_link_1].

In the first one's settings, choose the plain URL formatter and then go to the "Rewrite result" section. Select the option to output the field as link and enter [field_link] as url and _blank for target:

Finally, set the option "Exclude from display". Repeat that with the second link field, but use [field_link_1] as url and do not set the target.

With both field instances set up and excluded from display, add your checkbox field which may have the machine name field_link_is_external.

Now you need to rewrite that field to be [field_link]:

If the checkbox is checked, the link version with target set "_blank" will be shown.

Next, you need to set the "No result behaviour" as follows:

If the checkbox is not checked, it's value is zero, hence we treat 0 as empty and thus the second link field (w/o target) will be shown.

And that's all there is to it. No need for any editor to enter some url twice. They just need to set the link and decide whether or not to check that checkbox.


commerce - add tax when creating order I don't seem to see an ability to add tax to an order when it's created by admin through Store->Orders->Create Order. Can this be somehow configured?

I have it working on a standard checkout for a frontend user, it depends on the billing address entered. I'd like to have the same for when order is created 'manually'

This used to be handled by an external module called Commerce Checkout Admin 7.x-2.11 but since Commerce Kickstart 7.x-2.16 this apparently came as part of core. As a result, Commerce Checkout Admin 7.x-2.12 now does not include this feature.

Since updating my site the 'Add an Order' no longer seems to calculate tax, so I am looking for this solution as well. Using:

Drupal 7.30
Commerce Kickstart 7.x-2.16


How to hide User Id's in Privatemsg Currently with the Privatemsg (v7.x-1.3) module it shows the user ids when sending a new message and I'd like it to show the user names instead. Firstly is there any problem with doing this?

Secondly the 'Send this user a private message' link is formatted as:

 /messages/new/3?destination=user/3

and if I change it to:

 /messages/new/user_name

the 'To' field on the write new message page does not contain the username. Is there a setting or module that would allow this.

I don't think there's an easy way to replace the user IDs with usernames, but you can easily add the usernames using the Realname integration (you have to set up the Realname module as well though).

My Privatemsg send page looks like this:

I did this by enabling Realname and following the instructions here.  You will need the dev version as well; the 1.3 release has broken Realname AJAX.


How do I import products using commerce_feeds and commerce_autosku? how do I import a CSV of products into a Kickstart site using commerce_feeds, with commerce_autosku enabled to generate the SKUs on import?

This sounds like it should be possible because an obvious use case is the one where you don't care about SKU and you have a CSV with Title, Price and Description of each product.  But I keep getting an error similar to:

SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry 'commerce_product-52' for key 'PRIMARY'

Seeing this issue, seems that is not currently 100% possible: https://www.drupal.org/node/1662620

Answer from the mainainer in that issue:

  Have you tried unchecking the "Always regenerate SKU's" checkbox for this product type? That should allow your SKU's to be accepted without being overwritten.


Apache Solr Search show only currrent user language I'm using Apache Solr Search Integration to do the searching on our website, works great except i get results for all the language on the site instead of only the one the user is currently using.

Is there a way to show only nodes that are in the current users language? Either filter it out of the results by a simple check or directly in the query?

I was hoping there would be a hook to alter the results before the pager is created, i got as for as filtering out the other language in hook_apachesolr_search_page_alter() but thats to late, then you get a pager for 3 pages with only one result.

I also tried Apache Solr Multilingual but that doesn't seem the work really well at the moment for 7.x.

One way to do this is to implement hook_apachesolr_query_alter() to automatically filter on the current language. In a custom module called "mymodule", the code snippet would look similar to the following:

/**
 * Implement hook_apachesolr_query_alter()
 */
function mymodule_apachesolr_query_alter($query) {
  global $language;
  $query->addFilter("ss_language", $language->language);
}


Create an e-mail reminder depending on a date field in a custom content type I have created a custom content in which there is a date field and an e-mail field I would like to add an automatic email reminder that is triggered on that date and sent to the email specified in the custom field.

What is the correct procedure to do so?

I followed the following instructions to achieve what I wanted to do.

  Create a Rules component of type 'Action Set' and call it 'Send Notification'. Add a Variable of 'Entity: Node', give it a label
  and machine name of 'node'.

  Add an action to the loop (note: add it to the loop and not the
  component) of 'System: Send Mail'.

  Add a new rule and call it 'On new event', to react on 'Node: After
  saving new content'. Restrict it to the custom content type.

  Add an action to this rule, 'Rules schduler: schedule component
  evaluation', and select the 'send notification' component you created
  earlier.

  Set the evaluation date to node:field-event-date.

  Add an offset: -1 days (optional)

  Add an identifier of 'node-[node:nid]-event' and note its pattern as
  you will be using it to delete events.

  Select the Node as 'node'

Source: Send reminder to referenced users day before event date in cck date field


How can I hide empty Quick Tab item when there is no content in it? I don't want to show quicktab item when there is no content in it.
But I can see empty divs in it.

How Can I remove the quick tab for above empty content.

I already checked it. But still the 'View' I assigned to that quicktab renders some div's which I posted in my question. By the way, I found the solution, you just need to add the filter in that particular view. Suppose view of content type 'movies' then add a filter "content:movies => not empty (IS NOT NULL)". That's it.  Hope this help others too.


Show clrcle overlay instead of marker in google map? I'm using gmap module on Drupal 6. I create a view and select gmap as style for my display.
Everything works fine but the map shows a Marker and I need to show a circle overlay instead of the marker so that the map hide the exact address location.

I tried all setting within gmap module but...nope.

Where is the right place for this setting?

Thanks

The view settings should allow you to choose the marker style. Don't have the module installed to check but a comment on the "Provide Gmap marker field for use in Views listing" feature request illustrates how I remember it:

  Under style: GMap in your view try clicking on the setting icon next
  to where it says GMap. An option box should appear below the view with
  some options:

  Marker handling: By content type (for node views)
  By term (for node views)
  Use single marker type


how can i re-direct a user of a particular role, if that user tries to access a page containing certain content type? i have set a up a role called subscriber. If a non-subscriber (authenticated or anonymous user) tries to access a page with content type of ‘video class’ i’d like to have them redirected to a page that suggestions they subscribe.  so far, the content access modules i’ve looked at don’t handle page re-directs.

is there a module that would handle that?

the Context module doesn’t seem to handle content types. I could use it to set up a block with a javascript re-direct based on user role that seems kind of flimsy

You can consider Rules for this requirement.

You can add new rules for event such as "viewing a page" & put conditions to match user type & content type. In action you can add page redirect.


hook_commerce_order_presave firing on page load I'm trying to run some code whenever an order is updated. I've found the function hook_commerce_order_presave which fulfils this purpose, but it seems this also fires on page load. Is this normal, or is there another module that would be causing this? Is there a more suitable function I could use?

This is unusual. The hook should not be executed on every page load. You might want to check if some code in a custom module, custom theme, rule is causing an update of commerce_order which could trigger the hook.

To ensure that the order is updated on every page load, you can implement hook_entity_update(), in your custom module

function MODULE_entity_update($entity, $type) {
  if ($type == 'commerce_order') {
    // Execute your code here.
  }
}

If the code inside if loop is still executed, you can be sure that the something is triggering update of commerce order on each page load. And you can proceed to find out what is the actual cause of the problem.


How do I use custom user forms? After creating separate user registration form in Structure > Display Modes > Form Mode and creating those forms in Configuration > People > Manage Forms, how do I use these forms? I want different roles on my site to use different registration forms to register different users.

There is no option for this in ui.

You have to define the display mode for the form in mymodule.routing.yml:

Example from user.routing.yml

user.admin_create:
  path: '/admin/people/create'
  defaults:
    _entity_form: 'user.register'
    _title: 'Add user'
  requirements:
    _permission: 'administer users'

In the line  _entity_form: 'user.register' the form is user and the form mode is register.

Then you can access the form with the path defined here and restrict the access through roles with requirements.

Edit (place the form on any page)

If you want to place the form on any page, you need the form as a block.

You can use this module:

https://www.drupal.org/project/entityform_block

But it does not have the option for arguments like form mode.

This experimental module can do this:

https://www.drupal.org/project/entity_forms_in_blocks

  Interesting features that does not exists for now with the other modules : ability to choose the form mode as Drupal 8 allows to (in
  Drupal 8, you can create additional form modes).


Clear input field after click without attach any external script Are there any helper functions contained in Drupal core or Ctools to perform popular tasks such as clearing input field after an event occurs ?
I know how to do it using external js (javascript) file, but I was wondering whether an alternative way for this exists or not  ?

I doubt it, that would be re-inventing the wheel IMO...what you're describing is pretty much what jQuery is for. Consider this code, which is a basic representation of what you're trying to do:

$(function() {
  $('#some-element').bind('someEvent', function() {
    $('#some-other-element').val('');
  });
});

That's only 3 meaningful lines of code, and is so trivial that writing a function to wrap around it would be counter-intuitive. The resulting code would end up being equally or more verbose, and all it would do is basically pass parameters blindly to a jQuery function.

Don't forget if you want to invoke any Javascript at all you're going to need an external JS file (or at the very least inline code). I would suggest using the above 3 lines in that external/inline JS would be preferable to using any sort of wrapper function (even if one does exist).


How to give a particular role, the right to register new user We have been targeted by spam bot, and decided to set the option "Who can register new user" as "Administrator only". So far so good.

I would like to let another role (Webmaster) create users as he wishes.

In the permissions settings, I checked the checkbox for "Administer users", but I feel like the option "Administrator only" in the account parameter is overwritting this.

Anyone has an idea of how to do this?

I couldn't get why it's a problem, you are already there, just simply create a role "Webmaster" if you dont have one already, and give this role the same permission "Administer Users" too. but if you only want to give specific permission such as ONLY creating users you might need Administer Users by Role module

  This module allows site builders to set up fine-grained permissions
  for allowing users to edit and delete other users — more specific than
  Drupal Core's all-or-nothing 'administer users' permission. It also
  provides and enforces a 'create users' permission.

  To use this module:

  Create a role for the users who you'd like to be able to
  create/edit/delete other users Give that new role the 'administer
  users' permission and give it the desired Administer Users by Role
  permissions If the user-being-edited has multiple roles, the
  user-doing-the-editing must have permission to edit ALL of the
  user-being-edited's roles.


Overload permissions for specifics users On my website, I have users with classic roles, but I want to add the possibility to assign permissions to specifics users. For example, a user has a role that doesn't allow the user to create articles, but I want to have a checkbox (on the edit page of the user's account) to grant this permission (and not to all users that have this role). Of course I can't create a specific role for that because I'm talking of many permissions specifics to users.

How can I perform this ?

I came across a similar situation and I think my is solution either the Group module or the og module. I didn't try them yet but both seems promising. I'm about to try them now.


How to strip html comments plus all tags inside it? Any idea how can I remove this in $vars['closure']; ?

I tried the methods explained by kiamlaluno in this thread but I cant remove the above code in the view source using preg_replace but no luck.

//Remove omniture tags in unpublish node
  if(arg(0) == 'node' && $vars['node']->status == 0) {
    $vars['closure'] = theme('closure');
    $omnitureTags = preg_replace( "/\

This is what theme_closure() does (in theme.inc):

function theme_closure($main = 0) {
  $footer = module_invoke_all('footer', $main);
  return implode("\n", $footer) . drupal_get_js('footer');
}

which means it's going to ask every module to run its footer hook plus get all the js to be put in the footer and return it:

$variables['closure'] = theme('closure');

to populate the closure variable.  So.... if you can't preg_replace() or regex() it out, why not just find what module is putting in there in the first place (seems pretty obvious) and kill it off there?

EDIT/ADDITION:  IF it's a bug, fix it here, otherwise if it's just something you want different, preprocess it.  But it seems to me that a node status check might be in order in the module's footer hook.


Header and many components missing in Open Social Just installed Open Social:
https://www.drupal.org/project/social

The problem is that there is no content on the front page. No header or other blocks. I have reviewed videos of installation on YouTube, and notice that there is a header, and many other blocks available by default immediately after installation. Why does my new instance of Open Social have nothing on the home page?

I followed the install instructions on the module page:
https://www.drupal.org/project/social

Generating demo content is optional but recommended.
Follow these instructions on generating demo content (Drush support only for now).
Still stuck? Explore the thorough guide to installing and updating which includes help for working with Docker.

OR

drush command to add demo content

drush demo-content-add file user group topic event event_enrollment comment post like


Banner block (referenced by url) not displayed when using language extensions I have a Banner View block that appears on pages using a reference url field.

When the url: thispage is entered in the reference field of the banner, it appears on domain.com/thispage.

Now that i enabled 2 other languages en + de this reference is not working. Entering the url with the language extension (en/thispage) neither.

I looked into the Views Block. Maybe some code needs to be added. The block has this code under Visibility settings:

<?php $nids=arg(1); $datas=node_load($nids); if ( $datas->type=='referenced' ) { return false; } else{ return true; } ?>

In the View under contextual filter there is some global php. This might be changed to match the path from other languages (de/thispage)

This is the code from Views:

$match_path = ltrim($_SERVER['REQUEST_URI'], '/');

$match_path=explode("/",$match_path);
$match_path=explode("?",$match_path[0]);
return $match_path[0];
//return $_GET['q'];

Any suggestions about how to resolve this?

You may want to check your configuration at Configuration -> Languages -> detection and selection: the order specified there could be what explains the current behaviour in your site.

You'd have to experiment a bit with what the exact order in your case should be. In my experience, I often get these kind of issues to work by using an order like 'URL, Default, User', and not something like 'Default, URL, User'. So try to experiment a bit with the various combinations in this order to see if it helps.


Install New Module Link Not There I've seen this question posted elsewhere here but I haven't seen an answer for it. I am new to Drupal and I'm interested in installing some modules via the Drupal interface, but I don't see the "Install New Module" link on the modules page. (Yes, update manager is already enabled, and going to admin/modules/install doesn't get me anywhere).

There are 2 components to the Install New Module UI access callback:

It requires the Administer software updates permission for the user to be enabled. It can be enabled for any user role underneath the People > Roles administration section for the relevant user role.
It requires update_manager_access variable to be set to TRUE. By default, this should be TRUE, but it can be overridden in settings.php or manually set (e.g. drush vset update_manager_access 0). In which case, it needs to be adjusted in settings.php or by updating the variable in the database (drush vset update_manager_access 1).


Fetch user's realname (from Name Field) within database query (or an alternative method)? I'm building a custom field for a form based off of the values stored in a user reference field. The options for this field are being built from the following database query:

<?php
// Fetch the users referenced in the provided node
$args = array(':nid' => $nid);
$result = db_query("
    SELECT
        field_data_field_user_ref.field_user_ref_target_id,
        users.name
    FROM field_data_field_user_ref
        JOIN users
            ON field_data_field_user_ref.field_user_ref_target_id=users.uid
    WHERE entity_id = :nid", $args);
$arr = $result->fetchAll();

// Add these users as an array to be displayed
$users = array();
foreach ($arr as $val) {
    $crafters[$val->field_user_ref_target_id] = $val->name;
}

...returning the array in the form of...

uid 1 => name 1
uid 2 => name 2
uid 3 => name 3

This works fine, except for the fact that the user's username is displayed instead of their "real name." In my case, the Real Name is being generated by a Name Field (from the Name project). I can't seem to figure out a way to grab the real name from the database. Not sure if it is even stored in there.

Is there an alternative way to grab each user's real name? I'm assuming I could use some application of user_load but I don't know if there's a performance hit associated with loading an unknown number of users one by one just to grab their names. Probably will never be more than a handful of users, but I'd rather keep it optimized.

The Name project used entity fields that can be queried in the DB, just like any other field. All you need to know is the machine name of field that you attached to the user entity. To use your example above:

$result = db_query("
    SELECT
        field_data_field_user.field_user_target_id,
        nf.*,
        users.name
    FROM field_data_field_user
        JOIN users
            ON field_data_field_user.field_user_target_id=users.uid
        JOIN field_data_field_MY_NAME_FIELD AS nf
            ON nf.entity_id=users.uid AND nf.entity_type = 'user' AND nf.bundle = 'user'
    WHERE field_data_field_user.entity_id = :nid", $args);

All you need to do is replace MY_NAME_FIELD with the machine name of your actual field.  The result will be rows that contain name columns associated with the user reference.


It does not work when installed as "subsite" I tried to install Drupal 8.03 on a windows 7 64 bit server, with MySQL, Apache and PHP 7.03, using the default install procedure / script.

Drupal is only one of the applications on the website and that is probably different from what Drupal 8 seems to expect.

The website is like https:/www.mysite.nl and overall root folder is x:\myroot\homepage. Drupal, however, is installed in x:\myroot\homepage\drupal and it is supposed to be accessible via https:/www.mysite.nl/drupal.

Back to the installation. To a "certain" extend that seems(!) to work. That will say the install script runs and ends. But than I want to access Drupal and that does not work. I can not access any thing "page missing". Both the base folder and the base url is not what Drupal expects (e.g. Drupal generates https:\www.mysite.nl\xyz where that should be https:\www.mysite.nl\drupal\xyz and I can not change that (at least not from the UI which is not accessible, assuming there is a setting for that).

So drupal seems is completely lost, does not understand what its base url is and does not understand where the files are (both at least the url should be a question during installation!!!!!).

By the way I never really used other drupal versions, but from a last year test install my impression is that this problem did not exist in drupal 7.

I do not know how to solve this. Hope you can help and perhaps initiate a few corrections/extensions in Drupal 8.

Look for this code in the .htaccess file in the root of the Drupal site's filesystem:

# Modify the RewriteBase if you are using Drupal in a subdirectory or in a
# VirtualDocumentRoot and the rewrite rules are not working properly.
# For example if your site is at http://example.com/drupal uncomment and
# modify the following line:
# RewriteBase /drupal

and remove the '#' from the beginning of the RewriteBase line. That should tell Apache/Drupal how to properly rewrite URLs for your case.


Restricting view access to a line Item field based on role I have an order page that displays a set of line items.

However, my client wants me to remove the "Responsible Vendor" from display for authenticated users, but it should be displayed for administrators and store manager users.
I have tried the following, but I could not get the desired results.

Hide using Field Permission as described in https://stackoverflow.com/a/9187147/260665

Implementing hook_field_widget_form_alter() following https://stackoverflow.com/q/8009716/260665

I am using the following code.
function bricks_field_widget_form_alter(&$element, &$form_state, $context) {
  if ($context['field']['field_name'] == 'field_responsible_vendor') {
    // Users without the "administer nodes" permission should not see the
    // Responsible Vendor section
    if (!user_access('administer nodes')) {
      unset($element['#options']['field_responsible_vendor']);
    }
  }
}

This hook is never invoked for the field_responsible_vendor field  which represents the Responsible vendor entity reference field.
Now, I tried to dig deep and see why this hook was never invoked for the field in which I am interested. I placed breakpoints in /includes/module.inc with some test code in it.
    // Raj:
    $gotIt = NULL;
    if (is_array($context1)) {
      if ($context1['field'] == 'field_responsible_vendor') {
        $gotIt = $context1['field']['field_name'];
      }
      if (is_array($context1['field'])) {
        if ($context1['field']['field_name'] == 'field_responsible_vendor') {
          $gotIt = $context1['field']['field_name'];
        }
      }
    }

I tried it with $context2 too. The nearest I could get was the following.

I could never get to the field_responsible_vendor field to unset it based on the user roles.
Is there anything I am missing? How can I achieve what I am looking for?
As per @Darvanen's answer, I was able to remove the Responsible vendor value using this code.
function bricks_views_pre_render(&$view) {
  foreach ($view->result as $lineItem) {
    if (!user_access('administer nodes')) {
      unset($lineItem->field_field_responsible_vendor);
    }
  }
}

I have the following 2 problems.

This hook is invoked for all views, I would rather like to restrict either the invocation to this page / view alone, or provide a condition to check if it is the page where this code should be executed in order to make sure that performance is not impacted.

The column header is appearing though none of the line items will contain the value for it. I suppose I need to use another hook in order to address this?

The hook method is a good one but you'll need a different hook.

The order page uses a view of line items, not a node display, so you should use a views hook.

I would try either hook_views_pre_render or hook_views_pre_view.

Use dpm($view) (needs devel module) to inspect the view and then modify it however you wish.

To figure out that it was using a view I went to the page, inspected the element in my browser and followed the chain up until I found either a form or a view:

Additional information:

You will definitely need to put an if statement around your code.  Dig through the dpm results for a view id or some other identifier and do something like:

If ([address of view id] != [view id you want]){
  return;
}

To make the column disappear you'll need to unset the field itself, not just the value.  Look in $view somewhere other than ->result.  Sorry, without the dpm output in front of me I can't be more specific than that.


Field_image empty after database export and import I exported my previous D7 database (db1), and imported it into a new database (db2). That said, all of my data (pages, articles, content, etc) seems to have exported the way it should... EXCEPT for the images attached to my articles. Now when I navigate to an article, what was uploaded to my field_image previously is now a broken link (even though the fid in my database seems to be correct). Does anyone know why this might be or how I can fix it?

If it helps, this is the error message I get on the screen as well:

  Warning: array_key_exists() expects parameter 2 to be array, null
  given in theme_image_formatter() (line 605 of
  /modules/image/image.field.inc)

When I right click on the broken image and attempt to "show image address", it simply gives me my domain name. E.g. mydomain.com, and no real path to an image. Not sure if that matters.

I am assuming that the Images are showing as uploaded in the backend. But when trying to view it on the front it is coming broken. you can check the file system path in the drupal admin it should be sites/default/files

if the file path is not the issue, then look at here(https://www.drupal.org/node/920840) there was a thread going around the warning and seems to be resolved. #22 could be the solution to look.


User specific permission to add links to a menu When I create a content type, e.g. 'Basic Page' and I want to add a link to a menu I do usually the following:
Menu settings -> Provide a menu link -> choose a menu and its position of the link there

I know, that I can define, which menus are appearing here, in the menu settings section of a content type.

I have several menus, for specific users. For now, if they create a new 'Basic Page' they see all the menus, which are set for this content type. So as well, menus from other users. Is it possible to show just their own menu, so they do not have access to the other menus?

For now I solve this problem by assigning roles for each individual user, and granting permissions for this 'user role' per 'user menu', by using the Menu Admin per Menu module for D7. It would be much more convenient, to use user specific permissions here.

Is there any way, of doing that?

Thank you in advance!

Check this Menu Per User and let me know if you face any issues.