Botched my site upgrade I tried following the directions drupal provides for upgrading a site, but something went wrong. Now I can't log into the admin page (and the site is in maintenance mode). I'm getting the following errors:

Notice: Undefined index: bluemarine in drupal_theme_initialize() (line 100 of /home1/osuskite/public_html/includes/theme.inc).
Notice: Trying to get property of non-object in _drupal_theme_initialize() (line 145 of /home1/osuskite/public_html/includes/theme.inc).
Notice: Trying to get property of non-object in _theme_load_registry() (line 283 of /home1/osuskite/public_html/includes/theme.inc).
Notice: Undefined index: bluemarine in theme_get_setting() (line 1166 of /home1/osuskite/public_html/includes/theme.inc).
Notice: Undefined index: bluemarine in template_preprocess_maintenance_page() (line 2433 of /home1/osuskite/public_html/includes/theme.inc).
Notice: Trying to get property of non-object in template_preprocess_maintenance_page() (line 2433 of /home1/osuskite/public_html/includes/theme.inc).
Warning: array_keys() [function.array-keys]: The first argument should be an array in template_preprocess_maintenance_page() (line 2436 of /home1/osuskite/public_html/includes/theme.inc).
Warning: Invalid argument supplied for foreach() in template_preprocess_maintenance_page() (line 2436 of /home1/osuskite/public_html/includes/theme.inc).

And then a second error:

Warning: Cannot modify header information - headers already sent by (output started at /home1/osuskite/public_html/includes/common.inc:2567) in drupal_send_headers() (line 1018 of /home1/osuskite/public_html/includes/bootstrap.inc).
PDOException: SQLSTATE[42S02]: Base table or view not found: 1146 Table 'osuskite_drupal.cache_token' doesn't exist: DELETE FROM {cache_token} WHERE (expire <> :db_condition_placeholder_0) AND (expire < :db_condition_placeholder_1) ; Array ( [:db_condition_placeholder_0] => 0 [:db_condition_placeholder_1] => 1316109148 ) in cache_clear_all() (line 169 of /home1/osuskite/public_html/includes/cache.inc).
Notice: Undefined index: bluemarine in template_preprocess_maintenance_page() (line 2433 of /home1/osuskite/public_html/includes/theme.inc).
Notice: Trying to get property of non-object in template_preprocess_maintenance_page() (line 2433 of /home1/osuskite/public_html/includes/theme.inc).
Warning: array_keys() [function.array-keys]: The first argument should be an array in template_preprocess_maintenance_page() (line 2436 of /home1/osuskite/public_html/includes/theme.inc).
Warning: Invalid argument supplied for foreach() in template_preprocess_maintenance_page() (line 2436 of /home1/osuskite/public_html/includes/theme.inc).

From what I could surmise, there error is being caused by Acquia Marina. I have downloaded the latest version and put it into the themes directory, but the error didn't change.

Any help would be appreciated. Googling this issue only pointed me to hundreds of other sites with the error instead of a solution.

EDIT: Truncating the SQL caches did nothing.

Switch to a stock D7 theme - clearing the cache is not enough if there's a bug in your theme as the buggy code is still going to reload.

Either use drush (highly recommended) to change your default theme to another, or...
Use the techniques mentioned here (should apply to D7): http://drupal.org/node/200774 or...
Rollback to your D6 code/database, disable the borked theme, and then retry the upgrade.


Views: displaying a field from a vocabulary based on the name The following seems simple to me but i can't get it done in views:

A taxonomy vocabulary has two relevant fields: Name and Image. In the nodetype associated with this vocabulary i use Name as the linking field (i can not set the field up to directly use the image) but in the node view i want to show Image instead of Name. In my case Panels handles the display of my nodes.
I turned to views and tried two alternatives with a taxonomyterm view and a content pane display:

Add both vocabulary fields and rewrite the output from the Name field to use the Image field. If i put the Image field first i can see a replacement pattern that seems to match the Image field, but the result is crap. I think a real link between the node and the tax-terms is missing;
I added a contextual filter with Taxonomy Term: Name but get stuck because the value is not in the URL. Everything i tried in options like "Provide default value" and "Specify Validation Criteria" fails. Also, using the Argument Input option in Pane Settings, picking Name from the node list under "from context" seems to do nothing.
When i enter a valid Name value in Views Preview it returns the corresponding Image, exactly like i want. But someway that value isn't read when the view is run for real.

Any clues? Thanx in advance!

Kind regards,
Cas

If I understand question aright, you need to use a Relationship in your View.

Under the Advanced section (just below contextual filters) click 'Add' to add a Relationship
Select the field in your node for the relevant term reference, e.g. a field labelled 'Tags' and with a machine name 'field_tags' would appear as Content: Tags (field_tags) in the list that is shown when you select 'Add'
The default configuration should be fine for the use case at hand, so in the next dialog box it should be OK to simply select 'Apply'. (In some cases you do want to tick Require this relationship.)
Go to Add fields and add a new field. Find the image field in your taxonomy. If the taxonomy is called Tags and the field labelled 'Image', it'll look like: Taxonomy term: Image Appears in: taxonomy_term:tags. Select this and click on 'Apply', Then click on 'Add and configure fields'
When you are in the configure dialog you'll see an indication that a relationship is being used. It'll look something like this:

Configure as required and apply. In your fields list it'll look something like this:

What these steps do is say that you want to use the field in the node that contains the taxonomy term to bridge to the fields in the particular taxonomy vocabulary item. Having added the relationship you can now add fields that call upon it. That, if I understand the question, is what is needed here. And, again, if I've understood aright, no need for contextual filters - at least not to get the image from the taxonomy into your view.

These steps apply to Views 7.x-3.5. (In pre 3.5 versions, or perhaps bit further back,  the relationship set up was a bit more complex, but it's now more streamlined.)


How do you disable strict errors for PHP 5.4 & 5.5 in Drupal 7 via the settings.php file? Currently I disabled the error messages via UI under Administration > Developement > Logging & Errors:

But I want to be able to do this via the settings.php file. How can that be done?

And the Drupal way:

Add this line in settings.php

$conf['error_level'] = 0; // 0: None, 1: Errors and warnings, 2: All messages

You can set any persistent variable this way. You can get the variable names simply using Firebug or any browser's developer tool and check the name attribute of the input field in the administration form. Which in you case the Logging & Errors page. If you look at the source code, the radio buttons have the name attribute error_level and each radio button has a value attribute. Simply set this value to the variable in you settings.php using $conf array.

You can also set any variable using variable_set() function in any custom module, in an update script for example.

Or using Drush:

drush vset error_level 0


Include .inc file for my own module I have written my own module for example called: calc
and i have used module_load_include('inc', 'calc', 'form.inc') in my calc.module file,
and placed form.inc file inside my module's directory: calc/form.inc but it doesn't see that file. What am I doing wrong?

I am using Drupal 6.

It should be:

module_load_include('inc', 'calc', 'form');

(The 'inc' in the first argument automagically appends as the extension)


if current_node is in menu, do something in theme.inc I'm trying to check if the current node (of a specific content type) has been added to a menu (using the "Provide a menu link" in the node edit GUI).

if it has, I need to set a variable in .theme.inc, using THEME_preprocess_page.

I've been digging through drupal.org docs and found those two questions find Menu Settings of node, given URL alias (or node ID) and Get menu item of a node seem relevant but not quite right.

To set if the node has menu link you can use menu_ui_get_menu_link_defaults function from menu_ui.module something like:

/**
 * Implements hook_preprocess_HOOK().
 */
function YOUMODULE_preprocess_page(&$vars) {
  /** @var \Drupal\node\Entity\Node $node */
  if ($node = \Drupal::routeMatch()->getParameter('node')) {
    // Get the default menu link.
    $defaults = menu_ui_get_menu_link_defaults($node);
    if ($defaults['id']) {
      // It has a menu
     // set your variable here.
    }
    else {
      // It has no menu link
      // It mean Provide a menu link not checked
    }
  }
  }


Is there any compatibility issue with Amazon Aurora? I'm exploring the possibility of using Aurora as a database backend for a large-ish Drupal 7 site because of the potential performance gains. Before I do that, though, I'd like to know if there are any outstanding issues with this kind of setup.
So far, the only resource I've found are this fixed Drupal.org issue and a number of rather old questions on this site. I'm still a bit concerned because the Aurora FAQ states:

Q: What does "MySQL-compatible" mean?
It means that most of the code, applications, drivers and tools you already use today with your MySQL databases can be used with Aurora with little or no change. The Amazon Aurora database engine is designed to be wire-compatible with MySQL 5.6 using the InnoDB storage engine. Certain MySQL features like the MyISAM storage engine are not available with Amazon Aurora.

(Emphasis mine)
It's the "most" that has me worried, specifically. Are there any pitfalls when using Drupal 7 with Aurora?

We are running a couple of projects on Amazon Aurora  with no issues so far. Our largest project is a D7 project with many contributed modules, and a large amount of data being moved.

We've never noticed any DB related issues aside from normal MySQLisms. It's really transparent to Drupal. We use normal Mysql connection strings and zero core changes.

Aurora is more expensive. A lot more expensive. It only starts at the db.r3.large tier, and works out to a monthly (non upfront rate of 0.190 per hour). So the price difference must be considered.


How to control resource usage of my website? I'm using drupal 6 website and i don't know to check which module or script uses high resource. Below is the graph for my website Resource Usage from my hosting provider. They intimate me to control the usage. Really i don't know how i am going to solve this. And i am in shared hosting.

Any idea ?

Use the Devel module It should show you a list of queries run when
the page is loaded and the time taken to run the query. From there
you can check which query is coming from which module.
You can also try a PHP profiler which gives you a lot of metrics.
Or try disabling your modules one at a time to decide when the load
time gets really high
Another option lies in smarter caching


Hide user pictures from guests and web crawlers I'm using Drupal 7 with Blog and Comments and user pictures enabled. The theme is Bartik.

The user pictures are also used in the Flash game that is embedded in my website, so I can't just turn them off.

I'm looking for a way to hide user avatars from guests and web crawlers.

The background is that I've gotten a bill for EUR 1000,- from Getty Images, because one of the users has supposedly used their picture as avatar. I'm not looking for any lawyer or pseudo-lawyer advices here, just for the way to hide user pictures from web crawlers.

I've tried searching in the theme file for picture and bartik_preprocess, but haven't find any hints yet:

# grep -r bartik_preprocess .
./themes/bartik/template.php:function bartik_preprocess_html(&$variables) {
./themes/bartik/template.php:function bartik_preprocess_maintenance_page(&$variables) {
./themes/bartik/template.php:function bartik_preprocess_node(&$variables) {
./themes/bartik/template.php:function bartik_preprocess_block(&$variables) {

and print_r($variables); in the above functions does not contain a "picture".

Also I've tried setting $account->picture = NULL; in the hook_user_view($account, $view_mode, $langcode) hook, but then the picture is hidden for everyone including registered users and also this is for user profiles only, not for blog comments.

None of the core themes have all the preprocess functions or template file in use. The best way to find what's available to use is with the devel_themer module.

Here's what devel_themer gave me:

This says we can use template_preprocess_user_image() or user-picture.tpl.php. When doing logic such as this, it's standard to use preprocess functions. When you're changing HTML structure you use template files.

So you can add the following function to your theme and it should hide all user pictures for anonymous users (web scrapers are considered anonymous users).

function YOURTHEME_preprocess_user_picture(&$variables) {
  // this is the currently logged in user
  $user = $variables['user'];

  // this is the user the picture belongs to
  $account = $variables['account'];

  // If the current user is anonymous don't show the user picture
  if ($user->uid == 0) {
    $variables['user_picture'] = NULL;
  }
}


Drupal ExtJS4 (Sencha) integration Has anyone used ExtJS with Drupal? Is there any module for Drupal that supports Ext JS?  If so, what are steps to get it work? I'm wondering if there is any feasibility of creating an Ext based drupal theme.

There is just a module that integrates Ext in Drupal that I know of: the Ext module.

  Loads the Ext JavaScript library (version 2.2 & 2.3 for now) with Drupal. Other modules requiring Ext may use this module as a basis, or it may run on its own, simply loading the Ext library.

  Note: A new version of this module is being developed to provide relatively comprehensive integration functions with Ext 4.x (currently 4.1). For details please see http://drupal.org/node/1316616.

The module doesn't have a version for Drupal 7, though.


Editing a Custom Block I have taken over the maintenance of a site that was built with Drupal 6.x

Prior to this I have no Drupal experience, so I am rolling up my sleeves and getting stuck into how Drupal works, with vcarying degrees of success.

My problem is this:

There is a menu on the site which I would have presumed was primary navigation, but it turns out to be a block.

I need to edit this menu, but there are no options to do so under blocks, there is a configure button beside it, but this does not allow me to edit its content. There is no delete option shown either, as I notice some blocks have this option and others dont.

Any ideas where I can find the content of this block so that I can edit it?

You get the delete option in the block configuration page for those blocks that have been created using Add Block option (in Admin >> Site Building >> Block). In your case the menu block in question might have been created programatically using hook_block or any other means that I'm not aware of and the Delete link might not appear due to the same. Suggest that you identify the code/module responsible for generating the block before you proceed on to anything. Also if you wish to replace this block with something more easily configurable I'd suggest using Nice Menus which I feel is a wonderful module


Assign roles at registration I am trying to assign a user role at registration using Webforms in Drupal 8. Is this possible or is there another form module that would do it better? I have two user roles 'Venue' and Artist' which will be used throughout the site still using Webforms to enter data specific to user role. New to D8. Thank you.

Oneway you can do is using hook_form_alter()

function MYMODULE_form_user_register_form_alter(&$form, FormStateInterface $form_state, $form_id) {
     foreach (array_keys($form['actions']) as $action) {
        if ($action != 'preview' && isset($form['actions'][$action]['#type']) && $form['actions'][$action]['#type'] === 'submit') {
          $form['actions'][$action]['#submit'][] = '_add_role_submit';
        }
      }
}
/**
 * Implements submit to set role to user.
 */
function _add_role_submit(array &$form, FormStateInterface $form_state) {
  $values = $form_state->getValues();
// HERE YOU CAN SET ANY ROLE FOR USER.
}

Another way is using hook_user_insert()

use Drupal\user\UserInterface;
function MYMODULE_user_insert(UserInterface $user) {
  // HERE YOU CAN SET ANY ROLE FOR USER.
}


Captcha is not working as expected.Visible on webform when logged out and invisible when logged in I have not selected any of the options:

Default challenge on non-listed forms.
Add CAPTCHA administration links to forms
Allow CAPTCHAs and CAPTCHA administration links on administrative pages

I have selected persistence:
Omit challenges in a multi-step/preview workflow once the user successfully responds to a challenge.

That is expected behaviour. Under permissions there is an option:

Skip CAPTCHA
Users with this permission will not be offered a CAPTCHA.

Admin by default has this set meaning they won't see the Captcha. Captcha isn't necessary for an Admin since they are assumed to be trustworthy.
You can also set other roles here so that they don't see the Captcha. If you have strong Bot deterrents in user registration, you probably don't want authenticated users to have to go through the Captcha process after every node/comment/etc creation as this will just cause annoyance, especially for regular contributors. If you allow anonymous content creation, obviously you don't want to provide this option for that role, or the Bots will come knocking...


Why is hook_menu_local_tasks_alter called twice? For some reason, Drupal is calling hook_menu_local_tasks_alter twice. This results in either a) doubled tabs or b) really annoying code trying to determine if my custom tabs have already been added.

Can someone help me figure out what's going on here? Why would it be called twice? I'm using PathAuto, is this maybe a redirect issue?

If you are familiar with the command line, you can use the following command to return file names and line numbers where this hook is being called.

For example, change directories into your /sites/all/modules directory or other module directory and run,

(assuming your are using mac or linux)

$grep "menu_local_tasks" * -rn

or as Clive has it below.

$grep "drupal_alter(\'menu_local_tasks\'" * -rn

*Note, the backslashes escape the single quotes.

Jason.


Add a non-base field to a content entity form What is the proper way to add a non-base textarea field to the entity form of a custom content entity?

comment and user modules have non-base fields that display in their entity form (comment_body and picture), but it appears these fields are added to the form somewhere besides the main entity form method they use.

In my module, I've created a field and instance inside hook_install like this:

<?php
function mymodule_install() {
  $field = array(
    'name' => 'myfield',
    'entity_type' => 'myentitytype',
    'type' => 'text_long',
    'module' => 'text',
    'settings' => array(),
    'cardinality' => 1,
    'locked' => FALSE,
    'indexes' => array(),
  );
  entity_create('field_entity', $field)->save();

  $instance = array(
    'field_name' => 'myfield',
    'entity_type' => 'myentitytype',
    'bundle' => 'myentitytype',
    'label' => 'Field title',
    'description' => t('Field description.'),
    'required' => TRUE,
    'default_value' => array(),
    'settings' => array(
      'text_processing' => '0'
    ),
  );
  entity_create('field_instance', $instance)->save();
}

I think if I could be pointed to how comment_body gets added to the comment entity form, or picture to the user entity form, I'd be able to resolve this.

You can ship a locked Field with yml only, see core/modules/forum/config/field.*. Ie just make the fields in the ui and copy the yml files from your active store to a config folder inside your module.

This ships a locked boolean field for the container flag. You'll also need form and entity display entities, but you can create them in the ui and grab the yml for them too.


How to add a CSS attribute to Image generated with image style Pretty much all in the title. I would like to add a CSS classes to images generated via a image style theme function, so that the output looks like :

<img class="MYCLASS" alt="" src="site.com/sites/default/files/styles/profile_picture/public/pictures/picture-1-1318455022.jpg" typeof="foaf:Image">

Is there anyway to do so ?

If you are comfortable overriding theme functions in your theme's template.php you can just create a YOURTHEME_image_style() function:

http://api.drupal.org/api/drupal/modules--image--image.module/function/theme_image_style/7


jQuery getting loaded twice I'm using the jQuery Update module and decided to choose a more recent version of jQuery so in the module settings I changed it from 1.7.1 to 1.8.2

The issue I'm having is that the previous version (1.7.1) keeps getting loaded. So at the moment two versions of jquery are being downloaded. Its worth mentioning that I selected the Google CDN delivery method so the file comes from there.

I have no idea how to solve this. I disabled and uninstalled the module, manually removed the jquery_update_jquery_cdn from the variable table, cleared the cache, cron, restarted nginx and php-fpm, but still the issue persists.

The issue was memcached, apparently variables were cached in the service. Once the memcached service was rebooted the issue disappeared.


How to use t() function in controller? I understand Drupal 8 ControllerBase implements StringTranslationTrait so we can use $this->t() in Controller class.
But I found in Drupal 8 examples code, they setStringTranslation to use t() function. Here is the code.

public static function create(ContainerInterface $container) {
    $controller = new static(
      $container->get('database')
    );
    $controller->setStringTranslation($container->get('string_translation'));
    return $controller;
  }

The link for their module. https://git.drupalcode.org/project/examples/blob/8.x-1.x/tablesort_example/src/Controller/TableSortExampleController.php

My question is why setStringTranslation when you can just use t() function in the controller.

$this->t() assumes object context. $this isn't available in the static context of the create method above.

The ControllerBase provides access to t() via a protected function (see below from docs) to it is also not available from the public context.
setStringTranslation however is a publicly available method.

StringTranslationTrait::t   protected   function    Translates a string to the current language or to a given language.
...
StringTranslationTrait::setStringTranslation    public  function    Sets the string translation service to use.

https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Controller%21ControllerBase.php/class/ControllerBase/8.2.x


Webform Submission not Working with .tpl.php file I have a webform that i needed to style a little differently. So I did this creating a webform-form-3.tpl.php file (the node of my form is 3). Inside that I have this code:

<?php // Contact Us form ?>

    <?php print drupal_render($form['submitted']['event']);?>

        <?php print drupal_render($form['actions']['submit']);?>

Unfortunately, by doing this, it stops the submitting functionality of the form. I am assuming that I messed up on missing some of the submitting options. Does anyone have any ideas where i may have gone wrong? Any help would me much appreciated! Thank you!

Stick this at the bottom:

<?php echo drupal_render_children($form); ?>


an error occurred while installing jplayer and audiofield module on server in drupal 7 I tried to install jplayer and audiofield modules on server but the following error reported and I could not understand what it is and how to solve it:

An AJAX HTTP error occurred. HTTP Result Code: 500 Debugging information follows. Path: http://mywebsite.com/authorize.php?batch=1&render=overlay&id=28&op=do StatusText: Internal Server Error ResponseText: UnexpectedValueException: RecursiveDirectoryIterator::__construct(/home/username/public_html/C:/xampp/tmp/update-extraction-7a580f22/jplayer) [recursivedirectoryiterator.--construct]: failed to open dir: No such file or directory in RecursiveDirectoryIterator->__construct() (line 408 of /home/username/public_html/includes/filetransfer/filetransfer.inc

I installed these modules on localhost and there was no error.

Try to create a temp directory and give 777 permission and change file system's temporary directory from 'admin/config/media/file-system' to that temp directory. Because C:/xampp/tmp/ doesn't exist on your server.


Editing the 'default front page' base URL I rebuilt a new server from another server's image. And I want to use it for a new domain, but I'm finding that the new server continues to redirect to the original server's domain.

Going to the new server's drupal admin console, I see that the domain (ie, https://mysite.com/) is uneditable under Configuration > System > Site Information > Front Page > Default Front Page.

I tried setting the 'base_url' in /etc/drupal/7/sites/default/settings.php to my new domain and flushed the cache, but that didn't resolve the problem (and the old domain still persists in the console).

Have you tried the below changes in your settings.php and .htaccess?

 /sites/default/settings.php

$base_url = 'http://www.example.com'; // NO trailing slash!

and

.htaccess

  # Modify the RewriteBase if you are using Drupal in a subdirectory and
  # RewriteBase /drupal

Try using this.


Custom CCK Currency exposed filter for available currencies I am trying to set the available currencies programatically like this:

function mymodule_form_alter(&$form, $form_state, $form_id) {
    /** Modify exposed filter views */
    if ($form_id == 'views_exposed_form') {
        $form['field_1hour_currency']['#type'] = 'select';
        $form['field_1hour_currency']['#options'] = array('EUR','USD');
    }
}

But I get An illegal choice has been detected. Please contact the site administrator. error in the view.

How can I set a select list of available currencies in the views exposed filter for a CCK currency field?

Thank you

(using D6, Views 2 and latest CCK Currency)

function mymodule_form_alter(&$form, $form_state, $form_id) {
  if ($form_id == 'views_exposed_form' && $form_state['view']->name == 'myview') {
    // Add our custom All buttons.
    $form['field_1hour_currency']['#type'] = 'select';
    $form['field_1hour_currency']['#options'] = array(
      '' => t('<Any>'),
      'USD' => 'USD',
      'EUR' => 'Euro'
    );
  }
}

The key is to ensure you include the empty option:

'' => t("<Any>")

See http://drupal.org/node/463990

You may want to post this solution on your issue on drupal.org too if it works for you: http://drupal.org/node/1155934 ;)


Overriding permissions selectively via settings.php/settings.local.php The use case is a development module that you would only have installed on a local environment.

My thought was to use $config in settings.php to do this:

$config['user.role.anonymous']['permissions'][] = 'use browsersync';
$config['user.role.authenticated']['permissions'][] = 'use browsersync';

When doing this everything looks good in the permissions UI but in practice the permissions seem to be clobbered and permissions like 'access content' are no longer enabled for these users.

Permissions are clobbered because Drupal uses NestedArray::mergeDeepArray() to merge overrides with existing config.

For example, if we have this permissions

$ drush cget user.role.anonymous permissions
'user.role.anonymous:permissions':
  - 'access content'
  - 'access comments'

and then add

$config['user.role.anonymous']['permissions'][] = 'use browsersync';

to settings.php, the result will be

$ drush cget user.role.anonymous permissions
'user.role.anonymous:permissions':
  - 'use browsersync'
  - 'access comments'

An easy way to workaround this would be

$config['user.role.anonymous']['permissions'][9999] = 'use browsersync';

which will result in

$ drush cget user.role.anonymous permissions
'user.role.anonymous:permissions':
  0:'access content'
  1:'access comments'
  9999: 'use browsersync'

But if you need to remove a permission via settings.php, then I honestly don't know how to do it, even with module config overrides system (which has an ability to load original config before providing the override). Maybe overriding the unwanted permission with NULL may work, but I haven't tried.


Rendering a region fo a theme programmatically I am building a module that contains a route and a controller that only renders a specific theme region, without any surrounding HTML.

How can I load and render the region programmatically within the controller output method?

The region output from the controller contains one or more blocks and the entire region needs to be embedded on another site. The site will retrieve the markup using a custom route (e.g. example.com/partials/header or example.com/partials/footer).

I don't know which blocks are going to be in the region; the list of blocks in the region is not hard-coded in the module.

Using the block.repository service you can get an instance of the BlockRepository class.
You can then call the getVisibleBlocksPerRegion method on it which will return an associative array BlockInterface[][] (first key is the region name, second key is the block ID).

You will probably need to change the active context if some of these blocks only appear certain conditions.


Sorting in Filed Collection Views I am using Field Collection Views in Drupal and everything works fine, except Sorting. I am able to rearrange the Field Collection items in Edit form using both drag-and-drop also manually using Row weights option.

I would like the the Field Collection View results to be sorted by this Row weight, could you please guide how I could acheive this.

This could be achieved by creating a relationship, and using Delta to sort. Let us say that the field collection field's name in the entity is field_slides.

Create a relationship with 'Field collection item: Entity with the Slides (field_slides)'. Check the box for - Require this relationship


How can filter a view by several NID's? I try to filter a node by the criteria of NID. Naturally I can filter by a single NID, but in this case I need to to filter by multiple NIDs.

I tried to wrote the following number values and non worked:

1, 20, 31

1+20+31

How should I write the number values so that it would work?

Thanks.

You will need to add contextual filters in the view.

Just go to advanced -> contextual filter -> add new 'content:nid'
field.
Check 'profile default value' option from list entitled 'WHEN THE FILTER VALUE IS NOT AVAILABLE' -> Choose 'Fixed value' option and add multiple nids seperating them via '+' e.g. 1+2+3
Then from 'more' fieldset check on 'allow multiple values' option.

This should do it. You can check also in sql query generated by view below it which should show something like this in where clause e.g. WHERE (( (node.nid IN('1', '2', '3') ) )


Multilanguage database field setup We're looking to create a drupal commerce site with multiple languages for Drupal translated manually stored different translations in a seperate fields. Different fields would be displayed upon changing the language type.
i.e.

field_title (english) -> field_title_fr (french) -> field_title_gr (german)
field_description (english) -> field_title_fr (french) -> field_title_gr (german)
field_price (english) -> field_price (french)
-> etc...

Is it possible to click a link to have the website trigger a language change?
Also, how could you have drupal display a different field?
Would this method be the drupal way of doing it ? Or is there a module for this already?

This post actually gives insight on how multilanguage fields work using internationalization:
http://dominiquedecooman.com/blog/drupal-7-tip-get-field-values-entity-objects-nodes-users-taxonomy

As well as Gabor's Very authoritative one: http://hojtsy.hu/multilingual-drupal7


Override specific routing from a core module I want to stop anonymous users being able to access a specific set of routes offered by the core/forum module.

specifically:

forum.index:
  path: '/forum'
defaults:
  _controller: '\Drupal\forum\Controller\ForumController::forumIndex'
  _title: 'Forums'
requirements:
  _permission: 'access content'

and

forum.page:
  path: '/forum/{taxonomy_term}'
defaults:
  _controller: '\Drupal\forum\Controller\ForumController::forumPage'
  _title_callback: '\Drupal\taxonomy\Controller\TaxonomyController::termTitle'
requirements:
  _permission: 'access content'

I just need to add: _user_is_logged_in: 'TRUE' to the routes' requirements.

How does one do this without 'hacking' core?

I have alternative routes for the above in my own module - with different names and controllers and in an ideal word I would also wish to redirect both those routes through my own. However, for a start I will take being able to stop anonymous users seeing my forums.

You can override route details in a route subscriber:

src/Routing/RouteSubscriber.php:

namespace Drupal\example\Routing;

use Drupal\Core\Routing\RouteSubscriberBase;
use Symfony\Component\Routing\RouteCollection;

/**
 * Listens to the dynamic route events.
 */
class RouteSubscriber extends RouteSubscriberBase {

  /**
   * {@inheritdoc}
   */
  protected function alterRoutes(RouteCollection $collection) {
    if ($route = $collection->get('forum.index')) {
      $route->setRequirement('_user_is_logged_in', 'TRUE');
    }
  }

}

example.services.yml:

services:
  example.route_subscriber:
    class: Drupal\example\Routing\RouteSubscriber
    tags:
      - { name: event_subscriber }

See Altering existing routes and adding new routes based on dynamic ones

If you want you can also replace the core classes with your own classes. You can have multiple routes for one class. Then you don't need a redirect.


How do I set group fields in pairs? The code is taken from the "Form API examples" and supplemented. There must be a pair of first and last name fields. A button “Add more” should add a new pair of fields “name and surname” below the existing one. This works (a little later using css so that they are on the same line), but they are grouped incorrectly. They are displayed following this order.

Name
Name
Name
Surname
Surname
Surname

I need to get them in the following order. (Using CSS, I will inline them.)

Name
Surname
Name
Surname
Name
Surname

What am I doing wrong?

The code I am using is the following one.

public function buildForm(array $form, FormStateInterface $form_state) {
    $form['description'] = [
      '#type' => 'item',
      '#markup' => $this->t('This example shows an add-more and a remove-last button.'),
    ];

    // Gather the number of names in the form already.
    $num_names = $form_state->get('num_names');
    // We have to ensure that there is at least one name field.
    if ($num_names === NULL) {
      $name_field = $form_state->set('num_names', 1);
      $num_names = 1;
    }

    $form['#tree'] = TRUE;
    $form['names_fieldset'] = [
      '#type' => 'fieldset',
      '#title' => $this->t('People coming to picnic'),
      '#prefix' => '
',
      '#suffix' => '
',
    ];

    for ($i = 0; $i < $num_names; $i++) {
      $form['names_fieldset']['name'][$i] = [
        '#type' => 'textfield',
        '#title' => $this->t('Name'),
      ];
      $form['names_fieldset']['surname'][$i] = [
        '#type' => 'textfield',
        '#title' => $this->t('Surname'),
      ];
    }

    $form['names_fieldset']['actions'] = [
      '#type' => 'actions',
    ];
    $form['names_fieldset']['actions']['add_name'] = [
      '#type' => 'submit',
      '#value' => $this->t('Add one'),
      '#submit' => ['::addOne'],
      '#ajax' => [
        'callback' => '::addmoreCallback',
        'wrapper' => 'names-fieldset-wrapper',
      ],
    ];
    // If there is more than one name, add the remove button.
    if ($num_names > 1) {
      $form['names_fieldset']['actions']['remove_name'] = [
        '#type' => 'submit',
        '#value' => $this->t('Remove One'),
        '#submit' => ['::removeCallback'],
        '#ajax' => [
          'callback' => '::addmoreCallback',
          'wrapper' => 'names-fieldset-wrapper',
        ],
      ];
    }
    $form['actions']['submit'] = [
      '#type' => 'submit',
      '#value' => $this->t('Submit'),
    ];

    return $form;

The form is rendered as in this screenshot.

The second part of the code where the code is processed

  public function submitForm(array &$form, FormStateInterface $form_state) {
    $values_1 = $form_state->getValue(['names_fieldset', 'name']);
    $values_2 = $form_state->getValue(['names_fieldset', 'surname']);

    for ($i = 0; $i < count($values_1); $i++) {
      $arr[] = $values_1[$i] . ' ' . $values_2[$i];
    }

    $output = $this->t('These people are coming to the picnic: @names', [
      '@names' => implode(', ', $arr),
    ]
    );
    $this->messenger()->addMessage($output);
  }

You could add a fieldset for each person, something like this should work:

for ($i = 0; $i < $num_names; $i++) {
  $form['names_fieldset']['person_' . $i] = [
    '#type' => 'fieldset',
    '#title' => $this->t('Person ' . $i),
  ];

  $form['names_fieldset']['person_' . $i]['name'] = [
    '#type' => 'textfield',
    '#title' => $this->t('Name'),
  ];
  $form['names_fieldset']['person_' . $i]['surname'] = [
    '#type' => 'textfield',
    '#title' => $this->t('Surname'),
  ];
}

And then alter your remove callback and a few other bits to match


How would I add markup inside of page title input? If I wanted to achieve the below, can I insert HTML markup inside of the page title on the node?

For example,

Dummy page title content

Install HTML Title. It will solve your issue.

  Drupal node titles are restrictive and do not support italicized text
  or superscript text (e.g., Book titles, trademark symbols). The HTML
  Title module allows a limited set of HTML markup (em, sub, sup, b, i,
  strong, cite, code, bdi, wbr) to be used in node titles.

Also take a look at Stack Overflow question HTML\rich text in Drupal's node title?.


Creating a custom views access plugin I'm trying to create a custom views access plugin, so I can perform my conditions for accessing a view.

I read several tutorials and checked the source of existing modules, but I must be coding/doing something wrong because this never works properly.

Here's the code:

File: sample.module:

function sample_views_api() {
  return array(
    'api' => 3,
  );
}

File: sample.views.inc:

function sample_views_plugins() {
  $plugins = array(
    'access' => array(
      'test' => array(
        'title' => t('Custom access check'),
        'help' => t('This is a custom access plugin.'),
        'handler' => 'sample_access_plugin',
      ),
    ),
  );
  return $plugins;
}

class sample_access_plugin extends views_plugin_access {
  function summary_title() {
    return t('Custom acces plugin');
  }
  function access($account) {
    return sample_access($account);
  }
  function get_access_callback() {
    return array('sample_access', array());
  }
}

function sample_access($account = NULL) {
  return TRUE;
}

I can see the access plugin in views, and I can select it. However, no matter what I do, the access to the view will always be forbidden (access denied). There are no messages in the error log.

Any ideas what's wrong here?

Thanks!

It seems like the sample.views.inc file does not get loaded during the access-check (as the registry already cached the information which callback it needs to execute).

So you can just move sample_access() to the file sample.module and the callback works.


Are unique node titles neessary? I am considering automatically assigning the uid to several of my content types automatically.  However, one other data type uses a number as its title too (product number actually.)  There is a strong potential for a uid to be the same as a product number.  Could this potentially cause problems?  What are some common problems that can arise from non-unique titles?

Drupal itself does not depend on titles or labels to identify entities, and there is no expectation within the core system that they would be unique. You could in theory have a completely functional site with ten thousand nodes all sharing the same title, tagged with ten thousand terms sharing the same name, linked by ten thousand menu items sharing the same label.

Drupal is full of locally unique, automatically generated IDs: each node has an nid, each term has a tid, each menu has an mlid, and so on (though for identifiers unique across the system, one must use UUID or something similar). Provided your custom code, theme output, Views filters, and so on can be written to reference these machine IDs, I would expect few problems.

It is not always possible to rely on those machine IDs; they are content, and so are subject to editing, deletion, and replacement. You might want a banner to appear on your About Us page, but depending on the season the About Us page may be node/25 or node/29, for example.

Thus it is possible, even unconsciously, to build parts of the site that do depend on labels. Many themes insert a class on the <body> based on title, or on the alias/context (which pathauto will by default set to the title); you may have CSS rules applying to the wrong pages. You may have an editorial policy that all nodes pertaining to a particular product include its product code in the title, and set up Views to filter them. But only takes one typo for a node to go missing, or one forgotten edit to the title of a cloned node to have extras appearing.


How can I implement a RESTful API in Drupal? Can any one please let me know what modules are available to implement a REST API?

So far I've only found the Redmine REST API module, which is used for Redmine.

For a REST API implementation on Drupal, use the Services module.

  A standardized solution of integrating external applications with Drupal. Service callbacks may be used with multiple interfaces like REST, XMLRPC, JSON, JSON-RPC, SOAP, AMF, etc. This allows a Drupal site to provide web services via multiple interfaces while using the same callback code.


How can I create user profiles in drupal 7? I would like to know how to create a user profile (registered user block) similar to the one on this site. I am using Drupal 7 and the Zen theme.

In Drupal 7, users accounts are fieldable entities like nodes. From Administration » Configuration » People » Account settings, you can add fields and configure their display on the user page (ie. /user/$uid).

For a more complex setting with multiple profile types and separation of accounts (ie. user) and profiles, you can use the Profile2 module.

You can then use Views to easily crate blocks and pages to list users and information from their profiles.


The module is not working as expected I can't figure out why this module is not working. What is wrong with it?

/* hook_menu() */
function profilepage_menu() {
  $items['p'] = array(
    'title' => 'Profile page',
    'page callback' => 'profile_exe',
    'access callback' => TRUE,
    'type' => MENU_CALLBACK,
  );

  return $items;
}

/* Callback function */
function profile_exe($id) {
  $ar = array('uid' => $id, 'profilesload' => profile2_load_by_user($id));

  return theme('profilebuild', array('collected' => $ar));
}

/* Custom theme function. */
function theme_profilebuild($variables) {
  return "";
}

/* hook_theme() */
function profilebuild_theme() {
  return array(
    'profilebuild' => array(
      'variables' => array('profilesload' => array()),
      'template' => 'profilepage',
    ),
  );
}

The module is installed and a page called profilepage.tpl.php is in my theme directory AND in the module directory.

The output I'm expecting should be the text in the profilepage.tpl.php page along with the contents of the $variables array which I plan to use in my template.

However, when I open http://example.com/?q=p in my browser, the page loads without errors but the expected content is not there.

What am I doing wrong?

The problem I can see with your code is the file name for the template file that you declare in your hook_theme() implementation.
The file name for the template file should be the theme identifier used as array index in the array returned by hook_theme() (in your case, "profilebuild"); where the identifier uses underscores, the template name should use hyphens.

As example of how the template files are named, see the following hook_theme() implementations for Drupal core modules.

function book_theme() {
  return array(
    'book_navigation' => array(
      'variables' => array('book_link' => NULL),
      'template' => 'book-navigation',
    ),
    'book_export_html' => array(
      'variables' => array('title' => NULL, 'contents' => NULL, 'depth' => NULL),
      'template' => 'book-export-html',
    ),
    'book_admin_table' => array(
      'render element' => 'form',
    ),
    'book_title_link' => array(
      'variables' => array('link' => NULL),
    ),
    'book_all_books_block' => array(
      'render element' => 'book_menus',
      'template' => 'book-all-books-block',
    ),
    'book_node_export_html' => array(
      'variables' => array('node' => NULL, 'children' => NULL),
      'template' => 'book-node-export-html',
    ),
  );
}

function aggregator_theme() {
  return array(
    'aggregator_wrapper' => array(
      'variables' => array('content' => NULL),
      'file' => 'aggregator.pages.inc',
      'template' => 'aggregator-wrapper',
    ),
    'aggregator_categorize_items' => array(
      'render element' => 'form',
      'file' => 'aggregator.pages.inc',
    ),
    'aggregator_feed_source' => array(
      'variables' => array('feed' => NULL),
      'file' => 'aggregator.pages.inc',
      'template' => 'aggregator-feed-source',
    ),
    'aggregator_block_item' => array(
      'variables' => array('item' => NULL, 'feed' => 0),
    ),
    'aggregator_summary_items' => array(
      'variables' => array('summary_items' => NULL, 'source' => NULL),
      'file' => 'aggregator.pages.inc',
      'template' => 'aggregator-summary-items',
    ),
    'aggregator_summary_item' => array(
      'variables' => array('item' => NULL),
      'file' => 'aggregator.pages.inc',
      'template' => 'aggregator-summary-item',
    ),
    'aggregator_item' => array(
      'variables' => array('item' => NULL),
      'file' => 'aggregator.pages.inc',
      'template' => 'aggregator-item',
    ),
    'aggregator_page_opml' => array(
      'variables' => array('feeds' => NULL),
      'file' => 'aggregator.pages.inc',
    ),
    'aggregator_page_rss' => array(
      'variables' => array('feeds' => NULL, 'category' => NULL),
      'file' => 'aggregator.pages.inc',
    ),
  );
}

Drupal 7 implementations of that hook is slightly different from the implementation done in Drupal 6, but the "template" index is used in the same way in both the versions.

function block_theme() {
  return array(
    'block_admin_display_form' => array(
      'template' => 'block-admin-display-form',
      'file' => 'block.admin.inc',
      'arguments' => array('form' => NULL),
    ),
  );
}


Dynamic frontpage image changes every hour I want to have a frontpage with images changing every hour. As it is the frontpage, the page is cached.
Can this be done with views?
I'm thinking of creating a views block which shows a random image but I'm lost on the refresh every hour part.

Inside of views, over in its cache settings, you can choose TIME and then select one hour for the results and output. Then, if you have it show a random image, it will cache that and only select another image after that hour has passed.  This of course will be defeated if your page is cached, but if its cache lifetime is less than an hour, it will cache up eventually (I just made a pun lol)


How would you implement function rich forms to your module I'm having a hard time deciding on how to develop the following functionality in my upcoming module:

I'm developing a module which should eventually be able to create "event" type nodes. Which extend the nodes functionality to have:

One or multiple plannings which consist out of...
... timespaces, which has the following properties, per timespace:

from (datetime)
to (datetime)
limit of subscribers (int)
And other stuff (not related to the question)

The website visitors should be able to subscribe to each timespace with a form, filling out their information. But if, and only if the limit of subscribers has not been reached yet for this timespace.
After subscription, the visitor should get an automatic mail with a PDF (ticket) attached to it.
Our customer should be able to export all the data, at any time to an Excel sheet...
... and (preferably) quick-review all the subscriptions at all time.

Well, the plannings and the timespaces won't be a problem, I'll manage that. But I would absolutely LOVE to incorporate Webforms into this. Since, point 3 through 6 all address functionality that already exists in Webforms... It'll save my butt a lot of time developing this thing.

My question is... Does anyone have any experience developing a module, incorporating Webforms? If so, how did you combine the two? I was thinking about something in the lines of:

Developing a new Field widget which would make it possible for the moderators to create the event's plannings and timespaces.
Somehow, (and this is the part where I'm not sure how to do this) creating a field for "webform" that would fetch the possibilities from the field.

I'm not sure.. I don't think this is the right way to go... I wonder what you guys think about this and if I simply should develop my own form + all the functionalities with it. Or maybe know a contrib module that does all of this...

I've found the solution today myself. I've been developing Webform components. I've found this way to be the best solution without altering any database structures and still getting the full functionality I wanted to get.

Instantiating - The base of your webform component

hook_webform_component_info - will be your friend in defining your components base structure. Since I needed the planning which would consist out of more timespaces (could've done better here on the termonology ;) ), I added a component named "planning" and gave it a "feature": group. This way I can extend the component "planning" with the "timespace" component.

Values - Add a limit of subscriptions and other parameters for your timespace

_webform_edit_component - Makes it possible to alter the edit form of your component. Make sure you at least add an "limit_subscription" (adjust naming to your liking) field so we can check against it.

_webform_defaults_component - Will be needed to inject the defaults to your edit form, which you have created with the function here above.

Cosmetics and security - Make sure you get the checkbox and disable it when full

_webform_render_component - Arranges all the cosmetics on your webform component. So make sure you edit your timespace component to get the checkbox you want so people can check a timespace. Also, you can (ofcourse) add some additional markup to your liking.

Security, checking the limit

This is also the right place to check for your limits and disabling the checkbox when full. (see the function webform_events_check_timespace_limit($component), use that to set #disabled on your element. Also make sure you give your element the right validation, something like this, so they can't screw around by simply enabling the checkbox:

'#element_validate' => array('_webform_validate_timespace'),

Then check against the database in your validation function for the limits, this is how I got it done:

/**
 * Validation for timespace elements
 */
function _webform_validate_timespace ($element, &$form_state) {
    // If checked, make sure this timespace has some space left.
    if ($element['#value'] === 1) {
        $remaining_subscriptions = webform_events_check_timespace_limit($element['#webform_component']);
        if ($remaining_subscriptions === -1) form_error($element, t('The timespace that you\'ve chosen is already full!'));
    }
}

/**
 * Check if the limit has been reached, returns remaining count to the limit, or -1 when full, or FALSE when no limit is set
 */
function webform_events_check_timespace_limit ($component) {
    $limit_subscriptions = $component['extra']['timespace_properties']['limit_subscriptions'];
    if (!empty($limit_subscriptions)) {
        $count_subscriptions = webform_events_get_timespace_count($component['nid'], $component['cid']);
        if ($count_subscriptions >= $limit_subscriptions) return -1;
        else return $limit_subscriptions - $count_subscriptions;
    }
    return FALSE;
}

/**
 * Get the count of the current timespace subscriptions
 */
function webform_events_get_timespace_count ($nid, $cid) {
    $select = db_query('SELECT count(*) FROM {webform_submitted_data} WHERE nid = :nid AND cid = :cid AND data = 1', array(':cid' => $cid, ':nid' => $nid));
    return $select->fetchColumn();
}

Backoffice - Exporting, table views, analysis..

For this you need the following functions, I'm not writing out these, I could go publish a book if I would:

Exporting (CSV, Excel):

_webform_csv_data_component - The actual data per row.
_webform_csv_headers_component - The headers in the top of the sheet.

Submission view (The page you get at individual submissions)

_webform_display_component

Table view

_webform_table_component

Analysis view

_webform_analysis_component

More help

Since I've just outlined the basics of this thing, I'd recommend you check out some good examples.

I've managed to figure this all out and fix get somewhat of the following (of course; early beta screenshots)

Submission view

Analysis view

A simple export

Front-end example

Table view

Setting up a event


How to filter by month in view using a date field I have a field called birthday that is defined for users. In views, is there any way to create a filter that filters only by month? Smallest values it lets me select is year and month where I only need month. (to find users who are born in April for example). Thanks for any help.

If you are using the date module, then you can set the granularity to month in the date filter settings.

Then, you can configure the filter like so Operator: "is equal to" and Date: "this month".

If you don't see these filter settings, you would have to enable the date_views module.


How to get the "field" value of config entity, with bundles, that is defined in a bundle while creating content I am creating a custom entity (WebsiteType) with bundles (Website), where I want to define a URL, among other configurations, that all content in a given bundle should inherit.

I created the fields in the config entity type and managed to show and save these fields while creating a new bundle. Nevertheless, I couldn't manage to get these values in HOOK_entity_presave.

here is a sample of the code:

src/Entity/WebsiteType

Notation:

 *   entity_keys = {
 *     "id" = "id",
 *     "label" = "label",
 *     "uuid" = "uuid",
 *     "service_endpoint_url" = "service_endpoint_url",

Class:

class WebsiteType extends ConfigEntityBundleBase implements WebsiteTypeInterface {
  /**
   * The Website type Service Endpoint URL.
   *
   * @var string
   */
  protected $service_endpoint_url;

}

 /**
   * {@inheritdoc}
   */
  public function getServiceUrl() {
    return $this->service_endpoint_url;
  }

WebsiteTypeForm:

public function form(array $form, FormStateInterface $form_state) {
  $form = parent::form($form, $form_state);

  $website_type = $this->entity;

  $form['endpoint_settings']['service_endpoint_url'] = [
    '#type' => 'textfield',
    '#title' => $this->t('Argir Endpoint URL'),
    '#maxlength' => 255,
    '#description' => $this->t("The location of your service."),
    '#required' => TRUE,
    '#default_value' => $website_type->getServiceUrl(),
    '#attributes' => [
      'placeholder' => $this->t('https://XXXXX.com'),
    ],
  ];
}

WebsiteTypeInterface:

interface WebsiteTypeInterface extends ConfigEntityInterface {

  public function getServiceUrl();
}

I followed the documentation of Drupal of Entity API

Checked the answer here: enter link description here

also went through this outstanding tutorial: enter link description here

Tried to work with EntityTypeManager

All of that with no luck. Any advice is highly appreciated.

While creating content, HOOK_entity_presave() is called for the content entity and you can access only content fields. One of these content entity fields is a reference field to the bundle config entity, usually named bundle. Use this field to get the config entity via the magic property entity and get the config field value via the method you have defined in WebsiteTypeInterface:

$url = $entity->bundle->entity->getServiceUrl();

A more generic way when you don't know the bundle field name or the code should work for all entity types:

$bundle_field_name = $entity->getEntityType()->getKey('bundle');
if (!empty($bundle_field_name)) {
  $bundle_config = $entity->get($bundle_field_name)->entity;
  if ($bundle_config instanceof \Drupal\mymodule\Entity\WebsiteTypeInterface) {
    $url = $bundle_config->getServiceUrl();
  }
}


Create a Term Queue on views I have a views showing some selected terms of a vocabulary. The Views block is created using Taxonomy Terms as content(show). It showing order by the terms tree. But my client want to sort it as their business policy(most popular on top).

Is there any way to sort the terms like custom way as node queue.
Please suggest me any module, hooks or other custom solutions.
Here is my views settings :

Thanks in advance.

Note that I want to sort the terms Not the entities tagging with it.
I have installed nodequeue and smartqueue but unable to achieve the requirment.

Views Aggregation to count nodes tagged by terms

You can use Views Aggregation to count the number of nodes that each tag is assigned to, and use that as the Sort criteria.

In the Views of type Taxonomy term filter all the terms you're interested about. Add a Name Field to show the term name (you probably already have that covered)
Add a Relationship to the content that the terms are related to Content using field_yourname
Turn on Aggregation (Under Advanced, third column)
Add a Sort criteria Content: Title, (it will automatically use the Relationship from above), Sort descending and adjust its Aggregation settings to Count DISTINCT (if you allow nodes to use multiple terms then Count will count them more than once)

Your terms list will be sorted by the number of nodes tagged by each term in your Views results.

Views Summary for single value fields

If your Taxonomy term reference Field allows for only one value you can use Views summary in a Contextual filter to count the nodes tagged with a term.

You can do it from Taxonomy term Views or Content Views.

If starting from Taxonomy term Views you can use the above steps,
only instead of using Aggregation add a new Contextual filter Name from Taxonomy term Category and configure it to display a Summary:

When the filter value is NOT available
Display a summary
Sort order Descending
Sort by Number of records
Format List
Base path (you must enter the Page path if this isn't the first Page Display in your Views)
Display record count with link

This way you get a list of Taxonomy terms with node count next to them. When you click on them you go to another page listing the actual Fields you set up in Views (you'll probably want to list Content: Title here).

It's a similar procedure to do that from Content Views type.

You'll want to add a Relationship to the relevant Taxonomy field (Taxonomy term referenced from field_yourname),
then add a Contextual filter for Taxonomy term: Name, use the Relationship and configure it to display as a Summary.


Pass exposed filters values from one view to another view I have a view that lists some nodes, has some exposed filters, like countries and search and a registered path without any contextual filters.

I also have a second view with the same exact exposed filters, but with a different registered path, again without any contextual filters.

At the first view I have a link that points to that second view.

The question is how can I pass the filters values (if any) selected from the first view to that second view when I click to the link of the first view?

After trying some things didn't managed to solve that but only by using the $_SESSION variable, however I'm not sure how optimal is this?!

Option 1: Views Global Filter. I've never used it but it sounds like a good but very heavy solution.

Option 2: Create the url for the second view dynamically with jQuery every time the exposed filters are changed. If you disable Ajax in the second view, you can see the url change and then use that as basis. The url will still work if you switch on Ajax again.

Option 3: Tokenise the exposed filters and create the link like option 2 in the header or footer.  There seems to be a couple of modules / sandboxes that could help.

I'd probably pick option 2 but of course, there are probably other solutions like your session variable and some views hook.


Remove duplicates from field [array] I am using php in views and trying to make a custom field to remove the duplicates in [field_trucks_notification_no_ref_node_eb:field_trucks_agency] field, i tried to use the row->field_name from the available variables in Global:PHP (output) with no luck.

 stdClass Object
    (
        [entity] => 268
        [_entity_properties] => Array
            (
                [search_api_relevance] => 1
                [search_api_excerpt] =>
                [search_api_id] => 268
                [field_cons_country_border] => 35604
                [field_trucks_notification_no_ref_node_eb] => Array
                    (
                        [0] => 269
                        [1] => 272
                        [2] => 278
                    )

                [field_trucks_notification_no_ref_node_eb:field_trucks_agency] => Array
                    (
                        [0] => 35617
                        [1] => 35621
                        [2] => 35617
                    )

EDIT: using Global:PHP field in views, How can I retrieve the values of the last field (array) above and remove duplicates?

To remove duplicates in Views, if the views advanced settings "Distinct" don't operate, have a look at Views Distinct module: https://www.drupal.org/project/views_distinct. Really useful project and sounds better than php in views.


How to trim content from a heavy database I would like to trim content from a heavy production database (1GB), to reduce transfering time, local mysql import time and generally make it easier to work with.

I know I can ignore cache, watchdog and index tables and this reduces size greatly (about 50%) and I looked into deleting old node revisions.

But I'm looking further to, for example, remove all content older than 1 year, or all users that have not been active in the last 6 months.

In the workflow these clean-up operations could be done in a (recently synched) staging environement before exporting the databse for local usage.

Anyone know how to accomplish removing older content from a database so it can be easier exported?

For content, I know two options, both based on Views:

Create a view of old content only, and use Views Bulk Operations to purge it from your site. This is literally what you asked for, but also something I would discourage.
Create a view of new content only, and use Views data export to only export nodes recent enough to matter. That way you will still have old content on site, and only lose it if site crashes and you need to restore from incomplete backup.

Also, I suggest you to evaluate Universally Unique IDentifier, it helps with consistency if you are exporting data individually, not as a complete snapshot of entire site.


Sidenotes / Inline notes on nodes I was wondering, is there already a module making it possible to make inline or sidenotes/comments inside the content of a node. A good example is the notes you can add in Google Docs.

Would be great for editorial purposes!

If I am not mistaken, it seems you want to have something like "private comments" on a node. You can find some information in the following question: How to have separate private comments for nodes apart from the general comments?

It mentions the Reply module, which is still in alpha. There might be other similar modules.

Hope it helps,


Adding font-awesome to Omega 4 subtheme I want to use font-awesome in an Omega 4 subtheme. I added this line to Gemfile:

  gem 'font-awesome-sass'

and tried to import it in subtheme.styles.scss with:

@import "font-awesome-sass";

But I get this error after running compass compile:

"Syntax error: File to import not found or unreadable: font-awesome-sass.

I also tried @import "font-awesome-sass.css" with no error, but no new stylesheet file is added to the subtheme pages.

Any suggestion?

Adding it to the Gemfile alone doesn't install the library. The Gemfile is used by a program called Bundler that manages your Ruby gems for you. You need to make sure you have this installed with sudo gem install bundler and then run bundle install where the Gemfile is located (your theme directory).

Alternatively you could just install font-awesome-sass yourself with sudo gem install font-awesome-sass.


How to allow users to edit the profile of users in the same department? Department is a term reference or a list (text) field of the user entity. I want to let managers edit the profiles of users in the same department as the manager.

I know I should define a custom permission, but in which hook should I check this custom permission?

In Drupal 7 if you want to change the access check for any path you need to use hook_menu_alter.

After you change the access callback you can write your own code which does the check you want.

You just need to be careful so you don't override access callback with a bad check.

What I suggest here is to keep the original function which does the access callback user_edit_access check in your custom callback function.

I wrote sample code which gives you an idea which direction to go:

/**
 * Implements hook_permission().
 */
function example_permission() {
  return array(
    'edit own department users' => array(
      'title' => t('Edit own department users'),
      'description' => t('Allowed department manager to edit own department users.'),
    ),
  );
}

/**
 * Implements hook_menu_alter().
 */
function example_menu_alter(&$items) {
  $items['user/%user/edit']['access callback'] = 'example_custom_user_edit_access';
}

/**
 * Custom access callback for user account editing.
 */
function example_custom_user_edit_access($account) {
  if (user_access('edit own department users')) {
    // We perform our check only for user with edit own department permissions.
    global $user;

    // Load user ( Department manager) via entity api.
    $user_wrapper = entity_metadata_wrapper('user', $user);

    // Get array of managed department terms id.
    $user_departments = $user_wrapper->field_user_department_managed->value();

    // Load user (Editor) via entity api.
    $account_wrapper = entity_metadata_wrapper('user', $account);
    // Get array of department belongs to terms id.
    $account_departments = $account_wrapper->field_user_department_belongs->value();

    // Check any common term id.
    $common_departments = array_intersect($user_departments, $account_departments);

    return !empty($common_departments);
  }
  // For other user we perform default check.
  return user_edit_access($account);
}


Replace intro with message I have a custom module that creates a form. I want to display a message to a user, but I don't want to use the normal drupal_set_message method. I want to add a div with text and images to the top of the form after submission.

A user may be submitting this form multiple times. So after submission, I want to still be on this page. It's just that after the form is submitted, a new div will appear at the top.

I don't really know how to detect that the form was submitted. It's similar to replacing the form and displaying a thank you message.

What is the best way to achieve that with Drupal 8?

You can request a rebuild in form submit and then add the message to the top of the form:

  public function buildForm(array $form, FormStateInterface $form_state) {

    if ($form_state->isRebuilding()) {
      $name = $form_state->getValue('name');
      $form['header'] = [
        '#type' => 'container',
        '#attributes' => ['class' => ['form-header-message', 'alert', 'alert-success']],
        'message' => [
          '#markup' => $this->t('Thank you for submitting this form, %name!', ['%name' => $name]),
        ],
      ];
    }

    $form['name'] = [
     '#type' => 'textfield',
     '#title' => $this->t('Name'),
    ];
    $form['submit'] = [
      '#type' => 'submit',
      '#value' => $this->t('Submit'),
    ];

    return $form;
  }

  public function submitForm(array &$form, FormStateInterface $form_state) {
    $form_state->setRebuild();
  }


How to use the node title in the "Override title" field of contextual filter Situation:

A view has a contextual filter on a field named type.

The view sorts by date and has the pager set to display 1 item (I want only the newest node).

I want to show type + the node title as the view title.

So, what I want to put in the Override title field is
{{ arguments.field_type_value }} {{ title }}

But {{ title }} doesn't work. It outputs nothing. This isn't a surprise because (a) {{ title }} isn't in the Replacement Patterns list and (b) I assume the view expects to display multiple nodes, so there isn't just one {{ title }} to display.
Is there a straightforward way to do what I want to do using a view as I'm doing? There are reasons why I want to use a view.
UPDATE:

The view is set to Show: Content so I can use a Twig template I created. (I added this update after seeing No Sssweat's first two suggestions below that work perfectly for Show: Fields but don't work for Show: Content. Note that No Sssweat also gives a solution for the Show: Content situation.)

Simply add title as a field and checkmark hide from display, now {{ title }} should work despite not being listed as replacement pattern.
Also make sure your view's title is set to none

Alternatively, you could also solve it by not overriding it in the contextual filter settings and instead overwrite it directly in the view's title.
Add title and type as fields, hide them if you want/need to.

But, if you're using teaser

The above two solutions won't work, so you can solve it programmatically:
/**
 * Implements hook_views_post_render()
 */
function mymodule_views_post_render($view) {
  if ($view->id() == "view_name" && $view->current_display == 'page_1') {
    $node = $view->result[0]->_entity;
    $new_title = $node->type->entity->label() . ' ' . $node->getTitle();
    $view->setTitle($new_title);
  }
}


How to display a field when a media is uploaded to the media library field? I have block settings form where I have a media library field.
 public function blockForm($form, FormStateInterface $form_state) {
    $form = parent::blockForm($form, $form_state);
    $user_input = $form_state->getUserInput();
    $my_field = $user_input['settings']['my_field'] ?? $this->configuration['my_field'] ?? NULL;

    $form['my_field'] = [
      '#type' => 'media_library',
      '#allowed_bundles' => ['my_bundle'],
      '#title' => $this->t('Upload'),
      '#default_value' => $this->configuration['my_field'] ?? '',
      '#required' => TRUE,
      '#ajax' => [
        'callback' => [$this, 'ajaxCallback'],
        'event' => 'updateMediaLibrarySelection'
        'wrapper' => 'test-field',
      ],
    ];

    $form['test'] = [
      '#type' => 'textfield',
      '#title' => 'test',
      '#prefix' => '
',
      '#suffix' => '
',
    ];

    if (empty($my_field)) {
      $form['test']['#wrapper_attributes']['class'][] = 'visually-hidden';
    }

    return $form;
  }

public function ajaxCallback(array &$form, FormStateInterface $form_state): array {
    return $form['settings']['test'];
  }

but my ajaxCallback method never called and the test field is always hidden.

I did with javascript because the field type media_library is not an actual input field.
I overrided the setMediaUploadFieldValue jQuery function of the media_library_form_element module.
(($, Drupal) => {
  Drupal.behaviors.VideoComponent = {
    attach: () => {
      $.fn.setMediaUploadFieldValue = (data, element) => {
        const mediaElement = document.querySelector(element);
        const currentValue = mediaElement.value;

        mediaElement.value = `${currentValue}${
          currentValue === "" ? "" : ","
        }${data}`;

        try {
          fetch(`${my_url}`)
            .then(response => response.json())
            .then(result => {
              if (result) {
                // Do something
              }
            });
        } catch (error) {
          return false;
        }
      };
    }
  };
})(jQuery, Drupal);


HTML Form that Passes Information to Hidden Fields Through URL I am trying to build an html form that is stretched across several pages. My intention is to use the GET method to send all of the fields data in the query string (URL parameters) and then store this data in hidden fields on the next page. I need to know how to append the data to the URL and how to retrieve it on the next page. I think I will need to send information across at least three pages. I have searched for a way to do this but I haven't really gotten a clear explanation. I am somewhat new to HTML coding. This is the most difficult thing I have attempted to code. Also, (this is not strictly necessary) but I would like to show this information as dynamic text as well. So I can show that certain pieces information have been added to the form. This needs to be separate from the actual form though. Thank you in advance. Any help is greatly appreciated.

You need to write a multistep form with the Form API and CTools.

The Form API allows you to write forms: See Creating a builder function to generate a form.

Because your form is multistep you need CTools to implement it, and handles issues like carry those values over the different steps.

This two subjects are too broad to explian in an answer, but there's lot of documentation about them.


Pass variables from custom module to its template? I'm trying to query my DB, and return those values as variables, then print those variables on my custom module's custom template and I can't get it to work.

If I put this into my theme layer it works fine.

$name=db_result(db_query('SELECT name FROM {users} WHERE id = %d', 2));
print $name;

I'd rather keep my queries in the .module file and only have to print the variable on my template. So far I haven't been successful.
Also, since I'm planning on having many variables used in many places (like display tables, or as values in calculations) I'd rather be able to print variables where I need them, and not tie them to an $output, or $content variable.

I referenced this post but I couldn't get the example to work.

I'm really new at this, my experience so far as only to take form info and save it to the DB, not bringing it back. so I'd appreciate any help.

To use the theme API it requires three portions: the template file, the theme hook, and then displaying the defined theme. The below examples are for Drupal 7.

<?php
  // defines the theme hook - should follow the naming format "_theme()"
  function mymodule_theme(){
    return array(
      'example_template1' => array(
        'template' => 'mytemplatefile1', // mytemplatefile1.tpl.php
      ),
      'example_template2' => array(
        'template' => 'mytemplatefile2', // mytemplatefile2.tpl.php
      ),
    );
  }

  // in this function is where you would do your DB queries,
  // and pass to the theme function as shown
  function mymodule_customfunction(){
    $calculation = 1+1;
    return theme('example_template1', array(
      'example_variable1' => $calculation,
      'example_variable2' => '123',
    ));
  }
?>

The mytemplatefile1.tpl.php file could look something like this:

<?php echo $example_variable1; ?>

To display your output, you could then just execute the following and it would print your value, wrapped in the "example-markup" div.

<?php echo mymodule_customfunction(); ?>


Drupal 7 - How to loop foreach in multiple value in custom view I'm customizing a view (in views-view--myview.tpl.php) based on a node which has a field with multiple value (field_galerie_image).

I'm trying to list in a foreach loop that particular field, and I am wondering how to write it down.

In the following code, I can access a value with $vue->_field_data["nid"]["entity"]->field_galerie_image['und'][0]["filename"]; but I need to loop through it.

$vue->_field_data["nid"]["entity"]->field_galerie_image['und'][1]["filename"];
$vue->_field_data["nid"]["entity"]->field_galerie_image['und'][2]["filename"];

The code I am using is the following one.

<?php foreach ($view->result as $id => $vue): ?>
  <?php if($vue): ?>
    <?php print $vue->nid; ?>
    <?php print $vue->node_title; ?>

    <?php print $vue->_field_data["nid"]["entity"]->field_galerie_image['und'][0]["filename"]; ?>
  <?php endif; ?>
<?php endforeach; ?>

I found it out; the correct code is the following one.

<?php foreach ($view->result as $id => $vue): ?>
  <?php if($vue): ?>
    <?php print $vue->nid; ?>
    <?php print $vue->node_title; ?>

    <?php foreach ($vue->_field_data["nid"]["entity"]->field_galerie_image['und'] as $val): ?>
      <?php print $val['filename']; ?>
    <?php endforeach; ?>
  <?php endif; ?>
<?php endforeach; ?>


Display the taxonomy term as an image I'm trying to display the taxonomy term (filter (Better Exposed Filters) on Views) as an image. I added an image field, upload an image (marker). Create template views-view-field--maps--field-type.tpl.php. I found example how to make theming of taxonomy-term here: http://www.milesjcarter.co.uk/blog/web-design-development/drupal-views-templating-tutorial-outputting-respective-image-fields-multiple-taxonomy-term-references

My code looks like:

if(isset($row->field_field_type)) {
    $term = $row->field_field_type;
    foreach($term as $type){
        render(field_view_field('taxonomy_term', $type['raw']['taxonomy_term'], 'field_marker', array('label'=>'hidden', 'settings' => array('image_style' => 'thumbnail'))));
    }
}

For some reason, the code does not replace taxonomy term, it just show me messages:

  Notice: Only variables should be passed by reference in include()
  (line 8

What could be the reason? I would be grateful for any advice.

I try dpm:

dpm(render(field_view_field('taxonomy_term', $type['raw']['taxonomy_term'], 'field_marker', array('label'=>'hidden', 'settings' => array('image_style' => 'thumbnail')))));

And it show me this:

I know that there is a module Taxonomy Image I tried to install it, but after activation necessary functionality was not added to my site.

There are multiple ways to do it. The easiest way would be to use views. You can create a view of taxonomy terms with only an image field and display it as a view block.

See an example of view below.

Let me know if you need any help.


How to change redirect after adding node of a particular content type I am currently developing a D7 site.  One content type is a "resource," which is a link to an external site, or uploaded pdf file.  I have a page view to list out all resources (/resource-list/edit ) that allows an admin to see resources broken up by category, reorder them, edit, and delete.

The edit, and delete links were added via views.  I have also added an "Add new resource" button to the header of the view, which properly opens the add resource form in the admin overlay.  However, when the admin submits the new resource, they are redirected to the new node that was created.  Instead, I would like them to be redirected back to /resource-list/edit.  How would one go about changing the redirect only for this content type, and only when triggered from the /resource-list/edit view page?

You can do this with http://drupal.org/project/rules.

Just import this declaration and adjust it to your needs:

{ "rules_redirect" : {
    "LABEL" : "redirect to view",
    "PLUGIN" : "reaction rule",
    "REQUIRES" : [ "rules" ],
    "ON" : [ "node_insert" ],
    "IF" : [
      { "node_is_of_type" : { "node" : [ "node" ], "type" : { "value" : { "page" : "page" } } } }
    ],
    "DO" : [ { "redirect" : { "url" : "path/to/your/view" } } ]
  }
}


Generate match list from two different content type on price basis I have two content type A & B in my application. The content type A have some attributes and a price attribute. The content type B have some other attribute and a price attribute.

Now say A have one item as A1 having price value X. And B has one item B1 that has price value Y.

I need to populate items of content A and B based on following price matching algorithm:

 (y- 20 percent of y) < X < (y+ 20 percent of y)

E.g:

content type A :
items price
A1 - 100
A2 - 200
A3 - 300
A4 - 110

content type B :
    items price
    B1 - 80
    B2 - 100
    B3 - 290
    B4 - 310

Final list :
    A1 - B1, B2
    A2 -
    A3 - B3,B4
    A4 - B1,B2

Can any one suggest me how to archive this in drupal 7.

it could probably be done using Views

  You need Views if

  You like the default front page view, but you find you want to sort it
  differently. You like the default taxonomy/term view, but you find you
  want to sort it differently; for example, alphabetically. You use
  /tracker, but you want to restrict it to posts of a certain type. You
  like the idea of the 'article' module, but it doesn't display articles
  the way you like. You want a way to display a block with the 5 most
  recent posts of some particular type. You want to provide 'unread
  forum posts'. You want a monthly archive similar to the typical
  Movable Type/Wordpress archives that displays a link to the in the
  form of "Month, YYYY (X)" where X is the number of posts that month,
  and displays them in a block. The links lead to a simple list of posts
  for that month. Views can do a lot more than that, but those are some
  of the obvious uses of Views.

and Views PHP

  This module allows the admin account (user 1) to add fields, filters
  and sorts to views which use PHP code. It also supports additional
  accounts when the core PHP Filter module is enabled.

Creating a View limited to those content types, and including the relevant fields - it would allow you to create a Global:PHP sort field, in which you could use your formula to determine the sort order. It would be tricky though, since it appears you want to include duplicates and group them together.


Token replacement pattern is not working I am using Drupal 7, and I have a node reference field in my content type.
I used a token replacement pattern for auto-titling the node, but the token referring the node reference is not working. (The token is [node:field_package_name].)

Please help me.

I dont know what the reason was, but Its working fine, when i disabled the auto_nodetitle and enabled a new module "auto_entitylabel".


Two URL aliases for one node in menu In my case I do not care about crawler penalty.

I have multilingual site with menu. I use Path module for URL aliases. The URL aliases are language-specific.

I need to create two menu items with different URL aliases but both links have to render the same content node. I need to do it only for one particular node with known node id, so any hardcoded/hack solution is welcomed.

UPDATE:
I'm just thinking about such hack solution: I can create some new fake node, set the proper url alias and add menu item for this node. When Drupal is about rendering of this fake node then I'd interrupt the rendering in the code and just render the desired known node.

Is it possible? If so, how can I achieve this?

It sounds like you're looking for NodeSymlinks:

  NodeSymlinks allows you to display the same content to users at
  multiple locations in the Drupal menu system with unique URL path,
  unique navigation breadcrumb and without the SEO penalty that usually
  occurs with multiple copies of the same content.

  This is useful when you want to have the same page reachable though
  multiple menu items, each with its own URL, menu trail and breadcrumb
  path.


Ajax upload in Ctools Modal Window I have node creation form in a popup dialog box. I decided to give it a try using ctools modal window. But I seem to be getting errors when I upload an image into a image field after using browse to select it.

Warning: call_user_func_array() [function.call-user-func-array]: First argument is expected to be a valid callback, 'node_form' was given in drupal_retrieve_form() (line 795 of /var/www/html/test/includes/form.inc).
Notice: Undefined index: #node in comment_form_node_form_alter() (line 1193 of /var/www/html/test/modules/comment/comment.module).
Notice: Trying to get property of non-object in comment_form_node_form_alter() (line 1210 of /var/www/html/test/modules/comment/comment.module).
Notice: Undefined index: #node in menu_form_node_form_alter() (line 629 of /var/www/html/test/modules/menu/menu.module).
Notice: Trying to get property of non-object in menu_form_node_form_alter() (line 629 of /var/www/html/test/modules/menu/menu.module).
Notice: Undefined index: #node in menu_form_node_form_alter() (line 630 of /var/www/html/test/modules/menu/menu.module).
Notice: Trying to get property of non-object in menu_form_node_form_alter() (line 630 of /var/www/html/test/modules/menu/menu.module).
Notice: Undefined index: field_artwork_image in file_ajax_upload() (line 271 of /var/www/html/test/modules/file/file.module).
Notice: Undefined index: #suffix in file_ajax_upload() (line 280 of /var/www/html/test/modules/file/file.module)

Below is my code

function portfolio_cust_node_add_modal_callback($js = FALSE) {
  global $user;

  //If people are not using JS. I just tell them "sorry" it is '2012'
  if (!$js) return "Javascript required";
  ctools_include('node.pages', 'node', '');
  ctools_include('modal');
  ctools_include('ajax');

 // Create a blank node object here.
  $node = (object) array(
    'uid' => $user->uid,
    'name' => (isset($user->name) ? $user->name : ''),
    'type' => 'psuedo_portfolio',
    'language' => LANGUAGE_NONE,
    );

  $form_state = array(
    'title' => t('Add Portfolio'),
    'ajax' => TRUE,
  );
  $form_state['build_info']['args'] = array($node);
  drupal_add_library('system', 'ui.dialog');
  // change this to your type node form
  $output = ctools_modal_form_wrapper('psuedo_portfolio_node_form', $form_state);

  // This means the form has been exectued
  if (!empty($form_state['executed'])) {
    $output = array();
    // Close the modal
    $output[] = ctools_modal_command_dismiss();
  }

  print ajax_render($output);
  exit;

}

I am planning to use colorbox module or some other method which uses a iframe instead of how ctools implements the modal dialog.

Any help will be greatly appreciated.

I faced the same problem, and I managed to solve it using merlinofchaos's suggestion. I used form_load_include() just after form_state initialization:

  $form_state = array(
    'title' => t('Add new deal'),
    'ajax' => TRUE,
    'node' => $node,
  );

  $form_state['build_info']['args'] = isset($form_state['build_info']['args']) ? $form_state['build_info']['args'] : array($node);
  form_load_include($form_state, 'inc', 'node', 'node.pages');


Show a block if the page content has a specific taxonomy term I've got a content type (Brands) and a taxonomy vocab (Product Type) with a few options, so you can "tag" a brand with a specific product type. Using Views I'm filtering my content on my pages depending on the taxonomy term.

I've got a Views block (I'm also using this block as a dropdown in my navigation with the Menu Views module) that lists all the brands tagged with a specific taxonomy term. What I want now is that this block also shows up in my right sidebar on all the pages that display content of 'Brands' and are tagged with a specific term from my taxonomy vocab.

Example (menu structure):

* Product Type A
  - Brand 1
  - Brand 2
  - Brand 3
* Product Type B
  - Brand 2
  - Brand 4
  - Brand 5

If I'm on the 'Brand 1'-page, the 'Brands' list under Product Type A should show up in my right sidebar.

I can't filter using the 'normal' way since its the same content type, and the same taxonony vocab. And by the 'normal' way I mean using a URL pattern for the content type and then use
contenttype/* on my block config page.

Sidenote: I'm also adding a class to my <body> using hook_preprocess_html() for all the brand pages. So all the brands tagged with Product Type A have a class of product-type-a on their <body> field. Is there a way so show/hide blocks depending on a class through code?

Thanks.

You need to add two contextual filters to your view block:

Important: Use this block (override) for all these settings.

Content: Nid

Provide default value: Content ID from URL

More:check: exclude.

This contextual filter will exclude Brand X from the list if you're visiting Brand X page.

Content: Has taxonomy term ID

Provide default value: Taxonomy term ID from URL

check:  Load default filter from node page, that's good for related taxonomy blocks.

When the filter value IS available or a default is provided:

Override title: Type here your block title using %1 for the first argument, %2 for the second, etc.

This contextual filter will list all your brands from current visited Product type


How to execute a migration? I'm trying to use the Migrate API module to implement an ETL for some of the content of my Drupal 8 website, but the documentation doesn't explain how to execute the migration once everything has been set up. It only explains how to execute the migration using some contributed modules but not how to execute it using the Drupal API.

How do I programmatically execute migrations from a module?

Drupal 8 Migrations are plugins. So you can create instance and execute like this:

<?php

use Drupal\migrate\MigrateExecutable;
use Drupal\migrate\MigrateMessage;

$migration_id = 'MIGRATION_ID';
$migration = \Drupal::service('plugin.manager.migration')->createInstance($migration_id);
$executable = new MigrateExecutable($migration, new MigrateMessage());
$executable->import();


How To Show Node Comment Count in node.tpl? I have had the bright idea of changing my user permissions so as guests cannot see the comments on a node. I have no problems with Views around my site, as they can clearly see there are comments on nodes, and they will be more inclined to register. The problem seems to be when they arrive on my site directly to a node, they don't see any comment, and think "that's a bit crap; let's go."

Is there a way I could show the amount of comments below a node?

You can use $comment_count in node.tpl.php.

  $type: Node type, i.e. story, page, blog, etc.
  $comment_count: Number of comments attached to the node.


Breadcrumbs aren't working at all I'm trying to get my breadcrumbs to display in a default site template with panels, but they aren't showing up when I go to view my pages, although everything else is. It also says that they are there in layout designer.  I downloaded custom_breadcrumb module in hopes that it might right something with panels, but no luck.

This is how I'm adding them to my panels;
Add Content > Page Elements > Breadcrumb > save & update

No other settings.  It may also be worth mentioning that I'm using Bear and Aurora base  theme.

What can I do to get these back up?

This problem is related to using blockify, which is a requirement for Aurora. It is fixable with a patch.

There is a full explanation along with the patch here:  https://drupal.org/node/2074249

If you're new to drupal like me and haven't installed a patch before here is a guide with links to a video that explains how to go about doing this:  https://drupal.org/patch/apply


300000+ records user importing problem I’m trying to imports data from vBulletin into Drupal using this dev module vbtodrupal
But because the database is too large I experienced a difficult to import ALL data to drupal DB , I discovered that there is a specific limit to importing  is 300k user  ! I searched in google and found that there was a problem with "300000+ records user"

I hope to help . I did not find the response from the support module :(

For an import of that size you will need to run the import in the background and in steps.

This will use cron to run the feeds cron job. Drupal uses a poor-mans cron so it would be best to setup a cron on the server or use a module like Elysia cron. If you do not not you could try something link https://www.pingdom.com (you can use a free account) to ping your site every e.g. minute to trigger the drupal corn.

I would also make sure that your server is optimal for Drupal 7 and just for the import consider increasing php memory limit and execution timeout value.

Nevertheless I would recommend using a more generic module like "Migrate", though it needs some more work to be done.

I personally imported 23K user profiles into Drupal a few months ago, so it is possible.


How to implement a Rules Action to loop through quantity of a products bought? With the Drupal Commerce module, I created a new product type I use for selling points to my customers. The product has a custom field named “points” (field type integer) where I specify the amount of point to sell.

On checkout I grant the points to the user with this rule, using the Rules module (thanks to Vic, see "How do I sell points using a new product type?):

  Rule Event: on payment completed Action: loop through the order
  line-items. Each line-item has an action to call the next component
  with parameters of order and the line-item.
  Component Parameters:
  order, line-item Condition: data comparison line-item:type is Product
  (to expose line-item:commerce-product) Action: call next component
  with parameters of order and line-item:commerce-product
  Component
  Parameters: order, product Condition: data comparison product:type is
  Product (to expose the product:field-points-to-add) • Action: add
  userpoints, number to add being product:field-points-to-add

The problem comes when the quantity of the products sold is more than 1 because the action loops only through line-item and not through line-item:quantity.

Any suggestion for looping through line-item:quantity?

Consider this Rules Component (in Rules export format, use the Rules UI to import it in your own site):

{ "rules_grant_user_points_multiple_times" : {
    "LABEL" : "Grant user points multiple times",
    "PLUGIN" : "rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules", "userpoints_rules" ],
    "USES VARIABLES" : {
      "points_to_grant" : { "label" : "Points to grant", "type" : "integer" },
      "quantity" : { "label" : "Quantity", "type" : "integer" }
    },
    "DO" : [
      { "data_calc" : {
          "USING" : {
            "input_1" : [ "points-to-grant" ],
            "op" : "*",
            "input_2" : [ "quantity" ]
          },
          "PROVIDE" : { "result" : { "calculated_points" : "Calculated points" } }
        }
      },
      { "userpoints_action_grant_points" : {
          "user" : [ "site:current-user" ],
          "points" : [ "calculated-points" ],
          "tid" : "0",
          "entity" : [ "site:current-user" ],
          "operation" : "Insert",
          "display" : "1",
          "moderate" : "default"
        }
      }
    ]
  }
}

Some more details about this Rules Component:

It uses 2 parameters (both "integer"), i.e.:

Points to grant, which is like your custom field named “points”.
Quantity, which is like your quantity of the products sold.

Rules Actions:

Calculate a new variable (= calculated_points), which is simply a multiplication of the above 2 parameters.
Grant user points for an amount equal to ... euh ... indeed: calculated_points (adapt the details of the actual transaction to fit your needs).

These User Points will be granted to the "current user". Optionally you could just make that yet another parameter for the Rules Component also. I.e. if "current user" is not the customer who bought the quantity of products (which would allow one customer to buy such points for another user should you want to allow that, similar to a gift-card).

With that, all that's left is to finds the right spot in your existing Rules logic (related to checkout), to use the above Rules Component.

Easy, no?


How to upload file in Webform content type I want to be able to upload a file with Webform, is their any way to do this?

Yes you can upload files to webform. Create field for resume by choosing type as file. Check following screenshot


How to print the URL of a title field? I'm trying to print out the url path from the title in my twig template however I haven't been successful so far.

Printing out the title containing the link works fine using:

{{content.title}}

However, I would like to seperate the URL from the title so I can use it in other areas of my twig template. For example:

Example text

I've tried various combinations and suggestions from stackexchange/drupal forums but to no avail. e.g. {{ url }}, {{ uri }} etc.

Any ideas?

If the content that you refer to is a node then you can use the twig path function as follows:

{{ 'Example text'|t }}