How to add some JavaScript functions before Ajax begins

"beforeSubmit" handler attached that way will be executed right before Ajax request:

(function ($) {
  Drupal.behaviors.ReplaceWithAnyTextYouWant = {
    attach: function (context, settings) {
      // 'edit-submit' is the element ID where you execute the #ajax.
      Drupal.ajax['edit-submit'].options.beforeSubmit = function(form_values, element_settings, options) {
      // If cancel is clicked, do not continue submitting.
      if (!confirm('Are you sure you want to continue?')) {
          return false;
      }
    }
  };
})(jQuery);

You could perform some pre-submit validation of the user input, and even cancel form submission by returning false

Here is a good example

'edit-submit' - is the element html ID of submit button with '#ajax' settings. 'edit-' prefix is attached to the key of your form array item containing triggering element (submit button in your case).
For $form['my-submit'] = array(...), html ID of the resulting button will: "edit-my-submit".

JS file with code shown above, could be attached to your form in form constructor:

$form['#attached']['js'][] = drupal_get_path('module', 'your_module') . '/js/file.js';


Make some text of the calendar module multilingual?

The calender links are defined in the calendar/theme/theme.inc in the function function template_preprocess_calendar_main(&$vars) here you can see that the $calendar_links  use the function date_t() as found in the date_api.module and can be translated. In other words, if i am correct, you can translate this through the translate interface, as found on admin/build/translate.


How does data propagate from the formElement of a Widget to the properties of a FieldItem?

submitForm() of the content entity form calls via several other methods (which you find in the call stack) this method of the field widget, which then sets the values of the field items.

WidgetBase::extractFormValues():

  public function extractFormValues(FieldItemListInterface $items, array $form, FormStateInterface $form_state) {
    $field_name = $this->fieldDefinition->getName();

    // Extract the values from $form_state->getValues().
    $path = array_merge($form['#parents'], [$field_name]);
    $key_exists = NULL;
    $values = NestedArray::getValue($form_state->getValues(), $path, $key_exists);

    if ($key_exists) {
      // Account for drag-and-drop reordering if needed.
      if (!$this->handlesMultipleValues()) {
        // Remove the 'value' of the 'add more' button.
        unset($values['add_more']);

        // The original delta, before drag-and-drop reordering, is needed to
        // route errors to the correct form element.
        foreach ($values as $delta => &$value) {
          $value['_original_delta'] = $delta;
        }

        usort($values, function ($a, $b) {
          return SortArray::sortByKeyInt($a, $b, '_weight');
        });
      }

      // Let the widget massage the submitted values.
      $values = $this->massageFormValues($values, $form, $form_state);

      // Assign the values and remove the empty ones.
      $items->setValue($values);
      $items->filterEmptyItems();

      // Put delta mapping in $form_state, so that flagErrors() can use it.
      $field_state = static::getWidgetState($form['#parents'], $field_name, $form_state);
      foreach ($items as $delta => $item) {
        $field_state['original_deltas'][$delta] = isset($item->_original_delta) ? $item->_original_delta : $delta;
        unset($item->_original_delta, $item->_weight);
      }
      static::setWidgetState($form['#parents'], $field_name, $form_state, $field_state);
    }
  }


How to have one stylesheet for logged in users and another one for anonymous users?

The template_preprocess_html() preprocess function adds a 'logged-in' or 'not-logged-in' class to the classes array.
These classes get printed in the html.tpl.php template on the body tag.

So you should be able to target anything in your css for logged in or logged out users by using those classes. For example:

.sharing-block {
  top: 0px;
}
.logged-in .sharing-block {
  top: 25px;
}

Something like that should work without needing to worry about conditionally applied stylesheets or anything like that.


How to determine if {{user_picture}} is not empty in the comment.html.twig template

The comment entity is available and you can get the author and its field data from that, e.g.
{% if comment.uid.entity.user_picture.target_id > 0 %}
  {{ user_picture }}
{% else %}
  ...
{% endif %}


I was able to track the issue to a change made in views module that was committed with 3.1 release. Contextual links statement was changed from 'OR' to 'AND' causing issues with the setup that was run with version 3.0.

http://drupal.org/node/1451218#comment-5980636


You could use hook_facetapi_filters() to define a new filter for your facets.

/**
 * Implements hook_facetapi_filter().
 */
function MODULE_facetapi_filters() {
  return array(
    'uppercase_items' => array(
      'handler' => array(
        'label' => t('Uppercase items'),
        'class' => 'FacetapiFilterUppercaseItems',
      ),
    ),
  );
}

and then extend the FacetapiFilter class like this:

class FacetapiFilterUppercaseItems extends FacetapiFilter {

  /**
   * Filters facet items.
   */
  public function execute(array $build) {
    // Do your magic.
    foreach ($build as $key => $value) {
      $build[$key]['#markup'] = ucfirst($value['#markup']);
    }
    return $build;
  }

  /**
   * Adds hook documentation.
   */
  function settingsForm(&$form, &$form_state) {
    $form['uppercase_items'] = array(
      '#title' => t('Uppercase filters'),
      '#type' => 'checkbox',
      '#default_value' => TRUE,
    );
  }
}

I haven't actually tried this out but this is pretty much what Facet API Bonus does, which is also a great example for creating your own filters.


Solving performance issue DrupalDatabaseCache::clear

If you are facing performance problems using database as cache backend you should consider moving the caches to a better performing cache backend. Suitable backends for general caching are for example Memcached and Redis. For both of these you can find proper contrib modules (Redis & Memcache) and a lot of help in using them. If you want to have high performance page cache you could use Varnish for that. Also setting up APC to improve general PHP performance is a wise thing to do. Some basic information on using APC can be found from here.

Whatever caching methods you choose to use you should remember that form-cache must use non-volatile storage. This means that you should simply remember to keep form-cache in database. This can be achieved by inserting the following to your sites settings.php file.

$conf['cache_class_cache_form'] = 'DrupalDatabaseCache';


menu items saved with menu_link_save() don't have the delete button, and I can't edit the menu path

The reason the "delete" link is not shown is that the link is only shown when the menu item is created by (or associated to) the Menu module. _menu_overview_tree_form() contains the following code:

  // Only items created by the menu module can be deleted.
  if ($item['module'] == 'menu' || $item['updated'] == 1) {
    $operations['delete'] = l(t('delete'), 'admin/build/menu/item/' . $item['mlid'] . '/delete');
  }

menu_link_save() uses some defaults for the array $item passed as argument; this means that if the module associated with the menu link is not explicitly set, it receives the default value ("menu").

  // Load defaults.
  $item += array(
    'menu_name' => 'navigation',
    'weight' => 0,
    'link_title' => '',
    'hidden' => 0,
    'has_children' => 0,
    'expanded' => 0,
    'options' => array(),
    'module' => 'menu',
    'customized' => 0,
    'updated' => 0,
  );


Is there a problem defining a View using a path alias? Or did I just miss something?

It could be, that I'm still having difficulties understanding your question, but I have no idea why you would expect that to work?

/path/to/%term contains an argument, and as such there is essentially an infinite number of variations that could "fit" into that path.
A path alias "/pageone" to "/path/to/aterm", does not match "/path/to/otherterm", nor any other path in the system.

Each path alias must point to a specific path, and there is to my knowledge no way to automatically "Create all possible path-aliases to for a path /path/with/%arg". There is a feature request for such a tool though.


Tracking isotope clicks with Google Analytics?

You can use Google Event Tracking.
There is a great module for that already Google Analytics Event Tracking

Just enable both the main and the example module included so you can try it out.
In the selectors array you can define wich element you want to track (e.g. a#logo)
By setting 'label' => '!test' you can test if the click works (will show an alert box)

$selectors = array(
array(
  'event' => 'mousedown',
  'selector' => 'a#logo',
  'category' => 'Home Link',
  'action' => 'click',
  'label' => 'Logo',
  'value' => 0,
  'noninteraction' => TRUE,
),


How To Remove Table border or hid to show my page

Add this to your theme CSS:

table {border: none;}

Which will alter all the tables in your theme
To limit the border removal to just this view, find the view class [in Google chrome, use the code inspector] to find the div with the class 'view' and select the class appropriate to this view.
For example if you have the classes:

view
view-Tender
view-display-id-page_1

you can limit the table border css by:

.view-Tender table {border: none;}

for all the displays in the view or

.view-Tender.view-display-id-page_1 table {border: none;}

for just this display.


If you would like to get the current viewed nodes id you should be able to do like this:

// check so we're really viewing a node
if (arg(0) == 'node') {
  // grab the nid for the node
  $nid = arg(1);
  // you could also try to load the node to make
  // sure the supplied nid is valid
  if (node_load($nid) == FALSE) {
    // failed to load the node
  }
}

In the case of an ajax request I guess you really should supply the nid as an argument:

function <MODULE>_menu() {
  $items['sample/%1'] = array(
    'page callback' => '<MODULE>_sample',
    'page arguments' => array(1),
    'type' => MENU_CALLBACK,
    'access arguments' => array('access content'),
  };
  return $items;
}

function <MODULE>_sample($nid) {
  // use the supplied nid here
  $node = node_load($nid);
  if ($node) {
    // do something with the loaded node
  }
}

jQuery('#output').load('sample/21');


Allow blank search/list all items with 1.x apache solr module

I ended up with the below patch that seems to do the trick. The patch looks much larger than it needs to because I corrected the indentation after I removed an if.

Anyone that considers using this patch should be aware that this will hack the module. You should understand what that means, and be using a make file to avoid future complications.

$ diff -u apachesolr_search.module_ apachesolr_search.module
--- apachesolr_search.module_   2013-02-11 10:12:17.814561087 +0100
+++ apachesolr_search.module    2013-02-11 13:29:10.450336901 +0100
@@ -159,24 +159,22 @@
   if (isset($_GET['filters'])) {
     $filters = trim($_GET['filters']);
   }
-  // Only perform search if there is non-whitespace search term or filters:
-  if ($keys || $filters) {
-    // Log the search keys:
-    $log = $keys;
-    if ($filters) {
-      $log .= 'filters='. $filters;
-    }
-    watchdog('search', '%keys (@type).', array('%keys' => $log, '@type' => t('Search')), WATCHDOG_NOTICE, l(t('results'), 'search/'. $type .'/'. $keys));

-    // Collect the search results:
-    $results = search_data($keys, $type);
+  // Log the search keys:
+  $log = $keys;
+  if ($filters) {
+    $log .= 'filters='. $filters;
+  }
+  watchdog('search', '%keys (@type).', array('%keys' => $log, '@type' => t('Search')), WATCHDOG_NOTICE, l(t('results'), 'search/'. $type .'/'. $keys));

-    if ($results) {
-      $results = theme('box', t('Search results'), $results);
-    }
-    else {
-      $results = theme('box', t('Your search yielded no results'), variable_get('apachesolr_search_noresults', apachesolr_search_noresults()));
-    }
+  // Collect the search results:
+  $results = search_data($keys, $type);
+
+  if ($results) {
+    $results = theme('box', t('Search results'), $results);
+  }
+  else {
+    $results = theme('box', t('Your search yielded no results'), variable_get('apachesolr_search_noresults', apachesolr_search_noresults()));
   }
   if (empty($form)) {
     // The form may be altered based on the query that was run.
@@ -998,9 +996,6 @@
     $get['retain-filters'] = '1';
   }
   $form_state['redirect'] = array($base . $keys, $get);
-  if ($keys == '' && !$queryvalues) {
-    form_set_error('keys', t('Please enter some keywords.'));
-  }
 }


views 2 - how to fetch filepath of image field for output rewriting

One trick I like to use is adding a field that contains the value I need, then hiding it from display but using it's token value for your original field's override.

So your view fields would look something like:

image path (hidden from display)
image (using value from the above field)

Keep in mind that the order is important here, so you only have access to tokens that are above the field you want to use them in.

You may need to tweak the settings of the path field to make it the style of url you need (relative, absolute, etc).


how can I make date fields come out in other languages in webform with drupal 7

fixed, I was logged in as an admin and had admin language set to english


In drupal 7, views 3 if you add a relationship File Usage: File you get some new fields you can add to your view, including the filename. The filename includes the extension (.doc, .pdf etc). But even with that you could theme the specific field with a template where you could easily use php to cut the .mp3 part.


1.) What is happening

Twig sanitizes all variables before displaying them. Because it assumes, that the style attribute is from user input and is considered to be unsafe. You can pass most html as #markup, but not the style attribute.

2.) You asked about the most correct way to do this is.

This would be to put all html markup in templates.

3.) How to get around this

If you don't want to build a custom twig template for this, you can use an inline template instead:

$variables['book_now_widget'] = [
        '#type' => 'inline_template',
        '#template' => '
{{ var1 }}
',
        '#context' => [
          'var1' => 'bla bla bla'],
];


I use buildwith chrome plugin and Appspector, it does not looks like they use drupal CMS.


Can i populate /fill a Views exposed filter with a Rules result

I don't know if it's possible with Rules, though most things are!

But that should be possible with the Computed Field Module. It allows you to do just that, compute fields based on others and you can use it in your views.

https://drupal.org/project/computed_field


Greggles comment is most likely correct. Check your php path my going to the phpinfo path in the reports section. The URL is admin/reports/status/php.


Got the Problem. FB changes their structure of application. Not a bug


How do I reset a user's name using Drush in Drupal 7?

There isn't a built in Drush command, but you can use Drush's sql-query command (or sqlq shorthand) to update the user's name:

drush sql-query "update users set name='SOMENEWNAME' where uid=####"

Where #### is the user's uid and users is the user table.


Problem Trying to upgrade webform to latest version using composer

Manually editing composer.json to add "drupal/webform": "^6.0" did the trick.


How to hand over value of field 1 to class array of field 2 programmatically in .theme

Context between template variable arrays is an old problem already
  known in D6 and 7 on theming level. What about D8 now? Any light on
  the horizon?

No, there is no light on the horizon, quite the contrary. Because of the concept of nested render elements, that are rendered independently. In D8 it is getting far more complicated because of the dynamic cache. And it wouldn't work at all with the plans for the future with placeholders and lazy building.


How to load jQuery UI after bootstrap js files?

There are a couple of ways in Drupal 7 to control load/execution order.  The simplest is to change the module weight in the system table to get the right order.  Unfortunately, this will not work in this case since there is a module and theme involved.  Themes always get executed after modules (so UI changes are ensured to happen and not be overwritten).

This means you will probably have to write some code in order to modify the load order.  In your [theme.module] file, you will need to implement the Drupal hook: hook_js_alter.  E.g. add a function my_theme_js_alter(&$javascript) to the theme module file.

You will probably need to install devel and use dpm to dump the javascript array.  You can then use this information to rearrange the load order as you need it.  Probably just unset the jquery_ui entry and add it to the array at the bottom.


Trouble adding conditional to page-title.html.twig

You're doing it wrong. The method you are using is not consistent if you change the page title to something else, or use another page as your landing page.

There are two ways to solve this:

The long way, using hook_preprocess_html()

Instead of this, I recommend targeting the <h1> tag through a body selector, and add there a special class for front page through hook_preprocess_html(). This is a cleaner solution, and you can target other elements as well.

This code would go to your YOUR_THEME.theme file:

function YOUR_THEME_preprocess_html(&$variables) {
  // Add a custom class determining if we're on the front page.
  if (\Drupal::service('path.matcher')->isFrontPage()) {
    $variables['attributes']['class'][] = 'front';
  }
  else {
    $variables['attributes']['class'][] = 'not-front';
  }
}

In your html.html.twig file you need to have:

<body{{ attributes }}>

Then in your CSS file, you would use:

body.front h1.page-title {
  /* Your styles. */
}

The short way, using only twig - by 4k4

The root_path variable provided to you by template_preprocess_html() will be set to FALSE when you are on the front page. This means that you can use it as condition argument, and give different class to the body element.

Here's an example:

<body{{ attributes.addClass(root_path ? 'not-front' : 'front') }}>

Hope this helps.


Rules fatal error during update: Call to undefined method stdClass::events()

Debugging is the art of eliminating all possible causes for your problem. Below are some attempts to help you to find the real cause of your issue ...

1. Enable Rules debugging

Something that might help you find the answer to your question, is to have a look at Rules debugging ... Within the Rules settings, experiment a bit with the debugging facilities that come with Rules. At least have a look at the "Rules Evaluation Log" (to check that the Rules logic being executed, actually matches what you expect that logic to be).

For way more details about Rules debugging, refer to the answer to "How can I display the value of a variable inside a condition?".

2. Disable all active rules and re-enable them one by one

Instead of "disable" of the Rules module (which will possible resolve your issue until you enable it again), try to leave it enabled. But start with a disable of all Active (enabled) rules.

If it is some custom rule that is causing your problem, if none of your rules are active, the problem should have disappeared also after you disabled all active rules. If that's the case, re-enable your rules again, one by one, do some test to ensure the rule you enabled did execute. Keep doing this until you hit the custom rule that makes the issue come back again. Then disable that rule again, and check if there are other remaining rules that also make the problem show up again. In the end, try to adapt the rule(s) that seem to cause the issue so that the problem no longer shows up. If you cannot solve it, do not re-enable that rule anymore and think of some alternative.

3. Special watchdog entries

Make sure to also check for any unexpected watchdog entries, it may help to get a clue about what is happening


How do I troubleshoot 'Theme key "" not found'?

This warning message comes from theme() function in includes/theme.inc. For temporary debug you could just add ddebug_backtrace() there (if you're using Devel module) to see where the call comes from (and see what are the params). If not using Devel, just check output of debug_backrace(). And then it all depends what you are going to find out...


synchronise development website with live website

This is a very long topic to cover fully so I will just push you to the right direction to get things rolling and save you from lot of trouble.

You should never sync your local db to production db after you have first installed the site to production environment. The sync process of db is always one way: production -> staging -> local environment. Also when syncing the db from production you should always sanitize the sensitive data (user emails and passwords) for example with Drush sql-sync --sanitize option (yes you can have Drush for Windows too). To able to use this kind of workflow you need to have the configuration of modules, views etc. in code not in db. In Drupal 7 you can use modules like features to achieve this. In Drupal 8 most of this will be covered with cores built-in configuration management. Of course on top of everything you need to use version control system to not go nuts when developing the site. Services like Bitbucket, GitHub and GitLab give you the needed tools and ge you going with VCS in no time. With version control you can compare different versions of code, fall back easily to previous versions in your code and easily take more collaborators in the mix in the future. Doing any size of development without version control system is just plain stupid.

If you can't afford to have a staging environment on a VPS you should use your local environment wisely. Having your local environment as close as possible to the production environment is a wise thing to do in any circumstance. Use a virtualization product like Virtualbox and install the exact same setup on your local computer than you have on your production. When managing several production environments tools like Vagrant, Chef and Puppet can help you to keep configurations in sync and make your life easier :)

Things you should also remember is to have regular automated backups of your production data, know how to fall back to previous versions of code, configuration and db if something fails and to treat production environment always as a production environment. Remembering all of this makes your life a lot easier :)


How to include only an updated custom field in an email created using Rules?

Part 1: Processing a single field

Below is a sample of a rule (in Rules export format) that will send an eMail similar to what is asked in the question:

{ "rules_notify_author_of_selected_field_updates" : {
    "LABEL" : "Notify author of selected field updates",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "ON" : { "node_update" : [] },
    "IF" : [
      { "entity_has_field" : { "entity" : [ "node" ], "field" : "field_optionlist" } },
      { "NOT data_is" : {
          "data" : [ "node-unchanged:field-optionlist" ],
          "value" : [ "node:field-optionlist" ]
        }
      }
    ],
    "DO" : [
      { "mail" : {
          "to" : "[site:current-user:mail]",
          "subject" : "Notification about a node with a special field value",
          "message" : "Go checkout the node with nid [node:nid] and title [node:title]: it has a field with a value (which is [node:field-optionlist]) you needed to be informed about ..."
        }
      }
    ]
  }
}

Some more details to further explain the above above sample:

The Rules event I'm using is "After updating existing content".
In my case I have a selection list field with machine name field_optionlist, and a few possible values.
The Rules Condition checks if the "The selected value changed".
If the Rules Condition is true, then (as Rules Action), an eMail will be triggered to the editing user.

Change the field name of field_optionlist to match the field name of your content type, and adapt the actual eMail details (subject, etc) to fit your needs. Then import it in your own site (using the Rules UI). That's it.

Part 2: Processing a multiple fields

Option 1 - a SEPARATE rule for processing each field

If you have multiple fields, create a similar rule for each of them, so that it will send 1 single eMail for each field update.

Option 2 - a SINGLE rule for processing all fields together

If you have like a dozen fields, using Option 1 implies .... a dozen rules (fairly straight forward rules, but a bit of a maintenance challenge). To consolidate them all in a single rule, you should consider (both of) these refinements:

a Rules Component (which will replace the Rules Action as in the prior rule example), and which you'll be able to reuse within the Rules Action later on by assigning appropriate values to its variables (as further detailed below).
the Conditional Rules module which will allow for conditions to be part of a Rules Action.

Read on for more details on this refinements.

Rules Component

Create a Rules Component that will (simply) produce an eMail, using these Parameters:

User to be notified with machine name user_to_notify.
Updated Field Label with machine name updated_field_label.
Updated Field Value (old) with machine name updated_field_value_old.
Updated Field Value (new) with machine name updated_field_value_new.

Here is an example (in Rules export format) of such Rules component (I trust the eMail subject, content, etc is clear from just reading the source ...):

{ "rules_email_field_updates" : {
    "LABEL" : "eMail field updates",
    "PLUGIN" : "action set",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "USES VARIABLES" : {
      "user_to_notify" : { "label" : "User to be notified", "type" : "user" },
      "updated_field_label" : { "label" : "Updated Field Label", "type" : "text" },
      "updated_field_value_old" : { "label" : "Updated Field Value (old)", "type" : "text" },
      "updated_field_value_new" : { "label" : "Updated Field Value (new)", "type" : "text" }
    },
    "ACTION SET" : [
      { "mail" : {
          "to" : [ "user-to-notify:mail" ],
          "subject" : "Notification about an updated field",
          "message" : "Please be aware that the field labeled \u0022[updated-field-label:value]\u0022 has been updated from \u0022[updated-field-value-old:value]\u0022 to \u0022[updated-field-value-new:value]\u0022.",
          "from" : "[site:mail]",
          "language" : [ "" ]
        }
      }
    ]
  }
}

Conditional Rules

On top of the field_optionlist field from above, let's assume we add a 2nd field, i.e. a free format text field with machine name field_free_format_text. Assuming that you enabled the Conditional Rules module, you should be able to import the rules example below (in Rules export format) in your own environment (provided you first defined 2 similar fields with identical machine names to make the import work, or after you first edit the field names to match your field names):

{ "rules_notify_editing_user_of_selected_field_updates" : {
    "LABEL" : "Notify editing user of selected field updates",
    "PLUGIN" : "reaction rule",
    "ACTIVE" : false,
    "OWNER" : "rules",
    "REQUIRES" : [ "rules", "rules_conditional" ],
    "ON" : { "node_update" : [] },
    "IF" : [
      { "OR" : [
          { "entity_has_field" : { "entity" : [ "node" ], "field" : "field_optionlist" } },
          { "entity_has_field" : { "entity" : [ "node" ], "field" : "field_free_format_text" } }
        ]
      }
    ],
    "DO" : [
      { "CONDITIONAL" : [
          {
            "IF" : { "NOT data_is" : {
                "data" : [ "node:field-optionlist" ],
                "value" : [ "node-unchanged:field-optionlist" ]
              }
            },
            "DO" : [
              { "component_rules_email_field_updates" : {
                  "user_to_notify" : [ "site:current-user" ],
                  "updated_field_label" : "Option List",
                  "updated_field_value_old" : [ "node-unchanged:field-optionlist" ],
                  "updated_field_value_new" : [ "node:field-optionlist" ]
                }
              }
            ]
          }
        ]
      },
      { "CONDITIONAL" : [
          {
            "IF" : { "NOT data_is" : {
                "data" : [ "node:field-free-format-text" ],
                "value" : [ "node-unchanged:field-free-format-text" ]
              }
            },
            "DO" : [
              { "component_rules_email_field_updates" : {
                  "user_to_notify" : [ "site:current-user" ],
                  "updated_field_label" : "Free Format Text",
                  "updated_field_value_old" : [ "node-unchanged:field-free-format-text" ],
                  "updated_field_value_new" : [ "node:field-free-format-text" ]
                }
              }
            ]
          }
        ]
      }
    ]
  }
}

If you're familiar with Rules, the above Rules example should be self explaining. If you're not, here are a few more details to explain the rule:

Rules Event: After updating existing content.
Rules Conditions: Check if we're processing content that has either of our 2 fields.
Rules Actions:

If the value of field_optionlist changed, then invoke the Rules Component, with parameters related to this field.
If the value of field_free_format_text changed, then invoke the Rules Component, with parameters related to this field.

Voilà, happy (Conditional) Rules-ing!


How to create active menus for the content type in drupal 7?

If you're just about tabs in a content type you could try this.


WYSIWYG not appearing for custom content type

I know that wysiwyg is related to input filters, are these available on the body (if there is one) of the custom nodes?


How do I submit a user registration form in code?

if you just want to create new user, it is easy as you create the user object and fill it and save it:

$user = \Drupal\user\Entity\User::create();
$user->setPassword($values->getValue('pass'));
$user->enforceIsNew();
$user->setEmail($values->getValue('mail'));
$user->setUsername($values->getValue('name'));
$user->activate();
$user->save();

but in my case for example I wanted drupal to do other stuff like send welcome email...etc, so what i did, instead of last step ( $user->save() ):

$formObject = new RegisterForm($this->entityManager, $this->languageManager, $this->entityQuery);
$formObject->setEntity($user);
$formObject->save($form,$form_state); // $form and $form_state can be created like you did.
// if you want to get the newly created user
$user = $formObject->getEntity();

on the other hand I have tried to get your code working, and the following was the outcome code:

$formObject = $this->entityManager->getFormObject('user','register');
$formObject->setEntity($user);
$formStateObject = (new FormState())->setFormObject($formObject);
$form = [];
$form = $formObject->buildForm($form,$formStateObject);
$formObject->validateForm($form,$formStateObject);
$formObject->submitForm($form,$formStateObject);
$formObject->save($form,$formStateObject);

Hope that helps.


how to setup rule events for before/after video is played?

When video start/end it should call js function which trigger ajax call for path you create on drupal (using hook_menu) the callback of that menu item should call the rule you want using rules invoke function
    rules_invoke_component('rule_name', $arg);

So the case is how to trigger the ajax call on start/end

if you are using youtube, check this page, you can trigger js function to start the ajax

https://developers.google.com/youtube/iframe_api_reference

if you have another player you should look to the api


Arrays in query strings get converted into actual PHP arrays when you use $_GET.

To get the value in your case you'd use something like:

print $_GET['date_filter']['year']['value'];


How can I detect if node is the last one from within node.tpl.php?

In general, it is not a good idea for Drupal objects to not "know" how they are being used on a page.  When you make them "self-aware" you introduce artificial dependencies that can make changes down the road harder to make, or inadvertently introduce bugs.

In you case, I would handle this in the views templates.  Out of the box, the last row should have a views-row-last class on it.

Otherwise, you need to implement a template_preprocess_node in your theme.  The view object will be available as $variables['view'].  You would need to add logic to check page, view name, etc, to make sure you are doing things in the right place.  Off the top of my head, I forget which properties you need to check; do a kpr($variables['view']) and poke around.


Date selection with price - without commerce

You can accomplish this with the Field Collection module and Date module.

Navigate to manage fields under your node type
Create a new field with field type of Field collection
Set the number of values to unlimited under the field you created in step 2
Navigate to /admin/structure/field-collections and select Manage Fields under the field collection you just created in step 2.
Select Manage Fields
Add From Date Field
Add To Date Field
Add Price Field


Is it possible to send a response from a service, but return something else?

You can still use setcookie/setrawcookie in Drupal, if you are sending a response, you can use Symfony to set one:

$cookie = new Cookie('name', 'value', $expire, '/', 'domain', TRUE, TRUE, TRUE);
$response->headers->setCookie($cookie);

vs

setrawcookie('name', 'value', $expire, '/', 'domain', TRUE, TRUE);

Note that the internal Drupal function that writes a cookie adds a prefix that you probably don't want.


limit exposed filter to top X taxonomy terms in drupal 7

I think the closest I have seen to doing what you ask is http://drupal.org/project/better_exposed_filters which tries to at least make the exposed filters more manageable.

EDIT:

If you are prepared to switch the filtering to faceted search you could use search_api module in combination with its built in facets (through solr). Then you end up with being able to restrict the amount of terms you show in the facet.


Shopping cart contents section is empty for anonymous users

This is almost always due to some sort of relationship in the View's configuration linking from the cart order's line items to some other entity the user doesn't have direct access to view. Rather than try to find the right permissions, the easiest thing to do assuming you have other filters (or contextual filters) on the View to ensure the customer doesn't see other data is to disable SQL rewriting under the advanced settings for the View.

On a hunch, though, you should also make sure anonymous users have access to view their own orders. We have special code in the cart module to ensure access control works in that situation, and it could be the entire order is inaccessible and not just some related entity.


Programmatically Create 'full_html' Page Node in Drupal 7

OK, as it turns out, the 'body' field is not called 'body' in our Drupal installations; it's called 'field_page_body'. Changing that in the code made everything work.


You don't need to write a custom module. You can use the popups api module. All you will have to do is assign the link a class called as "popups". Refer to the api if you want to do it the custom way as well using the popup api.

Summary of the module

  API for building modal ajax dialogs. Its focus is on putting forms
  inside of ajax popup dialogs. Current example can present pages as
  popups (of the lightbox type). This is amazingly useful for things
  like confirmation pages. And the best part is it can be applied
  retroactively to a page without needing to modify the generating
  module, and (of course) it degrades gracefully.


Drupal 7 timestamp insert into mysql error

The 'datetime' value assumes the "YYYY-MM-DD HH:MM:SS" formatting, if I got it, you're trying to insert a 'timestamp'


Download drupal 8.0.2
Extract
Copy the core directory into your project.
Copy the .htaccess , composer.lock & composer.json files to your project
Copy the vendor directory to your project
Go to yoursite.com/update.php
Follow the on-screen instructions

Note: if you use composer then see my answer to this question


How to add a list of stock and node reference to create the perfect stock of beers?

Only use the Flag module, so that your users can just "flag" the nodes related to your Beer Content type. With such approach, there is no need for the extra content types InStock and MyBeers that you are considering (a commonly known best practise in Drupal is to try to keep the number of content types to a minimum).
Some details about the Flag module (from its project page):

Flag is a flexible flagging system that is completely customizable by the administrator. Using this module, the site administrator can provide any number of flags for nodes, comments, users, and any other type of entity. Some possibilities include bookmarks, marking important, friends, or flag as offensive. With extensive views integration, you can create custom lists of popular content or keep tabs on important content.
Flags may be per-user, meaning that each user can mark an item individually, or global, meaning that the item is either marked or it is not marked, and any user who changes that changes it for everyone.
In this way, additional flags (similar to published and sticky) can be put on nodes, or other items, and dealt with by the system however the administration likes.

Create a flag that can be used by each user individually (not a "global" flag), so that each user can flag the Beer Content types, and which would be the equivalent of your "MyBeers" type you had in mind. And by using the technique of Attaching fields to flags, you could create a field corresponding to that "int" field of your "InStock" content type you had in mind.
Super easy and straight forward. And by using the Flag module, as a bonus you get all those amazing features about integrations with other modules such as Rules, Views, Views Bulk Operations (VBO), etc. Some samples:

Build a view to see what is in "your" fridge, and or apply mass updates using the VBO module.
Use the Rules module to send eMail reminders when your stock "is running low".

If you're not familiar with the Flag module, checkout the set of 8 video tutorials about this module. Especially the Video about Creating non-global flags: between about 6:00 and 8:30 it explains how to add a Flag-related relationship in your view, so that you can then also use flag related data in your view (for fields, etc). The same video (near the end) also shows how to combine this with VBO.
Some more suggestions related to some additional (non-global) flags I recommend you to create, which would probably enhance the beer-experience of your users even further:

My favourites: a flag to indicate the favourite beer(s) of a user (... like "Leffe Blond" ...)
Looking for it: a flag to indicate the beer(s) a user is looking/searching for, like where to buy such beer (like "Celis White" ...).
Tasted it: a flag to indicate the beer(s) a user ever tasted, e.g. to create a contest about nr of different beers somebody every tried (like "400" ...), or an inventory of beers that are still on your whish list to ever try (like "empty" ...).


How do you view a log of previous visited visitors showing their IP in Drupal 7?

You can find visitors IP-adresses in both the sessiontable (field hostname) or, if you have the core statistics module enabled, in the accesslog table (field hostname).

You can view these logs in a tool that let you examine your database (I use phpMyAdmin), or you can write a small custom module that displays them for you.


Manipulating Theme Suggestion Priorities

You shouldn't need to add a theme suggestion if you're trying to override the view template for a given view ID. Confusing things is the fact that Views' suggestions don't show in the debug code (see: https://www.drupal.org/node/2118743).

If you add a file named views-view--view-machine-name.html.twig (replacing machine-name, of course) in your theme's templates directory and clear caches, it should pick it up. Note: it has to be templates and not in your theme's root or my_templates or anything else. Drupal is picky that way.

You should not need to worry about module/theme weights as all module alter functions run before theme alter functions.

Finally, if you are add theme suggestions I would recommend using the more targeted hook_theme_suggestions_HOOK_alter. (For views, the HOOK is views-view so your function would look like:

function mytheme_theme_suggestions_views_view_alter(array &$suggestions, array $variables) {
  $suggestions[] = ...
}

Hope that helps.


Filtering link associated with view based on permissions

Resolved by:

Installing views php
Creating a static class with the permission logic in it.
Editing the view to have Global:PHP as a field.

The class is autoloaded via module.info file. files[] = 'MyClass.inc'. Static function is just a facade to the module function so that it will be in scope.

class MeetingClonePerms {
  public static function accessCloning($nid) {
    // Calls module function here.

The php in Global:PHP views field is in 'output code':

<?php
if (MeetingClonePerms::accessCloning($row->nid)) {
  print  'nid . '">clone';
}
?>


How does Drush figure out modules that have updates?

Use pm-uninstall to completely remove a module from your system.

If you have already deleted the code for the modules in question, the safest and best thing to do is put the code back and run pm-uninstall.  If you just want to get rid of the reference to the module in the system table, you could take matters into your own hands, and just do this:

drush sqlq "delete from system where name in ('moduleone', 'moduletwo');"

If you do that, though, then the module won't have a chance to remove any other unneeded assets that would be deleted if you used pm-uninstall.


You need to set the state in the "value" key, so one level deeper as you tried.
E.g.:

$form['field_yourfieldname'][LANGUAGE_NONE][0]['value']['#states'] =
  array('visible' =>
    array('input[id="edit-field-otherfieldname"]' => array('checked' => TRUE))
  );


Use content field as data attribute in Views html

There are some limitations if you can't change the output templates for the view (and I'd assume if that's the case a views pre render is also out of scope). If you can accept them within the <li> (instead of on the <li>) you can rewrite the field to use a token. Make sure the field that is just data is listed before the field it will be attached to, enabled rewriting on the field, and use the field tokens to attach the value as an attribute. You'll most likely want to suppress the field from output and do some data cleaning to make sure invalid characters don't end up in the token (like ").

You can attach classes based on the row value to the li by using the same token you would use on the rewrite. Drupal will ensure it's safe for output, but then your data is a class and not the attribute you are seeking.

You'll have more control over the output, and you'll be able to build more elegant solutions if you use hook_views_pre_render() to modify the output more directly.


I looked further, but could not really find any documentation describing this.

What I needed was a way to join the users table with two other tables holding data for the users. However, the two other tables are in a 'one-to-many' relationship with the users table, meaning that I'll end up with a Cartesian join if I attempt to join the users table with both of these tables at the same time. However, since all I need is to count the number of records in the two other tables associated with any given user, a subquery should be able to do the trick. However, I couldn't find any documentation on Views and subqueries - so here is what I did.

Created two dummy fields

I created two dummy fields (which I'll call 'downloads' and 'listens') through hook_views_data(). The definition of the field are listed below.

function hook_views_data() {

  $data['users'] = array(
    'downloads' => array(
      'title' => t('Downloads'),
      'field' => array(
        'handler' => 'views_handler_field_numeric',
        'click sortable' => TRUE,
      ),
      'filter' => array(
        'handler' => 'views_handler_filter_numeric',
      ),
      'sort' => array(
        'handler' => 'views_handler_sort',
      ),
    ),
    'listens' => array(
      'title' => t('Listens'),
      'field' => array(
        'handler' => 'views_handler_field_numeric',
        'click sortable' => TRUE,
      ),
      'filter' => array(
        'handler' => 'views_handler_filter_numeric',
      ),
      'sort' => array(
        'handler' => 'views_handler_sort',
      ),
    )
  ),
);

Now, when you configure a view for users, the fields 'Downloads' and 'Listens' will appear. However, attempting to run a query now will result in an error as the dummy fields after all are dummy fields. They do not exist. The only purpose of these fields is to signal to to our implementation of hook_views_query_alter() that it needs to do a few replacemenets.

Implement hook_views_query_alter()

The trick here is to check wether the given query includes the 'Downloads' or 'Listens' fields. If it does, we'll remove the fields from the query and replace them with subqueries. The implementation of this function goes as below.

function mta_views_query_alter(&$view, &$query) {

  foreach ($query->fields as $field_key => &$field_values) {
    if ($field_values['table'] == 'users') {

      switch ($field_values['field']) {
        case 'downloads':
          unset($query->fields[$field_key]);
          $query->add_field(null, "(SELECT COUNT(*) FROM {fileusage} fu WHERE fu.externaluser = {users}.uid AND fu.action = 0)", $field_key);
          break;
        case 'listens':
          unset($query->fields[$field_key]);
          $query->add_field(null, "(SELECT COUNT(*) FROM {fileusage} fu WHERE fu.externaluser = {users}.uid AND fu.action = 1)", $field_key);
          break;
      }
    }
  }
}

Note that we're reusing the alias of the removed field for the subquery. That way, Views will think that the value returned from the subquery actually comes from the dummy field (which after all does not exist).

That's is. We're not getting a Cartesian join and both 'downloads' and 'listens' are counted correctly.


Taxonomy vs. CCK List for categorizing Events

If you use taxonomy, then using the calendar module they can be colour-coded in the legend based on their category.


How to prevent node creation using hook_node_submit?

To stop a node being created, you need to implement hook_node_validate instead, and raise an error. The hook is specifically to:

  Perform node validation before a node is created or updated.

Which is what you want.

The example in the docs page is probably quite close to what you'll need:

function hook_node_validate($node, $form, &$form_state) {
  if (isset($node->end) && isset($node->start)) {
    if ($node->start > $node->end) {
      form_set_error('time', t('An event may not end before it starts.'));
    }
  }
}

For the record, hook_node_submit is both conceptually the wrong place to try to stop a node being created, and too late in the process to do so anyway. The node hasn't been saved by that point, but you've lost any simple opportunity to stop the remaining submit handlers running and the default process completing. Even if you found a way to short out that functionality, there would be no sensible method to feed that back to the user.

You can throw an exception or kill the page request of course, yes, but Drupal obviously won't be able to recover from that and the request will terminate.


Which table stores the content type fields?

Drupal 8:

Content type = Bundle
Node = Entity
Base fields are in one table: [entity]_field_data
Bundle fields are in seperate tables: [entity]__field_name

Bundle fields are stored in the same table for all bundles of one entity and can be shared between bundles of the same entity but not with another entity.


Drush only partially working in both VM (Ubuntu) and host OS (Mac OS X 10.10)

If you are in docroot then the most likely cause is multiple site definitions which mean drush can't tell which is active. You may need to supply the -l or --url parameter to disambiguate if that is the case.

In your drushrc file you can set up parameters so as to avoid having to keep supplying the parameter explicitly.


How to create a module as a wrapper for js

If you've done work with themes and template.php, writing a module will be a snap. Review Creating Drupal 7.x modules for the basics, but at a minimum you need a yourmodulename.info and a yourmodulename.module file to get going. Declaring the block
 specifically will start you off on being able to define your blocks. As for including css and js, use the drupal_add_css and drupal_add_js functions respectively.


How can I create a custom html tag in the CKeditor wysiwyg editor?

What you need is a custom filter. Filters are the check boxes you can set on input formats like 'Filtered HTML' and 'Full HTML'.

There is an example available in the examples module: https://www.drupal.org/project/examples

Basically, you need this:

1) You need to implement hook_filter_info() to let Drupal know there is a new filter
2) You need to a function to process the input. This is where you can use your regex.

I highly suggest looking at the examples module or any other modules that use filters.


Drupal confusion when including multiple instances of same webform on a page

In either Display Suite or a node template just call the forms using drupal_get_form each form will given a unique build_id and there should be no problem displaying any number of forms on the page.

hook_forms in this answer https://drupal.stackexchange.com/a/6230/3279 has nothing to do with your question. You don't need to worry about incremental form IDs or anything.

Here is an example of how to use a preprocess function for a Node (type):
http://purencool.com/drupal-7-preprocess-tutorial-adding-variable-to-template this uses this Drupal API function https://api.drupal.org/api/drupal/modules!node!node.module/function/template_preprocess_node/7

Your code would look something like (this is example code not guarenteed to work):

function MYMODULE_preprocess_node(&$vars) {
  if ($vars['node']->type == 'MY_NODE_TYPE') {
    // link to webform paths.
    $vars['custom_form_links'] = implode(' ', array(l('Please Fillout Form 1', 'some/path/to/webform'), l('Please Fillout Form 2', 'some/path/to/webform2')));
    // Or just embed the forms.
    $form1 = drupal_render(drupal_get_form('myform1'));
    $form2 = drupal_render(drupal_get_form('myform2'));
    $vars['custom_forms_embed'] = $form1 . $form2; // You may want additional HTML wrappers, figure it out.
  }
}

Then in your themes template files for like node--YOURCONTENTTYPE.tpl.php you echo these new variables.

Display Suite makes all this a ton easier with Code Fields, or custom fields, and dynamic view_modes so you don't need to touch template files either ...

None of this code is guarenteed to run -- it's just a rough example.


EntityFieldQuery gives error on adding propertyCondition

Fields have columns. Properties do not. You want:

$query->entityCondition('entity_type', 'taxonomy_term')
  ->propertyCondition( 'tid',  $tid, '>=')
  ->propertyCondition('vid', 3)
  ->propertyOrderBy('tid', 'ASC')
  ->range(0, 1000);


I haven't figured out how to manually set the destination on comment post, but I did found the Comment Goodness module that works with More Comments, to remove the ?page-1#comment-# query. And this solves my question.


How to implement autocomplete for address field using google places/maps api?

I have created a working sandbox version of address autocomplete. https://drupal.org/sandbox/adammitchell/2126989. I will endeavour to get it created into a full blown project. However if you could help me and test it that would be greatly appreciated.


How do I compare two strings in a template file?

This depends on the context, but most likely item.url is not a native string variable test, but a function or a render array with the string representation / render result test.

This is similar to Drupal's well known content variable: When you render {{ content }}, you will get the string representation like
content...
. But when you do a dump or kint, you will see that content is an array, and doing a comparision {% if content = '
content...
' %} will be false too.

I'd recommend to always avoid boolean operations with rendered representations, always head for the raw data. E.g. don't do {% if content.field_something.0 == 'my_value' %}, instead inspect the entity {% if node.field_something.0.value == 'my_value' %}.

If you have to compare to a render array, you could do somehting like {% if some_var|render == 'my_string' %}.


How to use the uc_csv module for getting reports

you can create export reports by clicking the "CSV Export" menu item located under "Store administration" in the Drupal administrative menu system.

You can create any number of reports to export certain criteria. More granular criteria can be programmed later if there is demand for such a feature. Please provide feedback if this is the case.


In a writing a Views style plugin, how can I create a text input that accepts Twig?

To replace argument tokens in a Views plugin you need:

$tokens = $this->view->build_info['substitutions'];
$value = $this->viewsTokenReplace($value, $tokens);

If you've based your plugin on StylePluginBase you can use StylePluginBase::tokenizeValue, which additionally replaces row tokens as well.


How to create an entity reference view that contextually filters based upon current user ID

You need to add a relationship to the view. It will either be "node: author" or "content: author" depending on your distro/version (I'm commerce 7, views 3).

Once you've added the relationship, "User: Uid" will be an available option under contextual filters.


Importing Bootstrap CDN-mediated styles into the Sub-theme's Style.css

You can use Bootstrap Library module to do that. quoting from the project page:

  This module is fully compatible with the Bootstrap Theme. If you wish,
  use it as an alterative to the CDN loading.


The PUT request shows "HTTP/1.0 406 Not Acceptable: Missing node type"

This ticket might be of some help.
http://drupal.org/node/1191786


Is there a best form for security surrounding updating an entity of an unspecified type?

I think the entity metadata wrapper is semi indiscriminate aslong as the field is the exactly the same on both entities. So you can just wrap it and then use the default set/get methods

// All your code (it looks fine)
$wrapper = entity_metadata_wrapper($entity_type, $entity);
$wrapper->FIELD_TO_SET->set(VALUE);
$wrapper->save();

More info on the metadata wrapper


If you fx want to set the default value using, given it is passed as a parameter in the URL:

function hook_form_FORM_ID_alter(&$form, &$form_state) {
  $params = drupal_get_query_parameters();
  if (isset($params['my_param'])) {
    $form['FIELD_NAME']['und'][0]['#default_value'] = $params['my_param'];
  }
}

https://api.drupal.org/api/drupal/modules%21system%21system.api.php/function/hook_form_FORM_ID_alter/7


How to set the language for the user while it is created?

Actually it was a simple thing, just that I didn't enabled the language. So the steps are:

install and activate i18n module
go to admin/config/regional/language and add the languages you want
then in admin/people/create you will have a language selector.


How do I set Views Bulk Operations Fieldset Collapsed by default?

Use hook_views_bulk_operations_form_alter()

<?php
function mymodule_views_bulk_operations_form_alter(&$form, &$form_state, $vbo) {

 if($form['#form_id'] =='views_form_block_id'){

  $form['operations_fieldset']['#collapsed'] = TRUE;

 }

}
?>


How I can delete all node/field revisions?

There's not yet a stable release for Revision deletion but a D7 port is on its way (not sure if its functional at all).

In this thread someone suggested using VBO to isolate revisions and delete them.

If you feel comfortable with the API, make a loop through all your nodes, retrieves the revisions using node_revision_list() and delete them using node_revision_delete().

As a last resort and if you like messing with the DB (like I do) you can delete revisions' rows in field_revision_* and node_revision tables. Try this:

WARNING: not tested at all !

DELETE FROM field_revision_body
WHERE NOT EXISTS (
  SELECT NULL
  FROM node
  WHERE vid = revision_id
);

DELETE FROM node_revision
WHERE NOT EXISTS (
  SELECT NULL
  FROM node
  WHERE node.vid = node_revision.vid
);

You can find the complete list of your revisions' tables in the information_schema database:

SELECT DISTINCT TABLE_NAME
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME LIKE 'field_revision%'
AND TABLE_SCHEMA = 'your_database';


Output node.type in page.html.twig gives "EntityReferenceFieldItemList cannot be printed"

node.type is a reference to the node type entity. You can get the id of the content type with target_id, as you have mentioned in the comment. For debugging this might be OK, but most times you want to get the label, which is nicely formatted and translatable:

{{ node.type.entity.label }}


How to hook into adding watchdog entries by other modules?

Unfortunately hook_watchdog doesn't provide a return value which could block the insertion of the log entry in the database.

Note though that the responsible module for inserting the entry in the database is dblog. You could disable that and write your own implementation of it, although you'd have to replicate lots of functionality.

Another idea is to have a frequent cron job deleting the relevant log entries from the database table.


This forum post on d.o explains what may be your problem.

You need to:

  Set $cookie_domain='example.com'; explicitly in your settings.php file.

According to the post, Drupal keeps a long session ID string in a cookie, and without a proper cookie domain, the current user is anonymous.


How to limit direct access to URLs of nodes that are shown in a video gallery created with Views?

Try content access module and prevent access to video content individually( or also you can set access to it for you desire roles )

  This module allows you to manage permissions for content types by role
  and author. It allows you to specifiy custom view, edit and delete
  permissions for each content type. Optionally you can enable per
  content access settings, so you can customize the access for each
  content node.

Also you can use Node View Permissions module, but I suggest use Content access module.

(if you want work with drupal for future is better getting involve with this useful modules)


When should I use the Url::fromRoute method instead of "new Url"

From the documentation for the Url class:

  In most cases, use Url::fromRoute() or Url::fromUri() rather than
  constructing Url objects directly in order to avoid ambiguity and make
  your code more self-documenting.

So, generating a new Url object from a static method is preferred.


How do I render an entity view mode like 'teaser' in a twig template?

The best practice would be to configure the reference field in UI as teaser and use it in the node template:

{{ content.field_entity_ref }}

If this is not an option for your case, you would probably need some code in preprocess.

But much easier is to use the module Twig Tweak, which can render nodes without preprocess:

{{ drupal_entity('node', node.field_entity_ref.0.target_id, 'teaser') }}


Display Google Search XML results onto site within HTML

We can use the Google Search Appliance module for this.

This will retrieve the results as HTML and there are custom search-result(s) theme templates which will allow us to theme as per our requirements


Pantheon is now offering Panoply, a distribution built on Panels that features TinyMCE via WYSIWYG as well as the media module already set up and ready to go.  You can register for a free account with them and test out a pre-built version of Drupal with the modules already set up in a fairly intelligent configuration.

Disclaimer: I'm a Pantheon customer, but I really do think that trying out this distro is a great way to see a hands-on example of what can be done not just upon installing a bunch of modules but after someone has taken the time to polish up the site.


How to save the URL of anonymous user on a webform?

So you can achieve this using form alter,

create a text field namely 'refer_url' for saving referring url, then using following snippet in your module you can save the referring url. You can hide this field in display using css or form alter.

function module_name_form_alter(&$form, &$form_state, $form_id) {
    if ($form_id == 'webform_client_form_27') {
    $form['submitted']['refer_url']['#default_value'] = $_SERVER['HTTP_REFERER'];
    }
}


Using select expressions or derived field in Views2 as fields?

It looks like what I need to do is create a Custom Field Handler. From the linked article, a definition such as this

<?php
class scheduler_handler_field_scheduler_countdown extends views_handler_field {
  function query() {
    $this->ensure_my_table();
    $this->node_table = $this->query->ensure_table('node', $this->relationship);
    $this->field_alias = $this->query->add_field(NULL,
      'IF(publish_on AND publish_on > UNIX_TIMESTAMP(),
        publish_on - UNIX_TIMESTAMP(), NULL)',
      $this->table_alias . '_' . $this->field);
  }
}
?>

adds this to the query

SELECT node.nid AS nid,
       node.title AS node_title,
       IF(publish_on AND publish_on > UNIX_TIMESTAMP(),
           publish_on - UNIX_TIMESTAMP(),
           NULL) AS scheduler_publish_countdown
    FROM node node
    LEFT JOIN scheduler scheduler ON node.nid = scheduler.nid
    WHERE node.status = 0


How to show a menu for everybody but one role?

hook_menu is not called on every page load, because that make Drupal really slow. It is only called when the menu is being (re)built, and the resulting menu structure is cached.

In hook_menu, you can tell Drupal how to determine which users have access. Access is not granted by role, but by permission. That way, you can easily grant the same permission to other roles when needed.

You will need to:

Define a new permission using hook_permission
Add the new permission to the role you want to give access
Restrict your menu item to users with that permission by adding 'access arguments' => array('[name of your permission]'), to your menu item

For an example, see the menu_example module at api.drupal.org. More specifically, see how menu_example_permission defines a new permission and how menu_example_menu specifies that permission as access arguments for the $items['menu_example/permissioned/controlled'] item.


altering form with hook_form_FORM_ID_Alter

You shouldn't reset the form completely by doing $form = array();, since you will delete some of the stuff Drupal expects to be there.

You should instead do something like this:

function dental_form_simplenews_block_form_2_alter(&$form, &$form_state)
{
    global $user;
    // Remove what you don't want..
    unset($form['fields']);
    // Add what you do want..
    $form['#attributes'] = array('class' => array('newsletter'));
   ...
}


Drupal6 reference URL date in views filter?

UPDATE: I solved this by using the "Views PHP Filter" http://drupal.org/project/viewsphpfilter
after that i was able to choose Node PHP filter and added code to select the nodes based on the passed date like this:

$my_req = $_SERVER["REQUEST_URI"];

preg_match('/my_page\/(.*)-(.*)-(.*)/', $my_req, $matches);

# Get the month from the URL or use the current month:
if(isset($matches[1])){
  $my_Y = $matches[1];
  $my_m = $matches[2];
  $my_date = $matches[3]+1;
} else {
  $my_Y = date("Y");
  $my_m = date("m");
  $my_date = date("d")+1;
}
$the_date = $my_Y . "-" . $my_m ."-". $my_date;
$nodeids = array();
$query = "SELECT nid FROM content_type_event WHERE field_start_value > \"$the_date\" AND field_start_value < DATE_ADD(\"$the_date\", INTERVAL + 16 DAY) ";

$my_result = db_query($query);
while ($my_row = db_fetch_array($my_result)) {
  $nodeids[] = $my_row['nid'];
}
return $nodeids;


how to call/using geofield in a custom module

Geofield module is rather complex module which adds a lat/long fieldset and so many other stuff such as adding new fields, validation, etc.
Anyway, you can create a latitude and longitude input field using the #type => 'geofield_latlon'.
$form['geofield'] = array(
  '#title' => 'geofield',
  '#type' => 'geofield_latlon',
);

Note that this will return a generic longitude latitude form. NOT a Google Maps choose-location field.
See geofield.elements.inc for more information on how this element is validated and themed.
Update: I forgot to mention that the above element is available in the 7.x-2.x branch.


Calling a JS function after managed file has completed uploading

This is tricky in D8, as the ajax code does not offer any hooks or callbacks after the function has run. The solution is to override the ajax callback function that the managed_file element uses, adding an additional custom command that is triggered when the file upload is complete.
First, we create a custom AJAX command, that will be used to trigger the code we want to execute. Details on creating custom ajax commands can be found here.
First, the Ajax command on the PHP side. This will go into [MODULE]/src/Ajax:
<?php

namespace Drupal\[MODULE]\Ajax;

use Drupal\Core\Ajax\CommandInterface;

/**
 * Command to trigger an event when managed file upload is complete.
 */
class ManagedFileUploadCompleteEventCommand implements CommandInterface {

  /**
   * Implements Drupal\Core\Ajax\CommandInterface:render().
   */
  public function render() {
    return [
      'command' => 'triggerManagedFileUploadComplete',
    ];
  }

}

Next, the triggerManagedFileUploadComplete() command needs to be created on the JavaScript side. This is done in [MODULE]/js/managed_file_upload_complete_event_command.js.
(function (Drupal) {

  "use strict";

  /**
   * Add new custom command.
   */
  Drupal.AjaxCommands.prototype.triggerManagedFileUploadComplete = function () {
    // Do stuff here after file upload is complete.
    alert(Drupal.t("File upload complete!"));
  };

}(Drupal));

Now the new JavaScript file needs to be registered in MODULE.libraries.yml:
command.managed_file_upload_complete_event_command:
  js:
    js/managed_file_upload_complete_event_command.js: {}
  dependencies:
    - core/jquery
    - core/jquery.once

With this, the custom command can be attached using the library: [MODULE]/command.managed_file_upload_complete_event_command
Now that the custom command and it's related JS callback have been completed, the next thing is to add the new command onto the end of the ajax callback, so it is executed when the upload is complete.
The default ajax callback for managed_file elements is \Drupal\file\Element\ManagedFile::uploadAjaxCallback(). This needs to be overridden, adding the command created above to be run after all other ajax commands.
The #ajax property of the managed_file element is added in \Drupal\file\Element\ManagedFile::processManagedFile(). As such, if we want to alter the ajax, it has to happen after the above #process handler has been run. So we add another #process callback to be called after the default #process callback. In our process callback, we can change the #ajax callback to a function of our own. The #process callbacks are declared in \Drupal\file\Element\ManagedFile::getInfo(). Adding another #process handler can therefore be done in hook_element_info_alter().
/**
 * Implements hook_element_info_alter().
 */
function MODULE_element_info_alter(array &$info) {
  // Add a custom #process hook to the managed_file element:
  $info['managed_file']['#process'][] = 'MODULE_managed_file_process';
  // Add the custom command to managed_file elements, so that it is
  // available when called:
  $info['managed_file']['#attached']['library'][] = '[MODULE]/command.managed_file_upload_complete_event_command';
}

Now the command has been created and attached to all managed_file elements. The next step is to override the #ajax callback with our own, adding the custom command to it. Let's look at the overridden function (should be put in the .module file):
/**
 * Custom ajax callback for managed files.
 *
 * Overrides \Drupal\file\Element\ManagedFile::uploadAjaxCallback()
 *
 * @see \Drupal\file\Element\ManagedFile::uploadAjaxCallback
 */
function MODULE_managed_file_ajax_callback(array &$form, FormStateInterface $form_state) {
  // Retrieve the original response.
  $response = \Drupal\file\Element\ManagedFile::uploadAjaxCallback($form, $form_state, \Drupal::request());

  // Add our own command to the end, so our command is run last:
  $response->addCommand(new \Drupal\[MODULE]\Ajax\ManagedFileUploadCompleteEventCommand());

  return $response;
}

The last thing to do is to replace the original ajax command with our own. This is done in the process callback we registered in hook_widget_info_alter():
/**
 * Custom process callback added to managed_file elements.
 *
 * Replaces the original #ajax callback with a custom one.
 */
function MODULE_managed_file_process(array &$element, FormStateInterface $form_state) {
  $element['upload_button']['#ajax']['callback'] = 'MODULE_managed_file_ajax_callback';

  return $element;
}

This tells Drupal to replace the original ajax callback with MODULE_managed_file_ajax_callback(). This callback retrieves the response from the original callback, and adds our custom command to the end of it. The custom command is called when the file has been uploaded, allowing us to run whatever JS we need on the server side after files have completed uploading.


When a profile needs to create something to make it accessible once the profile is installed (e.g. blocks, content types, fields), it does it in its hook_install() implementation. For example, the standard profile creates content types, fields, and input formats in its standard_install(); it also enables some of the standard blocks, and it set the Seven theme as administrative theme.

Drupal doesn't use any directives in the .info file to automatically create nodes, but a profile could implement code to parse extra directives in a .info file, for example in hook_modules_installed().

I would rather go with implementing hook_install(). I may consider using directives in the .info file if there is a module handling them and I am writing more than three profiles for which being able to change the nodes added from the profile is much important. I understand that avoiding to keep changing the code make less probable to introduce errors; since I know the code to use to create nodes, and the task is relatively simple, using directives in the .info file doesn't simplify much the code I would write for a profile.
I would take more in consideration a module that would back-port to Drupal 7 the code that in Drupal 8 handles the configuration files used to create content types, and fields for those content types, using YAML files. For example, this is the core/modules/forum/config/optional/node.type.forum.yml file that in Drupal 8.3 allows the Forum module to create its content type.

langcode: en
status: true
dependencies:
  enforced:
    module:
      - forum
name: 'Forum topic'
type: forum
description: 'A forum topic starts a new discussion thread within a forum.'
help: ''
new_revision: false
preview_mode: 1
display_submitted: true


how to change alphabetic order to descending order in drupal 7

Drupal menu items are manually ordered. You can drag and drop into the correct order here: /admin/structure/menu/manage/navigation


Cancel user creation from hook_user_presave

The equivalent of hook_user('validate') used in Drupal 6 doesn't exist in Drupal 7. For that, you need to add a form validation handler to user_register_form(), and use form_set_error() when Taleo returns an error.


Maybe try Goutte. I thought there was a similar Migrate module + Goutte frontend out there ... but can't find it.


The code looks good! However, try the following:

See if there is already a permission or a module which lets you control the things you wish to control. Maybe you can mention the desired outcome or the objective in the question?
Add a dpm() or something to the end of the function to see if the $items are being modified correctly.
Add a dpm() or something in the _term_account() function to see if it is being called correctly and that it is returning TRUE or FALSE correctly as per your requirements.


Drupal won't look for the template in a theme path unless

You've added this code to a theme instead of a module or
You've put your module in the theme folder instead of sites/all/modules, and then perhaps moved it once installed (less likely I think).

If you've done either of these I'd advise fixing that problem and putting the code/module where it's supposed to go.

If you're too invested at this point, though, you can use the path argument to hook_theme() to provide a static path to your theme's implementation folder:

'upload_page' => array(
  'template' => 'templates/upload_page',
  'arguments' => array(
    'uploadurl' => NULL,
    'options' => NULL,
    'title' => NULL,
    'user' => NULL
  ),
  'path' => drupal_get_path('module', 'test')
)

The docs I've linked to are for Drupal 6 as I assume from your code that's what you're using; if you're using Drupal 7, the arguments property should be changed to variables.


Restrict webform component use to certain roles

Try Webform Webform Locked Fields module, you can set permission for specific role

  Users who have the "administer webform locked fields" permission will
  see a checkbox titled "Webform creator can modify" when they edit a
  webform component. If that box is unchecked, the component can only be
  modified or deleted by users who have the the "administer webform
  locked fields" permission. Other users who have webform creation
  permission will be taken to a page that says "Not allowed" if they
  attempt to edit or delete that component.


drupal_is_front_page() fails when using alias

drupal_is_front_page() compares the content of the "site_frontpage" variable with an un-aliased path because the content of that variable is set to an un-aliased path, on the page at admin/config/system/site-information.

In system_site_information_settings(), the form builder for that page, the content of the "site_frontpage" field is set using the following code:

'#default_value' => (variable_get('site_frontpage') != 'node' ? drupal_get_path_alias(variable_get('site_frontpage', 'node')) : ''),

In system_site_information_settings_validate(), the form validation handler for that page, the value of the "site_frontpage" field is set using the following code:

  if (empty($form_state['values']['site_frontpage'])) {
    // Set to default "node".
    form_set_value($form['front_page']['site_frontpage'], 'node', $form_state);
  }
  else {
    // Get the normal path of the front page.
    form_set_value($form['front_page']['site_frontpage'], drupal_get_normal_path($form_state['values']['site_frontpage']), $form_state);
  }

What is being saved in the "site_frontpage" variable is the normal path (a.k.a. the un-aliased one). It is the correct what drupal_is_front_page() does.
If there is a module that set the value of that variable to a path alias, then the code of that module should be changed, as that module is not working with the actual Drupal code.


How to reference a content-region block in node template?

In Drupal 6, you can do something like this:

$block=module_invoke(MODULE_NAME, 'block', 'view', BLOCK_NAME);

and now $block['content'] will contain the html content of BLOCK_NAME defined within MODULE_NAME.

I just noticed the -- in your template name, so in Drupal 7 it would be:

$block=module_invoke(MODULE_NAME, 'block_view', BLOCK_NAME);

and more details can be found here.


Why are they all showing up on the main entity page?

This is the easy part. I had the same issue with https://www.drupal.org/node/2299755, but I was dealing with several modules that were each defining a single entity.  Your configuration is a bit more complicated.

You are seeing the UI elements for Manage Display and Manage Field at admin/structure because admin/structure/gov-data doesn't exist. admin/structure is inheriting everything you've defined after admin/structure/gov-data like admin/structure/gov-data/bill/fields and admin/structure/gov-data/bill/display,  First you need to define a menu path for admin/structure/gov-data in your module, but this will only push all of the fields and display tabs up to that level.  You'll also need to either define a redirect for each entity so admin/structure/gov-data/bill goes to admin/structure/gov-data/bill/fields or alter the admin/structure/gov-data/bill/fields and display menus so they aren't tabs.

  How do I organize this so that it looks like content types?

This is a bit more complicated.  The display of node types found at admin/structure/types doesn't just automagically appear.  It is defined in the Node moduels's menu hook http://cgit.drupalcode.org/drupal/tree/modules/node/node.module?h=7.x#n2004.  To get something that looks like the content type list, you'll need to create a customized version of the node_overview_types() function found in http://cgit.drupalcode.org/drupal/tree/modules/node/content_types.inc?h=7.x#n8

So for your configuration, alter your hook_menu to add something like...

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

    $items['admin/config/services/gov-data'] = array(
        'title' => 'Government Data settings',
        'description' => 'Configure settings for Government Data',
        'page callback' => 'drupal_get_form',
        'page arguments' => array('gov_data_admin_settings'),
        'access arguments' => array('administer site configuration'),
    );

    // returns list of entities with menus "under" gov-data.
    $items['admin/structure/gov-data'] = array(
        'title' => 'Manage Government Data Entities',
        'description' => 'Links to manage field and display of entities',
        'page callback' => 'gov_data_overview_types',
        'access arguments' => array('administer gov data'),
        'weight' => -50,
    );

    return $items;
}
/**
 * Displays an entity type admin overview page.
 * Borrow from node/content_types.inc
 */
function gov_data_overview_types() {
  // This requires a lot more work
}

There is a lot of code you can repurpose from node_overview_types(), but that is something you can figure to meet your specific needs.  You biggest issues here are undefined menu paths being displayed at a level you didn't expect because the deeper, custom menu paths aren't defined anywhere.


How to display article metadata in a custom div?

"Read-only" usually means a file or an item that cannot be changed/edited, you can only view it. I'm guessing what you actually mean is "current, the one being viewed right now".

You have to add a contextual filter to your Views that would filter the results to only the node you're currently viewing.

Here are the steps to configure Views to show only the current node's results:

Expand the Advanced area in your Views
Under Contextual filters click on Add
Add the ID filter from the Content Category and configure it:
When the filter value is NOT available
Provide default value
Content ID from URL
When the filter value IS available or a default is provided
Specify validation criteria
Content
Article
Hide View if the argument doesn't validate, or some other options that make sense to you.
Place the Block on article pages in your theme region (your have this already), adjust Node from URL and other Block options.

The Views Block will only show on article pages, and it will only display output related to the current node.


Why is the subtheme_style.css not being called?

Turns out, I had everything set up correctly, but hadn't toggled "ON" the style sheet.

Navigate to: Site settings >> Appearance >> Settings >> Toggle Styles
Click "ON" checkbox next to New Theme global style. (all) - new_theme_style.css

I slept on it and woke early in the morning, remembering that not only do you need to enable your theme, you need to turn on the style sheet.


Drupal 8 uses libraries, and you can load these in templates. One way of achieving language direction dependant libraries would be to use the html_attributes['dir'] variable in html.html.twig and load different libraries depending on the value:

{% if html_attributes['dir'] == 'ltr' %}
  {{ attach_library('your_theme_name/styles') }}
{% elseif html_attributes['dir'] == 'rtl' %}
  {{ attach_library('your_theme_name/styles_rtl') }}
{%- endif -%}

Set up a couple of libraries:

styles:
  version: 8.x-1.0
  css:
    theme:
      css/styles.css: {}

styles_rtl:
  version: 8.x-1.0
  css:
    theme:
      css/styles-rtl.css: {}


7.26 /admin, /user not found on Localhost

This issue might be a variation of the question about "drupal /?q=user is working but /user not working". So verify if you can use an URL containing ?q=user or ?q=admin. If that gets you going, then probably tuning RewriteBase in your .htaccess (as described in the accepted answer of that question) should help.

It might be worth trying to further enhance your .htaccess file, by adding a line after that existing RewriteBase, which looks like so:

RewriteRule . index.php [L]

For more details on the above line, refer to the (accepted) answer in this question on StackOverflow.

Another option for debugging is to retry using another browser. If via that brower you are able to login, then it's probably a cookie problem (in your original browser).

If none of these suggestons help, then re-edit your question by adding more details about which modifications to your '.htaccess file, httpd.conf, etc' you already tried (and didn't work).

PS: Are you aware of the security issue fixed in Drupal version 7.32? Hurry to get your "site on a server" (as in your question) upgraded to the most Drupal core version!


Should I always save ContentEntityType after updating a value?

I think what it means is, that you shouldn't save changes that you don't want to keep.

Since you want to keep the change you are making, you have to save the entity.

The changes to make on they entity are only saved to the database when you call $entity->save().


Why will drupal not recognize my configuration?

This import is empty

This error might occurs when the config directory is not configured in the settings.php.
Check for the config directory settings in new site. It will mostly have a different directory configured.
Change to the same folder path as in the old site.


form ajax forget's changes made in previous ajax callback calls

AJAX callback function is meant to only tell Drupal what to update. By design all you do in it is for one call only.

Permanent changes needs to be done in main form creation function. I usually see them done in block like that:

if (!empty($form_state['values'])) {
  //here you are supposed to use these values
}


Filter out nodes with the same title in views

Consider looking at the Views Distinct module to do this ... Here are some details about this module (from its project page):

Relationships or other joins in Views often create "duplicate" results. For example, a node with a field that has multiple values may show up in the View once per value in the multi-value field. It's frustrating, and the "DISTINCT" SQL query option in the Views UI does not actually solve the problem because the result row is technically distinct. This module aims to give a simple GUI method to remove or aggregate these "duplicate" rows.
For any given field, including "Global: Text" fields, you can optionally mark the field as filtered ("Filter Repeats") or aggregated ("Aggregate Repeats"). All rows with the same value in that field will either be removed as duplicates (filtered), or aggregated in-line.
The "value" of the field as used for filtering or aggregation can be taken pre-render (fastest and totally cacheable), or post-render (after any rewrite rules or other transformations have occurred). Post-render actions are a bit slower (the View must be re-rendered, though the query is not re-run), but also work with Global fields, like Global: Text w/rewrite rules.

If this doesn't work for you, or for some reason you cannot / do not want to use this module, then consider any of the alteratives suggested by Sumit Madan ... (+1 !).


Drupal Multisite, same module name, different site

As long as they are in the individual sites' directories, the are only visible to the sites they are associated with. Should be no problem.


How can I automatically upload images on file selection rather than pressing the upload button?

You'd be better off doing this at the module level, rather than the theme level, as the JS will not take effect for admin pages otherwise (unless of course you're using the same theme for both).

Here's a small module to provide this functionality system-wide:

File: auto_upload.info

name = Auto Upload
description = Removes the need for users to press the 'Upload' button for AJAX file uploads.
core = 7.x
dependencies[] = file

File: auto_upload.js:

(function ($) {
  Drupal.behaviors.autoUpload = {
    attach: function (context, settings) {
      $('form', context).delegate('input.form-file', 'change', function() {
        $(this).next('input[type="submit"]').mousedown();
      });
    }
  };
})(jQuery);

File: auto_upload.module

function auto_upload_init() {
  drupal_add_js(drupal_get_path('module', 'auto_upload') . '/auto_upload.js');
}

Once you've installed the module all file inputs that are AJAX-ified (i.e. those that have an 'Update' button) will be affected...you won't need to press the 'Upload' button any more after selecting the file.

By using the delegate() method this will also work perfectly for file fields that allow multiple uploads, and also for fields that are loaded into the page as the result of an AJAX request.

I've tested that in Chrome, Safari and Firefox and it works a treat :)

Footnote: In the (probably very unlikely) event that your site is using jQuery 1.7, you should use the on() method, which has superseeded delegate().

UPDATE I've created a sandbox project for this module.


Well to address your concern about which version to download, if the instructions state Program Files (x86) then you want the 32-bit version of the dll. I'm not sure VC++ 9 or VC++11 should matter. As far as thread safe, you should check phpinfo() in your DevDesktop environment to make sure it's thread safe or not.

The XDebug site has a nifty wizard form where you can copy/paste your phpinfo() into it and it will point you to the version you need.


"An AJAX HTTP error occurred" when sending an email via VBO (view bulk operations)

As per this issue on VBO, you likely have a separate module that is stuffing up AJAX.

Try turning your custom modules off and then back on one by one to find the problem.  If it happens with your custom modules all off, try it with contrib modules.


Drush is a very useful tool and it will take some tasks from your hands, including running update.php after updating a module.

However if you cannot (or do not want to) use Drush, there are plenty of other options to update modules. You can use FTP to delete the module folder and then upload a new version of the folder. You can use SSH to obtain the module zip file by using wget and then delete the module folder and extract the zip file. Basically any possible way to get the contents of the zip file to your destination is a valid updating method.

Keep in mind that you cannot always safely unzip one module directly over another one. Always delete or empty the previous module version first. The reason for this is that several (class) files might have been removed from the module, but would not get removed from the file system this way. Drupal's registry might still load these files but then find another class with the same name in another file, resulting in fatal errors.

And no matter how you update the modules files, always stick to the regular updating instructions. This includes always running update.php.


How to get the correct 'base hook' to override a template file in a custom module?

Look into the *.module file where the base hook is defined, in this case the User module. The base hook is the key of the template definition:

user.module:

/**
 * Implements hook_theme().
 */

function user_theme() {
  return [
    ...
    'username' => [
      'variables' => ['account' => NULL, 'attributes' => [], 'link_options' => []],
    ],
  ];
}

Then in your *.module file

mymodule.module

/**
 * Implements hook_theme().
 */
function mymodule_theme() {
  return [
    'username__mymodule_template' => [
      'base hook' => 'username',
    ],
  ];
}

Start the name of your own hook  with the base hook and double underscores.


Cannot access commerce order relationship in Add relationship form in Drupal 7 Views

This was a false alarm. I was on a different branch with a single module missing. Enabling the module solved the problem.


Download and enable the devel module to use dpm() on $content. This will show you the proper structure of the $content array. Sometimes entities and fields will have different structures depending on their type or how they're being implemented for that content type.


Field Template Suggestions: Target a particular field type on a content type

I just happened upon this question while trying to remember how to solve the same problem. In this case, Drupal simply doesn't do what you're asking for by default. There are two ways to approach it, one by accepting Drupal's default behaviour, and one by overriding that default.

Default behaviour

As has already been pointed out here, Drupal's template suggestions for fields don't consider the field type (though they do accommodate the content type).

Living with Drupal's default behaviour

This is the simplest solution, though it's a bit inflexible. Since your goal is to use only one template, what you can do is this:

Create a field template in our theme according to the field--field-name--content-type.tpl.php pattern. This will customize one of your fields.
Create symlinks to your original template containing the names of the other fields you need to customize.

For example, given fields with names lorem, ipsum, dolor and sit, and the content type contenttype, you'd create one template:

field--lorem--contenttype.tpl.php

Then, you'd create the following symlinks to that template:

field--ipsum--contenttype.tpl.php,
field--dolor--contenttype.tpl.php,
field--sit--contenttype.tpl.php

Drupal will see these as four different but identical files.

Overriding Drupal's default behaviour

The previous solution is quick and simple, but slightly unsatisfying. If Drupal's so flexible, we should be able to handle this problem using the Drupal API, right?

Well, it turns out we can. It's possible for us to add our own template suggestions.

We do this like this:

1. Implement template_preprocess_field()

/**
 * Implements template_preprocess_field().
 */
function THEMENAME_preprocess_field(&$variables) {
  if ($variables['element']['#bundle'] === 'contenttype' && $variables['element']['#field_type'] === 'text_long') {
    $variables['theme_hook_suggestions'][] = 'field__contenttype__text_long';
  }
}

2. Copy field.tpl.php to your theme

Copy field.tpl.php from modules/field/theme/field.tpl.php to sites/all/THEMENAME/field--contenttype--text-long.tpl.php and then customize to suit.

Notes

The logic in the template_preprocess_field() implementation could be changed in several ways, e.g. to match only by field name in a given content type instead of all examples of a field type in that content type.
The process is almost the same when doing this task in a module except that you'll also need an implementation of hook_theme() in the module to make it work.
It would be possible to to this using only theme_field(), but theme functions are deprecated in Drupal 8, so this is the method that we'll all be using going forward.


Update field collection programatically - backend different to frontend

Well, as always happens I found the answer just after I posted the question:

// Unset and start afresh
unset($node->field_composition[LANGUAGE_NONE]);

foreach($fids as $fid){
  $comp = entity_load_single('field_collection_item', array($fid));
  $comp->field_chemical[LANGUAGE_NONE][0]['target_id'] = $id; // These values are derived elsewhere and are correct
  $comp->field_weight[LANGUAGE_NONE][0]['value'] = $value; // These values are derived elsewhere and are correct
  $comp->save(TRUE);
  $node->field_composition[LANGUAGE_NONE][] = array(
    'value' => $comp->item_id,
    'revision_id' => $comp->revision_id // ADDED REVISION ID HERE!
  );
}

node_save($node);


Programatically render field in specific language while leveraging core content language detection

You need get Translation of entity. function entity load just load default language, not load current language. Try this:

public function xmlController($entityType, $entityId, $fieldName, $displayName) {
    $entity = $this->entityManager->getStorage($entityType)->load($entityId);

    $entity_es = $entity->getTranslation('es');

    $field = $entity->{$fieldName}->view($displayName);
    new Response() object ...
  }

and you need detect language to auto. Code above just example.


How to remove results returned from Views UI

An answer to this question very much turns on what record you want to exclude from the listing. But the typical route here is to use a Contextual Filter on your view.

A typical pattern is that you are displaying a View alongside a node, e.g. a view of items that are related to that node. In this case, you want to exclude the node itself. For this you create a contextual filter that provides a default value of the the current node when there is no filter value present in the URL. You then check the exclude box in the contextual filter configuration. (Detailed steps below.)

Update In comments, you give more detail about what you want to exclude. Or, put another way, what you want to include. In general terms, you want to include nodes that share ANY taxonomy terms with the current node. Specifically, if you have a Teacher content type and a Subject taxonomy, then your requirement is to show every teacher that shares ANY of the taxonomy terms (representing subjects taught) of the currently displayed teacher.

Contextual Filters can do this out of the box, although the configuration is not especially intuitive. The approach is to add a Content: Has taxonomy term ID contextual filter and then configure it so it pulls taxonomy terms out the current node. (Detailed steps below.)

Stage one: Exclude current node

Add a contextual filter Content: Nid (under ADVANCED to the right of the Views configuration page).
Under WHEN THE FILTER VALUE IS NOT IN URL select 'Provide a default value' and choose 'Content ID from URL'. (This gets the node id.)
In the MORE section check the box 'Exclude'. (This says instead of filtering to show only the node, filter to show anything but the node. Of course, the normal non-contextual filters also apply.)

You can add more than one Contextual filter to build up more complex conditions. And, as noted above, you can write PHP for the Contextual filter.

Stage two:  Include all nodes that share ANY of the taxonomy terms of the current node

(aka, exclude any nodes that don't have any common taxonomy terms with the current node, but include everything else)

Add a contextual filter Content: Has taxonomy term id.
Under WHEN THE FILTER VALUE IS NOT IN URL select 'Provide a default value' and choose 'Taxonomy term ID from URL'. (This is a powerful option and what it does depends on the next configuration steps.)
Uncheck the 'Load default filter from term page' box.
Check the 'Load default filter from node page, that's good for related taxonomy blocks'
You will usually want to check the 'Limit terms by vocabulary' box and then select the relevant vocabulary, e.g. 'Subjects'. You might skip this step if you know you only have term reference field on kinds of nodes you are interested in. But it does not harm to check it even in these cases.
Under Multiple-value handling select the 'Filter to items that share any term' option.
Further down the configuration find the 'Reduce duplicates' check box and check it.
Open up the MORE fieldset at the bottom of the configuration and check 'Allow multiple values'


The easiest way is to create a block view of nodes (of whatever type you are calling a post). You actually create the block in Views. Views are one of the things that separates Drupal from WordPress. If you have no idea what they are, check out this page.


Custom "admin/people" view preventing user creation

Set your path to admin/people/list, not admin/people

Set the menu item for the page to "Default Menu Tab"

Set Default tab options to "Parent menu item already exists"

Worked for me, and didn't interfere with other items under the admin/people pages. It even added the "add user" link that normally appears on the regular admin/people pages.


Apply discount on checkout when a specific quantity of products are purchased with a specific taxonomy

I managed to resolve this by adding a condition to the rule that was created by the discount.

And
Total quantity of selected product comparison


I want to add functionality into my site that users may be able to sign agreement, pay, and then submit

You can use the Webform module to allow the users to fill it out and then use the Payment for Webform module for payment options.

  This module provides a payment reference Webform component, which
  allows users to associate payments (made through Payment) with Webform
  submissions. A possible use case is requiring users to pay before
  submitting a webform.

or you can do it with Commerce Webform module, by following this tutorial you can easily set up the payment options.


Getting current node paragraphs content from block

Paragraphs are separate entities, the field just stores the reference. To access them, you can do something like this:

foreach ($node->field_paragraphes as $item) {
  // Access the paragraph entity like this:
  $item->entity;
}