Is there anyway 'odd' and 'even' classes can be attached to node teasers so that they can be striped with different colored backgrounds? Is there anyway 'odd' and 'even' classes can be attached to node teasers so that they can be striped with different colored backgrounds?

In the same way that table rows can be striped.

Looking at the node.tpl.php doc page, there seems to be a way that you can print this in a node template.

Put the following in the node.tpl.php file (if your theme has no node.tpl.php file, just copy from modules/node):

<?php print $zebra; ?>

You can use Views module to generate node lists in the exact same criteria that Drupal core front page has.

Install Views module
There is a Views template called "front page" that you can edit.
Just save the View and make sure you have set the front page to this new views based page.

By default, Views adds odd/even classes to the node list. You can toggle this feature in field settings. Choose "Row style" to "nodes" and under settings, toggle this feature.


How do I migrate from Rhythmyx to Drupal? I am working on migrating a site from Rhythmyx to Drupal 7, and since they are so different I was wondering if anyone has done that and how they did it.

Rhythmyx is proprietary software. You're likely to find very little, if at all, people in the Drupal community that have experience migrating from it.

The first thing to know is what technology stack it's built on so you can evaluate tools to pull out content. The vendor's website is scarce on tech details. From what I could find, the language is perhaps Java. It's also supposed to have a static content export & pluggable API so that should be able to assist in pulling out data.

On the Drupal side, there's Feeds &  Migrate. Feeds is best for mostly static content migration where there isn't fresh content coming into the site on day-to-day basis (and thus an ongoing need to sync both the existing site and new site while development/testing is happening). Migration is a best when you have many different custom content types, taxonomy, users, and other custom data that needs to synced regularly while development is occurring.

Whatever means you find to pull out data from Rhythmyx will affect what import tools you use. If you have static structured data (e.g. CSV, XML, RSS Feed) Feeds is the better choice here. If you have an API that PHP can interface with, Migrate will be more useful.


Mainteance Mode Causes CSS to be removed I am getting my site ready for an update, but whenever I put my site in maintenance mode, all it does is remove all the CSS and images from the site and just shows the content.

Does anybody know what is happening?

Create a maintenance template file and place it in your theme folder. It's probably using a parent theme maintenance template or just the regular core one.


how do I return a count of items returned from an entityfieldquery Is it possible to return a count of the number of items returned in an entityfieldquery query?

if you just want the count then you could set the query to count.

something like

$count = $query->count()->execute()

See here for more detail


Workflow module blocked my admin user today i was adding the workflow module to my site and as i was not clear i used a trigger in it. using this trigger I blocked the current user to view the page and now if i login from my admin user it just tell me that The username webmaster has not been activated or is blocked.
please guide me what to do to restore my old position.

Use below Drush command to reset admin password.

> drush uli
    (or)
> drush uli user_name

// Display a one time login link for the given user account (defaults to uid 1).

Just copy the one time login link and paste it your browser. Here you will get reset password option.

After successfully login, disbale the workflow module and go ahead.

More about Drush.


Drupal function to delete folder How I created the folder i want to delete:

$form['logo'] = array(
'#title' => t('Upload logo'),
'#type' => 'managed_file',
'#description' => t('Allowed extensions: .gif .png .jpg'),
'#upload_location' => 'public://myfolder/',
'#upload_validators' => array(
  'file_validate_extensions' => array('gif png jpg jpeg'),
  'file_validate_image_resolution' => array('500x250'),
),);

Now how to delete it? I have tried this

file_unmanaged_delete_recursive('public://myfolder/');

and

drupal_rmdir('public://myfolder/');

There are files in the folder I'm trying to delete.

file_unmanaged functions are allowed to fail on managed items, so when you create folder using '#type' => 'managed_file', they are not the way to go.

drupal_rmdir is only a wrapper around PHP rmdir, and it requires folder to be empty.

It means both solutions you have tried was not able to work.

Correct way is to use EntityFieldQuery to load all files in the folder you want to purge, then use file_delete on them, with $force set to TRUE to remove files that are in use (think twice if that's really what you want to do!). Only when the folder is empty, call drupal_rmdir on it.


Fieldable entity issue I currently have an event entity, which is fieldable. My question is, how do I make it appear under admin/structure, and how can I access the Manage Fields page from the admin menu? Is there a tutorial on this? Any help is highly appreciated since I could not find anything related.

You'll need to provide a menu item and page that lists information about your entity type (typically settings). If you provide multiple bundles you'll need to provide a page for each bundle.

After you've done that you can add a simple snippet to your hook_entity_info similar to the foreach loop at the bottom of node_entity_info(). Specifying the 'admin' info under your bundles will provide the "Manage Fields" and "Manage Display" tabs for the path specified. Note that if you do not have multiple bundles, the only two required keys under the 'admin' section are 'path' and 'access arguments'

Keep in mind that the path referenced in the ['bundles'][BUNDLE_NAME]['admin']['path'] section has to exist and be defined elsewhere in your hook_menu. Field module will only take care of the two tabs and the pages they link to.


Perform math calculation in views On Drupal 8 site, I have a exact copy of the below excel example table made with views but without the yellow cell yet.

The view is displaying one content type: Client where all the below fields are available:

Date
Client Name
Client ID
Amount ($)

Now, as you can see, the yellow cell is displaying the total SUM of all amount ($) rows.
which basically is: 15+29+97+115+45+67+23+11+5+91+44 = 542$

How can i achieve this exact calculation in my view ?

I have tried to enable the Use aggregation option under the advanced section on my view, but it seems it doesn't do what i am asking for!

any help please ?

Note: I believe the use Use aggregation option doesn't add a row at the bottom of the table calculating the sum of all above rows and therefore this question Making a colums total (SUM) with Views is not a possible duplicate of this one.

UPDATE #1

After following the answer of @Stef Van Looveren, I am encountering a new error:

InvalidArgumentException: Field field_money_amount is unknown. in Drupal\Core\Entity\ContentEntityBase->getTranslatedField() (line 587 of /home/####/public_html/#####/web/core/lib/Drupal/Core/Entity/ContentEntityBase.php)

Knowing that: field_money_amount is the id of the field taken from the content type being used inside the view.

Complete code in the .module file:

<?php

use Drupal\views\ViewExecutable;

function my_module_views_pre_render(ViewExecutable $view){
  if ($view->id() == "view_id" && $view->current_display == 'display_id') {
    $total = 0;
    foreach ($view->result as $value) {
      $number = $value->_entity->get('field_money_amount')->value;
      $total += $number;
    }
    $view->attachment_after = [
      '#markup' => '

Total:	'.$total.'

',
      '#allowed_tags' => ['table','tr','td']
    ];
  }

}

Interesting question and a typical use case. In a custom module, do the following:

use Drupal\views\ViewExecutable;

function helper_views_pre_render(ViewExecutable $view){
  if ($view->id() == "numbers" && $view->current_display == 'page_1') {
    $total = 0;
    foreach ($view->result as $value) {
      $number = $value->_entity->get('field_number')->value;
      $total += $number;
    }
    $view->attachment_after = [
      '#markup' => '

Total:	'.$total.'

',
      '#allowed_tags' => ['table','tr','td']
    ];
  }
}

Change the names according to your view name & field names. I'm sure you get the point: you add a table below with the total result.

I did a test and it gave me the following result:


how to add 'OR' operator in views sort criteria How to add 'OR' operator in views sort criteria?

Is there any ui setting or have to do some custom work?

Any suggestion?

What do you mean add OR? There is no such condition in sorting. You can have different sorting levels. Add multiple values in the view's ui sorting criteria and then re-arrange properly.


How to update my module's dev branch on Drupal.org I have a module on Drupal.org and I only have a dev branch.  This is how I added my dev branch by tagging with 7.x-1.x-dev:

git commit -m 'Creating module'
git push origin 7.x-1.x
git tag 7.x-1.x-dev
git push --tags

Now I made some more changes and would like to have my dev branch updated with the latest code. I delete the tag and recreate the tag:

git tag -d 7.x-1.x-dev
git push origin :7.x-1.x-dev
git commit -m 'Adding new feature'
git push origin 7.x-1.x
git tag 7.x-1.x-dev
git push --tags

I did this and I don't see my files get updated on Drupal.org. Am I doing something wrong?

No need to deal with tags for the dev branch. Tags are only required for stable releases.

Since you have already added your dev branch you just have to add your files, commit them and push them, like this:

git add path/to/files
git commit -m "Commit message"
git push origin 7.x-1.x

Then you just wait for drupal.org to reroll a new dev version. It takes up to 12 hours to see a new dev version on the project page.

You should be able to see your commits though if you click the View commits link in the development sidebar block.


How do I add recaptcha to a custom form programatically? I'm using the following contrib module: https://www.drupal.org/project/google_recaptcha

How do I add a recaptcha to my form programatically, since the form I'm using isn't listed under forms on the config page of the module?

The following doesn't seem to work:

$form['recaptcha'] = array(
  '#type' => 'recaptcha'
);

The module doesn't implement hook_element_info, so it doesn't define a new element type. The code you're using looks like it's borrowed from the traditional captcha module, which does things a bit better and provides the element type.

Looking at the code, this is all you need in your form alter hook:

g_add_captcha($form, $form_id);


How do I programmatically remove a block? I have a custom module that is intended to be deployed as a pure web view, with no styling whatsoever beyond what I created in the .twig file.

I installed the Stark theme and in my local instance I went to Admin > Structure > Block layout to manually remove all the active blocks.

However, this module will be deployed and I will have to have it programmatically remove all blocks when integrated into the mobile client.

Is there a way to turn off any automatic/default activation of blocks?

You can use hook_preprocess_html(). For example, to remove the system navigation block from the "sidebar_first" region, define the following hook in your MODULE.module:

function MODULE_preprocess_html(&$variables) {
  if($variables['page']['REGION']['BLOCK'])
    $variables['page']['REGION']['BLOCK']['#access'] = FALSE;
}

with REGION = sidebar_first and BLOCK = system_navigation.


Why am I getting "Access Denied" on /user/login? Not sure what happened with my Drupal site, but I can't log in :s

When I go to /user/login, /user, /?q=user, /admin, whatever I just get "Access Denied", never presented with a Login form. Server response is 403.

Drupal 6 site.

Probably your IP has been blocked as a potential source of flooding/DoS attack. This may happen if there were a lot of requests from the same IP.

That happened to my company's site once when we rearranged our LAN structure so all intranet users could only access the site through proxy server, and proxy server IP was blocked by Drupal automatically.

You need to check flood table - there must be a record with your IP. Just delete that record or all records (DELETE from `flood`).


How to get Views caching working with contextual filters? Using Drupal 7.19 and Views 3.5 cache is not respecting contextual filter argument- it is displaying the same cache result no matter what argument given. How to get this working properly?

This is a Views bug actually and it is not solved yet, but you can work around it by using this patch if you are using contextual filter Taxonomy with depth as I guess, and if it didn't work you can turn off the "Field Language" for the view if you have neutral language content, but this patch is not complete as there is some issues not solve, you can see the full discussion of this issue here issue here


Config split settings file generated into split directory Drupal 8.7
I have a multisite split. The config_split.config_split.<sitename>.yml files are supposed to go into the config/default directory. For some reason when updating a split on one of my sites, instead of updating the existing file in that location, it creates a new file in the config/sitename directory. It only does it on this one site. When I compare the newly generated file to the one for that site in the default directory, only the new changes are different. The rest is the same.

Have you checked the $config_directories array in the settings.php/settings.local.php files.

It might be a good idea to explicitly set it via config as per https://www.drupal.org/docs/8/configuration-management/changing-the-storage-location-of-the-sync-directory:

$config_directories[CONFIG_SYNC_DIRECTORY] = '../config/sync';


Countdown Timer Field cannot find Countdown Timer Library - even though it's there I'm facing trouble with the enabling of the "Countdown Timer Field" module from within "Administrator" -> "Modules" -> Fields.
The error message I get is

  "The jQuery Countdown Timer Library could not be found. Please download it, install it in a libraries directory, and rename the directory to jquery-countdown. The library should be available at a path like sites/all/libraries/jquery-countdown/assets/countdown/jquery.countdown.js (Currently using jQuery Countdown Timer Library Not found)".

This doesn't really make sense to me, since I unzipped the JQuery in the correct location (I think.)

This is part of the "JQuery Coundown" module, version 7.x-1.0-alpha1. My end goal is to use Views on a field with a Countdown.

This is my directory structure:

root@brian-VirtualBox:/var/www/drupal/sites/all/libraries/jquery-countdown/assets/countdown# ls -laSh
total 16K
drwx------ 2 root root 4.0K Dec 30  2011 .
drwx------ 6 root root 4.0K Dec 30  2011 ..
-rwx------ 1 root root 3.0K Dec 29  2011 jquery.countdown.js
-rwx------ 1 root root 1.7K Dec 29  2011 jquery.countdown.css
root@brian-VirtualBox:/var/www/drupal/sites/all/libraries/jquery-countdown/assets/countdown#

Opening up index.html located in /var/www/drupal/sites/all/libraries/jquery-countdown/index.html works on my browser.

This looks like a permissions error.

root@brian-VirtualBox:/var/www/drupal/sites/all/libraries# chmod -R 777 jquery-countdown/

Then, the module will install correctly. However, I do NOT think 777 is a good permission to use on this, so I'm continuing to read about Drupal 7 Libraries, and what permissions should be used. It looks like the .zip I unziped did not preserve the correct file permissions for jquery-countdown.

More specifically, my question has now become, what should the permissions be for directories in sites/all/libraries for Libraries 7.x-20?

The permissions were wrong after unzipping. They should have been:

 drwxr-xr-x 4 www-data www-data

which can be accomplished by:

 chmod 755 -R jquery-countdown/


Adding a theme suggestion programatically I created a feature module containing only a view and a content type.

Right now my page-node-x.tpl.php and my views-view-y.tpl.php files lie in my themes directory.

Is it possible to move them into my feature module?

A module that implements hook_preprocess_page() or hook_preprocess_node() can suggest new template files by altering the variable $variables['theme_hook_suggestions'].

The code contained in template_preprocess_page() that initialize that variable is the following.

// Populate the page template suggestions.
if ($suggestions = theme_get_suggestions(arg(), 'page')) {
  $variables['theme_hook_suggestions'] = $suggestions;
}

Each theme suggestion needs to match with an entry returned by hook_theme().

In Views, there should be an equivalent preprocess function to use in the similar way, or a way that allows to hook_preprocess_page() that allows to the function to understand if the page is associated with a view.


Assign location from Profile2 to a node I would like to allow user when creating new content (an event) to assign (from drop down) one of the locations defined in his profile (Profile2)... Is there a module which could help? If not any hint how to solve it in custom module?
Im thinking entity reference field could do if it was possible to create list of location for each user...
Maybe it is simple but beyond my drupal skills... ;)
Locations are nodes referenced with entity reference but not necessarily created by the same user

Install the references module, once you done that, you can enable the node_reference submodule and attach a "Node Reference" field to your "event" content type. Choose the "select list" widget and the user will be able to link any location to the event.

If you want to let the user choose only from locations he created, here's a way:

On the field configuration page, you can see a fieldset called "Views - Nodes that can be referenced". It says that options from the dropdown can be filtered based on a view using the "References" display type.

Just create a view listing location nodes and select the correct "display type" as shown below:

And display nodes from the current logged-in user by adding a contextual filter "Content: Author uid"

Save all that and refresh the field configuration page. Select the view from the dropdown list that just appeared and you should be good to go ;).


Display Solr search form on every pages I'm working on a site which uses Apache Solr for the site search which is on the URL /search/site/.

What I want to do is add a form to every page on the site which allows the user to entered text in & submit it. The form will then take the user to the /search/site/ page displaying the results for their search term.

This sounds like it should be simple but I cannot see how to do it, I cannot find a way of creating a block for it & when I try to use the code below to programmatically display the form it is presented to the user but when submitted they are taken to the correct page (/search/site/) but the results of their search are not displayed.

$search_form = drupal_get_form('search_form');
$search_form_box = drupal_render($search_form);
print $search_form_box;
print render(drupal_get_form('search_form'));

I wasn't 100% sure that "search_form" was correct but when submitted it does take you to the correct search results page (/search/site/) but no terms or results are displayed.

I'm quite new to using Drupal & Solr so if there's any information you need that I missed out please ask.

I managed to work this one out, to get the block ready to be displayed I used preproccess_region (see code below)

function THEMENAME_preprocess_region(&$variables){
    $site_search_block = module_invoke('search', 'block_view', 'search');
    $variables["site_search_block"] = render($site_search_block);
}

Then in in my region .tpl file (region--menu.tpl.php for me) I put the following code to display it.

<?php if($site_search_block){ print $site_search_block; } ?>

As an additional bit of information if you want to edit the output of the form as I did, although I didn't ask about it here, this function should help you:

function THEMENAME_form_search_block_form_alter(&$form, &$form_state, $form_id) {
    $form['#id'] = 'siteSearchForm'; //Set form element ID

    //The form elements (I think)
    $form['search_block_form']['#title'] = t('Search'); // Change the text on the label element
    $form['search_block_form']['#title_display'] = 'invisible'; // Toggle label visibilty
    $form['search_block_form']['#size'] = 10;  // define size of the textfield
    //$form['search_block_form']['#default_value'] = t('SEARCH'); // Set a default value for the textfield

    //Submit button element values
    $form['actions']['submit']['#value'] = t('GO!'); // Change the text on the submit button
    $form['actions']['submit'] = array('#type' => 'image_button', '#src' => base_path() . path_to_theme() . '/img/search-icn.png');

    //Add extra attributes to the text box
    //$form['search_block_form']['#attributes']['onblur'] = "if (this.value == '') {this.value = 'SEARCH';}";
    //$form['search_block_form']['#attributes']['onfocus'] = "if (this.value == 'SEARCH') {this.value = '';}";

    //Prevent user from searching the default text
    //$form['#attributes']['onsubmit'] = "if(this.search_block_form.value=='SEARCH'){ alert('Please enter a search'); return false; }";

    //HTML5 placeholder attribute instead of using the javascript
    $form['search_block_form']['#attributes']['placeholder'] = t('SEARCH');
}


Creating an entity with an unlimited number of bundles So I want to create an entity that can have as many user-created fieldable bundles as possible.

My first thought was to look at the Profile2 module, however I notice that there appear to be two separate entities as part of it - the profile2 entity, as well as a profile2_type.

  // Add bundle info but bypass entity_load() as we cannot use it here.
  $types = db_select('profile_type', 'p')
    ->fields('p')
    ->execute()
    ->fetchAllAssoc('type');

  foreach ($types as $type => $info) {
    $return['profile2']['bundles'][$type] = array(
      'label' => $info->label,
      'admin' => array(
        'path' => 'admin/structure/profiles/manage/%profile2_type',
        'real path' => 'admin/structure/profiles/manage/' . $type,
        'bundle argument' => 4,
        'access arguments' => array('administer profiles'),
      ),
    );
  }

I want to have separate entities with only one instance, but unlimited bundles. Do I need to create two separate tables to accomplish this, or should it be possible with one table? I think it should be possible, but I'm not quite sure.

You have to register entities using hook_entity_info() so the system knows about them.

If you look at those docs it tells you about the different entity properties.

The one you are interested in at the moment is the bundle entity key and the bundles array.

You can see from the docs that you have to specify a list of bundles, otherwise it will be assumed you only have a single bundle with the same name as the entity type.

The example I would probably look at is node, because it is in Drupal core, so check out node_entity_info().

You can see it works similar to the profile2 one in that it gets its node bundle information from the database from where users have defined content types via the content type UI (and also from hook_node_info() for modules defining content types).

So you need a table for the bundle information, similar to the node_type table.

You also need your table to store entity data, similar to the node table.

If you want to support revisions you also need a revision table, similar to the node_revision table.

I can't see how it is possible with a single table unless you are storing 2 completely different types of data in a single database table, which would be bad.

Another thing to consider is that the system needs to know about bundles to provide UI screens for managing fields.
You have to manage the fields before the user creates any content so at the time you need those UI pages there is nothing in the node table so it couldn't pull bundle data from there at that point.
If you pulled bundle data from the main node table you wouldn't be able to administer the fields until a node was created of that bundle type.

I'm also not sure why you are apprehensive about having 2 tables.


how to include globals.php in template.php file I need the variables from the globals.php and I can't seem to call/register them in theme's template.php file. These variables are needed for my custom hook function for the template. Am i missing something (since it's been global and be called somewhere else during rendering)?

1.in order to include entire file into some other file,we have 2 functions in php:-

a) include('filename'):this function will include the file and if any error occurs during the importing of the file,then the script will not stop and will continue with its execution.

b) require('filename'):this function will include the file and if any error occurs during the importing of the file,then the script will stop.

include() function is recommended for including files.


Ubercart shipping quotes are being based on total before discounts I'm hoping someone can help with this.
A site I built (www.bebeperla.com) is using Ubercart 7x-3.8 and Ubercart Discounts 7x-2.0 Alpha3.

The customer gets free shipping for orders over $80, but if they use a coupon to bring the total for the order below $80 they're still getting free shipping.

My shipping quotes are flat rate and the rules are based on a data comparison of the order:order-total.  Unfortunately it's not working - it seems to be calculating the shipping from either the sub-total or the total before the coupon is applied.  Any ideas?  I've searched the web but I can't find an issue that matches.

So apparently I needed a good nights sleep.  For anyone else in my situation, advise your client that this is not a good idea.  Why?  Because you WANT the shipping module to calculate the amount of shipping on the final total WITHOUT coupons because you still need to incur the cost of shipping the items.  (head smack)

For example - if I changed it to calculate shipping on the total AFTER the coupon is applied, for all the other shipping methods this might bump the customer down to a lower shipping rate - and the store owner would lose money on the shipping.

My solution - exclude free shipping from carts that contain a coupon and create a new free shipping for carts including coupons with a higher $ amount.  For example instead of being $80 for free shipping it would be $100 for free shipping with carts including a coupon.  It's not a perfect solution, but it's better then screwing up all the other shipping settings.


Disable submit button if none selected using #states The code

     $form['type'] = array(
      '#type' => 'select',
      '#title' => t('Type of new field'),
      '#options' => $field_type_options,
      '#empty_option' => t('- Select a field type -'),
      // '#empty_value' => 0,
      '#description' => t('Type of data to store.'),
      '#required' => TRUE,
    );

    $form['save'] = array (
     '#type' => 'submit',
     '#value' => t ('Save field'),
     '#states' => array(
       'disabled' => array(
         ':input[name="type"]' => array('value' => 0),
         // Tried value = NULL, value = FALSE - no luck
)),

);

The goal is to disable submit button if none selected from drop-down list. Which "value" should I provide? Tried "0", "FALSE", "NULL"

The "#empty_option" will not give a value, which is needed for #states, a workaround is to add the default as an actual option:

$field_type_options = array( 0 => '- Select a field type -');

$form['type'] = array(
  '#type' => 'select',
  '#title' => t('Type of new field'),
  '#options' => $field_type_options,
  '#description' => t('Type of data to store.'),
  '#default_value' => isset( $form_state['values']['type'] ) ?  $form_state['values']['type'] : 0,
  '#required' => TRUE,
  );

  $form['save'] = array (
   '#type' => 'submit',
   '#value' => t ('Save field'),
   '#states' => array(
     'disabled' => array(
       ':input[name="type"]' => array('value' => 0),
      )
    )
  );

This allows #states to test the value and disable the item


Show taxonomy children terms when searching parent term I have a question about taxonomy term search and I hope someone can help.
What I need to do is be able to perform parent taxonomy term search and pull all children terms so that the resulting page shows content tagged with children terms to the searched parent term.
There might be already a solution out there but I can’t seem to find it, so if someone knows where to get to it, please let me know.
I have already created a vocabulary, which contains about 100 terms; some terms have with sub-terms (children terms).
When I search for a parent term, I don’t get the content tagged with its children terms related to the parent. When I click the parent term the only thing I get is: “There is currently no content classified with this term”.
Thanks for help.

Add these helper functions to your module
  - Call function get_all_nodes_belong_to_taxonomy_hierarchy(), with argument as parent term id, to get all nodes related to parent term
  and child terms both

/**
 * function to get all term ids inside a vocab in a flat array
 * No matter if vocab consists of hierarichal order of terms,you will get all term ids in a flat array.
 * @param
 *   $vocab_machine_name takes vocabulary machine name as parameter.
 * @return
 *   $tids return array of tids in a flat array format
 */
function get_taxonomy_term_ids_inside_vocab($vocab_machine_name) {
  $vocab = taxonomy_vocabulary_machine_name_load($vocab_machine_name);
  if (is_object($vocab)) {
    $term_tree = taxonomy_get_tree($vocab->vid);
    if (is_array($term_tree) && !empty($term_tree)) {
      foreach ($term_tree as $key => $value) {
        $tids[] = $value->tid;
      }
    } if (empty($term_tree)) {
      $tids = array();
    }
  } else
    return "No Vocab Found with the given name";

  return ($tids);
}

/**
 * function to get all the node ids directly mapped to the given taxonomy terms.
 * Returns Flat array of node ids belong to the given term ids.
 * @param
 *   $tid takes term id can be a single term or array of terms.
 * @return
 *   $nid/$nids returns node ids array or sinly node id directly mapped to the given taxonomy term.
 */
function get_nodes_directly_mapped_to_term($tid) {
  if (is_array($tid) && !empty($tid)) {
    foreach ($tid as $key => $value) {
      $nids[] = taxonomy_select_nodes($value);
      $flat_nids = multitosingle($nids);
    }
    return $flat_nids;
  }
  else {
    $nid = taxonomy_select_nodes($tid);
    return $nid;
  }
}

/**
 * function to convert mutlidimension arrays to flat arrays.
 * Returns Flat arrays.
 * @param
 *   $input takes input array as multudimension array.
 *   $output takes output array as paramter in the recursive call.
 * @return
 *   $output return flat array format for the input multidimenional array
 */
function multitosingle($input, $output = array()) {
  ksort($input);
  foreach ($input as $value) {
    $key = count($output);
    if (is_array($value)) {
      $output = multitosingle($value, $output);
    }
    else {
      $output[$key] = $value;
    }
  }
  return $output;
}

/**
 * function to get array/single nids which are attached with any of the taxonomy term of the given vocab.
 * Returns Flat array of nids.
 * @param
 *   $vocab_machine_name takes the machine name for the vocabulary.
 * @return
 *   $nids_inside_vocab returns array of nids/single nid attached to any taxonomy term under the given vocab.
 */
function get_nodes_belong_to_vocab($vocab_machine_name) {
  $vocab_tids = get_taxonomy_term_ids_inside_vocab($vocab_machine_name);
  if (is_array($vocab_tids) && count($vocab_tids) > 0) {
    $nids_inside_vocab = get_nodes_directly_mapped_to_term($vocab_tids);
    return $nids_inside_vocab;
  }
  elseif (is_array($vocab_tids) && count($vocab_tids) == 0) {
    return array();
  }
  else {
    return "There is no vocab found with the given machine name";
  }
}

/**
 * function to get array/single nids inside a single taxonomy term/array of taxonomy terms
 * function to get all node ids recursively inside a taxonomy term.
 * if parent term is passed as parameter then the function returns nid belongs to the parent term and nids related to its child terms.
 * Returns Flat array of nids.
 * @param
 *   $tids takes array/single tids for which you need nids recursively.
 * @return
 *   $nids flat array of nids
 */
function get_all_nodes_belong_to_taxonomy_hierarchy($tids) {
  if (is_array($tids)) {
    foreach ($tids as $key => $value) {
      if ($value <= 0) {
        return "Please Enter a valid taxonomy term id set";
      }
    }
  }
  if (is_array($tids) && !empty($tids)) {
    foreach ($tids as $key => $value) {
      $term = taxonomy_term_load($value);
      $hierarchical_terms_object[] = taxonomy_get_tree($term->vid, $term->tid);
    }
    $flat_terms_object = multitosingle($hierarchical_terms_object);
    if (is_array($flat_terms_object) && !empty($flat_terms_object)) {
      foreach ($flat_terms_object as $key => $value) {
        $flat_tids[] = $value->tid;
      }
      $flat_tids[] = $tids;
      return array_unique(get_nodes_directly_mapped_to_term($flat_tids));
    }
    else {
      $flat_tids = $tids;
      return array_unique(get_nodes_directly_mapped_to_term($flat_tids));
    }
  }
  elseif (!is_array($tids) && $tids > 0) {
    $flat_tids = $tids;
    get_all_nodes_belong_to_taxonomy_hierarchy(array($flat_tids));
  }
  else {
    return "Please Enter a valid term id";
  }
}


Gmap Views Module - Popups are too big I'm using GMAP module and its views counterpart.  The issue I'm having is that I'm using a custom text field to display fields wrapped in HTML that I have pulled in from the query.  However, the popup won't size correctly; it ends up being too big. This is my code for Custom Text Field:

  [field_thtr_img_fid]

[title]

  [address_1]

Any help would be greatly appreciated.

looking at the details from https://stackoverflow.com/questions/5186047/drupal-gmap-views-popups-are-too-big I would suggest to wrap everything in the custom text field in a div with a specific class then do .myclass { width: DESIRED_WIDTH; } in your stylesheet.

or try to div.gmnoprint .views-field-nothing { width: DESIRED_WIDTH; } where div.gmnoprint is the wrapper div for the gmap popup and .views-field-nothing is the default wrapper for a custom text field in views.

Without a live example, it is harder to give an exact answer. I suspect you may have to add overflow:hidden; to your wrapper div if you have any floating going on there.


Change the description for username field in user registration I would like to disable the spaces in the usernames. For that I installed a rules module and i applied a rule. Everything is fine but now the label is still saying : "Spaces are allowed; punctuation is not allowed except for periods, hyphens, apostrophes, and underscores."

How can i change that label ? I looked everywhere and i didn't find a thing.

I am new to drupal.
I use drupal 7.

Thanks in advance for you responses.

Another couple of options using string translation techniques:

Contrib module: String Overrides
settings.php snippet insert

The string overrides module lets you do the string translation via the UI.
Otherwise, you can set the override in settings.php - the search string needs to match exactly.

/**
 * String overrides:
 *
 * To override specific strings on your site with or without enabling locale
 * module, add an entry to this list. This functionality allows you to change
 * a small number of your site's default English language interface strings.
 */
$conf['locale_custom_strings_en'][''] = array(
  'Spaces are allowed; punctuation is not allowed except for periods, hyphens, apostrophes, and underscores.' => 'Spaces and punctuation are not allowed except for periods, hyphens, apostrophes, and underscores.',
);


How to get a "node" value from URL using arg(0)? I have this problem in getting a value from URL.

First I've created an url alias for a certain articles.

In example, from this /node/899 the alias I've created it's /news/investments/899

Then when I use arg(0) which is to get the value of first parameter which is "news" I get a result "node". The url alias works.

You can get aliased path using drupal_get_path_alias API Function..

$alias_path = drupal_get_path_alias();
$alias_arguments =  explode('/', $alias_path);
print $alias_arguments[0];


Block not displayed on translated views page I'm having an issue where my menu block doesn't appear on certain pages in a different language.

I have my main navigation shown in a menu block and it appears on my news view at mysite.com/consumers/news/year/2015 and articles at /consumers/news/article-title

The problems is there is content in other languages and the block does not appear on /fr/consumers/news/year/2015 nor /fr/consumers/news/test-fr-article

The block is not restricted to any users, roles, languages or content types. The visibility filter is set to Only the listed pages

consumers*
fr/consumers*

but it just doesn't show up on those specific French pages for some reason.

Ok, I figured out the issue was there was a menu position rule for consumers/news* in any language appearing under a menu item in the English language menu. I set this rule to be English only then replicated it for French language items under the French menu


How to place blocks in code with zen theme? I've been tasked with maintaining a site I didn't make and I don't have access to the original developers.

The site is built with a custom zen theme. The block that I'm interested in is listed in the disabled section of blocks and is configured to the "None" region of the enabled themes and is set to be displayed on all pages with no restriction for users or content types. There doesn't appear to be any obvious settings in the page that the block is on or in the block itself that would determine it's placement. So, I'm a little lost as to how to proceed. Any advice would be appreciated.

Add the following function in your template.php

function THEMENAME_render_block($module, $delta, array $options = array()){
  $default_options = array(
    'title' => '<none>',
    'region' => -1,
  );

  $options = array_merge($default_options, $options);

  $block = db_query('SELECT * FROM {block} WHERE module = :module AND delta = :delta', array(':module' => $module, ':delta' => $delta))->fetchObject();
  if($block) {
    $block = block_load($module, $delta);
    $block->title = $options['title'];
    $block->region = $options['region'];
    $blocks = array($block);
    $rblocks = _block_render_blocks($blocks);
    $render_array = _block_get_renderable_array($rblocks);
    return drupal_render($render_array);
  }
  return "";
}

then in your tpl file of your specific page/node

<?php print THEMENAME_render_block('<moduleName>', 'delta', array('title' => t('Block Title'))); ?>


Bulk update for unchecked "Generate automatic URL alias" I have a lot of programmatically generated nodes with the option "Generate automatic URL alias" unchecked, so i can't use the Bulk Update of the pathauto module.

How can i to bulk generate the pathauto alias for these nodes?

Edit: i use Drupal 7

Have you tried using Views Bulk Operation. All you will need to do is create a view that will list all the nodes that will meet your criteria and then assign an action 'Generate Url alias' (I haven't tried it though.)


How to display a custom block as a pop on home page? I have a custom block created, it contains 3 links in it. Now I want to display that block as a popup on home page. I looked at the Popup module but it didn't work.

There are other modules which provide you the popup functionality.

Popup message

  Display popup message for users once per browser session. Based on
  javascript code:
  http://yensdesign.com/2008/09/how-to-create-a-stunning-and-smooth-popup-...

Lightbox2

  The Lightbox2 module is a simple, unobtrusive script used to overlay
  images on the current page. It's a snap to setup and works on most
  modern browsers.

Shadowbox

  Shadowbox is a JavaScript modal media viewer application for viewing
  images, video, Flash and other content in a modal window.


How to add predefined text to contact form? I would like to add a couple paragraphs of predefined text (not an input field) to my contact page.  What are my options to do this in Drupal 8?  Until this point I've been using JS to get the job done.

You can create a module, hook on hook_form_alter and add a #prefix to the first input field.

More simple: Create a block with your paragraphs and switch it on for region "(main) content" on the contact page (no programming needed).


During migration D6->D7 I get an error message "Integrity constraint violation" I use Migrate and Migrate_D2D in my process of migrating from D6 into D7 and I get this message for each an every node when using "MigrateFileUri":

    SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry 'public://instrument/instrumentbilder/63379742-s_1.jpg' for key 'uri': INSERT INTO {file_managed} (uid, filename, uri … and so on…

The strange thing is that on another computer with the same development environment (WAMP) most of the nodes are imported without problem with exactly the same code. Something must be different though… Some mysql setting in WAMP maybe?

I have searched for the "duplicate files" in the table "file_managed" and I can confirm that these files are not present in that table. So the duplication must happen during the import. For some reason the node must be saved twice?

I should mention that when importing all files in a separate migration and using MigrateFileFid as file class, there is no problem. The thing is that I need to use urlencode to clean file names and also I want to decide where different files from different node types are to be saved (different destination_dir for different file types), and as far as I understand those options are not available with MigrateFilFid.

The error message indicates that your underlying database is having a problem. It looks like you've tried the migration multiple times, and that parts of it were successful previously. What the error message is stating is that you are attempting to insert duplicate records into the database, or at least duplicate keys for an existing record. You need to reset/empty the NEW database prior to running migrate and migrate_d2d to remove the problem.


In a taxonomy view, enabling aggregation causes HTML tags in description to be output I created a view of taxonomy terms and turned on aggregation for the view.
My view shows fields, including the description.
However, when I turn on aggregation, HTML tags are output like this:
**Term name: Addition**

Learn about addition.

When I turn off aggregation, the HTML tags disappear.
Is this a bug in Views?

This is unintuitive behavior, but it is Views functioning as designed.
To get the HTML tags to render properly, you need to choose Aggregation settings for the taxonomy description and check the box Format under Group columns (additional).


white-space and minimum length validation in custom search I'm using custom search for my website. Now I wan't to validate user input before search like validate white-spaces (just enter space in search box and you'll find all things goes wrong).

For minimum length validation drupal take cares for minimum 3 character, but if you enter less then 3 characters and press search button search results page appears and then it shows an error that you need to enter keyword with 3 characters or more.

I don't want to go on search results page until all validation criteria passes. In this case I want just red border on search box (this is happen when no text inserted in the search box and you press search button).

How can I validate white-space, minimum search keyword length and restrict user on same page until all validation criteria passes in custom search module?

You can use hook_form_alter(&$form, &$form_state, $form_id) and extend your validation process by adding $form['#validate'][] = 'custom_validation()'


Upgrade Devel module and disable Kint When upgrading from Devel 8.x-2.x to Devel 8.x-4.x in a composer based build, how do I handle the Kint module being removed per Remove Kint module and create a kint dumper plugin in devel?
The service container can't be created because the Kint class is missing. I'll add the class path to Kint when I blow up the build again. :) Thank you.

Since Devel 4 you have to add Kint youself:
composer require drupal/devel kint-php/kint

You can read through this epic issue to learn more: Unknown "kint" function. in Twig\ExpressionParser.

Also important to read the release notes. On all 4.0.0+ releases the following is written. You have to do this before upgrading:

If you have Kint module enabled, please run these commands before
upgrading:

drush pm:uninstall kint or uninstall Kint using the Drupal UI
composer require kint-php/kint

To fix any Kint-missing-module-error, simply downgrade Devel composer require 'drupal/devel:^2.1', uninstall Kint drush pmu kint and then upgrade again composer require drupal/devel kint-php/kint.


Get paragraph id in field template I have a paragraph template where I print a field, for instance :

{{ content.field_products }}

In this template, I can get the paragraph id with :

paragraph.id()

I need to pass this paragraph id in the field template. What is the cleaner and simple way to do this ?
I found a solution like this :

{{ content.field_products|merge({666:paragraph.id()}) }}

and then I get the value in field template like this :

{% set paragraphId = items[items|length-1].content %}

But this is dirty and generate a warning "Message d'erreurUser error: "4" is an invalid render array key in Drupal\Core\Render\Element::children() (line 99 of core/lib/Drupal/Core/Render/Element.php)." that I can understand giving that it's a dirty hack and drupal try to render my "666" array.

I'm probably gonna get the array with "666" key I added in a preprocess_field(), create a new variable for the field template et delete this diabolic hack from $variables to remove the warning due to a tentative to render this fake array, but I guess there is a better way to do ? I want simply to pass a variable from a template to its child...

thanks !

The clean solution is template preprocessing: In yourtheme.theme create something like

function yourtheme_preprocess_field(&$variables, $hook) {
  $element = $variables['element'];
  $parentEntity = $element['#object'];
  //might be useful for if-clause: $variables['field_name'] and $variables['field_type']
  if ($parentEntity && $parentEntity->getEntityTypeId() == 'paragraph' ) {
    //whatever logic you need goes here, e.g. something like
    //$variables['attributes']['data-from-parent-paragraph'] = $parentEntity->getYourStuff();
  }
}


Hook menu url giving access denied for post method but working for get method I defined a custom url using hook_menu and a custom delivery callback that returns json output.

I wanted the url to work on the post method but it is giving access denied for requests done using the post method but it is working without issues for get method.

How do I debug and see why post methods are being denied access?

/**
 * @file
 * Implements menu functions for returning json output.
 */

/**
 * Implements hook_menu().
 */
function mymodule_menu() {
  $items['api/json/select/programs'] = array(
    'access callback' => TRUE,
    'access arguments' => array('access content'),
    'page callback' => 'mymodule_api_return_aid_program',
    'delivery callback' => 'mymodule_api_json_output_wrapper',
    'type' => MENU_CALLBACK,
    'access callback' => TRUE,
  );
 return $items;
}

/**
 * Custom page callback function - Retuns the uid of the user on passing
 * valid username and passowrd returns error otherwise
 *
 * @return $uid
 *   Uid of the user on success, NULL if other wise
 *
 * @return $status
 *   success of the user on success, failure if otherwise
 */
function mymodule_api_return_aid_program() {
  try {

    // Fetching the primary parameters
    //product code
    $product = $_POST['product'];
    //country code
    $country = $_POST['country'];
    // language code
    $language = $_POST['language'];

    // age
    //citizenship
    // veteran_status
    $values = _find_product_specific_to_country($product, $country);

    return array('message' => array('nodes' => $values));
  }
  catch(Exception$e) {
    return array('status' => FALSE, 'message' => $e);
    watchdog('Aid API ERROR', $e);
  }
}

/**
 * Custom delivery callback function
 *
 * @param $var
 *   The argument to the delivery callback function
 *
 * @return array
 *   Contains json encoded format of $var on succes,
 */
function mymodule_api_json_output_wrapper($var) {
  // If the access callback is FALSE
  // it will pass MENU ACCESS DENIED to the
  // delivery callback function
    //return drupal_json_output($var);
  if ($var == MENU_ACCESS_DENIED) {

    return drupal_json_output(array('status' => FALSE, 'message' => 'Invalid Token. Access Denied'));
  }
  else {
    return drupal_json_output($var);
  }
}
e

your code works for me:

Try to move watchdog before return if there is any exception, will log into your report log.
Change your function to like this:

function mymodule_api_return_aid_program() {
  try {
    // Fetching the primary parameters
    //product code
    $product = $_POST['product'];
    //country code
    $country = $_POST['country'];
    // language code
    $language = $_POST['language'];
    // age
    //citizenship
    // veteran_status
    $values = _find_product_specific_to_country($product, $country);
    return array('message' => array('nodes' => $values));
  } catch (Exception $e) {
    watchdog('mymodule', 'Aid API ERROR ' . $e->getMessage(), array(), WATCHDOG_NOTICE, NULL);
    return array('status' => FALSE, 'message' => $e->getMessage());
  }
}

Update: debug
Getting access denied maybe another module add/alter your menu and add another access arguments then access content so in your callback function print you menu object and see something like :

  $menu_item = menu_get_item('api/json/select/programs');
  // print the menu array
  print_r($menu_item);
  // Print access arguments
  print_r($menu_item['access_arguments']);
  // Print access callback
  print_r($menu_item['access_callback']);


Deleting field collection items There is a content type called library which has a field collection type as a field and  unlimited number of this field is allowed. I used Devel module to generate 200 nodes of library, so more than 1000 field collection items were generated. after deleting the nodes from /admin/content the field collection items were not deleted. How do I can delete these field collection items?

After a few search I found this code

for($i = 1 ; $i <= 700 ; $i++)
    entity_delete_multiple('field_collection_item', $i);

but it deleted nothing.I also found a few other codes on Drupal Stackexchange but none of them worked.

Thanks

You could delete the field collection records from there – either through custom Drupal code, or through direct database access if you have that.

Since you have devel enabled and you are generating content, I'm assuming you're not working on a production site, but it's worth saying that deleting records from the database is a risky proposition.

I'm also assuming that you want to delete all of the field collection data for this field collection and not cherry pick just the content that was generated by devel.

You didn't mention what your field collection or its fields were named, but let's say that you have a field collection with the machine-name testcollection and in that collection you have two fields with machine-names collectionfield and collectionfield2.

The data for these will be stored in several tables. In my example, collectionfield1 and collectionfield2 are text fields. Therefore the data will be stored like so:

{field_data_field_testcollection}        // the field collection
{field_revision_field_testcollection}    // the field collection (revisions)
{field_data_field_collectionfield}       // field attached to "testcollection"
{field_data_field_collectionfield2}      // field2 attached to "testcollection"
{field_revision_field_collectionfield}   // revisions
{field_revision_field_collectionfield2}  // revisions

You could remove the fieldcollection content by running the following queries:

DELETE FROM field_data_field_collectionfield WHERE bundle = 'field_testcollection';

DELETE FROM field_data_field_collectionfield2 WHERE bundle = 'field_testcollection';

DELETE FROM field_revision_field_collectionfield WHERE bundle = 'field_testcollection';

DELETE FROM field_revision_field_collectionfield2 WHERE bundle = 'field_testcollection';

If you have data in the testcollection field even after deleting the generated nodes, you should delete that too:

DELETE FROM field_data_field_testcollection;

DELETE FROM field_revision_field_testcollection;


How can I access block field values in mytheme_preprocess_block? My fundamental question is this: in Drupal 8 how can I access block field values in mytheme_preprocess_block.

I am trying to achieve something like https://www.drupal.org/project/block_class_styles in Drupal 8.

So far I have created the block field, and extracted the raw field value in twig (and then add classes or conditional statements) by doing something like:

{{ content.field_layout_style[0]['#markup']|escape }}

This looks really bad, I would rather access this field value in mytheme_preprocess_block, and then pass it to twig, and/or access it in  mytheme_theme_suggestions_block_alter and make separate template suggestions based on it.

Help very much appreciated.

Here is a code snippet that we use to create block template suggestions based on the block content type (bundle), doing something similar based on a field should be fairly easy (...->yourfield->value):

/**
 * Implements hook_theme_suggestions_HOOK_alter() for block templates.
 */
function ourtheme_theme_suggestions_block_alter(array &$suggestions, array $variables) {
  if (isset($variables['elements']['content']['#block_content'])) {
    $suggestions[] = 'block__' . $variables['elements']['content']['#block_content']->bundle();
    $suggestions[] = 'block__' . $variables['elements']['content']['#block_content']->bundle() . '__' . $variables['elements']['content']['#view_mode'];
  }
}


Limit menu items available as possible parents on node creation As I create a node I want to assign i to a menu item parent. I know that I can limit it to what menu(s) are available on:

  /admin/structure/types/manage/my_type

But it would narrow it down to "only some of the menu items". For instance if I have a menu like this:

  Main menu

  Home (page)
  Service type A (page)
  Service type B (page)
  Service type C (page)
  About us (page)
  Contact us (page)

If I then have content type "Service", I don't want the editor to by mistake place the new node under About us. They should only be able to select "Service type A" (or B or C).

I would be nice if I just missed the module that does this trick.

For Drupal 6 there is http://drupal.org/project/node_menu_parent. A Drupal 7 version exists only as attachment in an issue: http://drupal.org/node/1138946
You may consider http://drupal.org/project/menu_position which sets the active menu item when viewing the page based on certain rules.


Global $pager_total_items replacment I updated a website to Drupal 8.9.6 version. I saw that the global variable $pager_total_items was used, but is deprecated since D8.8.0.
So, I'm looking for an alternative to retrieve the total items of the pager.
This was used on a Search API page.
The old code looks like this :
$variables['count_results']     = empty($GLOBALS['pager_total_items']) ? 0 : $GLOBALS['pager_total_items'][0];

And now, looking this change record : https://www.drupal.org/node/2779457 I try to replace this like this :
/** @var \Drupal\Core\Pager\PagerManager $pagerManager */
$pagerManager = \Drupal::service('pager.manager');
dpm($pagerManager->getPager());

This renders nothing in the dpm(), so no Pager was found. It appears that Search API doesn't use a Pager...

This works for me:
$pager = \Drupal::service('pager.manager')->getPager();
$count_results = $pager->getTotalItems();


What module do I turn off to hide or remove the voting widget in Drupal Commons? Our client wants this voting widget turned off? At worst, I could hide with CSS but I'd like to turn this off. What module produces this? Should I remove/hide a field from the content type?

Nevermind. I found it was the Rate module.


How to display language switcher block as buttons, instead of simple links? the language switch block looks like this:

I would like to display it as bootstrap buttons or whatever else is possible. At least not in plain links.

<button type="button" class="btn btn-primary">Primary</button>

Now in my D8 core, I found the PHP file for the language switcher, but I don't see where i can put my HTML code.

/**
 * Provides a 'Language switcher' block.
 *
 * @Block(
 *   id = "language_block",
 *   admin_label = @Translation("Language switcher"),
 *   category = @Translation("System"),
 *   deriver = "Drupal\language\Plugin\Derivative\LanguageBlock"
 * )
 */
class LanguageBlock extends BlockBase implements ContainerFactoryPluginInterface {

  /**
   * The language manager.
   *
   * @var \Drupal\Core\Language\LanguageManagerInterface
   */
  protected $languageManager;

  /**
   * The path matcher.
   *
   * @var \Drupal\Core\Path\PathMatcherInterface
   */
  protected $pathMatcher;

  /**
   * Constructs an LanguageBlock object.
   *
   * @param array $configuration
   *   A configuration array containing information about the plugin instance.
   * @param string $plugin_id
   *   The plugin_id for the plugin instance.
   * @param mixed $plugin_definition
   *   The plugin implementation definition.
   * @param \Drupal\Core\Language\LanguageManagerInterface $language_manager
   *   The language manager.
   * @param \Drupal\Core\Path\PathMatcherInterface $path_matcher
   *   The path matcher.
   */
  public function __construct(array $configuration, $plugin_id, $plugin_definition, LanguageManagerInterface $language_manager, PathMatcherInterface $path_matcher) {
    parent::__construct($configuration, $plugin_id, $plugin_definition);
    $this->languageManager = $language_manager;
    $this->pathMatcher = $path_matcher;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
    return new static(
      $configuration,
      $plugin_id,
      $plugin_definition,
      $container->get('language_manager'),
      $container->get('path.matcher')
    );
  }

  /**
   * {@inheritdoc}
   */
  protected function blockAccess(AccountInterface $account) {
    $access = $this->languageManager->isMultilingual() ? AccessResult::allowed() : AccessResult::forbidden();
    return $access->addCacheTags(['config:configurable_language_list']);
  }

  /**
   * {@inheritdoc}
   */
  public function build() {
    $build = array();
    $route_name = $this->pathMatcher->isFrontPage() ? '<front>' : '<current>';
    $type = $this->getDerivativeId();
    $links = $this->languageManager->getLanguageSwitchLinks($type, Url::fromRoute($route_name));

    if (isset($links->links)) {
      $build = array(
        '#theme' => 'links__language_block',
        '#links' => $links->links,
        '#attributes' => array(
          'class' => array(
            "language-switcher-{$links->method_id}",
          ),
        ),
        '#set_active_class' => TRUE,
      );
    }
    return $build;
  }

  /**
   * {@inheritdoc}
   *
   * @todo Make cacheable in https://www.drupal.org/node/2232375.
   */
  public function getCacheMaxAge() {
    return 0;
  }

}

First choice
If you wants some design related change you can easily achieve using CSS.

Second choice
Enable twig.config: debug: true

See some template file where you can made changes.

  FILE NAME SUGGESTIONS:
  links--language-block.html.twig
  links--language-block.html.twig
  links.html.twig

Changing markup of the language switcher

Trird choice
Alter _language_switch_links_alter.
How do I alter a language item link?


How to override markup in my .theme file? Below is markup from SearchController.php file. I want to change the "Search results" from my search page and also markup.

File : \core\modules\search\src\Controller\SearchController.php

if (count($results)) {
  $build['search_results_title'] = array(
    '#markup' => '<h2>' . $this->t('Search results') . '</h2>',
  );
}

I am afraid there is no way to fix this markup in theme file. In case you simply need to change spelling I suggest using string overrides as it is described in settings.php file.

$settings['locale_custom_strings_en'][''] = [
  'Search results' => 'New text',
];


How do I uninstall and remove Drupal Console from my project? 1 year ago, I installed the Drupal Console module on my site.
This module seems to be completely abandoned, so I'm asking my question here.
https://www.drupal.org/project/console
I had installed this module with Composer and in my composer.json file I have this line :
"drupal/console": "~1.0"

In drupal /admin/modules I don't see any module with the name Console. How to remove this module ? Is it normal that there is nothing in Drupal ?

Drupal Console is not a Drupal module, is a shell for Drupal that is installed as a Composer package. This means it is not installed in Drupal so you don't have to uninstall it.
To remove it simply use composer and update your dependencies:
composer remove drupal/console
composer install

Update
You may also need to remove the Drupal Console Launcher if you have installed it. Drupal Console Launcher is an executable usually installed in your PATH that allows running Drupal Console without writing the complete path.
This process depends on the method used to install it. If you followed standard installation process just remove the launcher deleting it (Keep in mind that Drupal Console is named drupal):
rm /usr/local/bin/drupal

You probably need to be root to do it.
If the launcher is not there try to locate it using whereis:
$ whereis drupal
drupal: /usr/bin/drupal

Once you locate the file just remove it.


Top article image not showing when I share content with Facebook or Google Plus So I inspected the image element and everything looks fine compared to other sites code. But when I share an article from my blog nothing shows in the image section. Interesting enough if I share the same article on Linkedin the top article image appears like it should. Body images always show if any are present. it's just the top article image with the issue.

Here's an example: http://thepoliticus.com/content/how-well-do-you-know-state-union

Element:

We need to pass the url for the image derivative based on the style we're using.

So - not this:

[my_site]/sites/default/files/my_image.jpg

Rather, this:

[my_site]/sites/default/files/styles/large/public/field/image/my_image.jpg?itok=kB4r6YaD

This image derivative url is not part of the $node object, so we have a bit of wrangling to do. One way is to enable the php filter and use this as the value for facebookpost:field-facebook-picture:

<?php
  if($node->field_image) {
    if(array_key_exists(0, $node->field_image['und'])) {
      $fid = $node->field_image['und'][0]['fid'];
      $result = db_select('file_managed', 'fm')
        ->fields('fm', array('uri'))
        ->condition('fm.fid', $fid,'=')
        ->execute()
        ->fetchAssoc();
      $path = $result['uri'];
      $style_name = 'your_style_name';
      print (image_style_url($style_name, $path));
    }
  }
?>

I used similar logic in a custom token instead of using php evaluation for the value of facebookpost:field-facebook-picture.


In Ubercart Which Hook is reponsible for adding product to the cart page(On clicking add-cart-button)? In ubercart,While buyer sees a product and clicks on add-to-cart button for buying that product, i want to know which action is responsible for that product being added in to the cart?

I want to edit the sell price, so that only this question.
Already tried this hook, but it was not printing anything,

    mymodulename_uc_add_to_cart($nid, $qty, $data) {
    print "<pre>";print_r($data);print "</pre>";exit;

    if ($qty > 1) {
        $result[] = array(
                'success' => FALSE,
                'message' => t('Sorry, you can only add one of those at a time.'),
        );
    }
    return $result;
}

Which of these hooks

hook_uc_add_to_cart
hook_uc_add_to_cart_data
hook_uc_cart_checkout_start
hook_uc_cart_display
hook_uc_cart_item_delete
hook_uc_cart_item_insert
hook_uc_cart_item_presave
hook_uc_cart_item_update
hook_uc_cart_pane
hook_uc_cart_pane_alter
hook_uc_checkout_complete
hook_uc_checkout_pane
hook_uc_checkout_pane_alter
hook_uc_update_cart_item
uc_checkout_pane_callback

is responsible for adding quantity and price to cart in the cart page.Or is there any other hook which is doing it ?

Any ideas? Thanks in advance

If you want to alter the cart item, then you can use hook_uc_cart_alter of ubercart.

This hook is not in documentation of ubercart 7 but its still working for Ubercart 7.

  This is called every time the cart is rebuild (e.g. when products are
  added), so it's a good place to alter the cart item.

I have checked uc_coupon module and hook hook_uc_cart_alter is implemented into that module. So, you can try this hook.

Edit:
Code snippets to modify the price of item

/**
 * Implements uc_cart_alter.
 */
function mymodule_uc_cart_alter(&$items ) {

  foreach ($items as $index => $item) {

   //you can add condition for your bid product

    $items[$index]->price = 100;
  }
}

For reference:

http://www.ubercart.org/docs/api/hook_uc_cart_alter


How do I clear or delete a queue? I scheduled a big queue with VBO, but I changed my mind. How can I delete it? I don't seem to find any UI/interface to manage queues. Do I have to delete it in the database?

drush has no option to clear queues, there is just drush queue-list and drush queue-run. However, you can use it to delete the corresponding queue records from the database:

Use drush queue-list to find out the name of the queue you want to clear. In my case, it is message_subscribe.
Use a command like this, replacing with your queue's name accordingly:

drush sqlq "DELETE FROM queue WHERE name='message_subscribe'"

Confirm with drush queue-list that the queue in question now has zero items in it.

This solution is quite similar to @batigolix's, just that it clears a specific queue instead of all queues.

Careful. Like @batigolix said, take care not to lose data! This solution might not be for a production environment …


How do I avoid API calls are cached? I'm using Drupal 8 in headless mode with Angular 8 as my client, but Drupal caches the API calls. For example, I have an end point which suppose to give items in random order, but this doesn't happen. I only get cache items in a particular order.
How can I overcome this? I have tried to disable the cache modules, but I still get the same behavior.

There are two level of caching in Drupal.

1.) Dynamic Page Cache

You have to provide the correct cache metadata on the json response.

For example use the cache properties from a config or content entity

$response->addCacheableDependency($entitiy);

or build a cacheable metadata object and add this to the response:

$build = [
  '#cache' => [
    'contexts' => ['url.query_args'],
    'tags' => ['node:1', 'node_list'],
    'max-age' => 300,
  ],
];
$cache_metadata = \Drupal\Core\Cache\CacheableMetadata::createFromRenderArray($build);
$response->addCacheableDependency($cache_metadata);

You can use this in a custom controller or implement this in an event subscriber to alter responses from other modules (core or contrib).

2.) Internal Page Cache

The module Internal Page Cache caches all responses for anonymous requests regardless of the cache metadata. You can uninstall this module to disable this cache.

Alternative solution

On the client side append a different query string on every request to get a fresh response:

node/123?_format=json&time=123456789

This will disable the Internal Page Cache and parts of the Dynamic Page Cache.

Reference: https://www.drupal.org/docs/8/core/modules/rest/javascript-and-drupal-8-restful-web-services


Enroll user on course module error due to permissions I want that a role called "Profesor" can enroll users on a course created using the course module, using the course-enrollments/search-add view but I'm getting the following error:

Type: views bulk operation
User: profesor1
Message: Skipped Enroll user on user alumno2 due to insufficient permissions.

Here is my permissions configuration:

Administrator can enroll users, any help?

EDIT:

The course permissions are configured as follows:

I haven't used the course module in quite a while but aren't there other permissions specific to the module itself?


Which webform hook and how use to set programmatically webform target email? First part as in title and how to detect different webforms?

Ex. function name - hook_webform_submission_actions

Replace 'webform' with form id?

If you just want to customize the target email, webform do this quite easily.
Go to node/123/webform/emails (where 123 is you nid) and there you can configure the recipients.
The option "component value" allows you for example to set the email regarding a select list. Configure a select list for the subject, put these values in the option textarea:

contact@example.com|General inquiries
marketing@example.com|Marketing

Then when the user will use webform the email will be sent to the direction chosen in the subject list.

If you want something more advanced, have a look at my previous answer in "pass cck email value to webform block". This will help you to detect different webform (using hook_form_alter.


My views slideshow doesn't work when the display is called from page.tpl.php I am working on Drupal 6.  I have a view with a display block.  My view contains an animation of 6 images with slideshow as Style.

If I put the block in the content the view works fine, the images changes.  However, when I call the same block from template the images not change, I can see only one image.   What is my error?

my code is:

<?php
$block = module_invoke('views', 'block', 'view', 'images_home-block_1');
print $block['content'];
?>

Also, I tried this code:

<?php
print views_embed_view('images_home', $display_id = 'block_1');
?>

Thanks in advance.

you can try views_embed_view to call a views block programatically.

views_embed_view

<?php
print views_embed_view($view_name, $display_id, $argument); // with single argument
print views_embed_view($view_name, $display_id, array($arg1,$arg2,$arg3)); // with multiple arguments
?>


Error: Call to undefined function twig_render_template() when accessing website Error when accessing drupal 8.

The website encountered an unexpected error. Please try again later.
Error: Call to undefined function twig_render_template() in Drupal\Core\Theme\ThemeManager->render() (line 384 of core/lib/Drupal/Core/Theme/ThemeManager.php).
Drupal\Core\Theme\ThemeManager->render('views_view', Array) (Line: 437)
Drupal\Core\Render\Renderer->doRender(Array) (Line: 450)
Drupal\Core\Render\Renderer->doRender(Array, ) (Line: 195)
Drupal\Core\Render\Renderer->render(Array, ) (Line: 226)
Drupal\Core\Render\MainContent\HtmlRenderer->Drupal\Core\Render\MainContent\{closure}() (Line: 582)
Drupal\Core\Render\Renderer->executeInRenderContext(Object, Object) (Line: 227)
Drupal\Core\Render\MainContent\HtmlRenderer->prepare(Array, Object, Object) (Line: 117)
Drupal\Core\Render\MainContent\HtmlRenderer->renderResponse(Array, Object, Object) (Line: 90)
Drupal\Core\EventSubscriber\MainContentViewSubscriber->onViewRenderArray(Object, 'kernel.view', Object) (Line: 108)
Drupal\Component\EventDispatcher\ContainerAwareEventDispatcher->dispatch('kernel.view', Object) (Line: 158)
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: 99)
Drupal\page_cache\StackMiddleware\PageCache->pass(Object, 1, 1) (Line: 78)
Drupal\page_cache\StackMiddleware\PageCache->handle(Object, 1, 1) (Line: 47)
Drupal\Core\StackMiddleware\ReverseProxyMiddleware->handle(Object, 1, 1) (Line: 50)
Drupal\Core\StackMiddleware\NegotiationMiddleware->handle(Object, 1, 1) (Line: 23)
Stack\StackedHttpKernel->handle(Object, 1, 1) (Line: 657)
Drupal\Core\DrupalKernel->handle(Object) (Line: 19)

Searched for twig_render_template function found in core/themes/engines/twig/twig.engine file.
I new to drupal 8 so I don't know what I did wrong? It just broke.

Here is the line this error occurs in ThemeManager.php:

$output = $render_function($template_file, $variables);

and here is $render_function defined also in ThemeManager.php:

$render_function = 'twig_render_template';
      $extension = '.html.twig';

      // The theme engine may use a different extension and a different
      // renderer.
      $theme_engine = $active_theme->getEngine();
      if (isset($theme_engine)) {
        if ($info['type'] != 'module') {
          if (function_exists($theme_engine . '_render_template')) {
            $render_function = $theme_engine . '_render_template';
          }
          $extension_function = $theme_engine . '_extension';
          if (function_exists($extension_function)) {
            $extension = $extension_function();
          }
        }
      }

Solved! Apparently core has been damaged, restored core everything is back to normal.


How can I have default field values for the node add form as arguments in the URL? I have a path in drupal 6, which allow me to add new content with 2 fields completed. For example, path node/add/my_content_type/4/6 means that I am on page /node/add/my_content_type, and first field has value "Philip" and second field has value "Oleg". Those names are in database, because user put them in in another content type.
I try to do the same in Drupal 8, but I cannot put arguments after /mycontent_type/. So right now, on the /node/add/my_content_type I see a form with fields, I can select names in input select, but nothing shows when I put more arguments in url.
I will give an example:
I have a module with students and school trip. On custom content "students", I add students names in text input. Those names are saved in database.
Let's say, that my second content type is "trip".
I have a function, which allow me to add a trip, when students names are given. I can simply click add content 'trip' and select names in select fields, but I want to make it more simple and redirect to page /node/add/trip/4/6 where 4 is id of "Philip" and 6 is id of "Oleg". In this way I have a form with to fields already completed. It is posible in drupal 6, but no in drupal 8. Have can i do that?
I think that one of the problem could be the fact, that Drupal 8 require field "Title". So I have to modify url a little bit /node/add/trip/??TITLE??/4/6.
I need exactly this -> https://www.drupal.org/forum/support/module-development-and-code-questions/2020-04-27/webform-field-default-value-from-url
but for custom content :)

I figured it out.
in .module, hook_form_after()
$value = \Drupal::request()->query->get('q');
$value = Html::escape($value);
$form['student']['widget']['#default_value'] = [0 => $value];

with url /node/add/trip?q=6, where 6 is id of student Oleg


Civicrm Membership Type in webforms I am using the webform_civicrm module. It is not having the option to link the membership type to webforms.
How can I link membership type to webforms?

Support for memberships was just added in version 4 of Webform-CiviCRM integration. If you upgrade to that version then membership types will become available.


Is there any module for Restful API in drupal 7 with commerce I am working in a ecommerce website in drupal 7 by using commerce module, also developing for mobile (android/ios) application for the same project.

So that I want to send data's for mobile application, for that I am searching API integration module.

Anybody found any module or have any relevant idea?

Both Drupal and Drupal Commerce support API integrations with mobile apps.

Look into the following:

Start with Services for basic web service support in Drupal.
Throw Commerce Services on top of it to expose Drupal Commerce entities.

There are a couple of good articles by Tyler Frankenstein:

Drupal Services Example
Build a Mobile App to Sell Products with Drupal
Sell products with a custom mobile app a Presentation with Scott Hooker (then Commerce Guy) at DrupalCon Austin


Is there a module for limiting CCK select list options per role? I notice we can define a custom php list for options widget in CCK.

Would love to limit allowed values per role?

What would be the easiest way?

Such a solution could replace a lot of other modules, like Workflow etc...

You dont need a module, this is in core.

  $values = array(1|one, 2|two, 3|three);

  global $user;

  // Check to see if $user has the administrator role.
  if (in_array('administrator', array_values($user->roles))) {
    $values[] = 'special|special';
  }
  return $values;


I need an AJAX cart like these below: Is there a project or something that already integrated a cart similar to:

http://interface.eyecon.ro/demos/cart.html

or an integration of jcart:

http://conceptlogic.com/jcart/

I tried ubercart but despite the fact is an overkill it doesn't work like these.

Well, you didn't write the required version. I found a module Ecwid shopping cart. This module has drag and drop features for items and ajax support everywhere.

For more information, have a look at Ecwid Demo.


Contextual filter in Views for taxonomy browsing I'm having a problem with setting filter value from the URL. What I want to do is to list all terms in a taxonomy node, so I list all terms whose parent ID equals what's provided by URL. I have the relation set, I have the contextual filter set, but unfortunately when I enter %1 as the parent term ID value to be matched by the filter, it's treated literally and returns nothing. That's because no term has the ID of '%1'. However, when I expose the filter and type in the term ID, works as expected.

How do I use the placeholders in the filter definition?

Since that moment I have messed with my views to a fubar state. But looks like I pinpont the rule of thumb that I haven't heard anywhere: when you set up a context filter, eg. for "Content: nid", you don't add it to the regular filter list on the left hand side. And you don't have to bother with %-style placeholders.
At any rate, thanks JoeS for your readiness to help. I bet you will have a bunch of chances to help me out, as I seem to attract all kind of Drupal surprises ;-)


Bulk enable/disable modules I have just begun development on a Drupal 7 site in a team of three and I am trying to determine the best practice for versioning. This is causing me a bit of a headache because much of the work on a Drupal site is made in the database as well as the code.

I have installed the 'Features' module which allows for exporting views, content types, rules, ect. into an XML file which can them be included in the checkin, but we need to ensure that whenever we add a new module it is enabled on our machines before a feature is imported in case there are dependency issues.

When modules are added to our local machines, both code is added and the module is enabled in the database, so checking in the code to our git repo takes care of half of the problem, but we are left with the possibility of crashing each other's site if we fail to contact each team member notifying them of the manual changes to be made.

I have searched but I have failed to find a module or any other solution to this problem. Ideally there would exist a module that would create an XML file of which modules are enabled on one machine, then after checkin a second machine would be able to read this file and ensure that the two sites were in sync.

Has anyone found an elegant solution to this problem?

This is how we are working:

Keep as much as possible in code. Features strongarm and other modules are helpfull here. Often we figure out the configuration variables of the modules and put them into settings.php by hand.
Things like enabled modules are left to the DB. We maintain a central copy of our db in GIT. If someone adds a new module, he is responsible for taking this DB, adding the module and pushing a new copy to git together with the new module code. The backup & migrate module is very handy here.

An other alternative would be to develope against a single central DB. The disadvantage of this is that you will likely face situations where one developer trashes the DB and therfore the work of his colegues as well. You could set up a cron job taking a DB dumps at regular times to make sure you don't loose to much in such a situation.


What is the proper RewriteBase setting for my staged server? I'm having issues with Clean-URLs not working on my staged server, possibly stemming from the fact that the installation is pulled down from a Git repo, for staging.

I suppose the .htaccess file is configured properly for my local installation, but not for the staged one which has a different file path. (http://drupal.org/node/1018346)

I have my drupal installation on my staged server (which is having the clean URLs problem) in this location:

/home/user/drupal_dev/www

And in my web server's /var directory, I set a symlink pointing to that www directory in my home. That way I don't have to worry about copying files into a root directory that requires sudo.

Can you offer suggestions on what my .htaccess file should look like, in regards to RewriteBase?

Unless you are running in a subcdirectory (eg, http://www.whatever.com/sub/directory/that/has/drupal/), you should use

RewriteBase /

RewriteBase is really used when you are doing rewrites from a directory that doesn't match your DocumentRoot.


Easiest way to expose existing data in secondary database as entities? Given a "node-like" database table in an "external" or "secondary" database, what's the easiest way to expose them as entities?

Documentation for the entity module makes it seem easy for data stored in the local database, but I'm not sure how that can be translated to another db.

Some googling has revealed that the easiest solution is

Declare a new entity
Create a new Controller class for it that knows how/where to apply data operations.
Declare all your metadata as properties as opposed to fields.

I hope I'll be able to expand on this answer once I actually try it out. :)


How to query external database for Count How do I query the below SQL query to an external database table from Drupal 8 custom module,

Select Count(requestID) FROM requestDB.request where request.dateCreated >= DATE_SUB(CURRENT_DATE, INTERVAL 30 DAY) and ek_borrowerID = 111;

I have configured the settings.php already. Below is the query I tried to build, but it does not work

Database::setActiveConnection('requestDB');
$db = Database::getConnection();
$db->select('request')
    ->fields('request', array('Count(requestID)'))
    ->condition('dateCreated','DATE_SUB(CURRENT_DATE, INTERVAL 30 DAY)', '>=')
    ->condition('ek_borrowerID','111')
    ->execute();
Database::setActiveConnection();

You need to use ->addExpression() instead of ->fields()


Theming Views Display Can I use Views templates to theme the row style output of a specific display in my view so it doesn't affect the other displays I created? If so, how?

Try this:

on the view edit screen click on the display you want to theme
click on the "Advanced" tab so that it slides down
in the "Others" section click on the "Theme: Information" link
in the "Row style output:" section you'll see the template file names you can use, you are currently using the one that is bold, the last name is the most specific, i.e. something like views-view-fields--VIEWNAME--DISPLAYNAME.tpl.php

simply copy views-view-fields.tpl.php from the "theme" directory of the Views module to the directory of your theme, rename the file and modify as you wish (and clear the cache)


Is there a way to know the node being viewed? I have a context where I'm placing a block onto a wiki page. Is there anyway for the block to know the node id of the wiki page?

I'd like to write some code in the block's views-view--block--field.tpl.php template file to display something only to the wiki page's owner. With the block being placed on the wiki's page via context, the block needs what node(wiki) page it is displaying and who the node's owner is.

Wow - I just got a reply back from Acquia support that answers the issue. menu_get_object() seems to be one of those magically functions I never knew about. Neat.

global $user;
$node = menu_get_object();

if ($node && $user) {

  print '
node uid = ' . $node->uid;
  print '
user uid = ' . $user->uid;

  if ($node->uid == $user->uid) {
    print t('
You are the author of the current node.');
  }

}


How to set a contextual filter based on an entity reference field I am currently working on a radio website.
Here is the basic information to keep it simple.

I have two content types: [emission] (programme) and [podcast].
The [emision] content is merely a general presentation with the broadcasting time. The [podcast] content has a field [field_emission] in which I can make a reference to the [program] you can hear (it works with entity reference).

I have a View displaying all podcasts.
I have another display of that View, a block, shown only on the [emission] pages.
I want to restrict to results of the view to all [podcast] concerned with the displayed [emission]. How should I set the contextual filters.
Here is how I tried so far. Up to now, nothing shows up.

On the View you started (Podcast Views) the Contextual filter you need to add is the Entity reference field, not the Nid.

Here are the settings for it:
When the filter value is NOT available:
Provide default value
Content Id from URL
When the filter value IS available or a default is provided (optional)
Specify validation criteria
Validator Content
Emission

Place the block on Emission nodes. The block will take the NID of the Emission node it's on, pass it to the Entity reference contextual filter to match Emission in question, and Views results will be limited to only Podcasts which reference that Emission through the field.

You don't need the Relationship unless you plan on displaying Emission information in this block, which you probably don't.

Another approach would be through the opposite side, through Emission Views, where you list Emission content type, but you don't have to display any Fields concerning Emission. Instead you'll display only the Title field of the Podcast that is referencing that Emission.

You do that by adding the Contextual filter ID (it's not the same field as above, but the settings are are the same).

And you have to add the Relationship for the Entity reference field, but the reverse one (Relate each Content with a field_emission set to the content.)!

Then you add the Title Field, but make it uses the above Relationship. This will make the Title Field show Podcast title, and not Emission title. Set its label to something like "Podcasts referencing this Emission".

Make sure to tick "Hide if empty" under "No results behavior" so nothing is output on Emission pages that have no Podcasts referencing them.

And in the end display that block on Emission pages.


View arguments in entity selection I have a profile type which uses an autocomplete field which references to another profile. As an entity type i selected user and for filtering the results i use an entity selection with views where i choose what view to filter my content. So far so good , but i've seen that i can pass additional arguments to the view. My question is: How could i pass the input from autocomplete to the referenced view ? ( what should i type in the view arguments field to get the input from autocomplete ? )

What you're asking doesn't quite make sense if I understand it correctly.  You see, the view you're choosing when setting up the field is used before your user has even entered anything in the auto-complete field.  So you can't have that be an argument.  The view is generated and used prior to any input.

The view is used simply to determine which set of users are available for the auto-complete field.  It doesn't make sense to generate the view after the user has already entered in a value, because at that point they've already made a selection anyway.

So - I'm wondering, since you're asking about basing that view on user input, if what you're looking for is simply something like the 'auto-complete' functionality which exists with entity and user/node references.  If you select for your field to be Autocomplete, when the user starts typing in a username, a list of related suggestions will automatically appear at the bottom.

Here's an example of a user reference field with autocomplete turned on


Adding a new column to users table: db_drop_field errror I'm trying to add a column to the 'users' table. When I install my module, the column gets created and when I uninstall it gets deleted.

The issue is that after I uninstalled, I run a 'drush cc all' and I receive this error:

  WD php: PDOException: SQLSTATE[42S22]: Column not found: 1054 Unknown[error]
  column 'base.firstname' in 'field list': SELECT base.uid AS uid,
  base.name AS name, base.pass AS pass, base.mail AS mail, base.theme
  AS theme, base.signature AS signature, base.signature_format AS
  signature_format, base.created AS created, base.access AS access,
  base.login AS login, base.status AS status, base.timezone AS
  timezone, base.language AS language, base.picture AS picture,
  base.init AS init, base.data AS data, base.firstname AS firstname
  FROM
  {users} base
  WHERE  (base.uid IN  (:db_condition_placeholder_0)) ; Array
  (
      [:db_condition_placeholder_0] => 0
  )
   in DrupalDefaultEntityController->load() (line 193 of
  /var/www/includes/entity.inc).

Here is my code inside the .install:

function mymodule_schema_alter(&$schema) {
  $schema['users']['fields']['firstname'] = array(
    'type' => 'varchar',
    'length' => 60,
    'not null' => FALSE,
    'default' => '',
    'description' => 'Field added by profile common module',
  );
}

function  mymodule_install() {
  $schema = drupal_get_schema('users');
  db_add_field('users', 'firstname', $schema['fields']['firstname']);
}

function  mymodule_uninstall() {
  db_drop_field('users', 'firstname');
}

Thanks.

There is the difference between hook_schema() and hook_schema_alter(): The first is used to create a database table when a module is installed, but the second is not used to alter an existing database table when a module is installed. hook_schema_alter() is used to alter the values returned from hook_schema() to let other modules know an existing database table (created from a module) has been altered (from another module).

What you need to to is:

Implement hook_schema_alter() to make public the changes you made to a database table created from another module
Make the changes in that database table, in hook_install() or hook_update_N()

The reason you need to alter what returned from hook_schema() is that there are functions that write on the database which use the information returned from hook_schema(), in primis drupal_write_record().

  $schema = drupal_get_schema($table);
  if (empty($schema)) {
    return FALSE;
  }

  $object = (object) $record;
  $fields = array();

  // Go through the schema to determine fields to write.
  foreach ($schema ['fields'] as $field => $info) {
    if ($info ['type'] == 'serial') {
      // Skip serial types if we are updating.
      if (!empty($primary_keys)) {
        continue;
      }
      // Track serial field so we can helpfully populate them after the query.
      // NOTE: Each table should come with one serial field only.
      $serial = $field;
    }

    // …
  }

Without hook_schema_alter(), which is invoked from drupal_get_schema(), such functions would not be able to correctly write on the database tables.


How to display multiple multi-value fields inside one for loop? Here is what I've come up with but it seems I can't do [key] to increment along with the body for loop...

 {% for key, item in content.body if key|first != '#' %}

{{ item }}

  {{ content.field_text.[key] }}

   {{ content.field_image.[key] }}

{% endfor %}

If you use square brackets [] in twig, you don't need a period .

{% for key, item in content.body if key|first != '#' %}

  {{ item }}

  {{ content.field_text[key] }}

  {{ content.field_image[key] }}

{% endfor %}

A better solution for this might be a field collection or a paragraph, because you depend on that the user is keeping the deltas of the fields in sync.


How to allow filtering by only date parts selected by user and make not selected work as "Any"? I am using the Date module and I am creating a view to display news content; I made a exposed filter to search news content by year, month, and day. When I search, I need to select all the date fields.

Is it possible to search entering values for just one of those fields?

How can I remove these validation in search time?

How can I remove this validation from exposed search filters ?
I want to search content
condition should like this:-
Year "OR" Month "OR" Day

condition should not like this:-
Year "AND" Month "AND" Day

It validated, because by default it set to AND operator in your exposed setting. You can do it easily, but I have done it in Drupal 6, I don't have D7 setup. Check the below screenshots. Just select the Method as OR in the exposed filter setting.

Click the setting icon and then select the OR under method.


Possible cause of the one time login link sent via e-mail to be broken? edit: it appears to be a bug, reported here https://www.drupal.org/node/2329723

When I, as the Admin, add a new user and let Drupal notify him via mail, the one-time login link is broken:

http://www.exmaple.com///www.exmaple.com/user/reset/...

Any idea why Drupal would create such a link? There is no module which alters this mail or tokens.

There must be something, Drupal does not create broken links by default. Sadly, we can't debug your site for you. literally are not able to. See here - URL is accessible as [user:one-time-login-url] token, so if nothing overrides default support for this token, it must be OK.
Inspect http://example.com/admin/config/people/account, Password recovery tab. By default it should look like this:

[user:name],
A request to reset the password for your account has been made at [site:name].
You may now log in by clicking this link or copying and pasting it to your browser:
[user:one-time-login-url]
This link can only be used once to log in and will lead you to a page where you can set your password. It expires after one day and nothing will happen if it's not used.
--  [site:name] team

If this token is alone in it's line, just like above, then you know something interferes with tokens. If it's not, then maybe some automatic HTML syntax correction kicked in, and messed up your layout? It is impossible to tell without actually debugging your site.


Commerce 2 - how to get guest user email from custom submit handler? I'm altering "review" form in checkout process and adding custom submit handler. From that handler, if user is registered I can get it's email address as:
$user = \Drupal\user\Entity\User::load(\Drupal::currentUser()->id());
$email = $user->getEmail();

But if I go to checkout as a guess user I can not get email of anonymous user that way - returns null.
How can I get guest user email address? I need a way to get email provided on previous checkout page, no matter if user is registered or not.

Found the way over the cart:
$store = \Drupal::service('commerce_store.current_store')->getStore();
$cart = \Drupal::service('commerce_cart.cart_provider')->getCart('default', $store);
$email = $cart->getEmail();


Can I update directly from 7.7 to 7.12?  Or do I have to do 7.7 to 7.8, 7.8 to 7.9, etc? I just updated my Drupal website from 7.7 to 7.12, but there were a lot of issues when running update.php.
I was wondering if it is possible to update Drupal 7.7 directly to 7.12, or you have to get 7.8, 7.9, 7.10 and 7.11 before you can update to 7.12.

You should be able to go right from 7.7 to 7.12.  The messages from update.php depend on changes to the database schema from version to version made by drupal and other modules, and they are normal.

You may be interested in drush.  It allows you to run updates with the pm-update command and automatically runs update.php for you.  It also saves backups in your home directory.  There is a website, http://drushmake.me/, that allows you to build out sites with drush make if you are using drush version 5.