Go to the content types page on admin/structure/types, click on "Manage display," and drag the field to the "Hidden" set.

For D6

You can do the same in node-type/<type>/display. Click exclude/ make the select box to hidden.

Also you can use this code in node.tpl.php.

if ($teaser) {
  // node is being displayed as a teaser
  // Anything here will show up when the teaser of the post is viewed in your taxonomies or front page
} else {
  //all other cases
  //Anything here will show up when viewing your post at any other time, e.g. previews
}


We've been through the same scenario as you in our company, and currently we've ended up with a situation where we work on a remote development server and have our code locally via sshfs mounts. It works pretty well, you can read more about it in this blog post I wrote.

You can't use graphical clients (e.g. gitx or gitl) so we use git and drush on the commandline, but that actually made people more aware of how those tools works rather than just clicking the same buttons every time.

On a different note, you should also use memcached so your cache doesn't get shared via cache tables in the shared database. It's pretty simple to setup and after that just make sure every developer has a unique memcache prefix.


A peek in the code reveals that the macro builder registers the path map/macro.

function gmap_macro_builder_menu() {
  $items['map/macro'] = array(
    'type' => MENU_NORMAL_ITEM,
    'title' => 'Build a GMap macro',
    'access arguments' => array('create gmap macro'),
    'page callback' => 'drupal_get_form',
    'page arguments' => array('gmap_macro_builder_form'),
  );
  return $items;
}

It is understandably hard to find when it's not under admin; though, perhaps, gmap registers map for its own set of admin pages.


Drupal's 7 sites folder with its mysterious permissions and ownership

You need to insure that the php process (web server) is a member of the group for the Drupal files.  You should make sure that the owner of the files is some user other than the php process / web server, because you do not want to allow the web server to overwrite the Drupal code files.

To change the group of all of the files in your root:

sudo chgrp -R webgroup /path/to/drupal

To add a group to the web server user:

sudo usermod -a -G webgroup www-data

For more advice on correctly setting file permissions for Drupal, see Securing File Permissions and Ownership.

Edit: It was suggested that this answer be expanded to point out that the above page contains a script for setting your permissions. There is also a Drush command for setting permissions in progress at http://drupal.org/node/990812. Both of these scripts can be helpful, but only if you set the user and group ownership of your files correctly, and insure that the web server user is a member of the applicable group as explained above. Please read the quoted page carefully, as it explains these concepts.


Instead of importing configuration as suggested previously, you could as an alternative, programmatically re-create the field. Here is some code that does that.

<?php

use Drupal\field\Entity\FieldConfig;
use Drupal\field\Entity\FieldStorageConfig;

// Create the user profile field and instance.
FieldStorageConfig::create([
  'entity_type' => 'user',
  'field_name' => 'user_picture',
  'type' => 'image',
  'translatable' => '0',
])->save();
FieldConfig::create([
  'label' => 'User Picture',
  'description' => '',
  'field_name' => 'user_picture',
  'entity_type' => 'user',
  'bundle' => 'user',
  'required' => 0,
])->save();

Assuming the code above is placed in a file called recreateUserPicture.php that is stored in your docroot, you can run the following Drush command:

drush scr recreateUserPicture.php

Best of luck!

N.B.: An alternative answer (since the importing of configuration from the standard profile has a problem with having the field being available in Views UI).


How to convert username to hyperlink in comment reply similar to StackExchange?

You are looking for the Mentions module:

  The Mentions module offers Twitter like functionality, recording all references to a user's username - using the [@username] or [@#uid] filter format - from various locations, providing a centralized page to track all mentions (via the Views module).


Where to include javascript instances in drupal

To Add any js file to your Drupal site , a good way is to create a custom module and add your js file there.Following points may help you.

Create one custom module of yours. Useful Link. https://www.drupal.org/developing/modules/7
In your module , create one folder name js.
Add your js file here.You can copy paste your js file also here.
Now in yourmodule file the following code to tell drupal about your js file.

function YOURMODULENAME_init(){

 drupal_add_js(drupal_get_path('module', 'YOURMODULENAME') . '/js/yourjs.js');

}

At the end enable your custom module.You are ready to go.


Multiple select do not save for my custom field with custom widget

The values won't save when you don't have any storage to write into.

Make sure your widget implements hook_field_schema() and provide necessary schema for a field structure in your .install file. E.g.

/**
 * Implements hook_field_schema().
 */
function MYMODULE_field_schema($field) {
  switch ($field['type']) {
    default:
      $columns = array(
        'value' => array(
          'type' => 'text',
          'not null' => FALSE,
        ),
      );
      break;
  }
  return array(
    'columns' => $columns,
    'indexes' => array(
      'value' => array('value'),
    ),
  );
}

Then in hook_field_info() make sure you've FIELD_BEHAVIOR_DEFAULT for multiple values behavior, e.g.

/**
 * Implements hook_field_widget_info().
 */
function MYMODULE_field_field_widget_info() {
  return array(
    'my_widget' => array(
      'label' => t('Default'),
      'field types' => array('select'),
      'behaviors' => array(
        'multiple values' => FIELD_BEHAVIOR_DEFAULT,
      ),
    ),
  );
}

When implementing multiple field properties as part of one widget (such as address field), please check: How to override default cardinality for the field widget?

For complete example, check existing modules under field core module or check field_example module (part of Examples).


You might have a JQuery version conflict. Do you have the JQuery Update module? Or did you include some script not compatible with Drupal's version of JQuery?


How to change path of taxonomy facet search

There is a version for Drupal 6 here: Taxonomy menu with custom path for taxonomy terms

However, it uses hook_term_path, which in Drupal 7 has been replaced by hook_entity_info_alter.

Too see note of how to convert this from Drupal 6 to Drupal 7, see guidelines on Drupal.org about  Converting 6.x modules to 7.x


Cookies change when I navigate to another page (Using jquery cookie)

Not really Drupal related, but it sounds to me like you are only setting the cookie for the current path.

Change:

$.cookie('font', 'x2');

to:

$.cookie('font', 'x2', { path: Drupal.settings.basePath });


Cron Run resulted in Fatal Error Message

Whatever cron is doing, you'll need to allow it more memory for it to succeed. You can find out about increasing PHP's memory_limit at http://drupal.org/node/207036

However, it looks like you already have memory_limit set to a high value for a small site.


Is there a way to alter a node save confirmation form?

Yes. I was writing a huge response before regarding confirm_form in Drupal 7. I recommend you google and look at the examples module for confirm_form usage.

In short you probably want to:

use hook_form_alter to override the #submit or #action (or pre-pend to the list) the form will send to.
then you want to show a new form -- just like confirm_form does and do more logic in your custom confirmation form submit handler.
then redirect wherever using drupal_goto for instance or $form['#redirect'].

This may sound vague -- but the Form API can do all of this. You just have alot of learning to do. I have used confirm_form. I've made workflows for 8 Node forms to wizard through 8 Node add forms; and even made a "login" form fake login people from a login form completely overridden with a dropdown list of students on a Test server (to mock out users) using hook_form_alter().

Drupal can do all of this -- you just have to read the API and look at examples and experiment until you get what you want.


The question is bit confusing and contradicting. The html.tpl file is just there to take care of the HTML structure. If you need to add regions or change blocks, then page.tpl.php is the one you need to change.

SR


Why do Drupal core functions get node object instead of nid as argument?

I think it's to avoid the repetition of node_load that could occur.

I searched a little in the source and you can see node_type_get_name($node) is called from others functions which also take a $node object argument, node_promote_action for exemple

function node_promote_action($node, $context = array()) {
  $node->promote = NODE_PROMOTED;
  watchdog('action', 'Promoted @type %title to front page.', array('@type' => node_type_get_name($node), '%title' => $node->title));
}

It seems DRY to me. Imagine you gave a nid as argument in node_promote_action :

function node_promote_action($nid, $context = array()) {
  $node = node_load($nid);
  $node->promote = NODE_PROMOTED;
  watchdog('action', 'Promoted @type %title to front page.', array('@type' => node_type_get_name($nid), '%title' => $node->title));
}

And then node_load again in node_type_get_name :

function node_type_get_name($nid) {
  $node = node_load($nid); // repetition
  $type = _node_extract_type($node);
  $types = _node_types_build()->names;
  return isset($types[$type]) ? $types[$type] : FALSE;
}

With nid as argument, each time a node related function (A) need to process some node's properties (often if not always), they would call node_load. This would lead to unnecessary repetition when another node processing function (B) is called inside the first (A), just like in the above example.


drupal add class to form-item if error on form to all forms

If you copy the theme_form_element() function out of includes/form.inc and into your theme's template.php file, re-name it to match your theme, and change the initial setting of $attributes['class'] accordingly:

  if (form_get_error($variables['element'])) {
    $attributes['class'] = array('form-item', 'da-error');
  } else {
    $attributes['class'] = array('form-item');
  }

...this will put a da-error class in the overall <div> wrapping this element.


How to design a page created using Views

The easiest way to style a page generated by views is to simply edit the CSS.

If you need more control over the markup generated you can use Semantic Views to clean up and improve the generated HTML.

Another simple solution is to manually add a template: there's a "Theme" section in the Views UI (just above where you set the Path and Menu Item). There you can select the best template to use (views-view--YOURVIEWNAME--page-1.tpl.php or something similar) and copy & paste the default template code.

Then, create a file with the same name in your Templates directory (views-view--YOURVIEWNAME--page-1.tpl.php or something similar) and past the code there.  You can now edit the template as if it were any other!

If it isn't getting recognized by the View, don't forget to go back to the "Theme" section in Views UI and click "Rescan template files" to make sure it's found!


alias the path of single - node views (pagination on single nodes)

I would not use views at all. Pathauto will help you with the aliasing. So, on hook_init you can set the pathauto pattern for that node type to be 'myview/[node:title]'. Such as this:

function myMod_init() {
  variable_set('pathauto_node_yournode_pattern', 'myview/[node:title]');
}

For the pagination, I'm not sure what your use case is like. If you could have the nids gathered via a db_query and passed to your 'page callback' function, you could construct your own "next" and "previous" buttons containing the correct href. You will find function such as drupal_get_path_alias() or url() to be very useful here.

If you wanted a pagination with proper numbering, you can look into EFQ. It has pager as a public method. Although, that will probably give you query like url such as ?page=1, etc. and not the nice alias pathauto had created for you.

All in all, more information about your usecase will be useful. But this method will give you a lot more flexibilities than using views IMO.


Debugging what has been submitted in a form

You can display the submitted values in your hook_form_submit() and set it like this (example):

function form_example_tutorial_7_submit($form, &$form_state) {
  drupal_set_message(t('The form has been submitted. name="@first @last", year of birth=@year_of_birth', array(
   '@first' => $form_state['values']['first'],
   '@last' => $form_state['values']['last'],
   '@year_of_birth' => $form_state['values']['year_of_birth'],
  )));
}


Policy Question: Can I Use a Submodule that Does Not Follow Drupal Code Guidelines?

Since the MVVM library is actually a submodule, can I submit the plugin to the Drupal repository if the Drupal-specific parts (just a couple of files) are set up to use Drupal standards?

Yes, as long as your Drupal project conforms to the GIT repo policy - where just one of terms are: "All code should comply to the coding standards." you can commit it (such projects are known as "bridge modules") to the Drupal repo (provided you have the access level required to do so - the access bar is low for sandboxes, but a lot higher for full projects). Note: You should only commit the Drupal-specific part.  The rest has to be hosted somewhere else.  Tell your users how to find it, and how it shall be combined with the Drupal-specific bridge.

However, there are other terms, and it looks like the BMLT License, as it currently appears, is a blocker:

  "BMLT is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version." (my emphasis)

Drupal.org doesn't accept this license for any code in its repo.  For code to be permitted in the repo, it must be licensed under: "version 2 of the [GPL] License, or (at your option) any later version".  There are no exceptions to this rule.

Provided you can get the license right, there is nothing in the Drupal.org Git Repo Policy that prohibits a bridge module that requires other software (i.e. not packaged on Drupal.org) to be hosted on Drupal.org.

  For that matter, since Git is so horrible with submodules, I wonder if the Drupal repository can even handle submodules.

When a bridge module is hosted on Drupal.org (and there are plenty of them there already), it has to be combined with other required bits and pieces manually (i.e. there must be human readable instructions in the README about where to find the other software and how to assemble the pieces).  While I can see the beauty of using Git to pull all the pieces together, that is not how it is done.  Provided you and your users can deal with a two phase install where a human is required to do the assembly, it is doable.

As noted by Alfred Armstrong in a comment, the convention is to have a directory below the libraries folder (usually sites/all/libraries) to hold files the user must download from elsewhere. Then use the Libraries API module to integrate the bridge with the other files.


I didn't find a direct answer, but I used the module "Menu Link Attributes" to add a class and used JS to add the parameter:

$('#menu ul li a.parameter').each(function() {
    $(this).attr("href", $(this).attr("href") + "?p=parameter");
});

Maybe that's helpful.


Enabled Panels In-Place Editor module but cant see the edit icon

you need to select the Renderer mode:

Standard or   In-Place Editor

Standard
Renders a panel normally. This is the most common option.
  In-Place Editor
Allows privileged users to update and rearrange the content while viewing this panel.


What are methods for tracking discussions or issues on Drupal.org

Thankfully, the "+1 subscribe" phenomenon is dead: you can now track issues without commenting. To track an issue, you can just click the giant "Follow" button now available in the sidebar:

Followed issues will show up on your Drupal.org account under Your Posts.

If you want to track all the issues for a project, there are a few additional options:

You can subscribe by e-mail by going to a project page and clicking on Subscribe via e-mail under the Issues for PROJECT heading.
You can subscribe to an RSS feed if you go to the issue list for the project and click the link at the bottom of the list (but your reader should also autodiscover the feed).


how to programmatically set unpublish_on

Follow the examples set by the scheduler module when it loads, inserts, and builds the form. Add the unpublish_on property to the node object with the value of the UNIX timestamp (of when it will unpublish). When the node is saved, the scheduler module will save the unpublish date.

$node = node_load(123);
$node->unpublish_on = strtotime("2018-06-25 12:23:11");
node_save($node);


Drupal 8 doesn't respect the menu structure anymore when displaying the node types. Node types have no weight concept, so there is no direct way to control this.

What you could do is to implement a template/preprocess for node_add_list/node-add-list.html.twig and then reorder the types in code.


Sounds like you want to use the Field Group module.

This module allows you to group a number of fields on a content type together. You can then choose from a number of different display options for that group, including tabs.


What is standard approach to module development?

I think this post may be helpful to you:

https://www.mediacurrent.com/blog/registering-migrations-drupal-8

When developing migration configs, you need to update the configs, and it's difficult to get the changes within the install folder to re-register, so there are some scripts you can use, and there are some example drush commands.

Basically you can edit the configs with

$editable = \Drupal::configFactory()->getEditable($config_name);

And you can reinstall configs with

\Drupal::service('config.installer')->installDefaultConfig('module', $module_name);

I'd take a look at the code in /core/lib/Drupal/Core/Config/ConfigInstaller.php in the installDefaultConfig function.  You could probably use part of that code to update just the config you need to update without touching the parts that should stay the same.


You don't really need a drupal behavior to do this.  Instead just simple do this:

;(function($){
  $(document).ready(function(){
    $('.page-node-166 a').attr('target', '_blank');
  });
})(jQuery);

or

jQuery(document).ready(function(){
  jQuery('.page-node-166 a').attr('target', '_blank');
});

By default drupal uses jQuery.noConflict() so that it does not interfere with the $ that may be used from other libraries.


How to order unions separately in db_select?

I found the answer not in Drupal, but in MySQL:

I added a new column to the subqueries with an indicator of the query. The first sub query has the sort column value "0_" and the second one "1_".

Here is the drupal db_select code:

$subquery1 = db_select('tab1','t1');
$subquery1->fields('t1',array('id','fname');
$subquery1->where('fname=:fname',array(':fname'=>'Frank');
$subquery1->addExpression("'0_'",'sort_column');

$subquery2 = db_select('tab2','t2');
$subquery2->fields('t2',array('id','fname');
$subquery2->where('lname=:lname',array(':lname'=>'Sinatra');
$subquery2->addExpression('1_','sort_column');
$subquery2->orderBy('sort_column', 'ASC');
$subquery2->orderBy('fname','DESC');

$subquery1->union($subquery2);

$result = $subquery1->execute();
...


The latest version of the colorbox plugin uses a different version string in its js file ( sites/all/libraries/colorbox/colorbox/jquery.colorbox-min.js ) so it doesnt get recognised by the colorbox module requirements check.

If possible look at the version string from the previous file, it's the first line, and copy that over, incrementing the number in the new file.


Which Rules Event in the Rules module gets triggered after clicking on a link?

Whatever you want to happen via Rules module when some link is clicked, if you're using Rules Event 'Content is viewed', you'll probably be too late:

the content (or whatever the clicked link is about) is already being shown, so if the Rules Conditions are satisfied, the Rules Actions will be performed. That is what 'Content is viewed' is all about.
if you didn't want to content (or whatever the clicked link is about) to be visible at all, well sorry, but you're too late.

If however you did want something to happen BEFORE showing the content (or whatever the clicked link leads to), then you should use Rules Event 'Drupal is initializing'. Refer to 'How to specify a Rules event like "Content is 'going to be' viewed"?' for way more details on this.

Attention: Rules Event 'Drupal is initializing' gets triggered on every (repeat: every) page load in a Drupal site. So for performance reasons, you really want to limit the number of active Rules that use this Rules Event to an absolute minimum, i.e. as your last resort (if anything else fails).


$pattern = '/user/*/edit';
$route_provider = \Drupal::service('router.route_provider');
$found_routes = $route_provider->getRoutesByPattern($pattern);
$route_names = [];
foreach ($found_routes as $route_name => $route_object) {
  $route_names[] = $route_name;
}


How to programmatically register a user with Mailchimp API

Drupal 7, Mailchimp module 3.4

$list_id = '12345asd'; // use mailchimp_get_lists() and look for 'id'
$email = 'some_email@gmail.com';
if ( mailchimp_subscribe (
    $list_id,
    $email,
    array (
        'EMAIL' => $email,
        'FNAME' => $first_name, // fields in your mailchimp list
        'LNAME' => $last_name,
    ),
    false,
    false
)) {
    drupal_set_message ( t('Thank you. From now you will receive our promo materials'));
} else {
    drupal_set_message ( 'Error occurred while adding your email to subscribe list', 'error' );
}

NOTE: If mailchimp will deside that your email is invalid module will only put watchdog error. To grab that error and display you can patch mailchimp.module
find function mailchimp_subscribe_process and goto approx line 412. and add drupal_set_messaga or whatewer you want.

Approach without patching module (but it's too hacky)

$list_id = '12345asd'; // use mailchimp_get_lists() and look for 'id'
$email = 'some_email@gmail.com';
if ( mailchimp_subscribe (
    $list_id,
    $email,
    array (
        'EMAIL' => $email,
        'FNAME' => $first_name,
        'LNAME' => $last_name,
    ),
    false,
    false
)) {
    drupal_set_message ( t('Thank you. From now you will receive our promo materials'));
} else {
    // Get last watchdog mailchimp error
    $query = db_select ( 'watchdog', 'w' );
    $query -> fields ( 'w' );
    $query -> condition ( 'w.type', 'mailchimp', '=' );
    $query -> condition ( 'w.timestamp', time() - 10, '>' ); // check for message in last 10 seconds
    $query -> condition ( 'w.message', 'An error occurred subscribing @email to list @list. "%message"', '=' );
    $query -> orderBy ( 'w.timestamp', 'DESC' );
    $query -> range ( 0, 1 );
    $ans = $query -> execute();
    if ( $wd = $ans -> fetchAssoc() ) {
        $wd['variables'] = unserialize ( $wd['variables'] );
        $message = $wd['variables']['%message'];
        // Get only error message
        if ( preg_match ( '#Internal\sServer\sError:(.+)$#si', $message, $m )) {
            $message = $m[1];
        }
        drupal_set_message ( $message, 'error' );
    } else {
        drupal_set_message ( 'Error occurred while adding your email to subscribe list', 'error' );
    }
}


How to add registration and login in a custom modules

You to need render the form element.

Use the following to print the forms:

print(drupal_render(drupal_get_form('user_register_form')));
print(drupal_render(drupal_get_form('user_login_block')));


better exposed filters and bootstrap 3. Problems with alignment

https://www.drupal.org/node/2121203 gives some answers...

  Look at bootstrap/theme/process.inc at function
  _bootstrap_process_input and comment out or remove the 'select' in there.

Still looking for the "ultimate solution" myself as well.


Show warning for viewing only some nodes

If you have registered users, you might do it with a role. This would have the benefit of not having to show this more than once.

Other than that, (this is just an idea, I haven't tried it), you could write a small module which implements hook_node_access() .

What you could do in this function is:

allow the user to view the node if there's an adult=true GET variable
disallow the user to view the node if there's an adult=false GET variable
redirect the user to your own YES/NO form when there's no adult variable in GET, appending your current path as a destination GET path, which is then used as the action target for the form, which itself uses the GET method and has an options box with the name of adult

I have no idea how easy it actually is to pull this off, but it seems quite reasonable.

Tell me whether you've done it and if it worked well, that'd be interesting.

EDIT: References you should read to accomplish this task, as you mentioned you are totally new to this.

Learn the basics about creating a new D7 module
Learn what hooks are
Learn how to create a new page with a path with the hook_menu() hook
In the callback function for hook_menu() provide the yes/no-form: Learn about the Drupal form API . Maybe get started with this tutorial on forms and complete it with the given API link.
Learn about hook_node_access() here and what to return. In this function, do what I mentioned in the list above and complete your functions.

I hope I could help you in any way, and trust me I know how hard it is to get started.


#attributes is not supported by item form elements.

  item

  Description: Generate a display-only form element allowing for an optional title and description.

  Note: since this is a read-only field, setting the #required property will do nothing except theme the form element to look as if it were actually required (i.e. by placing a red star next to the #title).

  Properties: #access, #after_build, #description, #element_validate, #parents, #post_render, #prefix, #pre_render, #required, #suffix, #theme, #title, #tree, #type, #value, #weight

You would then need to add a custom theme call such as:

function MYTHEME_preprocess_form_element(&$vars) {
  $vars['#attributes']['class'][] = 'another-class';
}


How can I execute Drush commands programmatically?

Just start it from the other side. Imagine that every Drush command executes some PHP code. Then check the code of the Drush command you want to run. And then refactor it into the submit function of your button.

Doing it like suggested in your question doesn't seem to be very sustainable, taking into account that not every host has Drush installed. So you better make that functionality work independently from its environment.

Found one possible way: How to run Drupal console command from code? using Symfony's Process and flagged question as possible duplicate. And regarding drush_invoke_process(), as how I understand it so far, it seems to be callable only from within other Drush commands.

Next thing that came to my attention: In the comments to your question you are saying that you are trying to execute /vendor/bin/drush/drush status which would mean you have the vendor folder at the root of your machine. Which very probably is wrong and you just need to fix that path.


Did you enable text format as Full Html.

In your html code there were two closing div are missed. here is the closing div added.

You are here

Home » Administration » Structure » Content types » Article

Article

Add to Default shortcuts

Primary tabs

Edit

Manage fields

Manage display(active tab)

Comment fields

Comment display

Secondary tabs

Default(active tab)

Teaser

&nbsp;

Content items can be displayed using different view modes: Teaser, Full content, Print, RSS, etc. Teaser is a short format that is typically used in lists of multiple content items. Full content is typically used when the content is displayed on its own page.

Here, you can define which fields are shown and hidden when Article content is displayed in each view mode, and define how the fields are displayed in each view mode.


Displaying image from referenced entity in a view

I think you want to display the content of "Album" with the contents reference to "Biblio", first in views follow these steps:

Select the content type of "Album"
Create a relation ship with reference to "Biblio"
Then again select an image in fields and enable the relationship with the same (which you have selected in relationship).


if i am on a node page how can i get one of the taxonomy terms for that node?

You should be able to access it via its field:

$node->field_taxonomy->value


Changing the target path of a Views more link

I used this method (views 3.x):

 <?php
 // get the $view object somehow and alter the display_handler options
 // see views_plugin_display.inc ~ render_more_link() method
 $view->display_handler->set_option('link_display', 'custom_url');
 $view->display_handler->set_option('link_url', 'node/!1/somewhere');


Dynamically adding a CSS class to a view row with template.php

function pgc_preprocess_views_view_unformatted__home_listing(&$vars) {
  // Borrowed this bit from http://drupal.org/node/312220
  $view = $vars['view'];
  $rows = $vars['rows'];

  foreach ($rows as $id => $row) {
    $data = $view->result[$id];
    $event_class = get_the_classes($data->nid);
    $vars['classes'][$id] .= ' ' . $event_class;
  }
}

function get_the_classes($nid) {
  $node = node_load($nid);
  global $user;
  if ($user->uid != 0) { // Not for anon users.
    $event_class = '';
    if ($node->field_trainer[0]['uid'] == NULL) {
        $event_class= 'red';
    } else {
        $num_trainers = $node->field_number_of_trainers[0]['value'];
        $count = count($node->field_trainer);
        if($count < $num_trainers) {
            $event_class = 'red';
        } else {
            $event_class = 'green';
        }
    }
    return $event_class;
  }
}

Don't know if it's pretty.  Don't know how it performs.  But it works.

EDIT (02-01-2012): after working with Drupal for another year now, I'd have tried to find some other way to do this besides running node_load() on every row of the view.


I finally found the solution, instead of

$zip->addFile($file_path, $media->entity->field_media_image->entity->name);

I simply put

$zip->addFile($file_path, basename($file_path));

and it does the job.


I find two solution links, please check them:

Sol-1: https://www.drupal.org/node/1430034 (Most relevant solution)

Sol-2: How to theme a webform - D7 (It another solution to theme webform with another tpl name: webform-form.tpl.php. Here is the link which provide tpl code.)

I guess you need to use node--webform.tpl.php and also add preprocessor in template.php.

function themeName_preprocess_page(&$vars, $hook) {
  if (isset($vars['node'])) {
    $vars['theme_hook_suggestions'][] = 'page__'. $vars['node']->type;
  }
}

And when you create tpl file you can check preview variable to check and theme accordingly.

If this doesn't help try second solution.

See similar issue here.


How do I use FAQ module views with accordion effect?

If the FAQ module uses views to display the answers, then you can install the Views Accordion module, which creates a new plugin in views to render each result.
Views Accordion:

Views Accordion provides a display style plugin for the Views module.
It will take the results and display them as a JQuery accordion, using the first field as the header for the accordion rows.
For Drupal 7 the module integrates the jQuery UI Accordion plugin as a views style plugin. You can configure the options provided by the jQuery UI plugin.
For Drupal 6 the module used it's own jQuery code, so a different set of features is available for D6.


Load a views block in a tpl file with his custom template

So to do this you just need to use the views_embed_view() function. I just had a typo in my template file.

So for someone who's looking for a way to do something similar:

<?php print views_embed_view('VIEW_NAME', 'DISPLAY_NAME', 'ARGUMENTS'); ?>


add/change div wrapper around specific radio button?

If you're defining the form yourself you can wrap an element with HTML using the #prefix and #suffix properties:

$form['radios'] = array(
  '#type' => 'radios',
  '#title' => 'Options',
  '#options' => drupal_map_assoc(1, 2, 3),
  '#prefix' => '
',
  '#suffix' => '
'
);

If you want to add a class to the existing wrapper you can do so using the #attributes property:

$form['radios'] = array(
  '#type' => 'radios',
  '#title' => 'Options',
  '#options' => drupal_map_assoc(1, 2, 3),
  '#attributes' => array(
    'class' => array('some-class')
  )
);

If you're not defining the form yourself then you can still use the same logic and implement a hook_form_alter() to change the existing form:

function MYMODULE_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'some_form_id') {
    $form['some_element']['#attributes']['class'][] = 'some-class';
  }
}

Note that when using the hook_form_alter() method you should append to the existing classes array so as not to override any classes that have been set previously.


How to limit search results based only on OG group membership?

Editing my answer here as there seems to be a glitch in Views. Even with no contextual filters or relationships, just filtering by groups audience and exposed search doesn't work. The SQL query has both values but I don't know enough about sql to debug it.

  Contextual filters > (OG membership from node) OG membership: Group ID
  Relationships > OG membership: OG membership from Node

Instead, here's a hacky way of getting it to work by not using the search module.

Do the same as above to limit results by group.
If you only want to search by title for example, just add an exposed filter for the title and select "contains".
If you want to search by more fields which is likely, add the fields you want to search by (and maybe hide them) eg. Node title / Body. Then create a Global: Combine fields filter (exposed) and select the above fields with "contains".

That will let you search whichever fields but just not as nicely as with the search module.

If anyone else has a solution to the exposed search problem, post please.


I do not need to synchronize, but combine (merge) them in one list.
In Webform Views Select  I can also combine by using Rewrite Results,

field "Item Number", exclude from display

field "Price List",
Rewrite Result:
[value] - price [value_1]

Then I can get in a single select option list:
20 - price 100
35 - price 200
40 - price 300


How to deploy a module locally for testing?

I do not think there will be a way to reduce time of reverting the database changes. However you can get a shortcut command to re-install a module.

Checkout answer by @MPD Quick Uninstall/Reinstall of a Custom Module, so you will need devel module to bind all those commands in one, also devel is good for development purpose.


How to get the entity ID in a twig template

You can just add the full object to a twig variable, so
$vars['myentity'] = $my_entity;

and then access with
{{ myentity.id }}

A bit more elegant is to implement hook_theme:
/**
 * Implements hook_theme().
 */
function MODULENAME_theme() {
  return [
    'customentity' => [
      'render element' => 'elements',
    ],
  ];
}

and a preprocess function to expose it to twigs customentity and maybe content variables:
function template_preprocess_customentity(&$variables) {
  $variables['customentity'] = $variables['elements']['#node'];

  // Helpful $content variable for templates.
  $variables += ['content' => []];
  foreach (Element::children($variables['elements']) as $key) {
    $variables['content'][$key] = $variables['elements'][$key];
  }
}


The admin panel under /admin/people/permissions. The /node/add/$CONTENT_TYPE access is controlled under the Node section as the ContentType: Create new content permission.


Useability of the user registration workflow

Use https://www.drupal.org/project/logintoboggan to allow users to login immediately and assign them a "not verified" role. Once they use the verification link they will become authenticated users.

Enjoy.


where does the drupal6 cck field default value stored in database?

No need to go directly into the database for that, you can use the content_field_instance_read() function:

module_load_include('inc', 'content', 'includes/content.crud');
$definition = content_field_instance_read(array('field_name' => 'field_foo'));

// Your mileage may vary here, inspect $definition[0]['widget'] to see what you've got available.
$default = $definition[0]['widget']['default_value'][0]['value'];

If you're dead set on going into the database, the info is stored as a serialised PHP string in the widget_settings column of the content_node_field_instance table.


You can achieve this goal via implementing hook_form_alter

Let e.g.

/**
 * Implements hook_form_alter().
 */
function MYMODULE_form_alter(&$form, &$form_state, $form_id) {

    if ($form_id == 'views_exposed_form' && $form_state['view']->name == 'test' && $form_state['view']->current_display == 'page_1') {
       // do your alteration stuff
    }
    if ($form_id == 'views_exposed_form' && $form_state['view']->name == 'test' && $form_state['view']->current_display == 'page_2') {
       // do your alteration stuff
    }
}


Install me aliases module.

  Provides shortcut paths to current user's pages, eg user/me, blog/me,
  user/me/edit, tracker/me etc.


Add image by pasting URL with media module

I found a module for your need.

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


Views will not use pathauto URL Alias when listing programatically saved nodes

Views doesn't see the alias.  When Drupal receives an alias URL, the first thing it does is change the URL to the default.  Views does not come into the process until after the URL is changed, so it does not know about the alias.


Simple Drupal page loads very slowly; slow 'DrupalDatabaseCache::getMultiple' query

Devel is telling you how slow the query is. From what you wrote on your question it does not appear however to be telling you what is executing that query. I would attempt to locate the source of that query first, since your doctor can't issue you a prescription, if he does not know your ailment first.

I tried searching my D7 codebase for the string "drupal_cache_menu" and did not find anything. So perhaps that is coming from a contrib module? Otherwise it would have shown up in my search. Regardless, you can see the pattern I used to locate the code responsible for that query:

Select a unique string from the query (I tried using an individual word).
Search your whole codebase for that string.
See if the matches returned from your search could possibly relate to the slow query.

Once you locate the source of the query then you will (most likely) be able to determine if the slow query was caused by:

An error.
A view (in which case all you have to do to solve the problem is set the caching for that View).
Legit custom code (without errors) that just needs optimization, in this case you could implement Drupal's Cache API (the cache_get() and cache_set() functions) and maybe static caching as well. The nice thing about the Cache API is that you can benefit from implementing it even when you don't have external persistent cache stores such as Memcached and APC installed. Lullabot's now classic Caching guide for beginners might well help you out as well.
Legit contrib code (without errors) that just needs optimization. In this case you would probably be better off consulting the module mantainer.

As you see, the corrective actions are too many to list, and which one you will take will depend on the source of the query.


Hide row in view if Content: Edit link field is empty

If you really are using hook_node_access to prevent users from editing those nodes then there's no good solution.  You could implement some Views hooks to hide the results, but then things like pagination are going to be screwed up since pagination is done at query time and it's impossible to write a query that will honor the results of hook_node_access.

If, on the other hand, you're using hook_node_access_records to actually write the node permissions to the database then you can use this Views patch: https://www.drupal.org/node/620392#comment-10222425

The patch will allow you to add a Content Access filter to your view and filter to only show content the user's allowed to edit.


Correct, according to the panels.api.php file, hook_panels_pane_update() is for changed panes.  There's one just above it for new panes called hook_panels_pane_insert().

If you want the same function to happen every time regardless of whether the pane is new or not, combine them like this:

function mymodule_panels_pane_insert($pane){
  mymodule_act_on_panels($pane);
}

function mymodule_panels_pane_update($pane){
  mymodule_act_on_panels($pane);
}

function mymodule_act_on_panels($pane){
  //Do the things here
}


How do I allow regular non-admin users to view other users' emails?

One route you can take is to allow users the View user information permission and display this information on the user profile page.

To do so, override user.html.twig in your theme (copy it from core/modules/user/templates/user.html.twig to your theme's template directory) then inject the email into the template via hook_preprocess_user() in your mytheme.theme file:

/**
 * Implements hook_preprocess_user()
 */
function mytheme_preprocess_user(&$variables) {
  $variables['mail'] = $variables['user']->getEmail();
}

In this example, you'll be able to user {{ mail }} to insert the email variable into your user profile template.


Rendering an image field in page.html.twig with a custom image style

Replace the image tag

<img class="swiper-image" src="{{ file_url(node.field_slides[key].entity.uri.value) }}" alt="{{ node.field_slides[key].alt  }}" />

with a render array for the image style:

{% set imagestyle = {
  '#theme':      'image_style',
  '#style_name': 'medium',
  '#uri':        node.field_slides[key].entity.uri.value,
  '#alt':        node.field_slides[key].alt,
  '#attributes': { class: 'swiper-image' },
} %}

{{ imagestyle }}

Edit:

There is a new filter in the module Twig Tweak. Now you can generate the image style url in twig directly from an uri or url:

{{ node.field_slides[key].entity.uri.value | image_style('thumbnail') }}


Is there an easy way to move non-English selected nodes into a language section?

From your comments I understand that you want to display URLs based on languages.You can achieve that by simply  editing each node and edit URL alias (under URL path settings) for each node.

If you have bunch of nodes and want to change the all URL aliases at once, follow the steps

1) Install and Enable Pathauto and Views Bulk Operations (VBO) modules.

2) Define Path alias patterns in URL alias settings (admin/config/search/path/patterns)

3) Create a view with Views Bulk Operation field and select "Update node alias" option.

From the View output you can generate Auto paths for selected nodes in one click action.


allowed values for node/entity/user reference field

For an entityreference fields use:

$allowed_values = entityreference_get_selection_handler("field_user_ref")->getReferencableEntities();


Webform with Content Access module not allowing access for the authenticated user role

I did have a similar issue, using Content Access module and getting Access Denied in a Role I created. My problem was that my Role did not have the "View Published Content" permission enabled. After enabling it, it works. But thanks for the detail explanation, it helped solve my issue.


Add a link for the route node.add in Twig:

{{ 'Add content of type "Basic Page"'|t }}


How to trick feeds into re-importing nodes?

In the feeds config area, under "Processor Settings", there is an option checkbox for "Skip Hash Check", which will cause the feed to update the items regardless.


That's not a problem, Drupal stores uploaded files under sites/default/files by default. There's no reason file paths for uploaded files would be similar to the URL of the node they're attached to.

www.example.com/sites/default/files/ADMISSION_FORM.pdf is the correct path if you haven't changed any of the default settings. I'm not sure why you've mentioned security, as that really doesn't come into it.


How can i make my comments field allow images as part of the comment? (drupal 7)

Install CKEditor module. Using this module you can use pictures in comments also

  This module will allow Drupal to replace textarea fields with the CKEditor - a visual HTML editor, usually called a WYSIWYG editor. This HTML text editor brings many of the powerful WYSIWYG editing functions of known desktop editors like Word to the web. It's very fast and doesn't require any kind of installation on the client computer.


You need to use views contextual filters. Add a contextual filter Content:Nid and provide default value as "Content Id from URL" and select Exclude checkbox in the settings. That's it !!


How do you add captions to each image of Flexslider? (already tried Google!)

Well, after investigating for a short solution, and one that involves the minimal number of modules, it seems that as of 2/1/2015 there are 2 main ways to give per-images captions, to the images of the slider. It's good to Install Flexslider and creating a working slider-View of images, and right afterwards, implement one of these ways below.

The first way:

Install the module Image Field Caption. It's install is simple but you might have to do about 10 minutes of CSS:

After you have installed the module your images will now have (besides the potential ALT\Title attributes) a third attribute named Caption. You can easily edit it and it can also integrate with CKeditor.

After you have printed the captions you could add some CSS. as of 2/1/2015, the captions appear naturally under the picture, but if you want it to be over the picture (not above, but flying over, in it's bottom for example) with some nice transparent background, just edit the CSS property "Blockquoute" and make sure you give it:

"Position: Absolute; right: 0; left: 0; bottom: 0; rgba(#,#,#,0.#); width: #%; height: auto;. The rest is rather simple...

The second way:

2 CSS guys I spoke seem to would have preferred this option, though bear in mind that it contains 2 modules instead of 1, in the first solution:

Make the images of the Slider appear as CSS backgrounds. This could be achieved via the module CSS Injector. After the images been presented as backgrounds, a way must be found to print a caption attribute below or on the Image. one way to print it is via the module mentioned above - Image Field Caption. The other is to print the image's very own Title attribute via the module image caption formatter.

All luck, Ben.


How to add Autocomplete to a Views Custom Textfield Filter

So it turns out that I just had a small typo :( Anyway, I'm keeping this question up in case others are having troubles since it outlines completely how to do this and I was personally unable to find any tutorials.

In the above code it needs to be #autocomplete_path instead of #autocomplete.

Furthermore, if you are trying to create your own custom autocomplete filter, remember that you have to indicate the file containing your handler class in your .info file (ie: files[] = views/handlers/name_of_my_handler.inc) and that you need to assign your handler to a field using hook_views_data() or hook_views_data_alter().


Prompt to translate a content after creating a new content

In the answer to "How to implement side-by-side translation?", I describe how to do side my side translation by adding an entity reference field and linking back to the original English article.

For your case, you could use rules to create a French node when an English node is created, save the entity reference and redirect to node/*/translate where the French node would be displayed next to the English one.

If you want to take this approach, I can add more details. I think it would give a very nice workflow.


It's simple in Filter Criteria, click add and add your entity reference field.

When you are adding your field, for Operator, select Is Empty (Null)

Drupal 8 Example:

Drupal 7 Example:


How to create a organic-group-alias/content-type subpage?

Views treats aliases the same as node/id. So, in the view, just set the path to node/id/post or similar.


How do I view the maintenance page without putting the site in maintenance mode?

By default there is no route to access the maintenance page via url. You can create a menu item and the corresponding page callback in your module :

// Access maintenance page regardless of the maintenance mode.
$items['maintenance'] = array(
  'title' => 'Maintenance',
  'page callback' => 'yourmodule_maintenance_page',
  'access callback' => 'user_is_logged_in',
  'type' => MENU_CALLBACK
);

yourmodule_maintenance_page () {
  // Just use the internal status code to make Drupal load the apropriate theme and template.
  return MENU_SITE_OFFLINE;
}

And that's all, go to /maintenance to see the page.

You may also want to override the 'maintenance_page' theme, have a look at :

the base preprocess function in includes/theme.maintenance.inc
base template file in modules\system\maintenance-page.tpl.php


How to change all hyperlinks in the content

I am not sure if I understand the problem correctly.

But if you're looking for a module that will do a batch search and replace, replacing the path of an URL embedded in node content with another path, the search and replace scanner can do plain text search-and-replace, or regular expression search-and-replace, against the body fields on all nodes in your system.


The page you configure for a 404 code in admin/config/system/site-information is not a redirect to the new path, it reuses the original request and keeps the path. You see this in the browser, where the url remains unchanged when the custom 404 page is invoked. So you can't use the path from the 404 page to control the visibility.

See this feature request: Allow blocks to be configured to show/hide on 403/404 pages. I doubt that there will be any progress soon, because there is no activity for some time and the patch no longer applies.

You could implement the block visibility in a custom condition plugin or if you are looking for a simple solution do this in preprocess on theme level.

Or what I would prefer use a custom controller instead of a block, create a route to this controller and put this in the site settings.


Incorporate dropdown list of nodes into a webform to link webform results to said content

You can create your own predefined lists by using the webform_webform_select_options_info() hook.

<?php
/**
* Implements hook_webform_select_options_info().
*/
function yourmodule_webform_select_options_info() {
  $items = array();
  $items['contentchoice'] = array(
    'title' => t('Content Choice'),
    'options callback' => 'webform_options_yournodes',
  );
  return $items;
}

Then generate your list of nodes using

/**
* Webform options info callback.
*/
function webform_options_yournodes() {
  $mynodes = array(
  //build your array up here
  );
  return $mynodes;
}


How do I include jQuery scripts at the bottom of the  tag?

The example on the documentation for drupal_add_js() can explain this.

drupal_add_js('jQuery(document).ready(function () { alert("Hello!"); });',
  array('type' => 'inline', 'scope' => 'footer', 'weight' => 5)
);

If you want to add jQuery files, just change 'type' to 'file'.


Restrict search results to only documents user can see

I think this module will help you Access by term and don't forget to enable Node access settings in search api settings.


Is there a way to restrict access to a particular node?

You can use this module Permissions by Term

Frontend Features

Restricts users from accessing the nodes related to specific taxonomy terms by their roles and/or specific user accounts.

Restricts users from access to forbidden nodes in views.

Tag the node to the specific taxonomy term and restrict access to nodes tagged with that specific node.


Textarea for Drupal 8 text fields content types

A long textfield is a textarea by default, there's no need to explicity configure it as such. For example here I created a textfield with label "Text" as plain, long:

And this is how it looks in the node/add page:


Get only one value from a multivalue field in template node

Assuming you already have a node template for that content type already (if not then you can read more here). Within the template, instead of outputting all content in one print command, you'd break them down into the fields you need. Then you can output the image field and  programmatically limit it to the first value, as described in this SE post.


Drupal commerce: product field based in calculation of other fields

Commerce out of the box has a quantity field and does by default a 'price-per-unit'. Watch this tutorial to give you an idea of how it works without any customizations.

https://www.youtube.com/watch?v=3KEJcieG4jI


In this example I load a node and change the value of a field called field_context and then saves the updated node:

$node = node_load($nid);
$node->field_context[$node->language][0]['value'] = 'foo';
node_save($node);

Use var_dump to show what fields your node contains.


You could use https://www.drupal.org/project/webform_addmore.

A more flexible solution would be to use the Entityform module in combination with https://www.drupal.org/project/field_collection.


How to add multiple taxonomy terms to node?

First of all, be sure that the taxonomy reference field exist in manage field page of your content type, then you can attach that field to your node via the function field_attach_update, before attaching that field to node let's get it from your data passed through Ajax :

 $terms = $form_state['values']['your_tax_field'];

 // attach to node :
 $node = new stdClass();
 $node->nid = $nid // Make sure that the nid exist;
 $node->type = 'your_content_type';
 $node->your_tax_field = $terms;
 field_attach_update('node', $node);
 entity_get_controller('node')->resetCache(array($node->nid));

Not tested but should work like that! You can use devel module to debug your data passed in the form.


Configuring PayPal Express Checkout to accept BRL currency

There is a patch in Issues for Commerce Paypal module. I have applied that patch and now BRL is showed. Going to PayPal page from my site's checkout section now works fine.


How do I find out the machine name of a view in hook_preprocess_views_view_field?

The view itself is in the $variables array for all of the views hooks.

/** @var \Drupal\views\ViewExecutable $view */
$view = $variables['view'];
$view->id();

should give you what you are looking for.


I would do it by adding a new template for the block. See Drupal 7 Template (Theme Hook) Suggestions

block--[region|[module|--delta]].tpl.php base template: block.tpl.php
Theme hook suggestions are made based on these factors, listed from
the most specific template to the least. Drupal will use the most
specific template it finds:
block--module--delta.tpl.php
block--module.tpl.php
block--region.tpl.php


I built a form like this for a website. If I wanted to I'm pretty sure I could use the same principle to build a form like Google Advanced Search. Whether it's the best approach or not I'm not sure.

Which sits on the front page of the websites and then sends to the search page from there.

What I'm doing is recreating the URL thats being created on the search page.  like 'search/applications?f[0]=field_location%3A2439'

I created a Custom Module
used hook_block_info to create a block
used hook_block_view to create a block view - assigned the form to its content
Example of the form code ->

function search_applications_form($form, &$form_state) {
$locations = db_query("SELECT tid, name FROM {taxonomy_term_data} WHERE vid     = 5")->fetchAllKeyed();  // vid will be the id of the location taxonomy data

$form['locations'] = array(
   "#type" => "select",
   '#multiple' => TRUE,
   "#title" => t(""),
   '#required' => FALSE,
   '#default_value' => 'Select Application Locations',
   '#options' => $locations,
   );
 return $form;
 }

And in the submit

function search_applications_submit($form, &$form_state) {
     global $base_url;

     $search = $form_state['values']['search_applications'];

     $i = 0;

     if($form_state['values']['locations'] != NULL && $form_state['values']['searchlocations'] != '0' && $form_state['values']['locations'] != 'none'){

     $tid = $form_state['values']['locations'];

     $addlocationsearch = '&f['.$i.']=field_job_location%3A'.$tid;
      $i++;
     }
     else {
     $addlocationsearch = NULL;
     }

     $searchUrl = $base_url.'/search/applications?'.$addlocationsearch;

     $form_state['redirect'] = $searchUrl;
     }

I think the logic used here could be used to make a much better module. If you've a plan for some development I'd be happy to join in a project.


Is it possible to add CSS to theme without a subtheme?

My understanding is to never use hook_init if possible. It's a hook that's call in the early stages of the bootstrap process and can produce some funky results. The API docs clearly state:

  To add CSS or JS that should be
  present on all pages, modules should
  not implement this hook, but declare
  these files in their .info file.

I'd suggest adding a stylesheets[all][] entry in the .info file -> Adding style sheets


How to add custom fields and display settings to built-in content types via custom module install?

For a beginner I'ld recommend to use Drupal's convenient user interface in the back-end. Create an admin user, log in, start adding fields, change display, reorder – all done by clicking through the interface.

For example you can add custom fields to the existing Article content type at https://example.com/admin/structure/types/manage/article/fields. There's is a button Add fields. Click it and explore. There is no difference in adding fields to a built-in content type.

As others said before YML are for configuration export and import, when deploying a site. As you would do as an advanced developer: You'ld have that page locally on your computer, add some fields by clicking through the back-end, export their config, push that to a Git repo, and then on your live page, pull from your repository, import the config files and get the same fields there without the need to click anything again.

Adding fields from a custom module can be achieved by providing certain YML in your modules /config/install folder. There as well is no difference between built-in content types or custom content types. It is described pretty good on DO at https://www.drupal.org/docs/8/api/entity-api/programming-custom-fields-into-your-content-type. Except that you would have to change the naming and especially change the value of the bundle: car_brand (content type) you want your fields to get added to.

Apart from that, you may need to install and uninstall this module pretty often during development. Get used to drush commands, for example drush dre module_name to do that in Terminal/Console (you need to have installed the Devel module to use drush dre). For your own good, I hope you already work with a UNIX based OS (Linux or OSX). Maybe you always have a fresh database backup available you can re-import with drush sql-cli < database.sql when you want to start over during development.

Just for reference I paste the deleted answer code here OP originally had put in his question. To finally make the fields available in the content type OP came up with this. I strongly guess he had put this into the module's *.install file calling hook_install() or hook_update_N(). Possibly deprecated functions, but I think you'll get the idea.

$entity_type         = 'node';
$bundle              = 'article';
$field['field_name'] = 'field_price'; // your field id

entity_get_form_display($entity_type, $bundle, 'default')
  ->setComponent($field['field_name'], array())
  ->save();

entity_get_display($entity_type, $bundle, 'default')
  ->setComponent($field['field_name'], array())
  ->save();


How to hide node edit / delete link in a view conditionally?

Although an old issue, the way to do this in D7 commerce is with

hook_commerce_entity_access

/**
 * Implements hook_commerce_entity_access
 */
function MODULE_commerce_entity_access($op, $entity, $account, $entity_type) {
  if ($entity_type == 'commerce_order') {
    // Prevent edit and delete of 'processed' status orders
    if ($entity->status == 'processed' && ($op == 'edit' || $op == 'delete')) {
      return FALSE;
    }
  }
}


How to add alt and title attributes field for user picture?

You would need to override this function in your template.php file and override the alt tag.

Another option would be to uncheck "Enable user pictures" in account settings and add your own custom imagefield.  Then you should be able to enable alt and title fields in the field settings.  You can also use this field in views.


Why are users seeing edit pages outside of Admin UI

D'oh.  I somehow missed this before in the permissions:

View the administration theme

Admins and editors had this permission enabled, but authors did not.  Enabling it for authors fixed things.


How to remove a taxonomy vocabulary via database query

From the world of weird solutions that work...

I tried using a module and 'drush entup' ... didn't work
I tried creating a module to use 'hook_update_N' to delete it ... didn't work
I tried using hook_update_N to Create it, so I could then delete it
... didn't work.

On a whim, I went to the admin page, listing taxonomies. I dragged the 'ghost' taxonomy to rearrange the list. Then I saved. Suddenly, all the options to edit it had returned. I was finally able to delete the taxonomy using the usual dropdown field.


To solve this, (1) I placed code in node--class.tpl.php which retrieved the current class date

$date = entity_metadata_wrapper('node', $node)->field_class_date->value->value();

Then, (2) I modified that value to get the start of the day and the end of the day ($start and $end) in the following format: Y-m-d H:i:s

(3) Perform a query using EFQ to grab a list of the nodes that share the same date:

$query = new EntityFieldQuery();
$query->entityCondition('entity_type', 'node')
  ->entityCondition('bundle', 'class')
  ->fieldCondition('field_class_date', 'value', array($start, $end), 'BETWEEN')
  ->fieldOrderBy('field_class_date', 'value', 'ASC');
$result = $query->execute();

(4) Loop through each result and create the content I want to display later in node--class.tpl.php

foreach($result['node'] as $i) {
  $node = node_load($i->nid);
  $date = entity_metadata_wrapper('node', $node)->field_class_date->value->value();
  $name = entity_metadata_wrapper('node', $instructor)->field_class_instructor->value();
  // Build a string of output that I want to display later in the $content array
  $classes_today = etc...
}

(5) Finally, I added the $classes_today string to the $content array:

$content['more_classes']['#prefix'] = '
Classes on this Day:

';
$content['more_classes']['#markup'] = $more_classes;
$content['more_classes']['#weight'] = '4';
$content['more_classes']['#suffix'] = '
';


Modify the links included in the user menu

Tested:

Go to yoursite.ca/admin/structure/menu/manage/user-menu
Click the edit button for "My account (logged in users only)"
Check the "Show as expanded" box
Click Save
Click the edit button for "Log out"
Select "My account" under the Parent link

Click Save


How can I let a plugin depend on another module?

Yes, this is possible.
You may declare a dependency on a module by using the "provider" key in the annotation. For your example, this would look like:
/**
 * @FieldWidget(
 *   id = "my_daterange",
 *   label = @Translation("Date and time range + All day"),
 *   field_types = {
 *     "daterange"
 *   },
 *   provider = "date_all_day"
 * )
 */
class MyPlugin {...}

Note that you can only list ONE provider, but of course that provider module can depend on other modules ...
This is a feature added to the DefaultPluginManager in order to allow plugins to declare a dependency on one (and only one) module. This only works for plugins that use a plugin manager derived from DefaultPluginManager.
Specifically, @FieldWidget plugins are managed by the WidgetPluginManager, which DOES subclass DefaultPluginManager, so this will work. (Most, if not all, core plugin managers subclass DefaultPluginManager.)


Try to update your database with update.php (http://www.YOUR-DOMAIN.com/update.php) or with drush : drush updb
The error says that your are missing one column in DB...


Show node if exists, else show node creation form

I ended up getting this to work with views, date and some custom code.  Basically I created a page view that with a conditional filter for a post date in YYYYMMDD format (a default argument provided by date), if one didn't exist I added some code in the "No Results" field that would load the node creation form with basically:

$form = node_add(arg(0));
print drupal_render($form);

So a url of /story/20110915 would show the story from that date if it existed, otherwise it would show the node/add form for the story content type.

In the final product I actually had the view load an .inc file from my custom module in the "No Results" field (also much faster than editing the view every time while developing). But I think this gets the basic point across.

Sorry @ram4nd if I made it seem like I didn't want to write code, I just was looking for the best approach.  So far this seems like it is pretty solid.


Can I enable both the Internal dynamic page cache and page cache modules?

According to Wim Leers, who is one of the main architects of the caching system in D8.

PUBLISHED on OCTOBER 12, 2015
Drupal 8 now has a Dynamic Page Cache. The Page Cache module only
works for anonymous users, the Dynamic Page Cache module takes that a
step further: it works for any user.
Since April 8, Drupal 8 had its Page Cache enabled by default. Exactly
5 months later, on September 8, the Dynamic Page Cache module was
added to Drupal 8, and also enabled by default.
source: Drupal 8's Dynamic Page Cache

Therefore, both of those caching modules come enabled by default out of the box, you don't have to do anything to enable them.

will not cause any issue?

No issues at all, Drupal 8 was designed to use both.

The Page Cache module caches fully rendered HTML responses — it
assumes only one variant of each response exists, which is only true
for anonymous users. The innovation in 8 on top of 7’s Page Cache is
the addition of cache tags, which allow one to use the Page Cache but
still have instantaneous updates: no more stale content.
The Dynamic Page Cache module caches mostly rendered HTML responses —
because it does not assume only a single variant exists: thanks to
cache contexts, it knows the different variants that exist of each
part of the page, and thus also of the final (fully assembled) page.
During the rendering process, auto-placeholdering ensures that the
parts of the page that are too dynamic to cache or are simply
uncacheable are replaced with placeholders. These placeholders are
only rendered at the very last moment. The Dynamic Page Cache module
caches the page just before those placeholders are replaced.
source: Drupal 8's Dynamic Page Cache


Rather than deleting the menu items myself through the DB (see here for possible explanation on how), I decided to try to find the underlying issue, and this is what I found:

In my case I have two modules which have the ability to add links to the menu(that I know of...):

Views (/admin/structure/views -> Edit a View -> Page Settings ->
Menu)
Pages (/admin/structure/pages -> Edit a Custom Page -> Click on Menu)

The above modules were adding menu items to the menu which cannot be deleted from the menu system unless you go to the modules and remove them first.

In order to remove the menu links I had to do the following:

In the module that creates the menu item (Views, Pages, etc.) set the Menu option to "No Menu".
In the menu config (/admin/structure/menu/manage/), go to the menu item and click on "reset" to remove it from the menu.
Disable the Custom Page or View (the individual view or page, not the entire module)
Re-enable the Custom Page or View
The menu item should no longer be present in the menu_links table.

My issue was related to what seems to be a core problem (see:  https://www.drupal.org/node/1058672 OR https://www.drupal.org/node/1029022) which is that if a menu item is created and then removed, it can leave behind a stale record in the menu_links DB table.  Disabling the affected Custom Page or View is what actually removed it from the DB for me.


How to color cards (hearts and diamonds) red in Drupal 7 comments?

If you need it to be configurable/re-usable then a custom filter is the way to go as Mołot said. The idea is that the raw data is always stored, and the filter is applied upon display. This is all well and good, but if you don't ever need the original text I find this method to be an unnecessary performance overhead (especially when you involve regexs, as most filters do).

The other way is to intercept the comment body before it's saved, and apply your filter then. For this you can use hook_comment_presave():

function MYMODULE_comment_presave($comment) {
  $comment->comment_body[$comment->language][0]['value'] = string_replacement_function($comment->comment_body[$comment->language][0]['value']);
}

I know this method is 'frowned upon' (heaven forbid we alter someone's input, even if we want to control what goes in the database!), and I can think of at least 2 people who will downvote this if/when they see it.

I think the benefits/drawbacks of both methods are pretty clear, though, so I'd advise you make a decision based on your use-case. If the module you implement to do this isn't being released back into the wild, I see no benefit in taking the extra performance hit here.

But if you think you'll ever want to use this method to filter text elsewhere on the site (e.g. in node bodies), a custom filter would make more sense.


This code worked for me:

$blockObject = block_load('book', 'navigation');
    $block = _block_get_renderable_array(_block_render_blocks(array($blockObject)));
    $output = drupal_render($block);
    print $output;


How to redirect /user to /user/UID, for logged in users?

If you were handcoding this, you would create a menu path using hook_menu, with %uid as the second parameter. And the page_callback value of the menu item would be the function rendering the user page. You will then use hook_user_login to set the redirect rule.

If you were doing this using contrib modules, I suggest you looking into profile2, it comes with a built in functionality where each user has their own profile page.

edited:
The last sentence on your question, makes me led to think that the user/%uid path needs to be accessible users/visitors other than the owner. So let's here is how you would do it.

Create your custom module, let's call it ea_custom for the sake of
this example.
Add hook_menu and page_callback to your ea_custom.module and register the path for the individual user page.

/* Implements hook_menu */
function ea_custom_menu() {
  $items['users/%user'] = array( //the %user will be used as argument for the page callback
    'title' => t('User Profile'),
    'page callback' => 'ea_custom_render_userpage',
    'page arguments' => array(1), //zero base array. This tells hook menu to first load user with the specified uid specified by %user parameter.
    'access callback' => 'user_access', //so non-onwer can also view it
    'access arguments' => array('access content'),
  );
  return $items;
}

/**** page callback for users/%user ****/
function ea_custom_render_userpage($user) {
   //you now have accessed to the user object
   drupal_set_message('' . print_r($user, TRUE) . '');

//assemble your output using the values inside $user object
   $output = $user->uid; //etc.. etc...

return $output;
}

Additional notes: you can use different methods to get values from entity objects such as user and node. I would recommend you to check entity_metadata_wrapper for one. Also, instead of using %user, to get user object, you could opt to use %profile2, since you have that module installed, and it will allows you access to fields you have attached to profile type.

wow, I can't seem to format this properly. Here is the paste bin: http://pastebin.com/kiv6GfPN


commerce_display_path is relative and doesn't work from Order page

I'm not sure where your second token is coming from, but assuming that's part of the View as well, why are you rewriting the link directly with HTML instead of using the "Output this field as a link" code that's designed to accept Drupal paths and generate appropriate absolute URLs from them? That's what I'd do or else I'd look into rewriting the commerce_display_path field as well to make it work.


How can I create a user list hierarchical select exposed filter?

Hierarchical Select for Drupal 7 does not have Views support.  At this point, the HS has not been actively maintained in more than a year so it is unlikely to expect this to be added soon, if at all.  There is an issue on porting the D6 functionality to D7.

If using Simple Hierarchical Select, which only works on taxonomy terms, you can follow the instructions on the module's page:

  add a new filter using the field set-up as "Simple hierarchical select" or use "Content: Has taxonomy terms (with depth; Simple
  hierarchical select)" as a new filter
  use "Simple hierarchical select" as selection type
  select "Expose this filter to visitors, to allow them to change it"
  enjoy ;)


An AJAX callback is not a submission callback; the submission callback is the usual one a form uses, independently from the form using AJAX or not.
An AJAX callback is given the $form and $form_state parameters, allowing it to produce a result, which it returns for rendering. Since it gets $form as parameter, accessing that value simply means parsing $form['id']['mypreview_modal']['#markup'].

function myid_user_page_form_ajax_submit($form, $form_state) {
  // Parse $form['id']['mypreview_modal']['#markup'].
}

Keep in mind that usually an AJAX callback just returns the part of the form that needs to be rendered. See poll_choice_js() as example.

function poll_choice_js($form, $form_state) {
  return $form ['choice_wrapper']['choice'];
}

The rest is done from the submission handler. (In the case of the Poll module, and for the form using the previous AJAX callback, this is poll_more_choices_submit().)

  // If this is a Ajax POST, add 1, otherwise add 5 more choices to the form.
  if ($form_state ['values']['poll_more']) {
    $n = $_GET ['q'] == 'system/ajax' ? 1 : 5;
    $form_state ['choice_count'] = count($form_state ['values']['choice']) + $n;
  }
  // Renumber the choices. This invalidates the corresponding key/value
  // associations in $form_state['input'], so clear that out. This requires
  // poll_form() to rebuild the choices with the values in
  // $form_state['node']->choice, which it does.
  $form_state ['node']->choice = array_values($form_state ['values']['choice']);
  unset($form_state ['input']['choice']);
  $form_state ['rebuild'] = TRUE;


How to add css to a form according to the user's role?

You need to call $user object and compare user role with current logged in user.

function theme_form_alter(&$form, &$form_state, $form_id) {
  global $user, $theme;

  switch ($form_id) {
    case 'formtype_form':
      // change user_role to whatever role you want to restrict this css
      if (in_array('user_role', array_values($user->roles))) {
        $form['#attached']['css'] = array(
          drupal_get_path('theme', 'projectname') . '/css/new.css',
        );
      }
      break;
  }
}


Drupal.behaviors, attach and origin of it

The attach() and detach() methods are part of the Behaviors interface defined by Drupal:

  Any object defined as a property of Drupal.behaviors will get its
  attach() method called when the DOM has loaded both initially and
  after any AJAX calls.

https://www.drupal.org/docs/8/api/javascript-api/javascript-api-overview


Why different available updates in Drush to admin/reports/updates?

Think it was using an old (i.e. Debian Squeeze's) version of Drush. Solution:

Add backports to sources.list

#
# squeeze backports
#
deb http://backports.debian.org/debian-backports squeeze-backports main contrib non-free

Then apt-get install drush=4.5-2~bpo60+1

Your version number may vary. Check apt-cache policy drush to see what versions are available.


Problem with programmatically creating a redirect

Rabbit Hole should get you close, if not entirely there. After enabling the rh_node submodule, admin/structure/types/manage/event will show "Rabbit Hole settings" where you can set the behavior to "Page redirect" and the "Redirect path" field has "You may enter tokens in this field" in the help text, so [node:field-external-url] should work there. You probably need custom code for your "Conditions: NOT Data value is empty" but you might be able to have a custom module for that, so long as you set the weight of your custom module such that it runs earlier than rh_node (alternatively, Rabbit Hole offers a PHP filter, but that has an implied dependency on Bad Judgement).

Out of the box, Rabbit Hole does offer a "Bypass Rabbit Hole action for nodes" permission that you can grant to administrators.


Forward authenticated user to user.page on /login uri

You also need to register your class in the event subscriber serivce. Create a YML similar to this:

asdentbase.services.yml

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


Copy data from Webform submission to a node?

Can this be done in the current state of Drupal 8 Rules?

To my knowledge the answer to your question is No (it's part of what this is all about).

If you're in for getting a better understanding about all this, then have a look at these links:

Roadmap.
Architecture.

One never realizes what has been done, only what remains to be done ...


Is there a way to display an 'All' link following the alphabetic glossary with Views 7.x-3.x?

Altering views-views-summary-unformatted.tpl.php is certainly the way forward. Don't be lazy and use the header if you can't get the template file to register initially, it's worth it in the end. That way you can add --view_name on the end and target all displays without having to copy bits of code around, or symlink the file to target another view or specific display so that you don't have to edit twice.

As I mention in the post we both linked to, the HTML doesn't validate if you use any exposed filters but it's fixable with regex.

The post has recently been updated; there is a version for 7 that includes 0-9 and ALL which works as described, if that answers your question?

Additionally you refer to the glossary as a filter but it is actually an argument selector. On my site I have it working with two taxonomy filters.


Oneway you can do is using hook_form_alter()

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

Another way is using hook_user_insert()

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


Perhaps all the available views have been added to other features? Try enabling the checkbox "Allow conflicts to be added" in the 'Advanced Options' section of the 'Create' page. If you can see the views then, it means they are already assigned to other features.


There aren't any releases for module "commerce_tax"

You're getting the error because commerce_tax is not included in Commerce 8.x-2.x branch, because of which Drupal Console is not able to find the module.


How can I count how many times a node appears in a view?

This can be done by tracking events with the help of Google Analytics
Drupal provides module for it
https://www.drupal.org/project/google_analytics

Events can be tracked by event tracking module
https://www.drupal.org/project/google_analytics_et

Will need to write custom js for making this event tracking, see documentation of google analytics event tracking module

I'm adding a code sample for tracking click on social media share icons:

    $('.facebook_popup', context).click(function (e) {
    // First register an event in Google Analytics
    if (typeof ga != "undefined") {
      if (jQuery(e.target).closest('.node-social-media').length) {
        ga('send', 'event', 'social-side-bar', 'fb-share', window.location.pathname);
      }
      else if (jQuery(e.target).closest('#block-menu-menu-share').length) {
        ga('send', 'event', 'social-shares-top', 'fb-share', window.location.pathname);
      }
    }

This might help you creating google analytics events


It's not about how you load the entity. It's how you build the response. You have to add the correct cache tags. A cacheable response has the method addCacheableDependency(), which accepts objects which provide cache metadata:

$response->addCacheableDependency($entity);

This adds the tag custom_entity:[id] to the cached response. All cached responses with this tag will be invalidated, when the entity is updated.

This is an example from core for the cache data and access checks you need in a response which contains entity data:

Drupal\rest\Plugin\rest\resource::get()

public function get(EntityInterface $entity) {
    $entity_access = $entity->access('view', NULL, TRUE);
    if (!$entity_access->isAllowed()) {
      throw new AccessDeniedHttpException();
    }

    $response = new ResourceResponse($entity, 200);
    $response->addCacheableDependency($entity);
    $response->addCacheableDependency($entity_access);

    if ($entity instanceof FieldableEntityInterface) {
      foreach ($entity as $field_name => $field) {
        /** @var \Drupal\Core\Field\FieldItemListInterface $field */
        $field_access = $field->access('view', NULL, TRUE);
        $response->addCacheableDependency($field_access);

        if (!$field_access->isAllowed()) {
          $entity->set($field_name, NULL);
        }
      }
    }

    return $response;
  }


Entity reference field pointing to a Configuration Entity

This is no problem, in ui you can configure bundle fields referencing all entity types, content and configuration. And for base fields this is an example from the user entity for a reference field pointing at the configuration entity user_role:

$fields['roles'] = BaseFieldDefinition::create('entity_reference')
  ->setLabel(t('Roles'))
  ->setCardinality(BaseFieldDefinition::CARDINALITY_UNLIMITED)
  ->setDescription(t('The roles the user has.'))
  ->setSetting('target_type', 'user_role');


Is access control necessary upon form submission if I've controlled access to the page containing the form?

It is not necessary to control if the user has access to a form in its submission handler.

Drupal protects its forms from form forgery, and verifies the values contained in the submitted form. The first control is done in drupal_validate_form(), where the form token (which is automatically assigned to every form built through the form API) is verified; if the value of $form_state['values']['form_token'] is different from the value of drupal_hmac_base64($form['#token'], session_id() . drupal_get_private_key() . drupal_get_hash_salt()), the form is rejected.
The submitted values are also validated in _form_validate(), where the length of the entered value is checked against the maximum length reported for the form field, and the value entered for a "checkboxes," or a "tableselect" form field is checked against its acceptable values. In both the cases, the value used to verify the submitted values is not taken from the submitted values.

To be more sure, you should not pass sensible data, such as the ID of the node being edited as hidden field; it is preferable to set it inside the $form variable, using an array index that starts with "#" and that is unique for that form (such as "#nid"), or use a "value" form field; in that way, the value will not be passed to the HTML form rendered in the browser, and a forged form would not be able to alter that value to effectuate an operation on an entity for which the user doesn't have access. For example, this is the code used for a confirmation form that allows to delete a node:

function node_delete_confirm($form, &$form_state, $node) {
  $form['#node'] = $node;
  // Always provide entity id in the same form key as in the entity edit form.
  $form['nid'] = array(
    '#type' => 'value',
    '#value' => $node->nid,
  );
  return confirm_form($form,
    t('Are you sure you want to delete %title?', array('%title' => $node->title)),
    'node/' . $node->nid,
    t('This action cannot be undone.'),
    t('Delete'),
    t('Cancel')
  );
}

Both $form['#node'] and $form['nid'] are not contained in the form passed to the browser.

The submission handler for that form builder is the following one:

function node_delete_confirm_submit($form, &$form_state) {
  if ($form_state['values']['confirm']) {
    $node = node_load($form_state['values']['nid']);
    node_delete($form_state['values']['nid']);
    watchdog('content', '@type: deleted %title.', array('@type' => $node->type, '%title' => $node->title));
    drupal_set_message(t('@type %title has been deleted.', array('@type' => node_type_get_name($node), '%title' => $node->title)));
  }

  $form_state['redirect'] = '<front>';
}

The value of $form passed to the form handlers is not passed to the browser, but it is retrieved in the Drupal cache from drupal_build_form(), which calls form_get_cache() when the form has been submitted. The documentation of drupal_build_form() contains the following sentence:

  The form may also be retrieved from the cache if the form was built in a previous page-load. The form is then passed on for processing, validation and submission if there is proper input.

If you look at Drupal code, you will notice that none of the core modules check if the user has the permission of accessing the form in the form submission; the only code you will find is the code that checks if an error message must be output, in the case that error message should be visible to a group of users that is smaller than the group of users that has access to the form.

As side note, Drupal.org has a security team that investigates on security issues reported for Drupal core code, and any third-party modules hosted on Drupal.org; for third-party modules, they don't investigate on reports for non official releases of the modules (e.g. alpha, beta, and development snapshots). If you find a security issue in Drupal, you should report it in the project queue for Drupal core.


How to fix search result "Access denied You are not authorized to access this page"

In admin/people/permissions, make sure that the roles that should be allowed to search are checked. Under the Search heading, look for the Use search permission. If anonymous users need this permission, check the box next to Anonymous User.
Next, clear your Drupal cache.

If you use Drush, you can use the following command.

drush cc all

There are several other ways to clear your cache as well.

Lastly, you can try rebuilding your permissions at admin/reports/status/rebuild.


You can add '#submit' => array('SOME_FUNCTION') to your submit button and write your function normally.


Specific role can only change status (active/blocked) of any user

As I mentioned in the question,

  I would like to give permission to that role he can change status (active/blocked) without editing the other fields...

I've done it without giving permission (Administer users) to role ONE.

I had to do configurations between tree modules Flag, Views and Rules. I created new flag, get flag in views using relationship and the add two simple rules. That's all

Let me post the answer, may be someone will need in the future.

Above mentioned three modules should be enabled with their UIs.

Creating Flag

Go to /admin/structure/flags/add, create a new flag and choose User as Flag Type, example
After saving the Flag Type, fill next form like this, you may choose options as you like.

Creating Views

Now, create a views page/block as you like with showing Users category and your all fields you want to show and add a Relationship for the flag you just created (in my case it was "Block User").
Now, add a new field as Flag link in the views and add relationship if its already not and choose settings
Save the views

Creating Rule

We have to add to rules one for block the user and other for activate the user.

Block User

Add a new Rule /admin/config/workflow/rules/reaction/add and choose event "A user has been flagged, under Block User" and save
Add a condition using "Data comparison" and continue
Add value in data selector for flagged-user:status and continue
On next form, choose value as active and save
Now, add an action with Block User action and continue and add choose data selector for flagging-user and save

Activate User

There are same steps to activate users using rules. You just only to change event as "A user has been unflagged, under Block User", check the status as blocked instead of active and finally add action Unblock User instead of Block user.

All done...

Now, go to view the views you just created check if it works.

I hope it'll help someone.


Different image for markers and cluster markers Openlayers

I'm not entirely sure what effect you're after, but I have a map that uses clustering and custom markers. I've added the code at the end of the answer. The code changes the marker dynamically: if there are visible markers of more than one type (taxonomy term) then it shows a general purpose marker; if all the visible markers belong to one type then it shows that type's marker. It works by creating a copy of the Style object with a custom context object that allows you to specify JS functions named after the placeholder that take the cluster as an argument and return a value to replace the placeholder. I've used the delete render intent to signify a marker's hidden and I get the feeling that might not be standard (but it works for me:). I'm not an OpenLayers guru, so no promises this is the best way!

var style_properties = settings.styles.service_providers;
var default_marker_path = style_properties.externalGraphic;
// Convert the path to an internal one. This can't be done via the
// OpenLayers interface.
// @see http://drupal.org/node/1166076#comment-5633868
default_marker_path = default_marker_path.replace(new RegExp('http(s)?://.*?' + Drupal.settings.basePath), '');

var options = {
  context: {
    /**
     * Dynamic attribute replacement function. Returns the path to the
     * appropriate marker for this cluster. It will return a specific
     * service type's marker if there's only one kind of visible marker
     * within the cluster; the default marker otherwise.
     *
     * @param OpenLayers.Feature cluster
     *   The cluster containing the pseudo features.
     *
     * @todo Create a TID-based index into the features array for
     *   performance benefits.
     */
    field_service_type_marker_path: function (cluster) {

      var marker_path = default_marker_path;

      for (var i = 0; i < cluster.cluster.length; i++) {
        var feature = cluster.cluster[i];
        if (feature.renderIntent !== 'delete') {
          // Feature is visible.
          if (marker_path === default_marker_path) {
            marker_path = feature.attributes.field_service_type_marker_path;
          }
          else if (marker_path !== feature.attributes.field_service_type_marker_path) {
            // There's more than one type of visible marker - early out
            // and use the default marker.
            marker_path = default_marker_path;
            break;
          }
        }
      }
      return marker_path;
    },
    /**
     * Checks through the features in the cluster and returns whether
     * this cluster should be visible (ie whether or not it has any
     * visible features).
     */
    cluster_display: function (cluster) {
      for (var i = 0; i < cluster.cluster.length; i++) {
        var feature = cluster.cluster[i];
        // I could use .getVisibility(), but there's no need at the
        // moment, because the only way that a feature might not be
        // visible is if I changed its renderIntent.
        if (feature.renderIntent !== 'delete') {
          // Any return value that's not 'none' will cause the cluster
          // to be rendered.
          return '';
        }
      }
      return 'none';
    }
  }
};

// Set up the variable externalGraphic to allow different marker images
// based on the TID.s
style_properties.externalGraphic = Drupal.settings.basePath + '${field_service_type_marker_path}';
// Set up variable display, so that the clusters can be hidden if every
// feature inside them is.
style_properties.display = '${cluster_display}';

// Set up new styles for both 'default' and 'selected' renderIntents.
layer.styleMap.styles['default'].destroy();
layer.styleMap.styles['default'] = new OpenLayers.Style(style_properties, options);
layer.redraw();


How to use drupal_add_tabledrag() with paging feature?

This can be done. If taxonomy module does it then its doable isn't it? So to do that you have to mainly follow 2 functions.

function taxonomy_overview_terms(..) in line # 249 @ /modules/taxonomy/taxonomy.admin.inc
function theme_taxonomy_overview_terms(..) in line 548 @ /modules/taxonomy/taxonomy.admin.inc.

The first function is the form that generates the list of items present in the term listing page. (The screenshot you attached)
The second function is the hook_theme implementation of the prior function and adds the table drag functionality to the page. If you look closely, the form has navigational steps added in it and then in the theme function they are made available for JavaScript to handle the back and forth navigation you mentioned. These are $form['#back_step'] & $form['#forward_step']. Those are converted to backStep & forwardStep and added to Drupal's JavaScript settings. So also you have to look at the taxonomy.js in where these are called and handled.


Those two statements are not equal.

$form['#attached']['library'] = array('somelibrary');

Resets the library array to only contain "somelibrary".  This would remove anyone else's library that may need to get loaded.

$form['#attached']['library'][] = 'somelibrary';

This adds "somelibrary" to the existing libraries array for inclusion. (this is correct)

$form['#attached']['library'][] = array('somelibrary');

This is the wrong structure.

For Drupal 8

$form['#attached']['library'][] = 'somemodule/somelibrary';


How to make a regular expression case insensitive?

The case insensitive usually is adding a "i" char after the delimiter bar, something like this:
/^AB37|^AB38|^AB41/i

but depends of the case it can be changed. In JS, for example is adding a new param (var re = new RegExp(myVar,"ig")) or in php is preg_match("[expression]i", $text, $matches);


Get the nid from current URL after the ? for views argument

Just put $_GET['gids'] this will return you an array in PHP.
Then if there's only one nid you can make:

$gids = $_GET['gids'];
return $gids[0];

Source: How to get PHP $_GET array?


How to display 9 products WITH images on one page

A Node is not a "Store", it's a Product display, meaning that it displays a group of Products that belong together (like t-shirts in different colors/sizes).

To have 9 separate products displayed on a page, you create 9 nodes and assign a product to each of them. Then you can for example build a view that lists them on a single page.


Can't create table when installing module

Follow the standard procedure to unisntall a module.

In short, once the module is disabled it may appear in the Uninstall tab of the modules page. Select the module in that tab and click 'Uninstall'.

When you disable a module its configuration and tables are kept, so if you enable again all data and configuration remains the same. When you uninstall a module you tell Drupal to wipe out any configuration and data by that module. When enabling it again Drupal detects that there's no configuration nor tables of that module and creates them again. If you only disable the module and enable it Drupal doesn't create configuration and tables because they should be in the database,m as Drupal knows module was enabled once.

In module list you have the available modules, some them enabled and some them disabled. If oyu want to comnpletely remove a module you have to disable, uninstall and delete the folder manually.


How to use Rules' "set data value" with image fields?

I do something similar on my site; though the solution will vary according to where you are getting the image file from.

On my site, I first use a "Download a file from the internet" action to fetch and save the image file I want.  When you are setting up this action, be sure to scroll all the way to the last fieldSet on the page - Provided variables - and make a note of the machine name there(or change it to something more memorable)

Next add a "Set a data value" action, and use the machine name from above as the Value.

[edit] I have just realised - while looking down my module list - that the "Download a file from the internet" Rules action is provided by a module, here is a link:- https://www.drupal.org/project/rules_download


How can I output markup fields or descriptions in my Webform email?

Did you tried using this? If the markup field foo sits within the fieldgroup bar, you need to inverse the order and the last % shouldn't be there.

%value[bar][foo]