Create duplicate registration form with extra fields

Use the LoginToboggan module

  The LoginToboggan module offers several modifications of the Drupal login system in an external module by offering the following features and usability improvements:

Allow users to login using either their username OR their e-mail
address.
Allow users to login immediately.
Provide a login form on Access Denied pages for non-logged-in
(anonymous) users.
The module provides two login block options: One uses JavaScript to
display the form within the block immediately upon clicking "log
in". The other brings the user to a separate page, but returns the
user to their original page upon login.
Customize the registration form with two e-mail fields to ensure
accuracy.
Optionally redirect the user to a specific page when using the
'immediate login' feature.
Optionally redirect the user to a specific page upon validation of
their e-mail address.
Optionally display a user message indicating a successful login.
Optionally combine both the login and registration form on one page.
Optionally have unvalidated users purged from the system at a
 pre-defined interval (please read the CAVEATS section of
 INSTALL.txt for important information on configuring this
 feature!).
Integrates with Rules module to do various tasks when a user
 validates via email validation process (see
 http://drupal.org/node/880904 for an example)

Demo is here http://doaproject.org/user/register


hook_init() equivalent for console command

I've found out what's going on with this. It appears that Drush uses its own event dispatcher separate from Drupal's and that's where the console command event is actually dispatched. That means I need to manually add a listener to Drush's event dispatcher like so:
\Drush\Drush::service('eventDispatcher')->addListener('console.command', 'Drupal\mymodule\EventSubscriber\DefaultSubscriber::setLdapEnvVariablesCli');

Unfortunately there's still a problem: I need to add that subscriber somewhere that's called before the start of the command in order to be able to call things before the start of the command.
I ended up having to actually subscribe to the Drush event dispatcher event in settings.php:
if (function_exists('drush_main') && method_exists('Drush\Drush', 'service')) {
  \Drush\Drush::service('eventDispatcher')->addListener('console.command', 'Drupal\mymodule\EventSubscriber\DefaultSubscriber::setLdapEnvVariablesCli');
}

This isn't ideal but it does at least let me keep most of the actual logic in the subscriber.
then I made the CLI callback method and the common method static:
public static function setLdapEnvVariablesCli(ConsoleCommandEvent $event) {
  self::setLdapEnvVariables();
}

protected static function setLdapEnvVariables() {
  // ...
}

It's a bit ugly but it works. I'll just have to document that a settings.php change is needed in the module README.


Auto add image to node listing from node body field

Install the Token Filter module. That'll tell you what tokens available and from them choose the field that you want to display in the node body. So when you save the node the token will replace with the field value you want.


Twig LoaderError: Template is not defined

Moving the templates to the Templates folder themes/THEMENAME/templates has solved the problem. I also had to change the path in the THEMENAME.layouts.yml


How to delete all translations when deleting a node using default language?

you first have to remove the nodes from the translation set before you can delete them. So do something like this:

function hook_node_delete($node){
    $all = translation_node_get_translations($node->tnid);

    foreach($all as $del){
        if($node->nid != $del->nid){
            translation_remove_from_set(node_load($del->nid));
            node_delete($del->nid);
        }
    }
}


Views Eposed filter - proximity search, include content without a postal code

If you can not do it with the 'And/Or' option on the filters (accessed by clicking the little arrow next to the filters in the views ui). This is the best option.

Or you could use hook_views_query_alter to add something like "or where postcode = '' ".
I can not really go into detail of adding to the query as I dont know the structure of your query but you can take a look at the database api or search google.


How to cache forms with a reverse proxy and deal with stale form tokens?

I use BOA for my sites, but by default BOA simply disables front end-caching on the fly for form submissions. Beyond my actual experience I came a cross a one year old artificial on how the New Zealand Post deals with Drupal & Varnish and the form token issue. Holy John Wayne, its a must read for Drupal caching -really. Focusing only on the the form issue:

  The final piece to our puzzle is the Cookie Cache Bypass Advanced
  module, which automatically sets a special NO_CACHE cookie whenever
  the user submits a POST form on the site, including things like the
  login form. Our Varnish is configured to bypass the page cache (but
  not the ESI cache) when it sees this cookie.

You can also disable form tokens when XSRF production is not reaquired with in form_alter (unset($form[‘#token’]);) or ($form[‘#token’] = FALSE;)

An Acquia Drupal performance article puts forth a Drupal Module Authcache, but reading the doc on Authcache, it works out the caching with a place holder for the form (not caching the form):

  Authcache attempts to intercept any customized content and set up a
  placeholder within the HTML. Then after the page is loaded, an Ajax
  callback is used to retrieve custom data and fill in the placeholders,
  dynamically updating the page HTML.

  Current Authcache placeholders: Form tokens (logged-in users only; required by > Drupal to prevent cross-site request forgery attacks)

The strategy is, cache everything but the form. So addressing everything else:
Maybe Varnish is not used at all, Memcache & Redis? My strategy would be to use what BOA offers because I use BOA and the wizards behind it (omega8.cc) know a ton more than I. I dont think there is an external cache that solves the problem. They all seem to bypass for the form.

Do partial caching with the aforementioned authcache and with finely tweaked Views and Panels as mentioned in the NZ Post article and described by the brain trust at Wunderkraut - its old, but addresses the issue.

Use Drupal ESI Module and Varnish is partially ESI compliant):

  ESI - or Edge Side Includes - is a high performance caching solution
  for Authenticated users but can be helpful for Anonymous users as
  well.

  Typically, pages which are personalised for authenticated users (even
  minor personalisations, such as a block which says "Logged in as
  manarth") will prevent reverse-proxies (which can easily perform 100
  times faster than Drupal) from caching the page, because messages
  intended for one user could then be seen by another.

Hope thats more helpful.


How do I uninstall and remove Drupal Console from my project?

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

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

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

Once you locate the file just remove it.


Remove image banner on individual pages?

On the body element there are page classes for each "node", and in Drupal every node has a number, called the "nid" or "node id".

The services page nid is 65.

Look at the body element in your browsers inspector (right click, "Inspect"), you'll see something like this for the body:

<body class="html not-front not-logged-in one-sidebar sidebar-first page-node page-node- page-node-65 node-type-page i18n-en-gb blue">

For every node in the site there is always going to be the page-node-[node-id] class, e.g. page-node-65

By "banner" I assume you mean the photo of the oil rig? If so you can use the body class and the wrapper on that image:

.page-node-65 .cover {
  display: none;
}

But - consider this a stop gap solution, you need to figure out how the site is structured/built and try to remove the picture/banner from being there in the first place.


How to implement a multi-node edit workflow?

You can achieve something similar with a combination of editable fields and views.

Then by loading all the nodes in a view with a table format, you can use the editable field and edit it right on the spot with AJAX.
Updating multiple nodes in a view using editablefields

If you wanted to update multiple nodes at once (assuming fields are the same) you can use Views Bulk Operations

The exact functionality you are asking for is defiantly custom and will require your own module. Selecting the nodes you want then editing them one after another is highly inconvenient IMO. A report/table format is much better for working with data.


Date Validation according to different type

use strtotime() on both the date fields and then compare that value in the validate function of the form.


Mobile tools will let you differentiate between what you consider to be your 'desktop' version and your 'mobile' version via the theme you choose.  For example, www.example.org as your desktop and m.example.org as your mobile.

Mobile tools will try to redirect based on device detection, if you configure it that way.  If you want the desktop version to show on all devices, computer and mobile, you can configure it that way as well, or include the desktop version for 'desktop and mobile.'

But, if you do want a separate mobile theme, there are several existing mobile themes out for drupal.  To make that work you would have to install and enable the mobile theme, and then mobile tools will automatically select that theme when it detects the mobile based site.

Whatever version of the site you want to display on any device is very possible. It's just according to your goals for each device.


Can I add Vertical Tab on a Node Edit Page in admin

You can achieve this with hook_form_alter. Similar example can be found in the Examples for Developers module. Take a look at this after you are done with your form tabs, add a custom submit handler like $form[#submit][] = 'my_custom_submit'; and then save the data in submit handler using variable_set() method like this:

variable_set('MYMODULE_' . $form_state['values']['your_value'] . '_special_option', $values);

Note: put it in template.php or in a custom module.


Unfortunately, there is no "right" solution for Drupal 7; in Drupal 8, the configuration management initiative hopes to solve this problem.  There are a few things that you can look at to help you out.

Features: http://drupal.org/project/features:  Take database settings and write them to code, making a new module containing your settings.  Use "strongarm" module (http://drupal.org/project/strongarm) to be able to save items from the variables table in your features.  Once you have your features module, you can copy it to another site and run 'drush fr' to "revert" the feature (copy code back into the database).
Deploy: http://drupal.org/project/deploy: The counterpart of Features, it allows you to move content from one Drupal site to another.
drush generate-profile: http://drupal.org/node/1368242: Work in progress: given an existing site, creates a profile that will recreate that site.  Create your features first, then run generate-profile.  In its current state, it does a good job of creating your makefile and setting up the modules you need, but the template files that generate the profile code are not finished or working yet.  I am still working on this command, as time allows.


Change the add content look and feel for an specific content type?

You will want to create a theme override template for that content type for the edit mode. Then you can style it how you want. See this link for more information about how to do this:
https://www.drupal.org/node/1142800#comment-4433994


Theme the progress bar when in batch API with AJAX

Ultimately decided to use the hook hook_js_alter() in order to replace misc/progress.js with my own version. You can declare your own markup in this file, and also react on progress update (every 1500 ms out of the box).

In case anyone was wondering, this is the outcome of this http://drupal.org/project/nyan


I cannot update because of Ubercart and Google Analytics module error

If you are seeing the message Unresolved dependency. Google Analytics (Version !=7.x-2.4 required) when you have Google Analytics 7.x-2.6 installed, then almost certainly you have a duplicate copy of the Google Analytics module somewhere under your web root. That is not allowed in Drupal. When Drupal scans the file system looking for modules it will find both copies, and you don't know which copy Drupal will end up using (you can even have a case where some files from one copy are used and some files from the second copy are used!). Make sure you delete the old module entirely, or if you really want to save a copy then move it somewhere NOT under the Drupal web root.


What is the correct way to create a translatable in four languages website logo with slogan?

Are you already using the i18n module? The package contains the 'Variable translation' module which allows you to make certain variables language dependent. Since the site logo is also stored in the variables (theme_settings['logo_path'] if I'm not mistaken) you can make that variable language dependent as well.

If you're not using the i18n module (and you're not going to need it soon), I suppose you can also switch between logo images in your theme's template.php.

I wouldn't recommend creating a node type for it. In my experience, whenever you're considering to create a node type that is meant to have a specific number of nodes, there probably is a better solution for what you're doing.


If you are displaying this block on only certain pages, looking at $_GET['q'] or arg(#) will tell you that path or one of its arguments, so maybe you can switch on that?  eg, path/to/my/page is in $_GET['q'] and arg(2)=='my'.  Note that paths to nodes are system paths, not aliases, so the path might be just node/# but you can do a drupal_get_path_alias() to find it if need be.  If you are displaying the block only on certain node types, you can grab $node=menu_get_object() and then switch on $node->type as an example as well.  In fact, if you do it that way, $node->path should already point to the aliased path, and it's already cached for your performance pleasure :)

Oh, and failing all the above, you could do all of this in a custom module block, too, eg, in there do something like:

$block['subject']='// subject goes here';
// do the hook form alter
$content=views_embed_view( // the view in question );
$block['content']=$content;

return $block;

All of the php above presumes D6, minor changes apply to D7, but since it is being called in the block itself, the form alter should only change the view there (unless it is also being displayed elsewhere on the same page)


How to build a simple content approval workflow between an administrator and a user?

Have a look at my answer to "How to implement a multi step approval with webforms/entityforms based on form components?". It explains how you can implement a workflow that is pretty (though not exactly) similar to what you are looking for.

To do so, it "only" requires you to use these modules (and regular content types):

Rules.
Node Convert.
Flag.
Content Access.

Use such approach, it does not require modules like "Webform" or "Workbench".


i have created a custom module.

function date_filter_form_alter(&$form, &$form_state, $form_id) {
  if($form['#id'] == 'views-exposed-form-birthdays-sliders-panel-pane-1') {
  $form['field_birthday_date_value']['value']['#date_format'] = 'm-d';
}
}

And query alter looks like:

function date_filter_views_query_alter(&$view, &$query) {
  if ($view->name == 'birthdays_sliders') {
    if (!empty($query->where[1]['conditions'][2]['field'])) {
    $query->where[1]['conditions'][2]['field'] = "DATE_FORMAT(field_data_field_birthday_date.field_birthday_date_value,
     '%m-%d') = :field_data_field_birthday_date_field_birthday_date_value";
}
  }
}


First off, there could be manly causes to this, most likely permissions but if you're saying these are correct I'd look at the caching.

From how you wrote the question it suggested you're using the php filter (I'd advise against the use of this really and opt for module development). If you are doing this within a module I would check that the hook you are using is the correct one and is being fired.

As for your code, check_plain isn't needed here because you're not outputting the uri to the browser only checking against it.

I would use the inbuilt drupal functions to do this though either way.

current_path() - https://api.drupal.org/api/drupal/includes!path.inc/function/current_path/7
drupal_get_query_parameters() - https://api.drupal.org/api/drupal/includes!common.inc/function/drupal_get_query_parameters/7

Take note, the current_path() function returns the internal path for the url, not the friendly one, 'node/1' instead of 'this-url'.

$query = drupal_get_query_parameters();
return current_path() === 'mypath' && $query['key_of_query'] === '123';


Seems like a odd piece of code you've got there, for instance this will render your form randomly in the page:

    echo drupal_render($render_estimate_form);

Which is probably what you're noticing already, that example you're linking is for render that piece of code inside a template but for what you describe you're rendering it in a form inside a block, I'd try something like this instead (untested):

function foiagen_form($form, &$form_state) {
    module_load_include('inc', 'entityform', 'entityform.admin');
    $entity_form_name = 'foia_generator';
    $render_estimate_form =
    entityform_form_wrapper(entityform_empty_load($entity_form_name), 'submit', 'embedded');
    $form['foiagen'] = $render_estimate_form;
    return $form;
}


How to hide completed event from view result based on it's end date?

You should Enable the "Date Views" module first. Then you will be able to find the Date CCK fields available in the filter criteria as Expected. You will also be able to provide a relative date in the filter criteria. Refer Screenshot.

Hope this Helps!


Extract field from content type in View and have it appear as a block next to appropriate node

This can be done with contextual filters.

Set up the view to display whatever information you need; put the view in a block that only displays on the page for that content type
Add a contextual filter, selecting a field that contains the NID.  For example, this could be content: nid
For "when filter is not available" select "provide default value", then "content ID from URL"

After doing this, the view will only display the single result, where the NID field matches the NID of the node currently being viewed.


How to put links in a menu programmatically?

Your question is relatively vague, but to answer the title, here's the code you need to use:

$link = array(
  'link_title' => t('Your link'),
  'link_path' => 'your-path',
  // Enter the name of the menu where you want this link to appear.
  'menu_name' => 'main-menu',
  'weight' => 0,
);
menu_link_save($link);


Assuming this is for D7, try this code (which includes a copy of your exported rule):

function my_module_default_rules_configuration() {
  $configs = array();
  $rule = '{ "rules_vote_points" : {
      "LABEL" : "Vote points",
      "PLUGIN" : "reaction rule",
      "REQUIRES" : [ "userpoints_rules", "voting_rules" ],
      "ON" : [ "voting_rules_insert_node" ],
      "DO" : [
        { "userpoints_action_grant_points" : {
            "user" : [ "node:author" ],
            "points" : "3",
            "tid" : "0",
            "entity" : [ "node" ],
            "operation" : "Insert",
            "display" : 1,
            "moderate" : "approved"
          }
        }
      ]
    }
  }';
  $configs['rules_vote_points'] = entity_import('rules_config', $rule);
  return $configs;
}

PS: have a look at the code of the Answers Userpoints module for an example where this technique is used also (contained in answers_userpoints.rules_defaults.inc).


I think you are using the wrong tpl file to edit the node/add/[content-type] form.

You need to create (if I remember correctly) a [content-type]-node-form.tpl.php and add the required elements you wish from there. See here for more details:

https://drupal.org/node/1092122


Get all submissions from specific webform

The Webform module stores submission data using a custom Entity-Attribute-Value model. Your example code is the easiest and fastest way to get all the submission data. The only limitation would be the number of submissions vs PHP's memory limit. You will run out of memory if you are loading 1000's submissions


List of images with checkbox (user registration)

You can do that by the following.

Go to Configuration » People » Account settings

Add a Field type : List (text) and WIDGET: Check boxes/radio buttons

In Allowed values list  textarea add key|<img src ='/your/path/to/image' />

Enter one <img> per line and set Number of values as Unlimited (to appear as checkboxes)

That's it. I tested it and working fine.

Add key whatever you want.You may have to make minor CSS changes in order to align checkbox and image.

Hope this helps.


How can I add a menu link to a page with a form in DrupalGap?

Figured it out finally:

path: 'in-app'

Comes from the hook_menu items array.


As often as you like :)

By default you can configure it on: /admin/config/system/cron (This will be executed on someone's page load, so it is importan to know that if nobody visits your site this will not be executed). This is known as poormanscron (Drupal 6).
Calling with a internal/external cron script (wget for example) to yoursite.com/cron.php

This is a heavy process so normally you want to limit cron functions like check updates. elysia cron is very useful in this case.

  Elysia Cron extends Drupal standard cron, allowing a fine grain control over each task and several ways to add custom cron jobs to your site.


trending topics view based on read counts

If your site is relatively low traffic, you could possibly use the statistics module, or as @clive pointed out, the radioactivity module.

For higher traffic sites, I'd be wary of writing to the db for every visit, however. Moreover, if you're using varnish or some other reverse proxy caching system (which you probably should), Apache and PHP normally aren't invoked for anon visitors, so you'd need to do something different.

I've landed on using google analytics for this. To do it, the site obviously needs a google analytics account, and you need to install the google analytics and google analytics reports modules. Once you've configured them, you can fetch an array of the most visited nodes from the google analytics api. You can then simply serialise it, and save it to the variable table. This uses hook_cron, and needs to be done in a custom module:

function YOUR_MODULE_cron() {
  $last_time = variable_get('YOUR_MODULE_last_time', 0);
  // DO EVERY 24H
  if ((REQUEST_TIME - $last_time) > (60 * 60 * 24)) {
    $data = array();
    $dates = array();
    $params = array(
      'metrics' => array('ga:uniquePageviews'),
      'dimensions' => array('ga:pagePath'),
      'segment' => 'gaid::-11',
      'filters' => 'ga:pagePath=@/PATH/TO/NODES',
      'sort_metric' => array('-ga:uniquePageviews'),
      'start_date' => strtotime('-7 days'),
      'end_date' => strtotime('-1 day'),
    );
    $feed = google_analytics_api_report_data($params);
    if (!$feed->error) {
      $k = 0;
      $nids = array();
      foreach ($feed->results as $f) {
        // SAVE 6 MOST VIEWED
        if ($k < 6) {
          $nids[] = (int) array_pop(explode('/', drupal_lookup_path('source', ltrim($f['pagePath'], '/'))));
          $k++;
        }
      }
      $nids = serialize($nids);
      variable_set('YOUR_MODULE_ga_items', $nids);
      variable_set('YOUR_MODULE_last_time', REQUEST_TIME);
    }
  }
}

Every 24 hours, this would save a serialised array of the most popular nodes that appear under the path http://yoursite.com/PATH/TO/NODES/REST_OF_PATH. To use the nids, you'd simply unserialise the variable after retrieving it:

$nids = unserialize(variable_get('YOUR_MODUE_ga_items', '');
foreach($nids as $nid) {
   $node = node_load($nid);
   ...
}


how to hide particular comment programmatically

You achieve this by adding a comment_post_render callback function to the build that outputs nothing:

function MY_MODULE_comment_view_alter(&$build) {
  $build['#post_render'][] = 'MY_MODULE_comment_post_render';
}

function MY_MODULE_comment_post_render() {
  // Nothing here.
}


CSS not working after Commerce AJAX processed on field

The problem is you're relying on an ID for your CSS selector, but when Drupal's Forms API refreshes a form via #ajax, it appends a numeric suffix to the ID to maintain a unique ID prior to replacement. Your CSS no longer applies because the selector no longer matches any element on the page. You should switch this to some class based selector instead.


You can cache mini panels from mini panels UI settings.
Go to the mini panel content edition page.

You have then 2 choices. Above in global mini panel display settings or per panel content piece : in its wheel settings at the bottom...


Getting form variables data into twig templates

Three possible solutions:

Valid render array

You get a valid render array by putting the content of city and count in #markup elements:

  'city' => [
    '#markup' => 'Singapore',

Form variable with a #

Or start the variable name with a hash, so that it is no longer
considered to be a form element which needs to be rendered:

$form['#job_locations'] = ...

Twig:

{% for location in form['#job_locations'] %}
  ...
{% endfor %}

Separate template

Or create a custom template
with a variable for the locations array to theme the list separately from the
form:

$form['job_locations'] = [
  '#theme' => 'job_location_list',
  '#locations' => $job_locations,
];


How do I group two nodes on the frontpage in a div?

The node template is not (usually) aware of the context in which it's been called; when you list nodes as teasers each node is themed individually, and has no awareness of the other nodes in the list.

What you need to do is find out what template/function is responsible for outputting the list of nodes in question and override that in your own theme/module to add the extra divs.

The Theme Developer module might come in quite handy here, it provides an in-page way of isolating which theme functions have been responsible for rendering which areas of the page.


Extract zip to server and upload the files to the node?

You can simply use file_unmanaged_save_data(), as in the following code, where $data is the content of the .jpeg file contained the .zip file.

file_unmanaged_save_data($data, 'public://work', FILE_EXISTS_REPLACE);

As side note, Drupal includes the ArchiverZip class, which should probably be used instead of the PclZip class.
You don't normally deal with the class directly, but you use code similar to the following one, used by update_manager_archive_extract().

  $archiver = archiver_get_archiver($file);
  if (!$archiver) {
    throw new Exception(t('Cannot extract %file, not a valid archive.', array('%file' => $file)));
  }

  // Remove the directory if it exists, otherwise it might contain a mixture of
  // old files mixed with the new files (e.g. in cases where files were removed
  // from a later release).
  $files = $archiver->listContents();

  // Unfortunately, we can only use the directory name to determine the project
  // name. Some archivers list the first file as the directory (i.e., MODULE/)
  // and others list an actual file (i.e., MODULE/README.TXT).
  $project = strtok($files[0], '/\\');

  $extract_location = $directory . '/' . $project;
  if (file_exists($extract_location)) {
    file_unmanaged_delete_recursive($extract_location);
  }

  $archiver->extract($directory);

archiver_get_archiver() uses drupal_realpath(); this means it is able to get the realpath of a file when its filename is using stream wrappers, such as public://archive.zip.


Is there a way to easily add image swap/rollover to images on a Basic Page?

You can try Rollover Filter module. This is the only module for rollover effect AFAIK.

  This module provides a simple method to enable content editors to use
  image rollover states. It makes no checks against the referenced image
  types, it simply converts [rollover] wrappers into actual rollover
  images. It does use a Javascript based approach, and causes no harm to
  images in an environment where there is no Javascript.


In views formatted as table, columns with taxonomy term fields are sorted according to term ID, not label

That's because the stored value of the field is the term ID, the label of it is just how it is displayed.

To sort on the name, you need to instead add a relationship using that field to terms, and then add the name field of that relationship. Then you should be able to sort it as well based on that.


How to show all content type images in a gallery

Follow below steps to resolve your issue.

Create a new view of type files.
Add Filter File:Mime Type and select the condition as Contains any word.
Give all image extensions in the value like jpeg jpg png etc
Rewrite the results of the File Path field and add img tag with src as file path.

Using above instructions you can list all images in Drupal independent of any content type or image field.


Are tests built into contrib modules a reliable way of testing the success of a module upgrade?

No
Automated tests was created to test code, and to ensure quality of patches. They are meant to be executed in specific, clean environment (e.g. Testbot environment), which your live site certainly is not.
Second reason why it's no is what is tested. These tests only test code. But downloading and unpacking code is simple. Not many thing that can go wrong, and if it goes wrong, you will rather see. The hard and important part is database upgrade - and tests will not try to verify if your data was updated properly.


Custom external read-only databases with Drupal, how to use views to communicate with the external database?

Yes there is a way to use views to get data out of an external database. You will need the hooks_view_data()

There is however the limitation the view can not cross databases I believe.

To solve this, you can write a custom module

<?php

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

function  yourmodulename_views_views_data() {
   $data['arTable']['table']['group'] = t('yourtable Data');
   $data['arTable']['table']['base'] = array(
      'field' => 'id',
      'title' => t('your title'),
      'help' => t('help text'),
      'database' => 'databasename',
      'weight' => -10,
   );

Where databasename is one of your db_names defined in settings.php.

For more information, look at this post


How to get work Internationalization module with l function?

There's no easy way to do this, but you can do something like this:

$nid = 22;
$node = node_load($nid);
if ($node) {
  $translations = translation_node_get_translations($node->tnid);
  $nid = isset($translations[$language->language]) ? $translations[$language->language]->nid : $nid;
}

Or use the Entity translation module, which relies on the ability of fields to have values in multiple languages and then the node id doesn't change.


Removing duplicate content caused by node/nid/talk pages

So /node/4 is your about page isn't it? you just added a url alias. Which means you can access the same page with /node/4 or with /about-us

To quote Clive from Non-existent URLs in Views 3 in drupal 7

  That's the expected behaviour - Drupal automatically routes you to the
  'parent' if it can't find the 'child' part of the URL

when I go to mywebsite.com/node/1/talk it displays the /node/1 content to me; even though, the url in the web browser says mywebsite.com/node/1/talk, and I haven't even installed the talk module at all.

Try going to mywebsite.com/node/4/ijustmadethisup and you'll see you get displayed /node/4

Therefore, this is just the default Drupal behaviour, nothing to do with the talk module.


best one out there from my experience would be: http://www.drupal.org/project/tb_megamenu --- it should take you no longer than 15 minutes to figure out how it works. you'll still need to do some css width adjustments to get it working with your own layout.


Activate bootstrap theme in BrowserTestBase phpunit test

Thanks to Berdir for the hint. The solution is to disable the schema validation here. It's done with this code in my testclass:

protected function getConfigSchemaExclusions() {
  return array_merge(parent::getConfigSchemaExclusions(), ['bootstrap.settings']);
}


Implement variable in node confirmation popup

It worked!
$text = "Really save?";
$form['actions']['submit']['#attributes']['onclick'] = 'if(!confirm("' . $text .'")){return false;}';


How to access the full html of a drupal basic page?

You will need to edit your themes tpl files to make changes to those areas.  If you are adding a js file you can add it in your themes template.php file. I would recommend you read through this link for

Drupal 7:

https://www.drupal.org/docs/7/theming

Drupal 8:

https://www.drupal.org/docs/8/theming


If you're using a twig template, you can add it there.

{{ attach_library('module/library') }}

Which is helpful when you want to control whether the library loads before or after the content.

https://www.drupal.org/docs/8/theming-drupal-8/adding-stylesheets-css-and-javascript-js-to-a-drupal-8-theme


Sounds like you've configured the entities properly. Nothing requires you to make use of attributes, so if you don't need them, you don't have to make them. : )

Re: the field formatter for Views to display an Add to Cart form, it hasn't been developed yet.


If you install the Internationalization suite of modules, you can enable the Internationalization blocks module (called Translate Blocks).

This will allow you to assign a language (or languages) to each block.

This way, you can create a menu for each language and then assign a language to each menu block.

Note that there is also a Translate Menu module in the Internationalization suite.  This module allows you to create one menu with items of multiple languages.  However, this can get confusing and complicated very fast and is often difficult to maintain over time.  For this reason, most people create separate menus for each language as described above.


As none of my attempts were working, I tried a completely new approach using views.

I've created a new content type named 'banner'. And in the body field, I've added an html img tag and map tag(for image mapping). Now, I've created a view with format as slideshow and field as content:body. Creating a block for this view and adding it in the advertise region (in marinelli theme) replaces the rotating banner image in Marinelli theme.

Before adding the view in advertise region, we need to disable the original theme banner. For this, goto admin->appearence->settings->marinelli->Banner configuration and choose 'Drupal region (advertise) for the question Do you want to use marinelli banners or a classic drupal region?


How do I return JSON data compatible with the Boost module?

Why do you need to cache JSON output? Anyhow, try removing header('Cache-Control: no-cache, must-revalidate'); and see what happens.


How do I prevent D7's ajax_deliver() from loading CSS?

Figured out the reason Bartik CSS was loading when the admin page was using Seven.

My admin page was located at /admin/mymodule/settings

My menu callback for the AJAX link was /mymodule/special-form

Because /mymodule is outside the admin area, the theme would be Bartik when actually visiting that page. So Drupal's AJAX system assumes I want the CSS that goes along with that page. Not a bug, but a feature to be aware of.


How to add css class to a table created using views

This is an old post, but I'd like to chime in with a couple of solutions.

First, and this may not answer your question directly, but you can change the CSS selectors you are using to target the table.

So, rather than using table.yourclass you could use .yourclass table. This can be accomplished by setting a custom class for the entire view under the advanced section.

Of course, this won't work if you are trying to add classes directly to the element as you might need to do with Bootstrap, i.e. table.table.table-striped.

The second solution will allow you to add the same classes to all your tables. In your template.php file, add the following:

function THEME_preprocess_views_view_table(&$vars)
{
    $vars['classes_array'][] = 'table table-striped';
}

If you need to target a specific table, you can also check the $vars variable first to find the name of the view and display being called and only apply your classes to the ones you want to target. I haven't checked, but it's probably found in something like $vars['view']->current_display.

Finally, it's worth noting that Views does actually support custom classes on the table. The variables are called in the template files, there just isn't an option for it in the views GUI. This is an oversight in my opinion, but the module's devs don't seem to plan on fixing it. That said, a patch for it does exist (direct link).


How to run Drupal console command from code?

Run shell commands via the Process class available in the Symfony framework.

From the Symfony docs:

use Symfony\Component\Process\Process;
use Symfony\Component\Process\Exception\ProcessFailedException;

$process = new Process('ls -lsa');
$process->run();

// executes after the command finishes
if (!$process->isSuccessful()) {
    throw new ProcessFailedException($process);
}

echo $process->getOutput();

  The component takes care of the subtle differences between the
  different platforms when executing the command.

Replace the ls -lsa command in the Process() constructor with your Drupal console command.


Filtering view by content author OR referenced field

As no one answered and I couldn't find a way to solve this trhough UI, I used views_pre_render hook to solve my problem.

You can see the solution I found here.


@kalabro Actually, it was Drupal problem, but in my own code, not in the core or some module. As a Drupal newbie, I had used "global $user" at a template file to show the current logged in user's username on the menubar... When I removed this, problem was solved.


Auto remove white background and add alpha channel to images?

I think you will need something like https://www.drupal.org/project/imagecache_actions if this is in fact not a CSS border added to the image. I would definitely check that first but the above module does do some alpha blending and you can also run your own PHP/GD code during an image cache action so if they don't include it you can find code that does and run that code to perform the change.

You could also put a border around the image with CSS that would separate the image from the site background to solve something like that.


Views Contextual Filters and URL Aliases

If you set the Views page path to node/% and add a Contextual Filter of Node ID and take the default argument from the URL you can use Views to override the node display.

However, this is probably not the best solution. You mention in your post that "I don't want direct access to the node as I want to control all the content formatting" but if you use the correct options you can fully control the node output. My recommendation would be to use Display Suite and control everything via the Manage Display tab of the content type and if necessary an override of node.tpl.php


Is it possible to login as / switch to a specific user using their password hash from the DB?

There's Masquerade.

Masquerade adds some items to the Navigation menu to allow quick switching and switching back. It also creates a "Masquerade" block for quick switching which can be added to a sidebar or elsewhere on your site. It is visible only to those users with permission to masquerade.

Another module which accomplishes something similar is Role Switcher.

--a different Dan H


Drupal 7 has robust CDN integration with a number of options. You can consider the Storage API module for S3 integration among others.

  Storage API is a low-level framework for managed file storage and serving.

Also consider the CDN module.

  This module provides easy Content Delivery Network integration for Drupal sites. It alters file URLs, so that files are downloaded from a CDN instead of your web server.


Running a custom query alongside Drupal Registration Query

The use of the hook_user_insert() it is call when the user is created. Here is an implementation example:

    function hook_user_insert(&$edit, $account, $category) {
      db_insert('mytable')
        ->fields(array(
        'myfield' => $edit['myfield'],
        'uid' => $account->uid,
      ))
        ->execute();
    }

Depending on your case you might want to check other hooks like:

hook_user_insert()

hook_user_presave()

hook_user_update()


Views AJAX Submit is removing my custom classes

I struggled with this recently in this question

The answer is to wrap your jQuery in a Drupal Behaviour so that the classes are not removed on every ajax request. Because your current jQuery is probably only run on the first page load.

(function($) {
Drupal.behaviors.myBehavior = {
  attach: function (context, settings) {

        // Put your jQuery Code Here

  }
};
})(jQuery);


Config import conflict, how to remove lock

My specific issue was that Redis module update to 1.0 brought with it new redis.services.yml file in the module. Updating my site's Redis services file, in sites/default/, resolved the issue.

What was happening was that the alreadyImporting() method of ConfigImporter defaults to true, when in fact my mis-configuration would have been returning an error I think.

This issue pointed me in the right direction: https://www.drupal.org/project/redis/issues/2996655

If it had been a simple lock issue the following should have worked I think:

drush ev "\Drupal::lock()->release('config_importer');"


Hide taxonomy term from a view filter where the filter results are empty

In Views, there is an option to specify a relationship and to require that relationship. You can find it in your View's config page, under Advanced. Just add a relationship to your taxonomy vocabulary and check the option to require the relationship.
The screen shot below is from the Content view that ships with Drupal 8, which is a great example of how to define a required relationship.


You can attach file with taxonomy as below:

Go to Administration -> Structure -> Taxonomy
Edit Vocabulary, which you want to use, from the list of Vocabulary.

Click on "Manage Fields" tab in the top of the page.

Add new field of field type as file and assign the required file extension which you want to upload and save the field.

When you create new term of the vocabulary, it will allow you to upload file with term.


If site 1 and 2 are compromised, it's entirely possible that
sites 3 and 4 are either in danger of being compromised or have
already been compromised.
More or less, yes. If they already have sites 1 and 2, it's extremely likely that they can directly access your server.

You should consider your current server and the sites running on it as tainted and rebuild from scratch. Despite @Clive's assertion, there is no user account sandboxing happening at the per-site level.


Why required form field has #required=FALSE on theme level?

In short, the hidden input field that stores the file ID (fid) is what is required, but the displayed file upload element isn't. The actual "displayed" element is added to that form element in file_managed_file_process() in file.module. Specifically, check out line 440 of that file:

  // The file upload field itself.
  $element['upload'] = array(
    '#name' => 'files[' . implode('_', $element['#parents']) . ']',
    '#type' => 'file',
    '#title' => t('Choose a file'),
    '#title_display' => 'invisible',
    '#size' => $element['#size'],
    '#theme_wrappers' => array(),
    '#weight' => -10,
  );

This has no #required property, and so therefore defaults to FALSE. If you dpm() your element earlier in the process (before it's expanded to include more hidden elements and attach the necessary javascript and CSS to be a full-fledged "managed file" element) you'll see your #required => TRUE.

I would add an additional function to the #process property of your form element, which will run after file_managed_file_process(). In it, you can check if the original element had #required => TRUE and then also set that on the $element['upload'] item. I haven't tried it, but I think that would get you what you want.

Edit: It would be wiser to do this in #after_build and not just append to #process. Here's an example:

<?php

function my_form_builder($form, &$form_state) {
  $form['file'] = array(
    '#type' => 'managed_file',
    '#title' => 'Upload a File',
    '#required' => TRUE,
    '#after_build' => array('my_file_element_after_build')
  );

  return $form;
}

function my_file_element_after_build($element, &$form_state) {
  // Set the 'file' element to have the same #required property as its original form element.
  $element['upload']['#required'] = $element['#required'];
  return $element;
}

?>


How to validate allowed file types in custom module

That's basic logic. Change your ORs to ANDs.

if ($p_filefilename[1] != 'pdf'
  && $p_filefilename[1] != 'xls'
  && $p_filefilename[1] != 'jpeg'
  && $p_filefilename[1] != 'jpg'
  && $p_filefilename[1] != 'zip'
  && $p_filefilename[1] != 'rar'
  && $p_filefilename[1] != 'png') {

  $form_state->setErrorByName('document', $this->t('Please upload document  in pdf, xls, jpeg, jpg, gif, zip, rar and png file.'));
}

Anyway, you should use in_array() for that check. For example:

$allowed_types = array('pdf','xls','jpeg','jpg', 'zip','rar','png');
if (!in_array($p_filefilename[1], $allowed_types) {
  // ...
}


You would get the values of the submitted form in hook_form_submit

function MY_MODULE_NAME_form_submit($form, &$form_state) {
         //your code here
        }

You would get all the required values in $form_state['values']


Views Slideshow - showing only one slide

The possible directions you can look into :

You need to install the jQuery cycle plugin. Create a directory in sites/all/libraries called jquery.cycle, and then copy jquery.cycle.all.min.js or jquery.cycle.all.js into it. You can find the plugin at http://malsup.com/jquery/cycle.
In views slide show settings check for the 'Timer delay' in 'View Transition Advanced Options'.

Also, check for the other options in views slide show settings.
In the views settings, you are only showing published contents for a particular type of content. Make sure you have more than one such content. (Based on your screen shot)
Considering you have enabled 'Views Slideshow: Cycle' module

(Answer is based on trial to regenerate the issue in D7, 7.22)

Hope it helps


Invoking the rate module in views template file doesn't work

The code you wrote doesn't work because $node->content['rate_poll']['#value'] is only present when the node is being viewed. The code that adds $node->content['rate_poll']['#value'] is in the implementation of hook_nodeapi(), and the code is executed when the operation is "view."

/**
 * Implements hook_nodeapi().
 */
function rate_nodeapi(&$node, $op, $a3, $a4) {
  // Adding the form to the node view
  if ($op == 'view') {
    $widgets = rate_get_active_widgets('node', $node->type, $a3);

    foreach ($widgets as $widget_id => $widget) {
      $widget_name = 'rate_' . $widget->name;
      _rate_check_widget($widget);

      $display_mode = $a3 ? $widget->teaser_display_mode : $widget->node_display_mode;

      $widget_code = array(
        '#value' => rate_generate_widget($widget_id, 'node', $node->nid, $display_mode),
        '#weight' => $widget->node_display == RATE_DISPLAY_ABOVE_CONTENT ? 0 : 50,
      );

      if ($widget->node_display != RATE_DISPLAY_ABOVE_CONTENT && $widget->node_display != RATE_DISPLAY_BELOW_CONTENT) {
        $node->$widget_name = $widget_code;
      }
      else {
        $node->content[$widget_name] = $widget_code;
      }
    }
  }
}

For the code to work, you should change it to the following one.

$node = node_load($row->nid);
node_invoke_nodeapi($node, 'view', FALSE, TRUE);
echo $node->content['rate_poll']['#value'];
echo $node->title;

node_invoke_nodeapi() invokes any implementation of hook_nodeapi(), using its first parameter as operation value. Once the function returns, $node will contain any $node->content value added by the modules, including $node->content['rate_poll']['#value'].


In Open Atrium is there a way to assign a user to a case that user is not in?

No, it isn't possible, at least not by using the Atrium web UI out-of-the-box. Cases can only be assigned to users in the current group.


It could be write permissions of the files - try chmod -R a+rw . command in Terminal in the root of your drupal folder. It could be a time out meaning that the database is not been written correctly (don't have a remedy for that, except for not using a native setup, but rather a Virtual Machine, VM-based setup...)

You might want to consider a VM-based setup (which would more closely resemble your production environment), see a guide I wrote to using Vagrant to automate generation of a setup here: https://stackoverflow.com/a/15067918/227926


Including a large amount of raw data with a module

Your intuition is correct; you should break out your large dataset into some include file. I don't believe there's a strict mention of large datasets in the Drupal coding standards, but isolating out large datasets is good way to isolate concerns (i.e. code-readability vs. dataset referencing).

A good reference example of this would be the Transliteration module. It has a transliteration dataset of include files indexed by unicode byte that's loaded on demand as it needs to transliterate a unicode characters to ASCII.

Your data will obviously be structured to fit your own use case, but given you're probably not the first person to work with large graphic library datasets and PHP, there's probably some general practices to glean from others who've worked on the same problem.


How to add data to Drupal.settings without drupal_add_js

Maybe I am missing a point to the question, but you should be able to do

scripts[] = path/to/your/script.js

in the .info file of your theme.  And within the script file something like

(function ($) {
$(document).ready(function () {
    Drupal.settings.yoursetting = {};
    Drupal.settings.yoursetting.property = some_value;
});
})(jQuery);

or use the Drupal.behaviors convention.


How do I disable modules via admin interface or via Drush?

Like the admin interface in Drupal 8 states in the message area, the paradigm and concept of how modules get installed and disabled has changed in Drupal 8, since there were many problems involved in the way how it was before, because of Database left-overs and data inconsistencies while disabling and enabling modules, etc.

Therefore users are encouraged to rather uninstall modules than disabling them now in D8. This doesn't mean the modules are gone or removed from the Drupal root, but they are completely removed from the database including their configuration.

Try drush pm-uninstall module-name instead and you will see the desired effect you are after.

The checkboxes are greyed out to be still able to enable and install inactive modules the way known from D7. But you can't disable them this way no more. And uninstalling should not be provided by checkboxes, since this would be to dangerous.

Look twice in the admin interface: You will find a new tab for uninstalling modules too.


What's the event triggered after an autocomplete has run and how to retrieve the value selected

No event is triggered at the moment (as of 7.34), but there's a patch on this issue that should let you use something like:

$('#input-id').on('autocompleteSelect', function(event, node) {

});

or if you're using on old version of jQuery

$('#input-id').bind('autocompleteSelect', function(event, node) {

});

Where node is the selected item. You should be able to get the tid from one of the properties on that object.


Can I add a custom link to "Main Menu" via hook_menu?

The correct code would be the following one; notice the commented line.

function custom_food_orders_menu() {
  $items['order_food'] = array(
    'title' => 'Order Food',
    'page callback' => 'page_creator_function',
    'access callback' => TRUE,
    'menu_name' => 'main-menu',  // This is the changed line.
    'type' => MENU_NORMAL_ITEM,
  );

  return $items;
}

There aren't properties returned from hook_menu() (and generally from any hook used from Drupal core code) that uses the equal character.


Any way to override view_mode in twig directly?

The fatal error is because Twig set is not able to manipulate arrays. This is only possible by using merge and then only on the top level of the array.

So first get the sub array where the key is placed and then merge the array key:

{% set item_content = item.content %}
{% set item_content = item_content|merge({'#view_mode': 'thumbnail'}) %}
{{ item_content }}

But I doubt that after you've solved the Twig issue this will work, because of how entities are rendered and cached. So you might have more success with Twig Tweak.


How is the hash for the files calculated?

The name of the aggregated files is the hash calculated from CssCollectionOptimizer::generateHash().
protected function generateHash(array $css_group) {
  $css_data = [];
  foreach ($css_group['items'] as $css_file) {
    $css_data[] = $css_file['data'];
  }
  return hash('sha256', serialize($css_data));
}

The method is called by CssCollectionOptimizer::optimize().
Without knowing to which group a resource is part of, and what other resources are part of that group, you cannot know the name of the file where the resources are aggregated.
There should not be any need to do that, as Drupal core takes care of removing any reference to aggregate files that don't exist anymore, and invalidate all the necessary cache bins.
The markup produced by Drupal core should never contain a reference to an aggregate file that doesn't exist anymore. If that happens, it's either a bug in Drupal core or in a third-party module.


For anyone looking to an answer to this, it really depends on whether or not you're working with an AJAX form or not. Ideally I wanted to avoid just populating a text area with my updated field to be submitted, so thankfully, since it was using the AJAX form, I was able to pass it information dynamically through Jquery.

In your javascript

// whatever your function is to get the information you want to pass
....
Drupal.ajax['edit-save'].options.data._my_vars = JSON.stringify(myList);

// Where 'edit-save' is the ID of my save button in my form
// you can console.log(Drupal.ajax) to see what options you have

Then in the callback for your AJAX request, the return request is stored in

$form_state['input']['_my_vars'] // or whatever variable name you passed above

Then you can check whether or not the response has comeback empty by using

 if (empty(json_decode($form_state['input']['_my_vars']))) {
   form_set_error('save'); // You can set the error to be any form element
 }

and in your callback code you can make your own error handling by doing

if (form_get_error() !== null) {
  // fail code
} else {
  // success code
}

Hope this helps someone else down the line


Ensure you have downloaded (if needed) and enabled the 'Locale', 'Internationalization', 'String translation' modules
Go to Configurations > Translate Interface > Strings (Tab) (admin/config/regional/translate/i18n_string)
Check the 'Quicktabs' checkbox under the 'Select text groups' heading, and click 'Refresh strings'
Go to the page where it the quick tabs is and refresh it a few times (normally, you WOULDN'T need to do this, but for me, if I didn't and it's not cached, it doesn't work)
Go back to Configuration > Translate Interface > Translate (Tab) (admin/config/regional/translate/translate) , and search, using the 'String contains' input box, for one of the tab titles. I.e. if your tab titles are 'Apples', 'Oranges' and 'Pears', search for 'Apples'.
You should be able to see an entry. Click 'edit' and translate away!


Non-static method view::load_views() should not be called statically with VIEWS

These errors, at least those coming from Views, does not really have a proper solution, because the versions of Views and Calendar that cause them, are no longer being updated.

Views 2 is officially not being updated anymore, and I doubt anything but serious security problems is going to change that. Calendar could potentially have the problem fixed, but this is also a module with a great deal of issues, and for an old version, I simply wouldn't expect these problems to be prioritized enough to get fixed.

Your basic options:

Upgrade to Views 3, and the corresponding Calendar version.
Disable E_STRICT error reporting.
Simply accept that the errors are there.

A more sophisticated and perhaps better solution would be to locate the relevant patches in the issue queues, and apply them in your drush make file.


Two branches of theming: templates and functions

Theme functions and preprocess functions do not do the same thing. A preprocess function is a precursor to a theme function. A theme function may optionally be implemented as a template file (.tpl.php) rather than a function.

Preprocess functions are created when a module implements hook_preprocess(). If you read the documentation for that hook, it explains that the purpose of a preprocess function is to prepare variables for use within a theme function or template. Also, not all theme functions have a complimentary preprocess function.

Similarly, a theme function (or template) is created when a module implements hook_theme(). A theme function or template is the place where the variables previous prepared in the preprocess function are printed to the screen and wrapped with any desired HTML.

So, the idea is that a preprocess function prepares the variables/data in question and the theme function presents the data to the user, usually wrapped in HTML.


With Drupal 7 you should be able to add a file field to a user.

Another solution would be a content type with a file filed. After creating the node of this new type make sure the receiving user is set as the owner. Finally make sure the user hass access to all files he owns.


This is the path for accessing single fields in a view table template, for example in the first row:

rows.0.columns.fieldname.content.0.field_output

In your code example, to get all field names available, use this in the first loop:

{{ dump(row.columns|keys) }}

The naming of the fields depends on how you have configured the view and is not necessarily the machine name of the field in the entity.


Vendor directory vs. Modules directory. What are the key differences?

[Assuming you are using composer in this answer]

The vendor directory contains non-Drupal dependencies that core and/or contributes modules require.  This is typically fully managed by composer.

The modules directory contains your Drupal modules.  It can be managed by composer if you are using drupal-composer/drupal-project or something similar where the install paths can be set.

Committing composer managed dependencies or now, like vendor or modules (if you are doing so), is a nuanced subject.  There is no 100% correct answer.

I tend to not commit, even when I am not using a full CI deployment, because the composer dev dependencies should not be deployed on a production server.  So, on the live server I want do do a composer install --no-dev.


preprocess views view field find view block name

Try the following

//gives you views current display - "block_1" or "page_1"
$variables['view']->current_display;

//gives you views id - "recent"
$variables['view']->id();


Drupal provides its own locking mechanisms.

  In most environments, multiple Drupal page requests (a.k.a. threads or processes) will execute in parallel. This leads to potential conflicts or race conditions when two requests execute the same code at the same time. A common example of this is a rebuild like menu_rebuild() where we invoke many hook implementations to get and process data from all active modules, and then delete the current data in the database to insert the new afterwards.

  This is a cooperative, advisory lock system. Any long-running operation that could potentially be attempted in parallel by multiple requests should try to acquire a lock before proceeding. By obtaining a lock, one request notifies any other requests that a specific operation is in progress which must not be executed in parallel.

  To use this API, pick a unique name for the lock. A sensible choice is the name of the function performing the operation. A very simple example use of this API:

function mymodule_long_operation() {
  if (lock_acquire('mymodule_long_operation')) {
    // Do the long operation here.
    // ...
    lock_release('mymodule_long_operation');
  }
}

  If a function acquires a lock it should always release it when the operation is complete by calling lock_release(), as in the example.

A function that has acquired a lock may attempt to renew a lock (extend the duration of the lock) by calling lock_acquire() again during the operation. Failure to renew a lock is indicative that another request has acquired the lock, and that the current operation may need to be aborted.
>
If a function fails to acquire a lock it may either immediately return, or it may call lock_wait() if the rest of the current page request requires that the operation in question be complete. After lock_wait() returns, the function may again attempt to acquire the lock, or may simply allow the page request to proceed on the assumption that a parallel request completed the operation.

In Drupal 8, the example code would not be much different.

function mymodule_long_operation() {
  $lock = \Drupal::lock();
  if ($lock->acquire('mymodule_long_operation')) {
    // Do the long operation here.
    // ...
    $lock->release('mymodule_long_operation');
  }
}

See  \Drupal\Core\Lock\LockBackendInterface for the interface exposed by the locking service.


Displaying Organic Group members based on a Views Contextual Filter

Okay so the problem turned out I was returning the wrong variable.

I needed to return $handler->argument instead of whatever variable I was using.

So my function I put in my contextual filter was:

if(arg(0) == 'groups' && arg(1) != null){
  $node_path = drupal_get_normal_path('groups/'.arg(1));

  $node_id = substr($node_path, 5);

  // Check if node referenced by arg(1) is a group
  if(og_is_group('node', $node_id)){
   // return $node_id;
   $handler->argument = $node_id;
   $node = node_load($node_id);
   $handler->validated_title = $node->title;
   return $handler->argument;
  }
  else {
    return null;
  }
}
else{
  return null;
}

(I cleaned up the code a little and adjusted it to strip out the unnecessary stuff.)


Make a specific content-type inaccessible

Yes, the Rabbit Hole module was built for exactly that:

Rabbit Hole is a module that adds the ability to control what should happen when en entity is being viewed at its own page.
Perhaps you have a content type that never should be displayed on its own page, like an image content type that's displayed in a carousel. Rabbit Hole can prevent this node from being accessible on its own page, through node/xxx.

It's highly configurable and works seamlessly in my experience.


Add template suggestions for location.tpl.php to use a different layout for addresses on specific content types?

@

Drupal 7 Template Suggestions
http://drupal.org/node/1089656

lists template suggestions in core.  It references,

Custom Template Suggestions

  Custom suggestions beyond the ones
  listed below can be created. See the
  page Working with template
  suggestions.
  http://drupal.org/node/223440#custom-suggestions

which provides examples for mod'ing template.php so that "All layers from core, modules, theme engines and themes can provide the suggestions."

which may provide a start for you.


How to place every node of a content type under a menu item?

You can use Default Menu Link module for this and core menu settings for content type..

  Provides the user with a check box on all content types to set the
  "provide a menu link" value to true by default.

  This is basically a nice way to ensure the menu system is adhered to
  by all content authors.

You need to set Menu settings for content type..


It is normal for the CPU usage to be at 100% when FFMPEG runs. Video compression is a computationally difficult task.

See this related question. If you have a two core VPS then you could make sure that FFMPEG only uses one core and thus always leaves at least one core for Apache/PHP/MySQL.

I created a similar site and it generally worked but it certainly had the occasional errors. It was a 4-core VPS and when transcoding all four cores were often at 100%. If I were to design the site again I think I would use a video transcoding service such as Amazon's Elastic Transcoder. Making sure FFMPEG would recognize all the different file encodings especially MP4 was quite a pain.


Attach a form submit handler (code here: Drupal 7 custom form submit handler is not being called).

Then set the file url to $form_state['redirect'].

The file download should begin when submitted.


How do I use rules to iterate over the subscribed users of a organic group to send email notifications?

There is a Flag action called Fetch users who have flagged [entity]. It will generate a list of users that you can then loop through and perform action on (e.g. send an email to). And since OG groups are entities, it should work (although I have not tested this). Also, beware that this might not scale if you have upwards of 1000 subscribers.

Reference: Nodeone's Learn the Rules framework. Checkout part 22 Flag and Rules: overview at the 4:00 minute mark.


How to restrict particular user roles from Adding child pages to the particular books only.

All node access modules, including Book access, are whitelist only.

  Node access modules always GRANT access and never restrict it. (It is a whitelisting rather than a blacklisting system.) If you use two node access modules and one grants access while another does not, access is granted. Exceptions are the Deny access module, as well as the old Module Grants module through which it is possible to combine access grants across multiple modules in a more intuitive way. Without it, the displayed behaviour may appear backwards from what most people would assume, and it's the reason why it is tricky to get involved with multiple node access modules. It is possible to use multiple node access modules in harmony however if for example they are applied to different content types or are giving out different grant types.

This means you need to deny access to books, generally, and then use  Book access to grant it per book. If you grant it via Drupal settings, you will grant it to all books, and grants are additive - so some people would be allowed, and some would be "doubly allowed", and no one will be denied.


It is my understanding that the update hook only runs once per update. The function is hook_update_n where 'N' is the instance of the update hook. Each time you want to revert your feature upon a code update you need a new update hook. This is why if you increase the number it works. If you are increasing your version numbers when you regenerate your feature, and also reverting your feature in code with an update hook, those numbers should match, and you will have an update hook for every version increment.

Source: Drupal API.


To send an email, Drupal 8 is not different from Drupal 7: You also need to implement hook_mail() as described in MailManager::mail().

See also the code used from MailManager::doMail(), which is the method that effectively composes and sends the email.
First, it initializes the $message variable.

  // Bundle up the variables into a structured array for altering.
  $message = array(
    'id' => $module . '_' . $key,
    'module' => $module,
    'key' => $key,
    'to' => $to,
    'from' => $site_mail,
    'reply-to' => $reply,
    'langcode' => $langcode,
    'params' => $params,
    'send' => TRUE,
    'subject' => '',
    'body' => array(),
  );

It passes that variable to the implementation of hook_mail() done from the module that is sending the email.

  // Build the email (get subject and body, allow additional headers) by
  // invoking hook_mail() on this module. We cannot use
  // moduleHandler()->invoke() as we need to have $message by reference in
  // hook_mail().
  if (function_exists($function = $module . '_mail')) {
    $function($key, $message, $params);
  }

Then, it sends the email.

  // Optionally send email.
  if ($send) {
    // The original caller requested sending. Sending was canceled by one or
    // more hook_mail_alter() implementations. We set 'result' to NULL,
    // because FALSE indicates an error in sending.
    if (empty($message['send'])) {
      $message['result'] = NULL;
    }
    // Sending was originally requested and was not canceled.
    else {
      // Ensure that subject is plain text. By default translated and
      // formatted strings are prepared for the HTML context and email
      // subjects are plain strings.
      if ($message['subject']) {
        $message['subject'] = PlainTextOutput::renderFromHtml($message['subject']);
      }
      $message['result'] = $system->mail($message);
      // Log errors.
      if (!$message['result']) {
        $this->loggerFactory->get('mail')
          ->error('Error sending email (from %from to %to with reply-to %reply).', array(
            '%from' => $message['from'],
            '%to' => $message['to'],
            '%reply' => $message['reply-to'] ? $message['reply-to'] : $this->t('not set'),
          ));
        drupal_set_message($this->t('Unable to send email. Contact the site administrator if the problem persists.'), 'error');
      }
    }

As you see, the email is sent using $message, not $parameters. If you don't implement hook_mail(), $message['body'] will be an empty array, and $message['subject'] will be an empty string.
That is why you get empty emails.


How to get submitted values on $formstate['values'] instead of $formstate['input']?

If you want to get $formstate['values'] or $form_state['input'] values .You have to write like below.

    function create_entry_form($form, &$form_state){
        $form['entry']['password'] = array(
          '#type' => 'password',
          '#required' => TRUE,
          '#default_value' => '',
          '#maxlength' => 15,
        );

        $form['entry']['submit'] = array(
          '#type' => 'submit',
          '#value' => t('OK'),
          '#weight' => 100,
        );
        $form['entry']['emailid'] = array(
          '#type' => 'textfield',
          '#required' => TRUE,
          '#default_value' => '',
          '#maxlength' => 25,
        );

        $form['entry']['reqbtn'] = array(
          '#type' => 'submit',
          '#value' => t('Request'),
          '#weight' => 106,
          '#submit' => array('request_site_password'),
          );

      return $form;
    }
   function request_site_password(&$form, &$form_state) {
    drupal_set_message('<pre>' . print_r($form_state['input'], TRUE) . '</pre>');
  }

You missed '&$form' in this function request_site_password(&$form, &$form_state)


Insert Block Inbetween Paragraphs of the Content Body Field

I think you want to be doing this on $body[0]['value']; And then in your output put echo render($content['body']); see the answer to this post on rendering fields.


Please check Remove width and height from img tag in Drupal output (for certain content type) for removing width and height from image.

You will never find width and height with grep command because width and height are added by drupal theme function.

Check https://api.drupal.org/api/drupal/modules%21image%21image.module/function/theme_image_style/7 and  https://api.drupal.org/api/drupal/includes%21theme.inc/function/theme_image/7 for more details.


How can I change the Available Menus to all, programmatically, for a specific content type?

If I understand you correctly you want to change the available menus for node types when new menus are created.

You can implement hook_menu_insert to respond to new menu creation and you can use variable_set to add the new menu to the available menus for the selected node types.

E.g. this will add all new menus to the page and article node types:

function mymodule_menu_insert($menu) {
  $types = array('page', 'article');
  foreach ($types as $type) {
    $menus = variable_get('menu_options_' . $type, array());
    $menus[] = $menu['menu_name'];
    variable_set('menu_options_' . $type, $menus);
  }
}

If you already have created a bunch of custom menus, you'll basically need to call variable_set as in the example above.


Translatable strings not appearing in the translation interface

As suggested by @prkos in the comments, visiting the pages (both public and admin) in the target language caused the corresponding strings to be discovered by Drupal and therefore become available in the interface translation. For each string, you have to visit the corresponding page (or block).

If you have custom error or confirmation messages, you apparently have to trigger them before they appear too. (? not entirely sure)

(I thought the "updating translations" progress bar that you see during the module installation was precisely Drupal listing all translations available in the module, but apparently that's not the case.)


How to fix a field with unlimited values where the "Add another item" is broken?

After many different tests, I have found the solution.

All the multi-value core fields using the module "Better Field Descriptions" were broken.

The help text added below by this module seemed to block the new option line to be created or at least displayed. Deactivate the module fixed the problem.

So, if you need a multiple values field and a permission to edit the help texts, be cautious with module interactions.

Thanks for those who tried to help me on this issue.


Need to display fields in a different format

For the above implementation

create a view with url  issue/arg(1)/arg(2)/arg(3)

where
arg(1) = year
arg(2) = volume
arg(3) = issue

like above u can pass argument

then by using contextual filter u can filter the view content and show the specific issue u want to.


How to hide the submit button on a node add/edit form page within which a entity reference select list has no valid option?

You can do this by using hook form FORM ID alter .

Once hooked in you find the $form item for the drop down list.  It'll be somewhere like

$form['field_my_entity_ref']['und']['#options']

So you should be able to make a check on the values in that array and if there are none then make the Submit button disabled .  My guess is

if ( count($form['field_my_entity_ref']['und']['#options']) < 1 ) {

   $form['#submit']['#disabled'] == TRUE;
 }

https://api.drupal.org/api/drupal/developer!topics!forms_api_reference.html/7.x/#disabled

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


Add the JS file inside the implementation of hook_user_login().
Function docs:

  The user just logged in.
  Parameters

  $edit: The array of form values submitted by the user.

  $account: The user object on which the operation was just performed.


It's pretty simple.

1 - Go to admin/structure/views/add
2 - write view's name & (auto)machine name.
3 - select Content as of your content view from select list.. second select list choose YOUR content type you want to filter the result of.
4 - Select Create a page .. you'd have to write the title of the page .. then the path to this page example: my_player // example.com/my_player

other options would be up to you!

hope this helps


Getting an email notification when a new Drush version is available

If you go to the Drush project page on Drupal.org then you can follow the "Releases" RSS feed found at the bottom of the page.

EDIT

You can also use the IFTTT.com service if you want the e-mails.  Just set up a rule on the site so that when the RSS feed gets updated, it sends you an e-mail.


how to disable and delete correctly the boost module

You have to delete the added boost code from .htaccess

In setting up the module you create this.

If you skipped that step you might check the htaccess tab in boost config and add those lines.

If you did not skip that step...

disable and uninstall the module then delete that added htaccess lines and directory.


How much RAM does a basic installation need?

It depends on a number of factors:

What contrib modules are you using? The bare minimum Drupal needs to run is 32 MB, but that truly is the bare minimum. Contrib modules and doing anything moderately complex with code will increase your memory requirements. While you're using Boost which is great, you still need to generate the cache, which requires RAM. But unless you're doing something really intensive, I've found you can generally be fine with 128 MB for PHP.
What web server are you running, and what type of load are you expecting? If you're running Apache with its default settings, it'll eat up a lot of memory: generally 128 MB or more. Optimizing your Apache environment or switching to a less memory-intensive server will free up more memory, but it's up to you if that's something that's possible.
Are you running your database on the same server? MySQL has its own memory requirements, and you'll find it takes up the bulk of a shared server's memory. You'll bump up to the memory limit on a small VPS pretty fast, especially if you're running InnoDB or have a large site. The general recommendation is somewhere between 70-80% of RAM should be allocated to MySQL running InnoDB, which is ~360 MB on a 512 MB instance: not a lot of room for PHP and Apache (or anything else).
Are you running any other service on the same server? If you're running Memecached, Varnish, APC, Jenkins, or any other service common to a Drupal environment, they all take up memory, and in many cases, a lot of memory.

If you're running a small Drupal site with an optimized Apache configuration, database on its own server, and no other service, I've found 256 MB to be the bare minimum. 512 MB is okay, not great, if you need to run the database on the same server and want to enable APC, but you still be looking for ways to save RAM.

I personally run the database, caching, and continuous integration services on other servers and use a Micro EC2 instance (613 MB RAM) for most Drupal installations I do. But I'll bump that up to a Small instance (1.7 GB, overkill, but there's nothing in between) if the site's going to get a lot of traffic.


Form API adds word "edit" in ID of every Form element

Drupal adds edit to denote that the element is an input element. It helps to identify form elements through CSS, and reduces the possibility of ID clashes with other elements on the page.

In case you're interested, this is done in the form_builder() function...and there's no easy way to override it system-wide.

You can easily override it for individual form elements though if it's bothering you:

$form['element'] = array(
  '#type' => 'textfield',
  '#title' => 'Some title',
  // ...
  '#id' => drupal_html_id('my-new-id')
);


RuntimeException when running drush commands in root folder

I still am not sure why I'm getting the RuntimeException, but I can work around this issue by running
vendor/drush/drush/drush st //or any other drush 9 commands


Determining What Text Editor to Use By Default Based on Site Location in Drupal 7?

I use the WYSIWYG module to define different profiles for each text input format and the Better Formats module to define which roles get what input formats on which content types.


Is there a pre-styled Omega subtheme out there?

Here is the complete listing of themes which uses the omega theme as a base theme.

Apart from that you can get the list of various themes/sites which uses omega theme on omega theme project page


Have you checked that $account->uid exists? I'm not sure that a new user would have a UID inside of hook_user_presave(). You may want try setting the flag in hook_user_insert() instead. Also worth making sure that users are allowed to be flagged by your flag type.


You will need Search API and Search API Database for this - though I suggest setting up Apache Solr + Search API Solr instead of Search API Database.

Search API
Search API Database

and/or also:

Search API Solr

Search API provides a lot more flexibility in terms of the types of search you want to configure and setup. Some functionality within say, Solr, allows for defining synonyms and abbreviations, as well as open you up to having facet based searches.


Views caching strategies - relationship between query cache and rendered output cache

I looked into some of the internal views logic, and from what I can there are elements from each theory that are correct, but neither is 100% accurate. It seems that both caching layers are separate, and always checked in series, so the "rendered output" cache does not really have the ability to "bypass" the query layer. Additionally, the query results do not factor-in to any cache keys, so changes to query results unfortunately do not trigger a refresh in the rendered output.

7.x-3.x

The "query results" cache is managed in view::execute() and the "rendered output" cache is managed in view::render(). Because execute() is called before the "rendered output" cache logic, a "rendered output" cache hit cannot bypass the query layer. It's not totally clear to me why this is as seems a little wasteful to run a query, or even check a query cache, if the display will just be built in-full from a cache. I suspect that there is plenty of other logic in view::execute() (access checks, hooks, plugin management) that must always be run independent of caching, and the "query results" cache part could not easily be separated from it. Anyway, that detail is a bit tangent to the question, but maybe someone else would be able to comment on it.

In terms of cache keys both cache layers are keyed by the view name, the display name, the cache type and then a hash of a bunch of contextual "stuff" from views_plugin_cache::get_cache_key(). A look at this get_cache_key() method is insightful as it shows that a some common contextual data is always factored-in (user roles, language, base_url), but the "rendered output" case takes things a bit further by also hashing the raw query string, but not the query results. So if the raw query changes, the rendered output will be refreshed, but if the query results change, the rendered output will still be returned from cache.

So I think that from a performance perspective each cache layer can really be dealt-with independently, but the "rendered output" cache will still most directly govern how often "stale" data is displayed. I could further conclude that:

The refresh interval for the base list of items in the view is greater-than-or-equal-to whichever cache interval is larger (the actual list of items can't update until both caches expire for any given view).
If the "rendered output" cache for a given view refreshes before the "query results" cache, the list of items won't refresh, but the content displayed for each item could (i.e. a new item added to the list 5 seconds ago still won't be shown, but teaser text that was updated 5 seconds ago on an item that was in the list previously would update).
Even when the "query results" cache is not influencing the final output it still offers a performance boost for view::execute().

It's also worth noting that some of this behavior could be changed by overwriting methods in the views_plugin_cache class locally, such as views_plugin_cache::get_cache_key().

8.0.0

As of 8.0.0-beta7 views (core) retains the option for time-based caching. As best I can tell it will behave like 7.x-3.x but it's really too early to do any conclusive testing - see this meta discussion. What is clear however is that many of the concerns and limitations around views time-based caching may become moot, as it looks like D8 views will also support tag-based caching.  This should offer a way for truly smart expiration of cached data.


The template file you want to use is not taxonomy-term.tpl.php; that's used for the taxonomy header at the top of the page. The template file used is node.tpl.php.

If you look at taxonomy_term_page() which is used to build the term page view, you will see the nodes are build separately by calling node_view_multiple(). node_view_multiple() is just a wrapper for node_view(), which uses the standard node.tpl.php file.

Also you should be able to use field_get_items() for taxonomy terms. I'll look for something like $field = field_get_items('taxonomy_term', $term, 'field_name');.

I haven't tried but it should work.

You should really never use 'und', but the constant LANGUAGE_NONE.


How to remove Quicktabs cookie on certain page?

Finally solved it. In case anyone is stuck with the same problem, this code now works for me. I learned that it's important to always set the path, to be able to retrieve the same cookie on different pages. I never got $.removeCookie() to work, so instead I used a default value. Also it did not work to use true, false and undefined as values, but it worked to use them as text inside quotes, 'true', 'false' and 'undefined'. Slowly getting there :-).

      Drupal.behaviors.quicktabsHistory = {
        attach: function(context, settings) {

        var default_tab = 'quicktabs-tab-instrument_flikar-0';
        if($.cookie('id', {path:'/'}) == 'undefined'){
            var id = $(this).attr('id');
        }else{
            var id = $.cookie('id', {path:'/'});
        }
        var tab = id;
        var flagga = $.cookie('flagga', {path:'/'});

        if($("body").is(".page-taxonomy")) {
            $.cookie('flagga', true, {path:'/'});
            $.cookie('id', default_tab, {path:'/'});
        }

        $('.quicktabs-wrapper', context).each(function() {
            if (tab != '' && flagga === 'false') {
              $(this).find('ul.quicktabs-tabs a#' + tab).click();
            }
            else {
              $.cookie('flagga', false, {path:'/'});
              $(this).find('ul.quicktabs-tabs a#' + default_tab).click();
            }

            $(this).find('ul.quicktabs-tabs a').click(function() {
                $.cookie('id', $(this).attr('id'), {path:'/'});
            });
        });
    };


How to use a content type form as a block

Thanks to the comments above, the working module code is here:
project_evaluation_form_block.module
<?php
/**
 * @file
 */
 function project_evaluation_form_block_entity_type_build(array &$entity_types) {
   $entity_types['node']->setFormClass('project_evaluation_form', 'Drupal\node\NodeForm');
 }

src/Plugin/Block/EvaluationBlock.php
<?php
/**
 * @file
 * Contains \Drupal\article\Plugin\Block\EvaluationBlock.
 */

namespace Drupal\project_evaluation_form_block\Plugin\Block;

use Drupal\Core\Block\BlockBase;
use Drupal\Core\Form\FormInterface;
use Drupal\Core\Entity\Entity\EntityFormDisplay;

/**
 * Provides an 'evaluation' block.
 *
 * @Block(
 *   id = "evaluation_form_block",
 *   admin_label = @Translation("Evaluation form block"),
 *   category = @Translation("Evaluation form block test")
 * )
 */
class EvaluationBlock extends BlockBase {

  /**
   * {@inheritdoc}
   */
  public function build() {
    $node = \Drupal::routeMatch()->getParameter('node');
    $edit_form = \Drupal::entityTypeManager()->getFormObject('node', 'project_evaluation_form')->setEntity($node);
    return \Drupal::formBuilder()->getForm($edit_form);
  }
}

Had to adjust the submission settings for the content type to have the save button appear.
And with this, I am able to add this form as a block to a page.


Apache filehandle issue expected to be mission critical for image uploading

Did you find this comment on drupal.org?

  The problem is a maximum open files limit per users.
  We had several web servers, and several new Apache2 VirtualHost; Apache2 (www-data) reached the maximum number of open files (1024).

  You can check that with ulimit -a  or ulimit -n. (The default is maximum 1024 open files.)

  You can modify it with ulimit -n 1500, but it will be lost after reboot.

  To make the change permanent, add in /etc/security/limits.conf:

#<domain> <type> <item> <value>
#
www-data soft nofile 1600
www-data hard nofile 65535

  Of course, restart your web server.

It explains how to set a per-user limit and increase the number of files that can be opened.  If you don't have enough memory in the server, there may not be many options.


How to add a image in your drupal.org bio?

I just did a similar experiment (followed by an undo ...), and tried adding this HTML code in the same "Bio" file:

Drupaler driven by Views/Flag/Rules/Message/Group.

And guess what, it worked!

The bio you can currently see in my drupal.org profile is created using this HTML code:

Drupaler driven by Views/Flag/Rules/Message/Group.

So I think you should use an existing image that you know already exists on drupal.org (such as within /files/ for both of my sample images).

Ps: note the special image I used from that pictures directory ... looks familiar?


Line line 29:

$nid = $node->nid->value;

Try this solution:

$node->id();

Very useful thing "Drupal 8 Entity API cheat sheet": https://www.metaltoad.com/blog/drupal-8-entity-api-cheat-sheet


How to set required POST parameters for routes

I did something like this before ( take a look at helper link ),it  not required to tell router about type

just post your data and in your controller  get them with

$value = \Drupal::request()->request->get('your_posted_variable');

Also you can get all $_POST variables with

  \Drupal::request()->request->all(); // equal to $_POST


Memory efficient way to load large entity set for data export

Batches allow heavy processing to be spread out over several page
  requests, ensuring that the processing does not get interrupted
  because of a PHP timeout, while allowing the user to receive feedback
  on the progress of the ongoing operations. It also can reduce out of
  memory situations.

  Source: Example: Batch API

You need to use the Batch API. There is no official docs for D8, but you can look at the batch_example module and the CSV Import module.

Good conceptual read, Drupal 8 Batch Processing but a bad code example.


Try the feeds module, or migrate for importing the data. Whatever module you end up understanding best for newsletters, is what I recommend.

Your question leaves out various details: show email templates be editable by site moderators or users, opt-in or opt-out features for the newsletters. Are newsletters recurring, or sent on-demand ... etc.

I recommend looking at the various newsletter modules, Rules based modules and scheduler modules to see what fits your needs.

I find leveraging an existing solution, like mailchimp and other email services typically well worth the cost (personally).

As example I wrote custom code that looks at emails in an imported DB table and uses a server-side cron task to run a Drush command to send emails with my own custom business logic (recurring scheduled emails, if tasks are completed they no longer receive emails)... my solution is not for everyone.


Services won't authenticate email address used as username

The Email Registration module doesn't create any service resource. Also it doesn't change user login resource of the Services module that allows users to login just with their names.
I have implemented user email and name login solution with this custom service:

  /**
 * Implements hook_services_resources().
 */

function custom_mail_login_services_resources() {
        return array(
   'custom_email_login' => array(

        'actions'=>array (
        'mail_login' => array(
        'callback' => 'get_mail_login',
        'access callback' => 'user_is_anonymous',
        'args' => array(
            array(
            'name' => 'data',
            'optional' => FALSE,
            'source' => 'data',
            'type' => 'array',
            'description' => 'Name or email',
            ),
     ),
    ),
   ),
   ),
  );
}

  function get_mail_login($data) {
  global $user;
  $username = null;
  if ($name = db_query('SELECT name FROM {users} WHERE LOWER(mail) = LOWER(:mail)', array(':mail' => $data['mail']))->fetchField()) {
      $username = $name;
  }elseif ($name = db_query('SELECT name FROM {users} WHERE LOWER(name) = LOWER(:name)', array(':name' => $data['mail']))->fetchField()) {
      $username = $name;
  }else{
        return services_error(t('No user with this email or name exists!'), 403);
 }
 if ($user->uid) {
    // user is already logged in
    return services_error(t('Already logged in as @user.', array('@user' => $user->mail)), 406);
  }

  // Check if account is active.
  if (user_is_blocked($username)) {
    return services_error(t('The user %name has not been activated or is blocked.', array('%name' => $mail)), 403);
  }

  // Emulate drupal native flood control: check for flood condition.
  $flood_state = array();
  if (variable_get('services_flood_control_enabled', TRUE)) {
    $flood_state = _user_resource_flood_control_precheck($username);
  }

  // Only authenticate if a flood condition was not detected.
  if (empty($flood_state['flood_control_triggered'])) {
    $uid = user_authenticate($username, $data['password']);
  }
  else {
    $uid = FALSE;
  }

  // Emulate drupal native flood control: register flood event, and throw error
  // if a flood condition was previously detected
  if (variable_get('services_flood_control_enabled', TRUE)) {
    $flood_state['uid'] = $uid;
    _user_resource_flood_control_postcheck($flood_state);
  }

  if ($uid) {
    $user = user_load($uid);
    if ($user->uid) {
      user_login_finalize();

      $return = new stdClass();
      $return->sessid = session_id();
      $return->session_name = session_name();
      $return->token = drupal_get_token('services');

      $account = clone $user;

      services_remove_user_data($account);

      $return->user = $account;

      return $return;
    }
  }
  watchdog('user', 'Invalid login attempt for %username.', array('%username' => $username));
  return services_error(t('Wrong username/email or password.'), 401);
}

You have to put this code into your custom_mail_login.module file and add custom_mail_login. info file. Module name is custom_mail_login.
Then enable this module and custom_email_login mail_login resource in admin/structure/services/list/your_endpoint/resources.

You have to send json request {"mail":"useremail@address.com", "password":"password"}. The parameter "mail" is an email or user name.


How can I force the user to select dates that have passed when using the Date picker in the form API?

They are talking about datepicker options here: Customize days that can be clicked on a Calendar popup

Apparently datepicker is quite versatile, with those options you can set max-date, min-date etc.


Login not redirecting to SSO (external) server login page

Unset the destination before calling drupal_goto():

unset($_GET['destination']);
drupal_goto('PATH/TO/SSO-SERVER-LOGIN-PAGE.ASPX', array('external' => TRUE));

Another option would be to code the redirection logic yourself (brought up as an answer by Dave here).

The problem exists because drupal_goto() is overriding the given path with the destination if the latter is not external (check the function code).

Additionally:

Since you are using the button type the submit handler isn't being invoked (documentation). For my solution to work you would have to change the type to 'submit' or move the redirection logic into the validation handler (by changing '#submit' to '#validate').


You can try Secure Pages and Secure Pages Hijack Prevention modules.


copying actual drupal content to a different drupal site

It may be too late for this, but I needed the same thing and came across this thread so thought others might also. There's a new module called Data Export Import which does exactly what you need:

  The purpose of this module is to be able to export nodes, taxonomy
  terms and users to data files and then be able to import these data
  files into Drupal sites. There may be many uses for this module but
  the main one would be that it can provide a way to export data from a
  live Drupal site and then to import that live data into an updated
  version of that site.


Create a hook suggestion in page preprocess and theme that page

for eg:

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

Now clear the caches
Duplicate page.tpl.php and rename it as page--specialcontenttype.tpl.php

Then, remove the <?php print render($page['header']); ?> etc.. from it


Why does not hook_menu_link_alter() work?

Not really a complete answer, but hook_menu_link_alter() is not called when the menu is rendered; it is called when the menu item is saved. Just an FYI.


Is there a module that can replace tabbed menus with contextual links?

The Custom Contextual Links module does this https://drupal.org/project/ccl

Jeff Eaton gives a good overview of this module https://www.lullabot.com/blog/article/module-monday-custom-contextual-links

Alternatively, you could theme the existing menu to be styled like contextual links since both use an unordered list, just different css classes that trigger style and javascript behavior.  To do so you could either use a custom module to add the css classes necessary or add your own css rules.