How can I create template for specific page in module? I am completely new to drupal, and just started learning.

Here's my issue:

I have created a module, called 'doom'. It has only one form.

I would like to remove all the default elements ( header, footer, sidebar ) and to add custom  elements.

I tried this,

/**
 * Implements hook_theme_registry_alter().
 */
function doom_theme_registry_alter(&$theme_registry) {
    $module_path = drupal_get_path('module', 'doom');
    $template_file_objects = drupal_find_theme_templates($theme_registry, '.tpl.php', $module_path);
    foreach ($template_file_objects as $key => $template_file_object) {
        if (!isset($theme_registry[$key]['theme path']) || !preg_match('#/themes/#', $theme_registry[$key]['theme path'])) {
            $theme_registry[$key]['theme path'] = $module_path;
            $theme_registry[$key] = array_merge($theme_registry[$key], $template_file_object);
            $theme_registry[$key]['type'] = 'module';
        }
    }
}

This code changes all the pages in the site. But I just wanted to customize the template for 'doom' page.  http://example.com/drupal/doom

As I understood, you need something like this:

/**
 * Implements hook_menu().
 */
function doom_menu() {
  $items['doom'] = array(
    'page callback' => 'doom_page_callback',
    'page arguments' => array(),
    'access arguments' => array('access content'),
    'type' => MENU_CALLBACK,
  );
}

/**
 * Implements hook_theme().
 */
function doom_theme() {
  // Get the path to this module and define theme dir.
  $module_path = drupal_get_path('module', 'doom');
  $theme_dir   = $module_path . '/theme';

  // Themable elements. This will look for "sample-template.tpl.php" file
  // in the "YOUR_MODULE_DIR/theme" folder. That file can be anything.
  return array(
    'sample-template' => array(
      'template' => 'sample-template',
      'variables' => array('content' => NULL),
      'path' => $theme_dir,
    ),
  );
}

/**
 * Menu callback.
 */
function doom_page_callback() {
  // Get your template and display ONLY the contents of that file.
  print theme('sample-template', array('content' => t('Optionally, pass dynamic content here.')));
}

And the sample-template.tpl.php file:

<div id="sample-template">
  <?php print $content; ?>
</div>

This should give you the idea. If you still want to theme the HTML header/footer from the front end theme, you should be able to create page--doom.tpl.php file there and customize what is displayed. In that case, just return the output instead of printing it in doom_page_callback().

Hope this helps.


How do I get the current path alias or path? How can I get the current alias and/or path in Drupal 8?

In Drupal 7 I did this with drupal_get_path_alias(). What is the equivalent code I should use in Drupal 8?

Some of the other answers were only correct during previous alpha/beta versions of Drupal 8, or seemed to be incomplete. As of beta7 (and hopefully permanently), the following rules should apply:

For the current raw path (the un-aliased Drupal path):

$current_path = \Drupal::service('path.current')->getPath();

For the current URI, which is pretty-much a direct representation of the request (it may even include a query string):

$current_uri = \Drupal::request()->getRequestUri();

There is of course no guarantee that this $current_uri value will give you an alias, even if one is available for the request, as it only represents what the user has requested. So to strictly do what you are asking about (get alias if available, and path if not) I think you could do:

$current_path = \Drupal::service('path.current')->getPath();
$result = \Drupal::service('path.alias_manager')->getAliasByPath($current_path);

Of course depending on the type of processing you are doing it may be best to be working with routes instead of paths, but I suppose that's a whole other topic.


How to call template when Custom form is submitted? I have created custom form and on submit of that form, I need to fetch data from database and need to display that content in well structured format in different template.

I am able to create form, on submission, I am able to fetch data from database but I am not able to pass that result to another template and display data on that template. I have also tried with

 function nexposed_menu() {
  $items = array();

  $items['form-example'] = array(
    'title' => 'Example Form',
    'description' => 'A form to mess around with.',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('nexposed_form'),
    'access callback' => TRUE
  );
  return $items;
}

function nexposed_form($form, &$form_state) {
  $toppings = array(
    'Jan' => t('Jan'),
    'Feb' => t('Feb'),
    'Mar' => t('Mar')
  );

  $form['month'] = array(
    '#title' => t('Months'),
    '#type' => 'checkboxes',
    '#description' => t('Select the Month'),
    '#options' => $toppings,
  );
  $form['submit_button'] = array(
    '#type' => 'submit',
    '#value' => t('Click Here!'),
  );

  return $form;
}

function nexposed_form_validate($form, &$form_state) {
}

function nexposed_form_submit($form, &$form_state) {
  drupal_set_message(t('Search submitted successfully.'));
  $query = db_select('node', 'node');
  $query = $query->fields('node', array('nid', 'title'));
  $query->condition('node.type', 'events');
  $rows = $query->execute()->fetchAll(PDO::FETCH_ASSOC);

  return theme('event_page', array('data' => $result, 'paging' => $paging));
}

Where $result contains data in the key value pair format, but that template is not called rather no result is displayed.

Any help regarding this is highly appreciated. Thanks in advance.

Please update your _menu function with this code.

  function filterevents_menu() {
  $items = array();

    $items['events-filter'] = array(
        'title' => 'Events Listing',
        'description' => '',
        'page callback' => drupal_get_form,
          'page arguments' => array('filterevents_form'),
        'access callback' => TRUE,
    );
    return $items;
  }

And then clear drupal cache. Hope it will work.

Thanks.


print custom image field for taxonomy page (page--taxonomy.html.twig) template How do I load an image from a taxonomy custom field into a custom location on the taxonomy page template?

It's easy to accomplish it when the image is in a node. The following code works for images, but it doesn't work for taxonomy pages.

    {{ file_url(node.field_reference_background.entity.uri.value) }}

How can I accomplish the same for taxonomy pages?

Only entities from type node are loaded in the page template by default. If you want this for other entity types you have to add custom code to page preprocess:

function mytheme_preprocess_page(&$variables) {
  if (\Drupal::routeMatch()->getRouteName() == 'entity.taxonomy_term.canonical') {
    $term = \Drupal::routeMatch()->getParameter('taxonomy_term');
    $variables['term'] = $term;
  }
}

Then you can access the fields from the term in page--taxonomy.html.twig:

{{ file_url(term.field_image.entity.uri.value) }}


What's the best option for responsive drupal theme using sass, Zen sub-theme or twitter Bootstrap I am going to start a new project using sass but not sure whether I should use twitter bootstrap and start fro scratch or use Zen. Any suggestion on which one to use and why?

In my opinion bootstrap, with bower you can download bootstrap-sass in your theme folder really handy.


Why do all my urls look like 'content/name-of-page' I just installed pathauto module. After installing it the path sticks to 'content/' in front of all the url names.
So how to change the default URL.

Go to /admin/config/search/path/patterns to configure your content types appropriately. I believe the first one acts as a default if you do not define the other paths for content types.


enable field groups programmatically I have created a field groups programmatically using this code:

in *.module file

/**
 * Implements hook_ctools_plugin_api()
 */
 function field_test_module3_ctools_plugin_api($module, $api) {

      if ($module == 'field_group' && $api == 'field_group') {
        return array('version' => 1);
  }
}

in *.field_group.inc

/**
 * Implements hook_field_group_info()
 */

function field_test_module3_field_group_info(){

 $field_groups = array();
 $field_group = new stdClass();
 $field_group->disabled = FALSE; /* Edit this to true to make a default field_group disabled initially */
 $field_group->api_version = 1;
 $field_group->identifier = 'generale|node|field_esempio3|form';
 $field_group->group_name = 'generale';
 $field_group->entity_type = 'node';
 $field_group->bundle = 'field_esempio3';
 $field_group->mode = 'form';
 $field_group->parent_name = '';
 $field_group->data = array(
   'label' => 'Generale',
   'weight' => '2',
   'children' => array(
     0 => 'coverage',
   ),
   'format_type' => 'fieldset',
   'format_settings' => array(
     'formatter' => 'collapsed', //collapsible
     'instance_settings' => array(
       'description' => 'provo a creare un field group',
       'classes' => '', //generale field-group-fieldset
       'required_fields' => 1,
     ),
   ),
 );
 $field_groups['generale|node|field_esempio3|form'] = $field_group;

 return $field_groups;
}

===================================================

Field groups is created but not dysplayed.
Bottom of the page there is a section "Disabled fieldgroups" where it appears

If it's enable there are no problem but I need that fieldgroups is activated automatically.
There is a way to enable this fieldgroups programatically?

Thank you.

You can use the following code.

foreach($field_groups as $field_group){
    ctools_export_crud_enable('field_group',$field_group->identifier);
}


Programmatically get View Custom Text I created a view with a "Custom text" field and want to get this field programmatically in Drupal 8.

I have:

$view = Views::getView('my_view');
$view->execute();
foreach($view->result as $row){
    $node = Node::load($row->nid);
    // Get here the view custom field with label "An example view field".
}

The $row field doesn't have the fields, nor the $node.

A screenshot of the view:

I now have:

$customField = $view->field['nothing'];

customField is an instance of Drupal\views\Plugin\views\field\Custom.

dpm($customField->render($row));

This returns class Drupal\views\Render\ViewsRenderPipelineMarkup with protectecd string with the same markup: {{ title }} test.

Thanks,

You should have something like

//already loaded
$node = $row->_entity;

Best way to get properties easily is probably to inspect variables with xdebug

If it is some king of header/footer, you can get the rendered array this way :

$view = \Drupal\views\Views::getView('Your view');
$view->execute();
/* @var $area \Drupal\views\Plugin\views\area\Text */
$area = reset($view->header); // $view->header['area'] or something else
$rendered = $area->render(); // rendered array

Ok, then :

$view = \Drupal\views\Views::getView('YOUR VIEW');
$view->execute('YOUR DISPLAY ID OR DEFAULT');
$nothing = $view->getHandler('YOUR DISPLAY ID OR DEFAULT','field', 'nothing');
$text = $nothing['alter']['text'];


Allow HTML style attribute for filtred HTML I'm using the Wysiwyg module with CKEditor 3.6.6.2.7696. The HTML attributes is disallowed in HTML text format, so I can't use font-size and text-align.
Any solution please?

go to admin/config/content/formats/filtered_html

In the limit allowed HTML tags, add the tags that you need. You could view source to see what tags are being added when you're trying to font-size and text align and then add them here.

go to:

/admin/config/content/ckeditor/edit/Advanced (for Filter HTML)

Then under Advanced Content Filter, select disabled.


Changing drupal_set_message red or yellow I am looking to change $errors[] = drupal_set_message(t(' Freshwater Shrimp should be a number!'));

Into a red or yellow message at the top of the page. Looking at the doc I should do this in drupal 6

 $errors[] = drupal_set_message(t(' Gammarus (Freshwater Shrimp) should be a number!', 'Warning',));

But I have no luck.

You've put warning as a 2nd argument for function t(). Look carefully at the syntax. It should be an argument to the drupal_set_message function instead:

Wrong:

 $errors[] = drupal_set_message(t(' Gammarus (Freshwater Shrimp) should be a number!', 'Warning',));

Correct:

$errors[] = drupal_set_message(t(' Gammarus (Freshwater Shrimp) should be a number!'), 'warning');


Change entity.field.FieldFormatter for a custom view For an Product entity I’m added custom field "images" // it contains all product images.

To display these images, CustomFieldFormatter is used, it is specified/set on the entity type "manage display" settings page.
So each time the entity is rendered, it uses that CustomFieldFormatter, which display grid of images, with on hover and other effects.

But now I want to create a view to display grid of products (catalog page)
and display only one (first) image of each product entity.

Please, help me find a way to change FieldFormatter for my field when it is shown inside "catalog" view. Or maybe there is some better architecture/solution?

The correct way to implement this, is to use "Display modes":
add custom "Display mode" for entity, and set the another formatter for images field. In the View settings set it to use that "Display mode" to display entity.


Are shared user tables still supported and working? I have tested a Drupal 7 multi-site before, and it worked for me perfectly. With Drupal 8, it doesn't work as expected.

Suppose there are two sites, site1  with site1_ as table prefix and site2 with site2_ as table prefix.
The documentation says that I should add the following lines in the settings.php file.

  'prefix' => array(
     'default'   => 'site2_',
     'users'     => 'shared_',
   ),

It doesn't work because the users table in Drupal 8 doesn't have username and password information.

If I add this lines, Drupal won't work normally too.

  'prefix' => array(
     'default'   => 'site2_',
     'users'     => 'site1_',
     'users_data'     => 'site1_',
     'users_field_data'     => 'site1_',
     'user__user_picture'     => 'site1_',
   ),

For example if a user in site1 changes password, this user cannot login with the new password on site2, but the user can login with the old password once, and sign out; then the new password works!

I expected that the migration path from Drupal 6 to Drupal 8 would support migration of the shared table too, but this doesn't seem to be true. Even reading https://www.drupal.org/node/2551549 and https://www.drupal.org/node/2768219 doesn't help me much.

Are shared user tables still supported and working, on Drupal 8?

Don't.

Per table-sharing is a relict of the past, deprecated and will be removed in Drupal 9. With all the layers on top that dynamically create tables for fields, cache invalidation and so on, this is never going to work.

If you want to have a shared authentication system, then look into an actual single sign on projects.
These are some links to get started; I don't have a lot of experience with either yet.

https://www.phase2technology.com/blog/implementing-cas-single-sign-on-in-drupal-8/
https://dev.acquia.com/blog/drupal-8-module-of-the-week/drupal-8-module-of-the-week-simplesamlphp-authentication/05/04/2016/10246


Assign node to one domain only I've installed domain access module and all its submodules.
I have two domains (both set already) and I would like to assign node to one of these domain only.

I set the proper domain in node edit form, but it really doesn't affect the anonymous user permissions, because ALL users can view this node from all domains.

Devel node access displays on the node page something like below:

I checked user permissions as well and everything looks pretty good there.

How do I configure this module to access node only from the right domain?

--- edit ---

after change suggested in one answer it looks like

In your screenshot above there is a "Send to all Affiliates" checkbox and then checkboxes for each individual domain. If you leave the "Send to all Affiliates" checked it overrides the individual checkboxes.

So, the solution for you is to uncheck the "Send to all Affiliates" checkbox.


Leaflet views how add marker by click? I'm using the module Leaflet and IP Geolocation Views & Maps to display the marker, I need to give the ability to add markers with the mouse click. I'm trying to add a mark on the map Leaflet, with the following code. But for some reason it does not work, if someone can tell what is the reason?

(function ($) {
    $(document).ready (function(){
        $(document).bind('leaflet.feature', function(e, lFeature, feature){
        lFeature.on('click', function(e) {
          var lMap = Drupal.settings.leaflet[0].lMap;
          var marker = lMap.marker(e.latlng).addTo(lMap);
        })
      });
    });
})(jQuery);

I got a solution as follows:

(function($){
    $(document).ready(function(){

    var lMap = Drupal.settings.leaflet[0].lMap;
    lMap.on('click', function(e) {
            marker = new L.marker(e.latlng).addTo(lMap);
    });

    });
})(jQuery);


How do I place connect a template to a certain content type As the questions says, how do I perform this and how do I render certain fields at certain spots placed in the template file?

I already got it so that everything is placed by using

  {{ page.content }}

But how do I do something like:

  {{ field_textblock }}

In where the given input in that field would be display on the site.

I think you could use the "without" filter on the {{ page.content }} as below:

{{ page.content|without(field_textblock) }}

and then you should be able to output "field_textblock" as you were before.

There is a good page about twig filters here https://www.drupal.org/node/2357633


Drush Bootstrap Error on Multi-Site Install I'm getting the "needs a higher bootstrap level to run - you will need to invoke drush from a more functional Drupal environment to run this command." error.

I know this means that Drush is not able to find the settings.php file because it is not in the Drupal root directory. I'm working with one site that is part of a multi-site install on a university server. Am I getting this error because I'm in my site's specific root as opposed to the Drupal core root?

Any help would be much appreciated, Drush seems extremely useful!

Thanks,
Kai

There are several ways to specify which Drupal site Drush will target.  The most basic option is fairly verbose; run:

$ drush --root=/path/to/drupal --uri=http://mysite.com status

You can do the same thing with a slightly different syntax:

$ drush /path/to/drupal#mysite.com status

You can also specify the Drupal site implicitly, by setting the cwd to the folder that contains the settings.php file for your site:

cd /path/to/drupal/sites/default # or /path/to/drupal/sites/mysite.com, as appropriate

$ drush status

In all of the cases above, if settings.php is in a folder called "default", then you do not need to specify the --uri component; you may, for example, cd /path/to/drupal followed by drush status, and the correct Drupal site will be found.  If settings.php is not in a folder named 'default', then you will need to either specify --uri, or cd to the folder that contains the settings.php file.

You might also want to investigate Drush site aliases, which are another way to conveniently specify which site you'd like Drush to target.


How to get search results sorted by language in solr? We have used Apache solr multilingual module for language specific search.
But we want the other language results to be shown below the current language search result.
How we can achieve it using solr?

Is there any module needed or any custom coding require?

Below is the example for displaying search results :-

  If I am currently using site in german and searched for any content
  then german results needs to be appear first and then other language
  content.

You could build your search with the apachesolr_views module (https://www.drupal.org/project/apachesolr_views), allow all languages and then group by language in the view.


Per node field access for paid members? I am setting up a site for a web series. I would like to setup the site so that members can only stream an episode if they have already paid for it. We are using Vimeo PRO to serve our videos, and are using Video Embed Field to display the videos on the site.

If the member has not paid to stream this video, I would like to display a field other than the one with the embed code -- likely a field containing either a banner or a trailer for the show.

I found a video that somewhat outlines how to do this on a node-by-node basis, but I need to restrict access to just a field within the node, and not the entire node.

Is there an optimal way to set up this workflow?

I ended up doing node-based permissions instead of field-based. To set it up, I followed the instruction in the video I linked to originally. I simply created content types for SD and HD streams, and am granting access by user to those. I'm probably going to create a view that will go on my original node that displays if the user has the correct permissions.


How do you add taxonomy with fields to page--node.tpl.php? I am trying to add to my node pages a taxonomy listing that includes fields I've added to the taxonomy. I'm able to add the field from the corresponding note into my page--node.tpl.php file with the following code:

<?php $field_country = field_view_field('node', $node, 'field_country');
     print render($field_country);
?>

Unfortunately this does not output the corresponding field I've attached to the taxonomy, which is an image field that contains a flag for the country.

Is there a way to print this field into page--node.tpl.php using Drupal 7 and no additional modules? It would be very useful to use these fields attached to taxonomy for more than just the taxonomy pages.

Thanks for the help!

This can be done without any need to use php code and tpl.php files.  The capability to generate content based upon a taxonomy including images can be done by using the modules.  These modules are intended to define and implement a site's design and are well written and tested. Template files will handle the layout and appearance of your content, but are not necessary for the content you have described.  IF you are not familiar with Drupal, take a little time to learn more about what it can do before you make changes in the template files.  If you are familiar with Drupal, then it might be helpful to understand more regarding what you are trying to do.


Send out welcome e-mail in users selected language Whenever I create a new user, I want to send a welcome e-mail to the user.
This email is translated in both English and Chinese using the Internationalization module.

But when I check Chinese for a user, it still sends out the email in English.

The only option is to switch to the Chinese interface and then create the user, is there a way that when I select Chinese it will send out the email in that language? Regardless or not the interface is in that language?

This is not a answer but can't fit this to a comment.
From what I see in the source of user.module, the function that fires drupal_mail favors user's preferred language.

3495 function _user_mail_notify($op, $account, $language = NULL) {
3496 // By default, we always notify except for canceled and blocked.
3497 $default_notify = ($op != 'status_canceled' && $op != 'status_blocked');
3498 $notify = variable_get('user_mail_' . $op . '_notify', $default_notify);
3499 if ($notify) {
3500 $params['account'] = $account;
3501 $language = $language ? $language : user_preferred_language($account);
3502 $mail = drupal_mail('user', $op, $account->mail, $language, $params);
3503 if ($op == 'register_pending_approval') {
3504 // If a user registered requiring admin approval, notify the admin, too.
3505 // We use the site default language for this.
3506 drupal_mail('user', 'register_pending_approval_admin', variable_get('site_mail', ini_get('sendmail_from')), language_default(), $params);
3507 }
3508 }
3509 return empty($mail) ? NULL : $mail['result'];
3510 }

Note the $language param defaults to NULL and, in line 3501, if the param is NULL, it will get the user's preferred language. Moreover, none of the function calls has the third argument, so in all cases, user_preferred_language() should be used to determine the language.

So,if you have correctly translated the message, with correct t() function's syntax, message should be translated.

However, rather than translating the entire message, I'd suggest a dirty hook_mail_alter() hack to translate line by line with t() or completely different messages on 2 languages.


How do I modify the HTML of my subtheme? I created a bootstrap subtheme ouf of CDN. Modifying the CSS works, but how do I do it with the HTML? Where do I put new HTML elements? For example: I'd like to add some elements to my footer, make it background color black and have it the width of the screen (it's not by default in Bootstrap)

This is my subtheme folder:

A sub theme inherits its templates from the base theme. When you want to edit templates for your sub theme you simply copy over the desired template from the base theme's template folder into your sub theme's template folder, flush the cache and start editing it.

And then flush the cache again.


if i have no right use the flag "Accepted",please hide it when user have no permission use flag "Accepted",how to hide it instead of when clicking and tell them "you have no permission"?

I found a function on flag.module: function template_preprocess_flag(&$variables) ,

but it seems not a hook to reuse...

I just added this to my sites/all/themes/mytheme/template.php file and it worked after clearing the theme registry:

function mytheme_preprocess_flag(&$variables) {
  // Do something here
  dpm($variables);  // Pretty print $variables if you have the Devel module installed
}

That should give you a nudge in the right direction.


hook_field_formatter_view does not get called I have a custom field, that hooks into profile2 and saves it's value in user data blob. Everything works fine, except the hook_field_formatter_view, that does not get called for a reason. As a result, when the field is viewed, it returns always an empty array. I have all declaration hooks in place.

<?php
 /**
  * Implementation of hook_field_info().
  */
 function profile_cal_field_info() {
  return array(
    'profile_cal' => array(
      'label' => t('Availability calendar'),
      'description' => t('Sets weekly available time.'),
      'default_widget' => 'profile_cal_cal',
      'default_formatter' => 'profile_cal_formatter',
    ),
  );
 }

 /**
 * Implements hook_field_formatter_info().
 */
 function profile_cal_field_formatter_info() {
  return array(
    'profile_cal_formatter' => array(
      'label' => t('Default'),
      'field types' => array('profile_cal'),
    ),
  );
 }

 /**
 * Implements hook_field_widget_info().
 */
 function profile_cal_field_widget_info() {
  return array(
    'profile_cal_cal' => array(
      'label' => t('Availability widget'),
      'field types' => array('profile_cal'),
      'multiple values' => FIELD_BEHAVIOR_DEFAULT,
      'default value' => FIELD_BEHAVIOR_NONE,
    ),
  );
}

 /**
 * Implements hook_field_formatter_view().
 */
 function profile_cal_field_formatter_view($entity_type, $entity, $field,     $instance, $langcode, $items, $display) {
  drupal_set_message('Called!');

  $element = array();

  return $element;
 }

 /**
 * Implements hook_field_is_empty().
 */
 function profile_cal_field_is_empty($item, $field) {
  return FALSE;
 }

 ?>

Your code is correct, I just tested it and it works for me.
I created fresh Drupal instance, created profile_cal module with your code without any modifications then added 'Availability calendar' field to 'Basic page' content type, created a page and got "Called!" message on the screen.


Custom Styles Applying to page.html.twig but not html--front.html.twig I'm new to drupal and am trying to make my own theme. Currently I have a page.html.twig for my pages, and my css styles show up fine. However, when I added a html--front.html.twig file, cleared the caches, and checked the homepage, there were no styles, even ones that apply to elements that are in every page (such as body). The code in html--front.html.twig is identical to the code in page.html.twig. I checked the console and the front page is successfully templating from html--front.html.twig. Every other page works fine. I just don't see why it is now ignoring all my styles for the front page. Here is the code for both pages:

    {{ page.header }}

    {# link is in html.html.twig #}

      {{ page.content }}

The code in html--front.html.twig is identical to the code in page.html.twig

That's your problem - those are two different templates, it doesn't make sense for them to have the same content.

html.html.twig contains (or more accurately, renders) page.html.twig, plus the <head> tags and all that lives within, the footer of the document, and so on. If you copied page.html into html.html, that explains why you don't see styles any more - your <head> is gone.

It's perfectly valid to have html--front.html.twig and page--front.html.twig, or some other combination, but the html template needs to contain the outer part of the document, and the page template needs to contain the inner part.


Pathauto changing drupal_get_path file path Pathauto changed where drupal_get_path looks for an image path I'm calling.

<img src="<?php print drupal_get_path('theme', 'maafs_subpage'); ?>/images/iafe.jpg" alt="Iafe the Network">

This was accessing http://localhost/maafs/sites/all/themes/maafs_subpage/images/iafe.jpg

Now it's trying to access http://localhost/maafs/news/sites/all/themes/maafs_subpage/images/iafe.jpg

Is there a work around for this or is there a better way of getting the path for the image?

Thanks in advance for your help.

Are you accessing this link from a subpage? It would seem that it is not appropriately pulling from the Drupal root when you are making the call (from a page other than the homepage).

You can use the global variable $base_path to get the Drupal root. More information on this global variable: https://api.drupal.org/api/drupal/developer%21globals.php/global/base_path/7


Get media image url in views-view-unformatted template I'm using drupal 8, in my template I created a file named views-view-unformatted--block-12.html.twig and this is it's content:

{% for row in rows %}
  {%
    set body = row.content['#row']._entity.get('body').value|striptags|render
  %}
  {%
    set title = row.content['#row']._entity.get('title').value
  %}

{{ title }}

{{ body|length > 70 ? body|slice(0, 70)|raw ~ '...' : body|raw }}

            Read more

    {{dump(row.field_images)}}
{% endfor %}

I try to dump(row.field_images) but null and dump(file_url(row.content['#row']._entity.get('field_images').value['0']['target_id'])) but url is /id_sample. How do I fix it?

I did with this code row.content['#row']._entity.YOUR_FIELD_NAME.entity.fileuri


Saving the module configuration form data I am using Drupal 7.

I want to create an add-on module for Entity External Rating module.

In that I want to give the form to users where users can select the content types, and based on that selected content type links of twitter and facebook will be displayed.
i.e if I select 'article' content type then facebook and twitter links will be displayed on that content type only.

I have created an admin file and configuration form, but i am not sure where should I store the selected values.

I have added the code  below which will display the form with listing of all the content types.

function entityrating_addone_admin_settings() {
$form['entityrating_addone_content_type'] = array(
        '#type' => 'fieldset',
        '#title' => t('Select content type for Entity Rating'),
        '#description' => t('Define title excluding settings for each content type.'),
        '#collapsible' => TRUE,
        '#collapsed' => FALSE,
);

$node_types = _node_types_build()->names;
foreach ($node_types as $node_type => $node_type_label) {
    $form['entityrating_addone_content_type']['entityrating_addone_content_type_value_' . $node_type] = array(
            '#type' => 'select',
            '#title' => $node_type_label,
            '#default_value' => variable_get('entityrating_addone_content_type_value_' . $node_type, 'none'),
            '#options' => array('none' => t('None'), 'all' => t('All nodes'), 'user' => t('User defined nodes')),
    );
}
return system_settings_form($form);

}

Above code will display the list of all the content type for configuration, but i don't know where to store this values, so i can retrieve while displaying node.

The form elements saved above will all be stored in the variables table.

Are you wanting to move this data or store it somewhere else? If not, then your answer is already in your code with the variable_get() default value.

system_settings_form()

  Add default buttons to a form and set its prefix.

System settings form will store your form data in the variables table and key it with the name of the form element.  For example, a form element defined as $form['foo'] will be retrievable by using variable_get('foo', NULL).  Because of this I always figure it's a good idea to namespace your form elements as you would functions (i.e. $form['mymodule_foo'])


DB Error after upgrading I upgraded a Drupal 6 site to Drupal 7. After upgrading, everything works fine. I had migrated all the content types and content. I am able to view all the content.

When I edit or add a content which contains an image field, I get the following error:

  PDOException: SQLSTATE[42S22]: Column not found: 1054 Unknown column 'field_image_alt' in 'field list': INSERT INTO {field_data_field_image} (entity_type, entity_id, revision_id, bundle, delta, language, field_image_fid, field_image_alt, field_image_title, field_image_width, field_image_height)

I came to know that field_image_alt is not found.

How can I manually add the field? I had run update.php specified in drupal documentation. But still i found that the field is missing. Anyone pls help me to add those fields.??

It looks like your image table field_data_field_image is not having the field_image_alt column. Which is strange, since Drupal creates that by default.

Are you sure you ran update.php after migration? Do that first. If so, then try these steps.

I guess the best thing to do would be installing devel module and then with devel reinstall the image module. (Make backups as you might lose data!)

If that doesn't work you could add the column manually, and hope it was only this column that was off. See the following image for the fields you should have.


Make blog on a subdomain I need some help figuring this out. I have a main site mysite.com on Drupal 7. I want to build a blog for it and want for people to access it using blog.mysite.com. So basically it's the same site (so I can manage content from the same place), just on different URLs.

NOTE*: Individual posts page should show the URL like so: blog.mysite.com/my-post

I was wondering if this can be done using a View under the path name mysite.com/blog and mask the URL somehow to show blog.mysite.com instead. I am using nginx as a webserver.

Sounds like you'll need to use the Domain Access module to get this right. This module allows you to run as many affiliated sites as you need from one single Drupal installation, sharing the same database.

I'm using it for another site at the moment, and it works really well.


How do you replace text surrounded by a custom delimeter with  around it? Overview

I want to have action asterisks in my posts. Basically, asterisks surrounding certain words. Examples: *gasp* or *giggle*

Simple enough. Now I could type that exactly into the editor but it needs to be styled via CSS. This of course calls for span tags.

However, I don't want to have to surround the text with span tags every time. Too tedious. I'll be using this often.

So, how can I make it so Drupal takes some text and replaces it with span tags surrounding it?

In Other Words...

I want to be able to write simple custom tags around text like:

[=gasp=]

and then have Drupal automatically convert it to:

*gasp*

A Possible Solution?

I've been led to the Custom Filter module and this seems closest to what I want. Now, it's already installed but in trying to add a 'rule', the module asks for the 'Pattern' to look for and the 'Replacement text'.

The problem is I am terrible with regular expressions.

Assuming this module is the right path, can someone tell me what to put in these two forms so the filter works? I have been holding this off for months because I was scared to ask for help.

If the Custom Filter module isn't what I need, what is the solution?

On a sidenote

I don't know what's a good custom tag to use. I came up with [=gasp=] but maybe you can recommend something better? Just as long as its short. I already use Markdown and don't want it to conflict with it.

Either way, thanks for any help in advance.

You can use preg_replace as the following in your custom module:

<?php

$string = '[=waves=] words
 words
 words [=jumps in air & rolls in ground=]
words
';
$pattern = '/\[=(.*?)\=]/i';
$replacement = '*$1*';
print preg_replace($pattern, $replacement, $string);

which return:

*waves* words
 words
 words *jumps in air & rolls in ground*
words


mysql_query doesn't work but db_query does on a simple SELECT query I'm receiving the following warnings when I use mysql_query() in my modules:

mysql_query(): A link to the server could not be established in ...... on line 6

If I use db_query() instead, it works fine.

The code is a simple SELECT query with no special characters or variables.
The actual query is mysql_query("SELECT * FROM custom_nodify WHERE nid = 345");

I should mention that this happens with ANY mysql_query(), not just the one above.

Any suggestions as to why this doesn't work?

Just to start with let me very clearly say, never ever use mysql_query unless you really have to (multiple databases with different backends fx).

Why? db_query has a lot of security features built in to help prevent SQL injections, and it makes your site database agnostic (you won't have to change code if you change the database backend) and it allows you to use table prefixes without hardcoding them in the queries.

Anyways the reason why mysql_query doesn't work is because you need to create a connection to the database first using the database credentials, something drupal does automatically for you, when you use db_query.

If you really want to throw away all the good Drupal does for you and use mysql_query anyways, take a look at mysql_connect.


Open the AJAX Login/Register popup when clicking on post titles The AJAX Login/Register module adds a block with a login button. Clicking on that button opens a nice popup login/register dialog.

But how to make the login dialog open when clicking on post titles?

I tried to add a block with this code:

<a href='ajax_register/login/nojs'
   classes='ctools-use-modal ctools-modal-ctools-ajax-register-style'
   rel='nofollow'>
     My Post Title
</a>

However it doesn't work. Anyone knows why?

You simply have a typographic error. Use "class=..." instead of "classes=..."


Views templates: How to print file fields I am creating a template for my table style view. I have several fields most of which are excluded from display. Inside my template I want to print those excluded from display fields. After some search I found that you can access all fields including those excluded by using:

$view->result[$row_count]->

Now the field I want to print is a file. This is the structure that dpm returns me:

  field_field_programme (Array, 1 element)

0 (Array, 2 elements)
    rendered (Array, 3 elements)
        #theme (String, 9 characters ) file_link
        #file (Object) stdClass
            fid (String, 4 characters ) 1011
            display (String, 1 characters ) 1
            description (String, 0 characters )
            uid (String, 1 characters ) 1
            filename (String, 10 characters ) seminar3.pdf
            uri (String, 40 characters ) public://seminaria/programmes/seminar3.pdf
            filemime (String, 15 characters ) application/pdf
            filesize (String, 6 characters ) 218882
            status (String, 1 characters ) 1
            timestamp (String, 10 characters ) 1333973478
            rdf_mapping (Array, 0 elements)
        #access (Boolean) TRUE
    raw (Array, 11 elements)
        fid (String, 4 characters ) 1011
        display (String, 1 characters ) 1
        description (String, 0 characters )
        uid (String, 1 characters ) 1
        filename (String, 10 characters ) seminar3.pdf
        uri (String, 40 characters ) public://seminaria/programmes/seminar3.pdf
        filemime (String, 15 characters ) application/pdf
        filesize (String, 6 characters ) 218882
        status (String, 1 characters ) 1
        timestamp (String, 10 characters ) 1333973478
        rdf_mapping (Array, 0 elements)

It is not as simple as using $field->content. How can I print my file? Do I need to create a link and add the information above? What code can I use so depending on the filemime the icon will change?

In other views I have created the output of files is:

With the information I get from the file I could create such a link. I am guessing length is the filesize? Maybe there is an api function that constructs file links?

Using  this seems to do exactly what I want

<?php print $view->style_plugin->rendered_fields[$row_count]['field_programme']; ?>

which is extremely useful since it can be used even for fields that have been excluded from the display of the view.


Using wget to get the latest module version I was contemplating building a quick bash script to wget all of the modules I use on Drupal sites but every time the module version changes, the link changes.

Take for example the views module. At the time of writing it's at version 7.x-3.0-rc3 and therefore the link is as such http://ftp.drupal.org/files/projects/views-7.x-3.0-rc3.tar.gz

If I were to add this to my bash script it'd obviously stop working as soon as the next version is released.

Is there a URL which I can use with wget which will always give me the latest non dev version of a Drupal module.

[...]drupal.org/projects/views-7.x-stable.tar.gz for example

I don't want to use GIT or CVS etc as this will mean anyone using the script will need to install said program first. I would just like to be able to pass this script around to developers in my office to quickly download and deploy the latest Drupal version and modules we use constantly.

The latest stable is published on an XML file, so your script would need to query and parse it to get the proper URL. http://updates.drupal.org/release-history/project-list/all this returns ALL the projects release history, obviously very large. You can get a specific project with this URL http://updates.drupal.org/release-history/views/7.x where "views" is the project name and "7.x" is the version.

Or you could just use DRUSH. It's super easy to install and will make your life 100x easier and better. Drush is a command line PHP script that allows you to simply type things like drush dl views or drush up views. It can do a lot more too, it's truly amazing. http://drupal.org/project/drush


How can I use LESS in a subtheme in Drupal 6? I have a site with the LESS module installed. The main theme CSS, main.css.less uses @import "lib.less" to define a set of variables that I use for different text colours, etc.

Now, I want to create a sub-theme. This subtheme is identical to the main theme except lib.less contains different colour values for some of the variables. I set it up in the normal Drupal 6 manner. Again, I want to keep the styles, just change the colours by getting the main lib.less to be overriden by my subtheme's lib.less.

When the subtheme pulls in main.css.less from the main theme, it also pulls the main theme's lib.less, even though in my subtheme I have a different lib.less. I have also tried adding this to my subtheme info:

stylesheets[all][] = css/lib.less

To try and get it to recognise the subtheme's LESS variables, but it always brings in the main theme lib.less. Any ideas?

I am looking for a cleaner answer to this as well but I have found I need to create a main.css.less file in the subtheme and copy all the references which use the new subthemes variables (lib.less) and then they work.

Without copying the main.css.less into the subtheme the new variables don't work.

Maybe this is the correct way, but it doesn't feel right to me.


Callback on Bean save? Is there any callback hook like hook_node_insert / hook_node_update when saving a bean block?

Beans use the entity system, so you have a couple options here:

As AyeshK stated, hook_entity_insert and hook_entity_update are the obvious options.

If you need to do something before creating OR updating you can use hook_entity_presave.

Finally, Drupal doesn't have any native hooks that runs after an entity is created/updated, but the Hook Post Action module offers a nice set of additional functions to solve this problem.  If you don't want yet another module dependency, read the module's codebase and figure out how it implements the post-save functionality, then add similar custom code in your own module.


Configuration values in Kernel Test are null I'm trying to write a kernel test for a service in my custom module.
This service depends on certain configuration values that are installed by default when the module is enabled. Values are stored in /config/install/mymodule.settings.yml
If I try to get these configuration values in my test setUp() function, I get the correct value.
However, when the test is running, the same value is null when called from inside the service.
Any idea why?

Turned out to be a very silly mistake...
I instatiated the service before installing the config with $this->installConfig(['mymodule'])


How to create custom form and theme? I am new to drupal and this community. I want to create a form like below.

I write my custom form but my question is how can I show my form table format like columns and rows headers?

There can be already asked question for this too.Can anyone provide me some links or give me some hints.I am using drupal 7.

Thank You.

This is more of a hint since I don't have "comment" privileges yet.
You could create 4 field sets to accommodate the rows. Then create the collected funds and donor fields and when you add fields in each field set, use the respective field rather than create new ones.

So you are then left with html that you can very easily manipulate into having the appearance of being a table.

You would need to position the fieldset label to the left rather than on top and then hide the field labels for all but the first field set (giving it an absolute position and setting the first field to have enough left margin should accommodate this.

Then position the fields by either setting max widths and floating left to keep it responsive or setting the width of the field and the fieldset so that it's not responsive.


Allow file access to specific users in Drupal (not roles) I have historical data recorded in pdf files for our clients. Now I am developing a website (in Drupal) from where clients should be able to access this data. The problem is that i don't want this files to be available to anyone else than the user to whom the information belongs.

Since this data is periodically recorded I could store it in a specific folder for each user.
My question is that if it's possible to give access to this folders or its content to specific users in Drupal. Because the alternative would be to create a Role for every user which is not good.

Create a new content type and add fields according to your
requirement or user reference field
Disable its Front page publish option.
Create new user Role like "client".
Create view of files and add relationship or contentuxal filter
against user loggin id.
Create block view assign this block into specific region.


How to display all media that references this taxonomy term and its immediate children? I have a hierarchical taxonomy vocabulary, "Living Things". A simplified excerpt looks like this:

Plants
--Roses
----Red Rose
----Pink Rose
--Orchids
----White Orchid
----Yellow Orchid

I have a library of media (images and videos) that have a field, "Primary Taxon", which references the appropriate term in that "Living Things" vocabulary. e.g. An image of various roses has its "Primary Taxon" field set to "Roses", and a video of a white orchid has its "Primary Taxon" field set to "White Orchid".

On my taxonomy term pages, how can I display all media that references that species, and that species' immediate children? i.e. The "Roses" page should show media that displays roses in general, as well as red roses and pink roses. The "Plants" page should show media that displays plants in general, as well as roses in general, and orchids in general, but not the individual species.

Ideally, it should also be possible to sort the view with either "this taxon first", or "children first", but I'm interested in any solution without this functionality too.

So far, I have made a view that shows all media on the taxonomy pages. However I can't find an appropriate contextual filter to limit the displayed media. Even a single contextual filter using "Media: Primary Taxon (field_primary_taxon)" stops any media from displaying.

I finally worked this out, using Views (which is a way of querying the database and presenting lists of data). My design places the View as a block on my taxonomy term pages, so I refer to a block display in this method rather than a page display:

BASIC VIEW TO SHOW ALL MEDIA

Structure > Views > Add view

Enter View name and Description
Show Media of type All sorted by Unsorted
Select "Create a block"
Unformatted list of Fields
Adjust "Items per block" as appropriate (e.g. 25)
Save and edit

Scroll down and check all your Media names are listed in the Preview section, to ensure the basic View is working correctly.
FIELDS > Add > Rendered entity (Category: Media).

Here you could alternatively add fields such as Image, Video URL and File rather than the general Rendered entity.
Choose the appropriate View mode > Apply. In my case I had set up a "Preview" display mode in /admin/structure/media/manage/MyMediaType/display, with a thumbnail image format and most fields disabled.

Scroll down to check your media is listed below the names.
Click "Media: Name" > Remove, if you don't want it. It's often unnecessary for media.
Save

CONTEXTUAL FILTER TO SHOW ONLY THIS TERM'S MEDIA

Here we need to make sure that in this block we will only display media that refers to the term whose page the block will be seen on. In this case, that reference is made in a field on my media labelled "Primary Taxon".

ADVANCED > CONTEXTUAL FILTERS > Add
Select "Primary Taxon (field_primary_taxon)" (Category: Media)(or whatever your field is called) > Add and configure contextual filters
WHEN THE FILTER VALUE IS NOT AVAILABLE > Provide default value > Type: Taxonomy term ID from URL > Select (only) "Load default filter from term page" > Apply > Save. We have to supply the value this way because, unlike a page, a block does not have a URL to find the value in.
For testing, find the taxonomy term ID number ("TID") for some of the terms in your vocabulary. You can find these in the URL of the taxonomy term's page. For example my Roses page has URL .../taxonomy/term/86 so the TID is 86. If you have a module such as Pathauto providing URL aliases, then you can find the TIDs by visiting .../admin/structure/taxonomy/manage/MyVocabulary/overview, hovering over "Edit" and looking at the URL at the bottom left of your browser.
In the Preview section, test the View is filtering correctly by entering your different TIDs in the "Preview with contextual filters" box and click "Update preview". For example if I enter 86, I see only media for which I had entered "Roses" in the "Primary Taxon" field.

RELATIONSHIP & CONTEXTUAL FILTER TO SHOW CHILD MEDIA

To list media that refers to children of the term whose page that the block will be seen on, we need to find media whose parent refers to that term. This "reverse thinking" helps with understanding contextual filters; think of the relationship from the thing you're listing, not from the thing you're displaying the list on. My media has no "Parent Taxon" field; that would have been redundant because terms' parents are inherently defined in the hierarchical vocabulary they belong to. This means we can't just add "Parent Taxon" as another simple contextual filter. So we need to extend the range of database tables that Views can query by adding a relationship:

ADVANCED > RELATIONSHIP > Add > Select "Taxonomy term referenced from field_primary_taxon" (Category: Media) > Add and configure relationships > Do not select "Require this relationship" > Apply. This looks at the taxonomy term specified in the media's "Primary Taxon" field and "pulls in" that term's taxonomy information so that Views can query it with our next contextual filter:
ADVANCED > CONTEXTUAL FILTERS > Add. You will see that the list of available filters to choose from is now longer than when we chose the first contextual filter, because of the new relationship.
Select "Parent term" (Category: Taxonomy term) > Add and configure contextual filters
Same as before... WHEN THE FILTER VALUE IS NOT AVAILABLE > Provide default value > Type: Taxonomy term ID from URL > Select (only) "Load default filter from term page" > Apply.
OTHER > Query settings > Select "Contextual filters OR" > Apply > Save. This means results will be listed that pass either the 1st contextual filter OR this 2nd one. Without this, it will filter for media matching both one AND the other, and no results will be displayed.
Note that after this 2nd contextual filter has been added, the view can no longer be previewed below (I don't know why). So we need to place the block on a page...

PLACE THE BLOCK ON THE PAGE

Go to Structure > Block layout > Find appropriate theme(s) (in horizontal sub-menu at the top) and region > Place block > Find your new block > Place block > De-select "Display title" if you want...

We only want our block to show on taxonomy term pages, however in the "Visibility" section there is unfortunately no "Taxonomy term page" listed under "Content type" (I don't know why). So click "Pages" and type /taxonomy/term/* in the box > Save block > Save blocks (at the bottom). This restriction will be applied before URL aliasing, so don't worry if you have a Pathauto alias set for your taxonomy pages.
Visit an appropriate taxonomy term page to check the View works. You may need to refresh the page and/or clear all caches (at .../admin/config/development/performance), especially if you haven't disabled caching.

DISPLAY THIS TERM'S MEDIA BEFORE CHILDREN'S MEDIA

The default order of display of the media is by the "Authored on" time. To display this term's media before child term's media:

Install the Views Argument Order Sort module (there's currently only a development version).
SORT CRITERIA > Add > Select "Multi-item Argument Order" > Add and configure sort criteria > Apply > Save. This put this taxon's media before child taxa's media, whether I selected "Sort ascending" or "Sort descending".
Despite exposing this sort criterion to users to try and allow them to change the sort order, I was unable to get that working. If you know how, please comment.

FURTHER GROUP MEDIA BY TAXON

You can group the media by the term they refer to, with headings:

FIELDS > Add > Primary Taxon > Add and configure fields > Select "Exclude from display" (not necessary but you can still group by this field even if it is hidden like this) > De-select "Link label to the referenced entity" (also not essential) > Apply
FORMAT > Format > Settings > Grouping field Nr.1 > Media: Primary Taxon > Apply > Save > Test the view.

VALIDATION BUG?

In theory, validating the output of the 2 contextual filters as follows is a good idea:

Click the contextual filter > WHEN THE FILTER VALUE IS AVAILABLE OR A DEFAULT IS PROVIDED > Select "Specify validation criteria" > Validator: "Media" > Select only the Media types you wish to show (or none for all of them) > Select "Validate user has access to the Media" > Apply > Save.
However, this validation prevents the view from displaying anything. Please comment if you know why, or if you think this is a bug.

IMPROVEMENT SUGGESTIONS

HEADER > Add > Result summary. This will give you a summary of results at the top of the block, as is standard on a page display.
Select ADVANCED > Other > "Use AJAX" to reduce page refreshes.
In some cases a Table view is useful, rather than unformatted list etc., because you can sort the media by field columns if you add extra fields.
You can add a "Media type" regular filter (not contextual) and expose it to visitors to allow them to show only certain type(s) of media (e.g. Images or videos or both). The Better Exposed Filters module allows the choices to be shown as checkboxes rather than as a drop-down menu, although I have a bug with it (link to follow) at the moment (version 8.x-3.0-alpha3 in Views 8.4.4).
The Views Infinite Scroll module can make for a nice improvement over standard paging if you have a lot of media.

Here is what my View looks like (with the optional Infinite Scroll and AJAX selected):

I have little Drupal experience, so feel free to suggest refinements to this method.


How to get the last updated time stamp of a field in field collection How to get  the last updated time stamp of a field in field collection.Is there any drupal built in function to get the timestamp

There is no timestamp for field collection items. (Drupal 7)


Translate simple code snippet - Get taxonomy term id im following this great podcast which is drupal 5 (i guess).

I want to add a View into my page--taxonomy.tpl.php and get the id of the taxonomy term im currently looking at. Could maybe anybody translate this code snippet for drupal 7?

<?php
$view = views_get_view('taxonomypages');
$display = $view->execute_display('block_1', 2);
print $display['content'];
?>

I figured out that this shows me the view:

$view = views_get_view('taxonomypages');
print $view->preview('block_1',$tids);

but $tids is undefined.
i need to have the current taxonomy term id that im looking at e.g when im at taxonomy/term/12 the id is 12 but $tids is undefined.

I never used "page--taxonomy.tpl.php", but based upon what you want to do, I guess your looking for taxonomy-term.tpl.php.

In Drupal 7, you have a $term variable, from which you can get the tid. Below is some D7 code I've used for a similar purpose, that I adapted a bit to yours. Note that the argument to Views must be in an array.

$view = views_get_view('taxonomypages');
$view->execute_display('panel_pane_1', array($term->tid));
$output = $view->render();

But I do not recommend you proceed down this path. Instead use Panels, and pass the argument to a View that way. Yes, it will require a bit more configuration, but it will also be much more sustainable, easier to maintain, and keep less logic in the template files.

Relevant panels tutorials here.


Use views with the Homebox module Is it possible to use views inside the Homebox module? If so, how?

Yes it is!

You embed blocks into Homebox regions, so just create a block display of your view, and include it into your Homebox on the layout page.

Any disabled blocks will be listed at the bottom, just pick a region for them!


Open poll results in popup / overlay I'm using the Poll module in Drupal core (also using Poll blocks and Ajax poll).

As designed, when I vote I'm taken to the results page, but I'm wondering if it's possible to display the results as a popup on the front page, where the poll block is.

I searched a bit and I know something similar can be done with lightbox2, colorbox, colorbox node, etc., but these solutions require that I assign a class or rel attribute to an anchor tag, and then open whatever URL I enter as a popup. However, the poll calls the results page on clicking the submit button. Is there a way I can change this to accomplish what I need?

Please check answer. I think this may help you toy solve your problem.

ANSWER LINK


Commerce free shipping for orders over €500 I am carrying on with this project where we are supposed to ship for free for orders over €500. I have two rules; Free shipping and NL/BE. I make an address based comparison and role based comparison for NL/BE and amount based in Free shipping. Now, the problem is, when I test if the customer places an order for over €500 and the shipping address is in Belgium, I am still asked whether I want a free shipping or a NL/BE shipping. Obviously this shouldn't happen. What am I doing wrong?

Thanks :)

These are my rules:

{ "commerce_shipping_service_nl_be" : {
    "LABEL" : "Rate NL\/BE",
    "PLUGIN" : "rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "commerce_order", "rules", "commerce_shipping" ],
    "USES VARIABLES" : { "commerce_order" : { "label" : "Order", "type" : "commerce_order" } },
    "IF" : [
      { "commerce_order_compare_address" : {
          "commerce_order" : [ "commerce_order" ],
          "address_field" : "commerce_customer_shipping|commerce_customer_address",
          "address_component" : "country",
          "value" : "BE"
        }
      },
      { "user_has_role" : {
          "account" : [ "site:current-user" ],
          "roles" : { "value" : { "6" : "6" } }
        }
      }
    ],
    "DO" : [
      { "commerce_shipping_service_rate_order" : {
          "shipping_service_name" : "nl_be",
          "commerce_order" : [ "commerce-order" ]
        }
      }
    ]
  }
}
}

and

{ "commerce_shipping_service_free_shipping" : {
    "LABEL" : "Rate Free shipping",
    "PLUGIN" : "rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules", "commerce_shipping" ],
    "USES VARIABLES" : { "commerce_order" : { "type" : "commerce_order", "label" : "Order" } },
    "IF" : [
      { "user_has_role" : {
          "account" : [ "site:current-user" ],
          "roles" : { "value" : { "4" : "4", "6" : "6" } }
        }
      }
    ],
    "DO" : [
      { "commerce_shipping_service_rate_order" : {
          "shipping_service_name" : "free_shipping",
          "commerce_order" : [ "commerce-order" ]
        }
      }
    ]
  }
}

I at last managed to find out. I should have paid more attention to the video I've watched. What I needed to do was add the exact opposite condition to NL/BE rule, that is if the order's total amount is lower than €500.


drupal notification for content type I have a requirement to allow users to subscribe content type. When a new node of the subscribed content type is created, notification mail must be sent. I tried notify module but it only allows to subscribe while registration.

Is there any solution for unsigned users to subscribe a content type?

I'd try to create a rule that's fired when new content is added and when a user is subscribed to it (check this with a condition). Use the 'Send email' action to send an email to the subscribed users.


Editing the navigation menu template in Drupal 8 I'm getting into Drupal with version 8, and trying to wrap my head around the template system.

I've created a theme with classy as a base theme. I would like to edit the markup for the navigation menu, adding two div's before the <ul>. I've copied the menu.html.twig file over from /core/themes/classy/templates/navigation into my-theme/templates/navigation.

I've added to div's right before the ul but they don't appear on the front-end. Is perhaps my template not being loaded? Or what would be the way to do this?

Simply needed to clear the cache... case closed!


drush updatedb for a single module Is it possible to perform a single module's update function via drush? I can see drush updatedb which does not take an modulename as argument and runs all available updates. Then there is drush pm-update wich also checks for new files. the documentation says:

  (same as pm-updatecode + updatedb)

Does this mean if I run drush pm-update every available (newer update_function exits) update will be perfomed? Is there a way to only (db)update exactly one module?

On Drush 5.7 you can run the command drush pm-update --no-core module-name. Drush will automatically backup the current module, download the new version and prompt you to update the database.


Adding a linked table to user profile I have a business case need to add a linked content type or table to a user's profile.  Basically, when they register an account, we want to know the make, model, and year of any recreational vehicles that they own.  I would like them to be able to enter as many vehicles as they currently own, each on their own row.  We will eventually be reporting on this data.  The make, model and year will be drawn from taxonomies, and the table or content type would basically consist of UID, Make, Model, Year.

I'm still relatively new to some of the more advanced features of Drupal, how would I accomplish this?

Sounds like a job for Field Collection:

  Provides a field-collection field, to which any number of fields can be attached.

and Field Collection Table:

  Provides a table formatter for the Field Collection module.


What is the right way to print variables with Twig? I want to know what is the right way to print with Twig.

Example:

node.field_related_articles.entity.get('field_color_theme').value
node.field_related_articles.entity.field_color_theme.value

What is the difference? Which one we should use and why?

Example 2:

When we need to access variables through node.field_something and when with content.field_something in node-something.twig.html?

Example 3:

When we are printing plain text in html like:

"< h4>Related articles< /h4>"

How should we print it with twig right way so that if in future we want multilanguage site we don't need to track all plain text in html to change it?

PHP

->get('field_example') and ->field_example

are the same and so is TWIG

.get('field_example') and .field_example

both get the field object (field item list) from which you can get the field value(s).

This only works for the variable node (or other entities when you are in a different template) and returns the raw values from the database. For example a date field would return a unix timestamp.

In contrast the content variable contains formatted data ready to be rendered. A date field would be rendered as configured in the content type in a human readable format.

So the answer is, you print variables by using content:

{{ content.field_example }}

Use node only when you need to process the raw data in some way where the formatted output won't work, like for example if you compare two dates you want to use a unix time stamp and not the formatted output.

Both methods are language aware, so there shouldn't be any problem from this side.

If you want to translate static text in twig use the |t filter:

<h4>{{ 'Related articles'|t }}</h4>


Display several user blog entries at once I use Blog 7.7 core module to display site updates at http://preferans.de/blog/1

However only 1 news item is always displayed at that link.

Is there maybe a way to change that amount?

I've tried looking around, including admin/content/book/settings

you can create a "view" to display a list of blogs. In Views you can specify how to layout those blogs, how many to show, in what order, etc.
NoneOne has a great screencast about learning views


Why view is not firing hook_views_query_alter? I'm using Commerce Kickstart 2 and I want to modify the query of the included view collection_products.

As a start, I've added a mymodule_views.inc file with this code:

function jch_utilities_views_query_alter(&$view, &$query) {
  dpm($view->name);
  if ($view->name == 'collection_products') {
    // my code goes here;
  }
}

dpm() fires for 3 times for each view on the page, but not for the collection_products view. Obviously, hook_views_query_alter() is firing, but why isn't that view showing up?

Just to be clear: The view / page display renders fine.

I saw this issue and I wonder if it applies.

Is there another way to modify the query?

Please read hook_views_query_alter() API, which say:

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

So double check that you're placing the hook in the correct place either in the main module file or MODULENAME.views.inc (not mymodule_views.inc) and make sure that you've MODULENAME_views_api function defined (unless it's already defined by Feature). After all that clear your all caches (including memcached if in it's in use).

See also: How do I use hook_views_query_alter()?

If there is still a problem, that means your view is implementing different query handler and possibly it implements views_plugin_query (which by default doesn't provide any alter code), so you have to find the right plugin query handler (a query class) and see which hooks they're using instead.

To find which plugin is in use.

Method 1: If view is already exported, check base_table name and which module is dealing with that table. If it's search_api_, then it's Search API module.

Method 2: Edit views/includes/view.inc, find the code which executes the query alter: $this->query->alter($this); and dump the $this->query object to see what class is used for that view.

Then find that class and its alter() method to see how it's implemented.

Here are few examples:

Views (class views_plugin_query_default extends views_plugin_query):

function alter(&$view) {
  foreach (module_implements('views_query_alter') as $module) {
    $function = $module . '_views_query_alter';
    $function($view, $this);
  }
}

Search API (class SearchApiViewsQuery extends views_plugin_query):

public function alter(&$view) {
  parent::alter($view);
  drupal_alter('search_api_views_query', $view, $this);
}

YQL Views (class yql_views_query_plugin_query_yql extends views_plugin_query):

function alter(&$view) {
  foreach (module_implements('yql_views_query_query_alter') as $module) {
    $function = $module . '_yql_views_query_query_alter';
    $function($view, $this);
  }
}

So as you can see, you need to use different hooks for different views types.

In your particular case collection_products views is handled by Search API, so you need to define hook_search_api_views_query_alter instead.


How to do core update with drush With which drush command can I update my Drupal 7.36 to 7.41?

I have tried so far the followings:

drush up drupal
drush pm-updatecode

But nothings has changed in either the code nor when I look at the currently pending updates.

Adi provided a good answer. So update the code with:

drush up drupal

But after that always preform database updates (if required):

drush updb


What's the best way to include PHP in nodes? We're converting some sites over to a Drupal 6 multi site and we have a number of existing pages that make heavy use of PHP.

What's the easiest way to include these scripts, assuming that they may want to live in different menus in different languages, and that we want these pages to also work like other pages on our site (e.g. take advantage of Rules, Views, CCK etc).

Using hook_menu() to create a MENU_CALLBACK seems to mean we couldn't
treat them like other pages (have people edit titles/content, use
Views/Rules etc).
Using hook_nodeapi() to add the PHP only works if it is always at the end (or beginning) of any content.
Using the PHP filter to include a file works, but means editors would need the right to use PHP.

The solution I'm leaning towards is creating a custom filter that replaces a keyword/token with a file/function so editors would add {{FOO_SCRIPT}} to their page and the relevant code would get included.

Is there a better way?

Normally I do heavy php lifting on nodes in hook_preprocess_node(&$vars) and parse / include content in the $vars.

hook_nodeapi() is of course another way to go about it and your additional content will be available in many different $operations, I don't use hook_nodeapi() unless I'm altering data that gets saved, deleted etc within nodes - for display layer stuff hook_preprocess_node() always treats me well.

If you could expand on what sort of preprocessing and content you are including in nodes I'm sure we could go into more details into the best suited solution :)

Update: Given the variety of the tasks you aim to use (APIs, Additional DB Calls, or User Input Parsing etc), I'd definately recommend you use hook_nodeapi so you have the fine grained control over the context. preprocess is view layer only and I feel as though you will likely want to hook the nodeapi(&$node, $op = 'load') so as to make your data entries high level enough to have the information widely accessible (like $node->your_custom_api_field in a node.tpl.php)

I highly recommend that you try to stay with Drupal's conventions as much as possible. Using database functions etc. Checkout the http://drupal.org/project/data module and possibly http://drupal.org/project/schema which both help working with your own tables (and the data module even helps expose that table to views so you can stay with Drupal core more!)

p.s.

My advice is to create a custom module for each data module you have so it can have it use it's own hook_nodeapi and any other hook's that may be required :)


Get value of programmatically (form_alter) added fields at form submit I'm altering a node creation form using the form_alter hook in a custom module. In this particular case, I'm adding an email field which is not part of the content type structure. At the node creation, I need to send an email to the address entered in the field.
Using the hook entity_presave or entity_insert I have access to the entity field that are part of its structure, but not to the programmatically added email field. How can I get that value at the form submit?

A field added in the form_alter hook is not created on the entity. Therefore you cannot retrieve the value in either hook_entity_presave or hook_entity_insert.

What you want however you can do by creating an additional submit handler for the form.

function _MODULE_NAME_custom_submit_handler($form, FormStateInterface $form_state) {
  $email = $form_state->getValue('email_field_name');
  // send email.
}

You can also get the saved entity (which does not have the email field) using $form_state->getFormObject();


How to print user role in body profile page I've got two roles in my website and I'd like to print the role name in the user profile page body classes for the user being viewed. How can I do this?

The html.tpl.php template uses the $classes variable to add classes to the body element. You can use template_preprocess_html() to add classes to this variable. Add this function to your theme's template.php

//Replace MYTHEME with the name of your theme
function MYTHEME_preprocess_html(&$variables) {

  //Check if the path is a profile page with a valid user
  if(preg_match('/^user\/(\d+)/', current_path(), $matches) == 1) {
    if($user = user_load($matches[1])) {

      //Add each role to the $classes_array which makes it available in $classes
      foreach($user->roles as $rid => $role) {
        $variables['classes_array'][] = str_replace(' ', '-', $role);
      }
    }
  }
}


How do I access field data in Twig? I have a list field for a custom block type that looks like this:

left|Align left
right|Align right

I can access the key in Twig by doing something like this:

{% block content %}
  {{ content.field_align }}  {# outputs 'right' #}
{% endblock %}

However, if I do a simple comparison, it outputs FALSE.

{{ kint(content.field_align == 'right') }}

The following code returns TRUE.

{{ kint(content.field_align['#items'].getValue()|first.value == 'right') }}

Is there a shorter version for getting the "real" string so I can use Twigs string filters and keep it tidy?

content contains the render arrays based on the configured formatters.

If you want to access the actual values, you want to access them through the entity object. Usually, that is available already to your template, for example node. For your case, it is a bit special because the block_content is rendered in the block content without its own template, so you have to make it available yourself in a yourtheme_preprocess_block($variables) like this:

if (isset($variables['elements']['content']['#block_content'])) {
  $variables['block_content'] = $variables['elements']['content']['#block_content'];
}

Then, you can access a field value with block_content.field_name.property. So in your case, block_content.field_align.value. The property is value for most field types, for references, you can either use target_id for the ID or entity for the referenced entity object. Yes, you can directly access fields on that, but make sure to always check that a reference exists otherwise you can end up with fatal errors or exceptions. To access the label of a term reference for example, you can access it as block_content.field_tags.entity.name.value.

If you don't specify the field delta, it defaults to the first. If you want to access a different delta, you can use entity.field_name.1.valueand so on. You can also loop over them.

This all maps directly to PHP, you can also do $block_content->field_tags->entity->name->value in preprocess and other places where you have the block_content.


How does module_enable works in Drush? I'm trying to automatize an install of CiviCRM and Drupal, but I'm getting so many errors! (Using PHP 7, Drush 8, Drupal 7, CiviCRM 4.7.18)

CiviCRM has a Drush extension, which calls function module_enable(array('civicrm'))

However, Drush 8 (which says is compatible with D6, D7 and D8) throws Undefined function.

I would like to know if I should downgrade my Drush 8 or what?
Can I fix this error in some way?

These are the errors I get.

Error: Call to undefined function module_enable() in drush_civicrm_install() (line 367 of /root/.drush/civicrm.drush.inc) #0               [error]
phar:///usr/local/bin/drush/includes/command.inc(422): drush_civicrm_install()
#1 phar:///usr/local/bin/drush/includes/command.inc(231): _drush_invoke_hooks(Array, Array)
#2 phar:///usr/local/bin/drush/includes/command.inc(199): drush_command()
#3 phar:///usr/local/bin/drush/lib/Drush/Boot/BaseBoot.php(67): drush_dispatch(Array)
#4 phar:///usr/local/bin/drush/includes/preflight.inc(66): Drush\Boot\BaseBoot->bootstrap_and_dispatch()
#5 phar:///usr/local/bin/drush/includes/startup.inc(458): drush_main()
#6 phar:///usr/local/bin/drush/includes/startup.inc(365): drush_run_main(false, '/', 'Phar detected. ...')
#7 phar:///usr/local/bin/drush/drush(114): drush_startup(Array)
#8 /usr/local/bin/drush(10): require('phar:///usr/loc...')
#9 {main}.
Error: Call to undefined function module_enable() in /root/.drush/civicrm.drush.inc on line 367 #0 phar:///usr/local/bin/drush/includes/command.inc(422): drush_civicrm_install()
#1 phar:///usr/local/bin/drush/includes/command.inc(231): _drush_invoke_hooks(Array, Array)
#2 phar:///usr/local/bin/drush/includes/command.inc(199): drush_command()
#3 phar:///usr/local/bin/drush/lib/Drush/Boot/BaseBoot.php(67): drush_dispatch(Array)
#4 phar:///usr/local/bin/drush/includes/preflight.inc(66): Drush\Boot\BaseBoot->bootstrap_and_dispatch()
#5 phar:///usr/local/bin/drush/includes/startup.inc(458): drush_main()
#6 phar:///usr/local/bin/drush/includes/startup.inc(365): drush_run_main(false, '/', 'Phar detected. ...')
#7 phar:///usr/local/bin/drush/drush(114): drush_startup(Array)
#8 /usr/local/bin/drush(10): require('phar:///usr/loc...')
#9 {main}
Error: Call to undefined function module_enable() in drush_civicrm_install() (line 367 of /root/.drush/civicrm.drush.inc).
Drush command terminated abnormally due to an unrecoverable error.

Changing it to drush_module_enable() ends in another error:

Drupal\Core\Extension\MissingDependencyException: Unable to install modules civicrm due to missing modules civicrm. in                     [error]
/opt/compucorp/core/lib/Drupal/Core/Extension/ModuleInstaller.php:85
Stack trace:
#0 /opt/compucorp/core/lib/Drupal/Core/ProxyClass/Extension/ModuleInstaller.php(83): Drupal\Core\Extension\ModuleInstaller->install(Array,
true)
#1 phar:///usr/local/bin/drush/commands/core/drupal/environment.inc(131): Drupal\Core\ProxyClass\Extension\ModuleInstaller->install(Array,
true)
#2 phar:///usr/local/bin/drush/commands/core/drupal/environment.inc(198): drush_module_install(Array)
#3 /root/.drush/civicrm.drush.inc(367): drush_module_enable(Array)
#4 phar:///usr/local/bin/drush/includes/command.inc(422): drush_civicrm_install()
#5 phar:///usr/local/bin/drush/includes/command.inc(231): _drush_invoke_hooks(Array, Array)
#6 phar:///usr/local/bin/drush/includes/command.inc(199): drush_command()
#7 phar:///usr/local/bin/drush/lib/Drush/Boot/BaseBoot.php(67): drush_dispatch(Array)
#8 phar:///usr/local/bin/drush/includes/preflight.inc(66): Drush\Boot\BaseBoot->bootstrap_and_dispatch()
#9 phar:///usr/local/bin/drush/includes/startup.inc(458): drush_main()
#10 phar:///usr/local/bin/drush/includes/startup.inc(365): drush_run_main(false, '/', 'Phar detected. ...')
#11 phar:///usr/local/bin/drush/drush(114): drush_startup(Array)
#12 /usr/local/bin/drush(10): require('phar:///usr/loc...')
#13 {main}

module_enable is a Drupal 7 function - it would seem you're not running this command on a drupal 7 site.

Downgrading Drush won't have any effect, if you want to use this extension with Drupal 8 the code will need to be updated to satisfy the new API.

The new equivalent is:

\Drupal::moduleHandler()->enable(['civicrm']);


missing cet_enable field in product type settings (Commerce Event Ticket) I have installed the Commerce Event Ticket module along with any requirements and have enabled it. I see the following under column description in  admin/modules:

  Allows tickets (with unique barcodes) to be generated for Commerce purchases.

  Version: 7.x-1.0-beta3

  Requires: Entity API (enabled), Commerce (enabled), System (enabled), Rules
  (enabled), Entity tokens (enabled), Product (enabled), Price (enabled), Customer (enabled), Address Field (enabled), Chaos tools (enabled), Line Item (enabled), Order (enabled), Commerce UI (enabled), Checkout (enabled), Cart (enabled), Product Pricing (enabled), Product Reference (enabled), Options (enabled), Field (enabled), Field SQL storage (enabled), Views (enabled), Order UI (enabled), Field UI (enabled), Product UI (enabled), Customer UI (enabled), Views Bulk Operations (enabled)

  Required by: Commerce Event Ticket PDF (disabled), Commerce Event Ticket Mail (disabled), Commerce Event Ticket Services (disabled)

Now, when I add a new product type (commerce/products/types/add) or go to Manage Fields of an existing product type, I do not get an existing field cet_enable. The list of available existing fields in the list box only contains:

<select class="field-select form-select" id="edit-fields-add-existing-field-field-name" name="fields[_add_existing_field][field_name]">
<option value="" selected="selected">- Select an existing field -</option>
<option value="field_link_to_page">Boolean: field_link_to_page (Link to page)</option>
<option value="field_date">Date: field_date (Date)</option>
<option value="field_eventdate">Date: field_eventdate (Date)</option>
<option value="field_price">Float: field_price (Price)</option>
<option value="field_image">Image: field_image (Image)</option>
<option value="field_img">Image: field_img (Image Gallery)</option>
<option value="field_myimage">Image: field_myimage (MyImage)</option>
<option value="uc_catalog_image">Image: uc_catalog_image (Image)</option>
<option value="uc_product_image">Image: uc_product_image (Image)</option>
<option value="field_table_description">Long text: field_table_description (Event Description)</option>
<option value="field_product_reference">Product reference: field_product_reference (Product reference)</option>
<option value="field_tags">Term reference: field_tags (Tags)</option>
<option value="taxonomy_catalog">Term reference: taxonomy_catalog (Catalog)</option>
<option value="field_external_link">Text: field_external_link (External link (leave empty for no link or use abov...</option></select>

How do I get access to the cet_enable field?
This is after a core update to 7.34

I've filed a bug with the module but am also interested in how I can troubleshoot this best myself???
Thanks for hints and tips!

Could this be related to some type of permission that is still missing? Also, consider adding a LINK in your question to point to the issue you created (it may help to further enhance this question also).

Did you receive any eMails by using this module?


How do i change the visibility of an existing block programmatically? How do i change the visibility of an existing block programmatically?

I created the block using yml, here's the configuration:

uuid: 67105709-2648-445e-9ddd-8b830a854d8d
langcode: en
status: true
dependencies:
  module:
    - pixelpin_openid_connect
    - system
  theme:
    - bartik
id: openidconnectlogin
theme: bartik
region: content
weight: 0
provider: null
plugin: pixelpin_openid_connect_login
settings:
  id: pixelpin_openid_connect_login
  label: 'PixelPin OpenID Connect Login'
  provider: pixelpin_openid_connect
  label_display: visible
visibility:
  request_path:
    id: request_path
    pages: /user/login
    negate: false
    context_mapping: {  }

The block visibility will change depending on whether a checkbox is checked so i cannot modify the existing block using yml (if that's even possible) unless you can call it in code.

You can load the block and modify the visibility settings:

$block = \Drupal\block\Entity\Block::load('openidconnectlogin');
$visibility = $block->getVisibility();
if (isset($visibility['request_path']['pages'])) {
  $visibility['request_path']['pages'] = '/new/path';
  $block->setVisibilityConfig('request_path', $visibility['request_path']);
  $block->save();
}


Why does my site fail after restoring the database? I tried migrating my Drupal live site to localhost to test it there. I followed the instructions in Migrating a site.

Cleared the cache
Disabled clean URLs
Enabled mod_rewrite

Then I backuped my live site database. On my localhost, I created a database with the same name as my live site and ran a clean install of Drupal 7.25. Everything worked. I installed the Backup and migrate module, and tried to download the database; after submitting the form, the local site simply became blank and I could not access it.

I checked the local database and found that the backup database was properly copied into it. So, probably, the issue is not with the database access permissions on localhost.

I cannot figure out what causes the local site to fail.

What are the possible reasons for such a failure?

I found the reason of mistake. I accidentally put Entity module into the core and it generated WSOD when I tried to restore the database on my localhost. You should never put contributed modules into core modules folder.


How to add a taxonomy term value as a class? I am trying to target a specific div with CSS. But for that, I need a unique class in order to target a specific taxonomy term. I look at this question, but that doesn't work as it will target all taxonomy terms.

I have created a vocabulary called 'Titles' which has the following terms in it:

Which will display the following in my browser:

Note that I am not using a view to display these titles. Instead, I used a preprocess function:

function MYTHEME_preprocess_node(&$variables) {
  $variables['authortitle'] = \Drupal::entityTypeManager()->getViewBuilder('user')->view($variables['node']->getOwner(), 'nodetitle');
}

How can I add "Writer" as a class to the <a> tag?

To append a term's name as CSS class to the term field itself you could simply implement template_preprocess_field() like so:

use Drupal\taxonomy\Entity\Term;
use Drupal\Component\Utility\Html;

/**
 * Implements template_preprocess_field().
 */
function MYTHEME_preprocess_field(&$variables) {

  if ($variables['field_name'] == 'field_MYFIELD') {

    if (!$variables['element']['#items']->isEmpty()) {

      // Get the term ID.
      $tid = $variables['element']['#items']->getValue()[0]['target_id'];

      // Load the term.
      $term = Term::load($tid);

      // Get the term name.
      $name = $term->getName();

      // Make the term name safe to be used as CSS class.
      $name_safe = strtolower(Html::cleanCssIdentifier($name));

      // Append class.
      $variables['attributes']['class'][] = $name_safe;
    };
  }
}


how to use panel to display content types but using condition? I have two content types.

Liquor product which have fields [Title, origin, effects, side effects, price, how to drink, etc.. ]
Liquor store fields are [store name, address, contact no.]
I am used panel to display Liquor content.I want to display all content of liqour if they have in store.
For e.g If I am click on absolute vodka then panel display absolute vodka info comes(i.e Title, origin, effects, side effects...) but now i want add condition show all stores which have absolute vodka

How to do this?

Create two blocks in Views, one that shows the Liquor info with a contextual filter of the nid, then a second block that lists stores again with contextual filter and a relationship to the nid of the liquor (with whatever field you are using to relate the store to the liquor).

Once your Views blocks are in place, you can then add them into your panel using the Content tab, then selecting the Content cogwheel on left top corner, then select Add Content, then in the dialog box look under Miscellaneous, you will see your Views blocks listed, add them and you're done!


Is it possible to force your module's update hook to run? I am the author of the Date iCal module, and the new major version I'm working on (3.x) requires a two-part schema update for users who had 2.x installed. I've written the update hook that makes these changes, but if one of my users fails to run the database update script, they will get an error message relating to their iCal feeds importers.

The right solution is for them to run the update script... but if they just go in and manually change their importers to get rid of the message, their importers will remain permanently broken (because the second part of the schema update won't have been executed).

So is there any way to display a message to users who haven't run the update? Or somehow forcibly execute the update hook the first time a page load occurs when 3.x gets installed overtop of 2.x?

There are few ways of forcing module update.

Calling the update function directly.

$sandbox = [];
module_load_include('install', 'FOO');
FOO_update_7001($sandbox);

Resetting the schema version to the point of interest and run the updates again as usual.

drupal_set_installed_schema_version('module_name', '7000');

Or reset to re-run only the latest update schema:

drupal_set_installed_schema_version('foo', drupal_get_installed_schema_version('foo') - 1);

Notes:

This can be placed in hook_install, so during the update process all sequent update hooks would be executed.
In order to use this function outside of the installation file, you've to include Drupal install.inc first and installation file of the module, e.g.

require_once DRUPAL_ROOT . '/includes/install.inc';
module_load_include('install', 'foo');

Consider adding ini_set('max_execution_time', 0); for longer installation updates to prevent PHP timeouts.

Using drush. Find below few examples:

drush eval 'module_load_include('install', 'foo'); $s = []; foo_update_7001($s);'
drush sqlq "UPDATE system SET schema_version = 7000 WHERE name = 'foo'" && drush -y updb


How does forum determine new replies for each user? When I visit drupal.org/forum/*, in Replies column I can see how many new posts have been added. Drupal also marks them with a New tag.

I'm wondering how does drupal determine which replies are new for me? Are they new since my last visit to the page, or my last logout from drupal.org? In case the later is correct, how does drupal know when I loggeout out last time?

I'm very interested to know what algorithm is behind this nice feature?

Drupal has a history table to record when any user viewed any node.

So it knows when you last viewed the node, and which comments have newer timestamps. So it marks those comments with newer timestamps as new or updated.

UPDATE: There is also a constant NODE_NEW_LIMIT set in the node.module file which defaults to 30 days ago. That means nodes changed before 30 days are always marked as read.


Responsive MainMenu for D7 I am struggling with Drupal menu. Currently my menu is not responsive. I know how to change it to become responsive using CSS. But I am wondering If there is any module that can do this easily.

Please give any menu module if available to be responsive and adaptive to different screen sizes or suggest me if there are any simple tweaks.

This is hard to answer, because it depends very much on how your menu is designed and which navigation method you're going to use.

There's a sandbox project for the omega theme though.

Maybe this will help as well: Complex Navigation Patterns for Responsive Design


How to override menu Item? I am using entity_translation module for translating node titles. And with this Translate tab appears on node view like in screenshot.

I am trying to override titles and access permissions for this menu tab and found that its coded in /sites/all/modules/entity_translation/entity_translation.node.inc like below:

/**
 * Node-specific menu alterations.
 */
function entity_translation_node_menu_alter(&$items, $backup) {
  if (isset($backup['node'])) {
    $item = $backup['node'];
    // Preserve the menu router item defined by other modules.
    $callback['page callback'] = $item['page callback'];
    $callback['file'] = $item['file'];
    $callback['module'] = $item['module'];
    $access_arguments = array_merge(array(1, $item['access callback']), $item['access arguments']);
  }
  else {
    $callback = FALSE;
    $access_arguments = array(1);
  }

  $items['node/%node/translate']['page callback'] = 'entity_translation_overview';
  $items['node/%node/translate']['page arguments'] = array('node', 1, $callback);
  $items['node/%node/translate']['access arguments'] = $access_arguments;
  $items['node/%node/translate']['access callback'] = 'entity_translation_node_tab_access';
  $items['node/%node/translate']['file'] = 'entity_translation.admin.inc';
  $items['node/%node/translate']['module'] = 'entity_translation';
}

In my custom module I tried overriding like this:

function my_module_node_menu_alter(&$items, $backup) {
  $items['node/%node/translate']['title'] = "My New Title";
  $items['node/%node/translate']['access callback'] = 'my_module_transaltion_access';

}

function my_module_transaltion_access(){
   // code for my permissions according to user roles.
}

But I am not able to alter this menu item. Please suggest what is right way to do this ?

UPDATE:

function my_module_menu_alter(&$menu,&$items) {

   $items['node/%node/translate']['access callback'] = "my_module_transaltion_access";
}

function my_module_implements_alter(&$implementations, $hook) {
  switch ($hook) {
    case 'menu_alter':

      // Move some of our hook implementations to the end of the list.
      $group = $implementations['my_module'];
      unset($implementations['my_module']);
      $implementations['my_module'] = $group;
      break;
  }
}

Thanks!

Try hook_menu_alter() to alter the menu,  https://api.drupal.org/api/drupal/modules%21system%21system.api.php/function/hook_menu_alter/7.

Moreover, entity_translation_node_menu_alter() is not a hook and it is a function called from entity_translation_menu_alter().


Managing multiple versions of files on nodes The client needs to be able to upload numerous files to each node. They would like only the new versions of files to be searchable/in the search results and for the previous document versions to be versioned, available on the page but not searchable.

I was thinking of adding a file field type to the content type with unlimited number of values. But I cannot figure out a way to disable the search from searching through the previous version.

Any tips on how to do this would be greatly appreciated.

You could try either Revision All

  Revision All allows for centralized management of content type
  revisioning. Revisioning can be turned on/off individually by type or
  enabled for all simultaneously. There is also support for enabling
  automatic revisioning of future content types and the disabling of the
  "create new revision" checkbox on node and/or content type forms.

or Document modules

  A Document Management System for Drupal.

Features:

Complete integration with Drupal node system. This module adds a custom Node Type, Document. Each Document you create is a Drupal node, and hence enjoys all features available to a node.
Support for Document revisions/versioning - This module allows you to maintain multiple versions/revisions of the same document.
Views 2 Integration - The custom fields added by the module to the Document node type are accessible in Views, plus the module provides some useful out-of-the box Views.
Theming support
Searching - The documents being nodes are fully indexable by the Drupal search system. In addition, the module provides its own custom search for Documents.
A couple of blocks are available for document search that can be placed flexibly in your theme layout.


text input in datepicker how can i add some default text in my datepicker ? I want to add text in the box.

Edit you field in Manage fields section of your content type and set default value for that date field.