How to set up Google+ authorship in Drupal 7

The easiest way is with the Metatag module:

  The Metatag module allows you to automatically provide structured
  metadata, aka "meta tags", about your website. In the context of
  search engine optimization, when people refer to meta tags they are
  usually referring to the meta description tag and the meta keywords
  tag that may help improve the rankings and display of your site in
  search engine results.

After you install/enable the module, you can edit the metatags at admin/config/search/metatags  The Google+ Author is under Advanced.


The 'publish on' date must be in the future

Under

  admin/config/content/scheduler

you can set your date format. What have you set here? Has the date format included time formatting?

The publish time has to be added after the date (that is today).


How to limit webform submissions access to only users who have Webform submissions?

Maybe not a complete solution but here is how you can start of

create a view that displays submissions
make it available to everyone (view has permissions)
put it in a URL that is not linked from your main site (its like being hidden but not exactly)
put the URL link at the submission completion page (thank you page)

beware this will not prevent a person that knows this URL to visit it and see the results.  I am not aware at this point of a module that will give the required permission see results after submission or something similar so if the above is not to your satisfaction then you might want to create a module to do that or modify webform to include such a feature


Memcache and form cache - is specfiying database for form cache still necessary?

Drupal 8 does not have a {cache_form} table; in-progress $form_state got moved to the key-value store.  The KV store for forms defaults to the database (there are core classes to support database and memory for KV).  And the KV store and cache backends are different concepts in Drupal 8 (the former is for persistent data with expiration, the later is for ephemeral data with expiration), so you should be fine.


If by static resources you mean resources for which the content is served from the server, using the content of a file, then hook_page_build() is not invoked for such resources.
It's the server that handles those requests, and Drupal doesn't do anything. In that case, you could edit the .htaccess file to redirect the users to the right domain.

That is what I would do also in the case it's Drupal to produce the content. Rather than letting Drupal produce the output, and redirect the user to the correct sub-domain, where the output would be produced again, I would rather redirect the user once it is clear what type of resource is being requested, and which is the URL of the resource.


Encrypting db password stored in settings.php

This is not a Drupal question specifically. Depending on the OWASP security standards you're following keeping the password in plain in settings.php could be considered a risk (in a normal, usual Drupal environment it won't be the case)

This thread on Information Security Stack Exchange discusses the topic, but in my opinion is a little paranoid and most of the options will slow down your site.


I've done exactly this before; I'll dump the code I used. Hopefully, it'll give you an idea.

/**
 * Implements hook_menu().
 */
function uc_giftwrap_menu() {
  $items['admin/store/settings/giftwrap'] = array(
    'title' => 'Gift Wrapping',
    'access arguments' => array('administer gift wrap'),
    'page callback' => 'drupal_get_form',
    'page arguments' => array('uc_giftwrap_admin_form')
  );

  return $items;
}

/**
 * Implements hook_permission().
 */
function uc_giftwrap_permission() {
  return array(
    'administer gift wrap' => array(
      'title' => 'Administer Gift Wrap Settings'
    )
  );
}

/**
 * Form builder for the gift wrap settings.
 */
function uc_giftwrap_admin_form($form, &$form_state) {
  $form['uc_giftwrap_cost'] = array(
    '#type' => 'textfield',
    '#title' => t('Gift Wrap Cost'),
    '#description' => t('Total cost of gift wrapping for an order.'),
    '#default_value' => round(variable_get('uc_giftwrap_cost', '0.00'), 2),
    '#field_prefix' => '&pound;',
    '#size' => 10
  );

  return system_settings_form($form);
}

/**
 * Implements hook_uc_checkout_pane().
 */
function uc_giftwrap_uc_checkout_pane() {
  $panes['gift_wrap'] = array(
    'callback' => 'uc_giftwrap_uc_checkout_pane_callback',
    'title' => 'Gift Wrapping',
    'desc' => 'Provide gift wrapping options for the checkout.',
    'weight' => 5
  );

  return $panes;
}

/**
 * Callback for the checkout pane.
 */
function uc_giftwrap_uc_checkout_pane_callback($op, $order, $form = NULL, &$form_state = NULL) {
  if ($op == 'view') {
    $description = t('Please check this box if you wish your order to be gift wrapped.');

    $contents['gift_wrap'] = array(
      '#type' => 'checkbox',
      '#title' => t('Add Gift Wrapping') . ' (' . uc_currency_format(variable_get('uc_giftwrap_cost', 0)) . ')',
      '#default_value' => isset($_SESSION['uc_giftwrap_checkout']) ? 1 : 0,
      '#ajax' => array(
        'callback' => 'uc_giftwrap_update_line_items',
        'effect' => 'slide'
      )
    );

    return array('description' => $description, 'contents' => $contents);
  }
  else if ($op == 'process') {
    if ($form_state['values']['panes']['gift_wrap']['gift_wrap'] == 1) {
      if (!isset($_SESSION['uc_giftwrap_checkout'])) {
        uc_order_line_item_add($order->order_id, 'gift_wrap', 'Gift Wrapping', variable_get('uc_giftwrap_cost', 0));
        $id = db_query('SELECT MAX(line_item_id) FROM {uc_order_line_items}')->fetchField();
        $_SESSION['uc_giftwrap_checkout'] = $id;
      }
    }
    else {
      if (isset($_SESSION['uc_giftwrap_checkout'])) {
        uc_order_delete_line_item($_SESSION['uc_giftwrap_checkout']);
        unset($_SESSION['uc_giftwrap_checkout']);
      }
    }
  }
}

/**
 * AJAX callback for the checkout form (allows instant updating of total when gift wrap option is chosen).
 */
function uc_giftwrap_update_line_items($form, $form_state) {
  $commands = array();
  if (isset($form['panes']['payment']['line_items'])) {
    $commands[] = ajax_command_replace('#line-items-div', drupal_render($form['panes']['payment']['line_items']));
    $commands[] = ajax_command_prepend('#line-items-div', theme('status_messages'));
  }

  return array('#type' => 'ajax', '#commands' => $commands);
}

/**
 * Implements hook_uc_line_item().
 */
function uc_giftwrap_uc_line_item() {
  $items[] = array(
    'id' => 'gift_wrap',
    'title' => t('Gift Wrapping'),
    'weight' => 2,
    'default' => FALSE,
    'stored' => TRUE,
    'add_list' => TRUE,
    'calculated' => TRUE,
    'callback' => 'uc_giftwrap_uc_line_item_gift_wrap',
    'display_only' => FALSE
  );

  return $items;
}

/**
 * Callback for line item type.
 */
function uc_giftwrap_uc_line_item_gift_wrap($op, $arg1) {
  // Required callback for hook_uc_line_item()
}

/**
 * Implements hook_uc_checkout_complete().
 */
function uc_giftwrap_uc_checkout_complete($order, $account) {
  if (isset($_SESSION['uc_giftwrap_checkout'])) {
    unset($_SESSION['uc_giftwrap_checkout']);
  }
}


Synchronizing Database Configuration Across Environments

You cannot reliably 'merge' database copies. One way or another, everything has to be managed through code.

In Drupal 8 this is handled with the Configuration Initiative, but in D6 and D7 you have to use a tool like the Features module, which provides an interface to create 'features' (which are really exportable content stored in specific modules). You can export things like site configuration, content types, views, etc. into a feature, then push the code from one branch to another, and have that feature's changes "apply" on to the new database.

The Features module has its share of problems, but it does work fairly well for the most part, and is the go-to solution for managing database changes.

In addition to Features, you'll likely also want Strongarm, which lets you use Features to export data from the variables database table.

Alternatively, many people use update hooks to handle their database changes; that's a bit more involved and requires a strong understanding of Drupal development.

You may also want to read through these resources:

Staging Drupal
Drupal Configuration Management With Features


You need to specify your Drupal root to Drush in one of several ways:

Pass --root=/public_html --uri=http://example.com as an option on the commandline.
Set $options['root'] = '/public_html'; and $options['uri'] 'http://example.com' in a drushrc.php (not a good option if you have multiple sites on the system)
Use an alias, and set 'root' => '/public_html', 'uri' => 'http://example.com' (per the article you quoted)
Change your current working directory to '/public_html/sites/default' before running Drush commands (only works if you don't do any of 1 - 3).


How to use mssql as database for my site running on redhat linux

Once your new server is running, you only have to do a few things.

Dump the old database (PgSQL)
Convert the dump to MSSQL
Import the dump.

If you search on google you should be able to find tools that will allow you to export convert the dump. This is not perfect but is probably the easiest solution.

Alternatively if that doesn't work, you can create a script that from within Drupal fetches data from one database and then inserts it into the other database, effectively using Drupal/PHP to translate the dump. This is much slower and requires more work, but have less chance of failure.


You shouldn't use this service because it is marked as internal and you shouldn't use any other method to generate links in custom code. Generating a link is like early rendering. See https://www.lullabot.com/articles/early-rendering-a-lesson-in-debugging-drupal-8
Instead add the link as render element to the build array.
Like this examples which also demonstrates how you can build nested render elements, here an image as link title:
      $link_title = [
        '#theme' => 'image',
        '#uri' => $image,
        '#alt' => $label,
      ];
      $image_link = [
        '#type' => 'link',
        '#title' => $link_title,
        '#url' => Url::fromUri($link_href),
        '#options' => [
          'attributes' => ['class' => ['feed-image']],
        ],
      ];

      $build[$id]['image'] = $image_link;

Example from /core/modules/aggregator/src/FeedViewBuilder.php


new product display content type not showing in products view

I finally found the problem. The answer is probably obvious for a drupal expert but not for someone who just use drupal commerce out of the box.

Right, so the search facility (search box and 'all product' link ) use the search API which needs to be re-indexed when something changed.

For some reasons it wasn't. I'm expecting that adding a new product/entiry will triggered a reindexation but it doesn't. It seems also it could be done via the cron (but I haven't set any cron either, nobody told me to so). And, anyway, it seems the indexation was 'broken' (I changed one of the category name) so I add to recreate the indexes form scratch.

So the answer is , my searches need reindexation.


In which table in the database are the email messages stored?

They are stored as system variables in the {variable} table, and normally accessed with variable_get() and variable_set().  The variable names are

user_mail_cancel_confirm_body
user_mail_cancel_confirm_subject
user_mail_password_reset_body
user_mail_password_reset_subject
user_mail_register_admin_created_body
user_mail_register_admin_created_subject
user_mail_register_no_approval_required_body
user_mail_register_no_approval_required_subject
user_mail_register_pending_approval_body
user_mail_register_pending_approval_subject
user_mail_status_activated_body
user_mail_status_activated_notify
user_mail_status_activated_subject
user_mail_status_blocked_body
user_mail_status_blocked_notify
user_mail_status_blocked_subject
user_mail_status_canceled_body
user_mail_status_canceled_notify
user_mail_status_canceled_subject

Look at the code for user_admin_settings(), which is a standard system settings form and has the variable names in it, and _user_mail_text() which has all of the default text.


How can I add a save button in my page variant?

This is a known issue with recent activity => enter link description here

Solution:

After you apply the latest patch to ctools, you need to add a "User form actions / buttons" element to your page.

Your page variant should look sth like this:

And the rendered form now comes with a submit button:

Good luck!


Drupal 8 - How to edit a user as admin without changing the password

You can do it from the command line using drush user-add-role.
To find the exact syntax, type :

drush help urol

Hope it helps.


Clear Example for drush rsync exclude paths

drush rsync has an  --exclude-paths parameter that will allow you to exclude your node_modules directory.

Have a look at the parameters for rsync.

You should be able to do something like :

drush --exclude-paths=sites/all/themes/themename/node_modules rsync @self @live

Because the Drush rsync command uses strict option handling, the --exclude-paths option must appear before the rsync command name.


For this you have to enable the Statistics module which is provided by  Drupal Core.
Follow these steps :
1. First enable Statistics Module
2. Then make a view and add a field provided by Statistics module. It basically provides three options:

Most recent view
Total Views
Views today

and then use Total Views as mentioned in your requirement.


In Drupal 7 the uid column in the users table isn't an autonumber, so there's nothing to reset/reseed.

When you add a user in D7 the user_save() function does this:

// Allow 'uid' to be set by the caller. There is no danger of writing an
// existing user as drupal_write_record will do an INSERT.
if (empty($account->uid)) {
  $account->uid = db_next_id(db_query('SELECT MAX(uid) FROM {users}')->fetchField());
}

So the next user ID is simply the next available free ID (current max + 1) from the users table.

If you have a record with a uid of 100, then you add 2 new users (101 and 102), the next available user ID will naturally/logically be 103; which will be returned by the above code in user_save().

If you need that to be 101 again for whatever reason, you need to delete the user you've just created that occupies the 101 ID, and set the uid manually on the new user record that you want to replace it, before you save it (as suggested by the above comments in user_save()).


Drupal 6 - Core Search Module Not Indexing Node Titles

I was able to fix this issue by changing the Indexing throttle setting for Number of items to index per cron run from 100 down to 10.

Once reindexing was complete all node titles appear to be indexed and appearing in search.


Module has conditional Checkboxes, need to remove value

Add a secondary submit handler to run before the main one:

array_unshift($form['#submit'], 'poetic_toolkit_admin_submit');

Then in that:

function poetic_toolkit_admin_submit($form, &$form_state) {

    // check if field A is checked
    if(!$form_state['values']['poetic_toolkit_mobile_viewport_setting']) {
        // if it is not then set field B value to 0
        $form_state['values']['poetic_toolkit_enable_webapp_setting'] = 0;
    }

}

Then after this the main submit handler will fire and save our updated values.

This will only update the values once the form is saved.

Additionally, you don't want the unchecked condition on the depending item poetic_toolkit_enable_webapp_setting, because then it becomes checked whenever the dependent field poetic_toolkit_mobile_viewport_setting is checked (double negative). You also want to make sure you have the #default_value on the second item set, so that the user see's what is currently set (which will always be unchecked when the first is unchecked but could still be unchecked if the first is checked).

If you want B to become unchecked as soon as A is unchecked then you will need a jQuery solution.


How do I alter the default node URL rendered in a view?

Usually when you set a URL alias when you creating/updating a node this new url will be used for your nodes links. If you didn't set a URL alias for your nodes, clear the caches after set. In my dev site working fine just doing this.


Emailing a bunch of users selected from a user reference field

You should be able to add another "Send email" action to your rule, but place it inside a Rules loop so it can iterate over the multiple values in the user reference field. You may need to first add an "Entity has field" condition to get access to these values.


Fatal error: Maximum execution time of 240 seconds exceeded in sites/all/modules/memcache/memcache.inc on line 353

Set max_execution_time = 0 in php.ini to allow unlimited execution times, and disable the set_time_limit() PHP function (also via php.ini) to prevent Drupal from self-limiting its execution time back to 240 s. Otherwise, you would have to find all the places where Drupal calls set_time_limit() and increase the values there or set them to zero.

(In Drupal 7, this got simpler through the new drupal_set_time_limit() wrapper function, which will not call set_time_limit() at all if the current time limit is 0 (unlimited). To be exact, this works since Drupal 7.40, and before was prevented by issue #2233929.)


Turns out multilingual modules were on, and using URL detection. When that is set, the URL for the particular language you are looking at gets inserted into all links.


Editing user submission of user registration form with hook_user_insert() and $edit

hook_user_insert() is invoked after the user object and all it's fields have already been committed to the database; that's why your code isn't taking effect at the moment.

There are a couple of ways you could go:

Use exactly the same logic in hook_user_presave(), which gets called before the data is committed to the database.
Implement hook_form_alter() for the registration form, add a custom validation function, and manipulate the field values in there.


Unable to submit form to database in custom module

If you write a block, use \Drupal\Core\Block\BlockPluginInterface::blockSubmit for submission


AFAIK, Drupal doesn't support any of the Symfony route annotations.  The code is present in vendor/, but not used by core.

The closest thing is the concept of Entity links, which are part of the Doctrine annotations on the entity class.  These link names can be used in the ::toUrl() method to generate the canonical link for an entity, the edit link, etc.  However, the routes still need to be defined in the routing.yml file.


After having lots of fun with rules, I have found a solution. Whew!

I created a rule:

Events:
Before saving content

Conditions:

Content is of type - Parameter: Content: [node], Content types: Community Group

AND

Data comparison - Parameter: Data to compare: [node:group-access], Data value: Public - listed in the...

Elements:

Set a data value - Parameter: Data: [node:group-access], Value: Private - accessible only...

I also send an email and show a message on the site, but that's not to important to the nitty gritty of the rule.

The purpose of my rule is that when a user selects "public" for a group, that the group is created as "private" but a request is sent to a Group Admin to review and change to public once approved. In the meantime, the user can still add members and use the group in a private state.


Translation does not work for promoted to front page nodes

I'm assuming this question is about D7 ...

The relative URL to display as the front page is specified within admin/config/system/site-information. If you want to be able to specify a value for it that is different for each of the site's languages, make sure you have made it a "multilingual" variable (it should say "This is a multilingual variable.") in the description of that variable on that page.

Refer to the community documentation about Variable translation for details about how to translate text and settings that are stored in Drupal as variables. Here is a quote from that page:

  The Variable translation module, part of the Internationalization (i18n) package, allows you to translate text and settings that are stored in Drupal as variables. These variables include text such as 'site name' and 'site slogan', as well as settings like 'Default front page' and 'Default 404 page'.

The Variable translation module has a dependency on the Variable module.

And these are the specific steps required to make a variable multilangual (mentioned on that community page):

Enable the Variable translation module included with the Internationalization package
Go to Administration > Configuration > Regional and language > Multilingual settings
Click on the Variables tab
Select the variables that will be multilingual
Click Save configuration button

Obviously, in this case in step 4 the variable to be selected is "Default front frontpage", within "Site information".

Finally, this is what remains to be done (another quote from that same page):

  Once you have the correct settings, they'll be marked with "This is a multilingual variable" when you go to the corresponding administration pages (Figure 2). You must switch the site language while in the administration pages to set the variables for each language. A language switcher link will appear at the top of each administrative page that has multilingual variables.

"That's all" what's needed to specify a language specific value for the frontpage of your site ...


Kint breaks in template and doesn't allow me to view anything

Deactivate the BigPipe module, it causes some errors in Google Chrome when the user is logged in.

There's no error in Chrome if you aren't logged in. Firefox and Safari will still work with Kint and BigPipe enabled.


Form redirection to registration for anonymous users while preserving data entered

One option would be to do this in a custom module with hook_form_alter(). You could use it to alter the CCK form to add a custom validation/submit handler that redirects anonymous users to the registration page. The inserted form data could be stored in the session (before redirecting) from where you can retrieve it later to fill in the form with default values (using hook_form_alter() again). I'm assuming that you do not need to store the data for long periods of time since session is not suitable for that. You should also unset the used session variables after use.


AJAX chats are pretty resource hungry by nature when running on Apache, so there are no easy configuration switches that will instantly give you better performance, I'm afraid.

The big difference between chat implementations is that GMail and Facebook uses a different backend, more suitable for AJAX polling / push. The node.js backend for Drupalchat might be able to help you in that regard. If I were writing my own chat from scratch, I'd probably try out http://www.ape-project.org/ which seems to be pretty good featurewise.


Display Months in dropdown for filtering

Using the Date project, you can add a "Date: Date (node)" (D7, not sure how it is called in D6) filter, where you can choose the granularity. By setting it to month, it will display a list of months in the filter.

I looks like a "All month" option is however currently missing, so you can't display all months by default, it seems. See http://drupal.org/node/574820.


Multiple sites routed to one codebase has the subdirectory name as prefix on the links

Try to set the $baseurl variable in settings.php, at Drupal site directory. Read the documentation around this variable in the settings file.


drush user-block feature and 'You do not have permission to block'

Sometimes modules does not respect that user with UID 1 should be allowed to do everything. And sometimes you simply want hooks to fire with specific user's ID.

When it happens, you can use drush --user=123 where 123 is UID of an user that is allowed to perform given action.

Source: Drush issue 1126240.


Use an existing Drupal site to create a new site

Hmmmm, you that settings.php should be the ticket, but to really trouble shoot it, it would be easier to see the code. But because that contains your DB connection, that's not something that you should be sharing with others. However, if your having troubles, you could always try going about this a different way.

You could start with a blank db, and toss your settings.php file. That will cause Drupal to think it isn't installed yet, and will take you through the install process. Once your done with that and have a clean Drupal site running on a clean DB, then you can dump your data from your old site into the new DB, which should transfer your data over, but you'll have a fresh settings.php file. That might be easier way to go about it.


“Show as expanded” selected but children menu items not displaying

I've solved it. I've figured that I should have to configure the block and extend the menu levels


do not use node/%/.. as your path, this will disturb the default routing system.

  change the view's path to gallery/% or something.

if you want to keep this url, register a local task like here How to add a local task tab to node view?

and in this page callback you can display the view with views_embed_view,
 in this case you will remove the path of the view, or change it to a test-path.

but still, the alias with /gallery needs to be registered too !


Can I write MySQL settings in drupal settings.php file?

No, those need to be set in your MySQL server's my.ini/my.cnf file.

Those settings can't be changed on the fly from any process (PHP, Apache, even MySQL itself), you need to set them in the .ini/.cnf file and then restart the MySQL server for the changes to take effect.


Does the Services module implement caching on GET requests?

No, the Services module does not support caching on GET requests:

http://cgit.drupalcode.org/services/tree/resources/node_resource.inc?h=7.x-3.x#n253

As you can see, each time the resource's callback function is invoked, it makes a call to node_load(). You can use the Services API to preprocess/overwrite the resources to implement caching though:

http://cgit.drupalcode.org/services/tree/docs/services.alter.api.php?h=7.x-3.x


Using taxonomy to give option of page layout - working but showing error (Notice: Undefined variable: node in include())

The page.tpl.php template file will receive a $node variable only if the user is visiting a node page; in other cases, it will not get any $node variable, even if the template file is still used (if a module doesn't suggest another template file that takes the precedence).
In fact, the documentation for page.tpl.php clearly describes the $node variable as follows. (Emphasis is mine.)

  $node: The node object, if there is an automatically-loaded node associated with the page, and the node ID is the second argument in the page's path (e.g. node/12345 and node/12345/revisions, but not comment/reply/12345).

Before accessing $node, you should be sure it has been set.

if (isset($node)) {
  $field_page_width = field_view_field('node', $node, 'field_page_width');
}

Also, field_view_field() is used to render a field. If you just need to get its value, you should use field_get_items().

if (isset($node)) {
  $items = field_get_items('node', $node, 'field_page_width');
}


How to check user has permission special node

Just tested this and $node->access('update'); works for me. I let the optional $account parameter out so that it would check the currently logged in user.

The only difference was that I loaded my node with:

\Drupal\node\Entity\Node::load($nid);

To just use Node::load($nid); Make sure to include:

use Drupal\node\Entity\Node;

at the top of your file.


I want to import my youtube videos to drupal when I upload a video in YouTube

Social Content module allows you to automatically import Youtube videos as nodes. It provides an easy-to-use graphical user interface where you can map node fields with the fields provided by the Youtube API.

To just display Youtube videos, you could map a link field to the Youtube Embed URL, and then output it with Link iframe formatter module (for example).


How to redirect URL of kind node/nid to its url alias

Even though you've figured out a great solution, Rules may well be a module that can help you out with this for other problems you have in the future. Rules contains several options to fire off several events. For example, if you tell Rules to React on event Content is viewed, you can then set certain events, conditions, and actions. One of these Events will cause the user to be redirected to another page - not as simple as Global Redirect, but if there's something you need done before redirecting, this could do a lot for you.


Creating Preprocess function to add extra classes dependent on field value

You can add the class to the body from the node field value in hook_preprocess_html

Something like:

/**
 * Implements hook_preprocess_html
 */
function THEME_preprocess_html(&$vars){
  // Check if on an article node page
  if($node = menu_get_object('node') && $node->type == 'article'){
    // Get field values
    if($text_color = field_get_items('node', $node, 'field_text_color')){
      // Add first text_color value to body class
      $vars['classes_array'][] = drupal_html_class(reset($text_color));
    }
  }

}


As a pretty easy workaround, you could set up a views-view.tpl.php on your own sites that prints $view->get_title() for the title on the attachments.


Button in multiform make it go to different steps

This could be done with jQuery, like this:

$('#SUBMIT-ID').click(function () {
  $('.step-1-wrapper').addClass('hidden');
  $('.step-2-wrapper').removeClass('hidden');
});

Then you can show both steps from the beginning, and then hide them.

You also need to create a global css rule that makes a display none, on all hidden classes


Run "git" on remote server with drush alias

This works just fine for me on both the 6.x and master branches of Drush, and on the 6.2.0 release.  So, your first step would be to try with the latest versions, and see if it works.  If that doesn't fix your problem, try running your command again using the -v flag to get more verbose output.  You will see something like this:

$ drush -v @mysite.prod git-status
Loaded alias @server.xxxxxxxxxxx from file                              [notice]
/home/ga/local/config/drush-aliases/server.aliases.drushrc.php
Loaded alias @mysite.prod from file                                     [notice]
/home/ga/local/config/drush-aliases/mysite.aliases.drushrc.php
Include /home/ga/local/drupal/drush_extensions                          [notice]
Include /home/ga/.drush                                                 [notice]
Calling proc_open(ssh -o PasswordAuthentication=no webuser@myserver.com 'cd /srv/www/myserver.com/htdocs && git status');
# On branch master
# Untracked files:
#   (use "git add <file>..." to include in what will be committed)
#
#   ../xxxxx.txt
nothing added to commit but untracked files present (use "git add" to track)
Command dispatch complete                                               [notice]

Try running the command inside of "proc_open(...)" from the shell, and see if it behaves the same way.  Adjust the ssh options until it works right.  Then, set $options['ssh-options'] to adjust.

NOTE:

If you want to do something like this without defining a shell alias, the following should also work:

drush @mysite.prod ssh git status


Views joining/relating a custom table entity to users through a field?

I know this is not timely, but if someone else is looking for an answer:

Assumptions:
- Using Entity API
- Joining to another entity where the entity id is a field in your entity's base table
- It's a one-to-one relationship

Add the views controller class to your entity info file
function my_entity_entity_info() {

$info['my_entity'] = array(
  'views controller class' => 'MyEntityViewsController',
  ...
 );

2 Extend EntityDefaultMetadataController

class MyEntityMetadataController extends EntityDefaultMetadataController {

  public function entityPropertyInfo() {

    $info = parent::entityPropertyInfo();

    // This exposes the fields as references to views.
    $info['my_entity_base_table']['properties']['uid']['type'] = 'user';

   ....
  }
}


Create your own text filter which just does nothing which means it allows really "all" input without any filtering.

Please make sure that you allow only trusted people to use this filter since it would be easy to add XSS code.


Check http://YOUR_SITE.NAME/admin/structure/types/manage/YOUR_CONTENT_TYPE/display/teaser

You have to add field_teaser_image to visible fields list.

Field UI module must be active.


Multi-site with two sites sharing the same domain?

I have done this before. Given a generic location / { ... } entry for Nginx which serves domain1.com to make the subdirectory install work I did the following 2 steps. I am not aware of a solution that doesn't involve making a symlink.

Step 1:

In your Nginx configuration:

    location / {
            # First attempt to serve request as file, then
            # as directory, then fall back to displaying a 404.
            index index.php;
            try_files $uri $uri/ @rewrite;
            expires max;
            # Uncomment to enable naxsi on this location
            # include /etc/nginx/naxsi.rules
    }

    location /blabla {
     try_files $uri $uri/ /blabla/index.php?$args;
    }
    location ~ /blabla/.+\.(jpg|jpeg|gif|css|png|js|ico|xml)$ {
            webuser /usr/share/nginx/html;
    }

Step 2:

Then wherever your docroot is for your site you add an alias with your subfolder name to the main docroot, allowing the path to be valid for Drupal:

$ pwd
/usr/share/nginx/html

user@localhost:/usr/share/nginx/html$ find . -type l -ls
41059    0 lrwxrwxrwx   1 webuser    webuser           21 Sep 25 01:58 ./blabla -> /usr/share/nginx/html

You will still need your sites.php configuration as you have listed. You will need to restart Nginx.


Confusion as to the meaning of `cid` in webform.module

A quick look at the webform_component table in the database, the description for that field is: "The identifier for this component within this node, starts at 0 for each node."

In my test, however, the first component has a cid of 1.  AND - keep in mind that if you delete a component, the next cid is incremental - so you can't assume 1 - 6 or whatever.


Menu Breadcrumb might be what you're looking for.


What about adding wrappers to the fields?

In your hook_form_alter:

$form['field_name']['#prefix'] = '
';
$form['field_name']['#suffix'] = '

';

Check https://www.webomelette.com/drupal-form-api-prefix-suffix


How to add multiple havingCondition with OR operator?

Create OR conditions separately, in a variable, and then just use them:

$or = db_or()->condition('a', 0, '=')->condition('b', 0, '=')->condition('c', 0, '=');
$query->havingCondition($or);

For more details, read db_or documentation on Drupal API page. This should always be your first place to go, before you ask API-related questions.


How to handle if Drupal site goes down, show a static fallback page instead?

Because Drupal is completely unresponsive when this happens, it's not something you can fix within Drupal.

Setting a static fail page is possible within your web server - most likely Nginx or Apache. If you are using a CDN, you can also configure it to display only cached versions of your pages if your server is unresponsive.

You'll have to consult your server documentation to get your answer.


How can I add a separate template for the user login form?

You can add a theme name suggestion in a hook_theme_suggestions_HOOK_alter:

function mytheme_theme_suggestions_form_alter(&$suggestions, $variables) {
  if ($variables['element']['#form_id'] == 'user_login_form') {
    $suggestions[] = 'form__user_login_form';
  }
}

If you want to add suggestions for form elements you need some more code. See the file themable_forms.module from the module Themable forms. This is the only code file in this module and it is a good example how you can approach this in form alter, preprocess form element and theme suggestions hooks.


Go to admin/appearance and you will see a fieldgroup called "Administration theme" at the bottom.


How to attach a field to an entity programmatically?

Yes, it is possible, the function is field_create_instance().
If the field was not created before, you will need to create it with field_create_field() first.


Ofcourse you can get user id by email, check this out: http://api.drupal.org/api/drupal/modules!user!user.module/function/user_load_by_mail/7


Drupal 6 version of JQuery is 1.26 and after install jquery_update it will be updrade to 1.3.2

If you want persist use jquery method likes effect maybe this article,but I think you can't using jquery 1.6 or upper in Drupal 6 .( I don't told you it's impossible but achieve this job is more struggle and maybe cause problem in other part of your site ).

maybe this question be helpful for you.


According to this page $node->data was used about Drupal 5 and is left there for legacy purposes only. It appears it's only purpose is to prevent "call to undefined property" errors. Do not use it.


Yes, add the contextual filter "Comment Author uid". Then, under the section "When the filter value is NOT available", select,

"provide a default value".

You can then select:

"User ID from logged in user"

or

"User ID from URL".

To use the latter, you will have to display the view as a block on a page that has the user->uid in the system path, such as the user account page (user/%uid). If you use the former, the view can be displayed anywhere, and will always show the current user's comments.


My own suggestion is a cron job that runs

@drush fu [feature 1] [feature 2]
git commit -m "Auto exported features" features-dir/
git push

and while that could certainly work, I'm also fairly certain all kinds of problems will be discovered along the way, meaning this script will need to evolve substantially over time.

Leaving question open at least until someone with actual experience (maybe myself) leaves an answer.


How can I display/hide a div based on taxonomy term value on node.tpl.php file?

In Drupal 6 add somthing like this to your template.

foreach ($node->taxonomy as $term ) {
  if ($term->tid == YOUR_TID) {
     print "<div>...</div>";
  }
}


How to pass/link the node id of the result of a view (say, content type A) to another view of content type B, which are referenced in content type A?

You can do this with the help of the Views Field View module by embedding one View display into another.

In your case you want to have one View showing only the one latest Newspaper, and the other helper Views Display listing Headlines referring to the latest Newspaper that will be embedded into the first Display.

Here are the steps how to do it:

Create a Newspaper View
Add Sort criteria "Authored on" (Descending)
Use pager: Display a specified number of items | 1 item

You should now have only your latest Newspaper node listed as a result. You don't need any Relationships or Contextual filters here.
Add a new field Content: ID, Exclude it from display and Rearrange fields so this one is on top
Create a new Views Display of type Embed in the same Views
Keep the filters (Newspaper) but override the Pager to show all items
Add a new Field Content: Headline and under Multiple field settings make sure you're NOT using Display all values in the same row, it should not be ticked
Add a new Contextual filter Content: ID for this display only and configure it:
When the filter value is NOT available
Provide default value
Content ID from URL

Now if you enter the node ID of the latest Newspaper node into the View Preview argument field you should see a list of Headlines referencing that node.
Save the View (Important! The next step won't work without it)
Edit the original View Display (from step 1 above) and add a new Field Global: View (Embed a view as a field.)
Under View settings for this field select the View you're currently editing. You may need to Save the View again at this point.
Then under Display option under it choose Embed and fill in the Contextual filters fields with the node ID token from the Replacement patterns below it. It will probably be something like {{ raw_fields.nid }}

You should now have a list of the latest Newspaper node with Headlines referring it also listed.

Even though the View is set to display Newspaper nodes, through the Entity reference field and an ID contextual filter you only see Headlines listed.

Descendant sorting and pager limited to one is making sure it's related only to the latest Newspaper.

Using a different View display to show Headline nodes enabled us to list them one Headline per view row. If we did that in the original Display we'd had to list them all on the same row, because if we didn't we might not get all the Headlines listed because of Pager limit. And Headline count per Newspaper probably varies so we can't predict anyway.

In the end Views Field View enabled us to embed one view into another one and pass argument to it.

Now repeat all the steps for the Local content type (clone and edit).

Your original Views Display will probably be Feed, but it would have been too complicated to include it in this explanation.


Linking slideshow thumbnail to slideshow views content

You will earn time by coding a small hook_block() that calls your JavaScript plugin for your slideshows. Then, you will be able to configure easily your module and your link.
Views can be really harmful when you try to do things like slideshows.

Just pick a jQuery plugin from the ones listed on 13 Super Useful jQuery Content Slider Scripts and Tutorials and the rest of the job will be easy.


How to index Drupal Commerce 2 products for the search?

The core search will only ever search node's and users. If you want to search other entity types, like products, use Search API.

Just install the module, create a server (you can use the search api db submodule if you just want to use your sql database) and create your index. You will have the option of selecting which entity types get added to the index, you probably want nodes and products. Then add which ever fields that you want to be searchable.

See the official documentation for screenshots and more info on how to take it further (like adding facets).


Redirect to last page after saving new content with rules

I solved it by taking another route. The original page I wanted to be redirected to is a node type page; on that page, there is a link to create a new node type (announcement).

I didn't mention that the announcement node is referencing the page node through the Entity reference module. To be redirected to the old node type page, I need to use the token [node:field-new-habit-ref:url] in the action section of the rule.


How to specify image paths for Commerce feeds imports on xampp?

It's possible that something like a drupal file system paths (public://poster_pics/name.JPG). There actual path: http://example.com/sites/default/files/poster_pics/name.JPG i.e place image or file here manually.


Bypass Redirect Rule which acts on user login, while logging through one time login link

Got answer for it https://drupal.org/node/480584 #25.
In brief the key was text comparison in the current page url to match if user/reset exists.

{ "rules_am_redirect_user_logins" : {
"LABEL" : "AM redirect user logins",
"PLUGIN" : "reaction rule",
"REQUIRES" : [ "rules" ],
"ON" : [ "user_login" ],
"IF" : [
{ "NOT text_matches" : { "text" : [ "site:current-page:path" ], "match" : "user\/reset" } }
],
"DO" : [ { "redirect" : { "url" : "user-home" } } ]
}
}


One option is to use the field collection. and field collection views

This would automatically create the add edit and delete links to those who have permission to do so both in views as well as node view. It will popup a nice box to make the changes or add items.

I followed the following steps.

Added a content type called Meter Reading
Added a field collection called Reading with widget embedded made its value as unlimited.
Add a field to the field collection.
Added a content of the type Meter Reading without entering anything in the reading.

Now when you visit the newly created content you would get something like below image.

Here you will notice the add link this and when you click that you would get a popup something like in the below screenshot.

In the popup you can enter the readings.

This is what I get after entering couple of readings.

By the way you can add field collection with in field collection and it would work the same. So in your case instead creating a content type called Meter reading you can create a field collection called meter reading and then add a field collection with in that called readings and with in that add a field called Reading.

So your entire page would look like this


How to hide a field of a content type except when editing?

Implement hook_form_alter() and check whether $form['nid']['#value'] is empty, if empty then it is creation else it is update. If creation then hide the  field by setting #access property to FALSE.

UPDATE : Create a custom module and use the following code with needed modification.

Here is an example to hide tags field  in article content type.

function MYMODULE_form_alter(&$form, &$form_state, $form_id){
  if($form_id=='article_node_form' && empty($form['nid']['#value'])){
     $form['field_tags']['#access']=FALSE;
  }
}

Here is a tutorial on how to create a custom module.


Create a form for editing a single field of an entity

You can install the Field Permissions module.


Image link does not href to proper page in multilingual site

Your multilingual detection settings may be configured incorrectly.

On /admin/config/regional/language/configure, make sure URL is at the top of the list and enabled.


Adding core Javascript libraries in my_module.libraries.yml

I just scraped the MY_MODULE.libraries.yml and utilized one of the other methods of adding assets, by:

function MY_MODULE_page_attachments(array &$attachments) {
  $attachments['#attached']['library'][] = "core/jquery.ui.accordion";
  //new addition below
  $attachments['#attached']['library'][] = "MY_MODULE/MY_MODULE.accordion";
}

This works for me. Perhaps you don't need a MY_MODULE.libraries.yml if you are trying to add libraries that already exist in core.

Edit: So I still have a MY_MODULE.libraries.yml file however it now just adds my module's javascript (with a dependency to jQuery). It's just some Javascript that initializes jQuery UI accordions. I still use the code above to add jQuery
s UI accordion javascript and my own.


To make sure the changes apply and work, it is needed to disable the module and unistall it. This important step was missing on the guide.


How to programmatically print all comments from a given node?

If you are looking for a ready to use function, take a look at comment_render().

Example use (say the node you want comments for has nid = 5):

<?php
  $node = node_load(5);
 print comment_render($node);
?>

Or else you can manually query the database (comments table) to get all comments that have a matching nid.

<?php
  $nid = 5;
  db_query('SELECT * FROM {comments} WHERE nid = %d', $nid);
?>


How to replace all Add To Cart buttons with alternative text in Ubercart for anonymous users?

I think I've got the solution. Any feedback would be greatly appreciated.

<?php
function uc_disable_cart_button_for_anonymous_form_alter(&$form, &$form_state, $form_id) {
    /* Overrides the Add to Cart form text*/
    if ( !empty($form['nid']) ) {
      $node = $form['nid']['#value'];
    }
    else {
      $node = 0;
    }
    switch ($form_id) {
        case (($form_id == 'uc_product_add_to_cart_form_'.$node)):
        // hide add to cart button for anonymous users and show text
        if(!user_is_logged_in()) {
            unset($form['actions']['submit']);
            $form['html_markup'] = array('#markup' => t('
Please login or apply for a Member account in order to proceed.

Log In &nbsp; Apply for Member account
'));
        }
        if(user_is_logged_in()) {
            $form['actions']['submit']['#value'] = 'Add to Order';
            $form['actions']['submit']['#prefix'] = '
';
            $form['actions']['submit']['#suffix'] = '
';
        }
        break;
    }

    /* Overrides the Buy It Now form text*/
    if ( !empty($form['nid']) ) {
      $node = $form['nid']['#value'];
    }
    else {
      $node = 0;
    }
    switch ($form_id) {
        case (($form_id == 'uc_catalog_buy_it_now_form_'.$node)):
        // hide buy it now button for anonymous users and show text
        if(!user_is_logged_in()) {
            unset($form['actions']['submit']);
            $form['html_markup'] = array('#markup' => t('
Please login or apply for a Member account in order to proceed.

Log In &nbsp; Apply for Member account
'));
        }
        if(user_is_logged_in()) {
            $form['actions']['submit']['#value'] = 'Add to Order';
            $form['actions']['submit']['#prefix'] = '
';
            $form['actions']['submit']['#suffix'] = '
';
        }
        break;
    }
}

The main drawback that I see is that the quantity and attribute fields are still displayed, but that could be good or bad based on use-case. I'd prefer to hide them, so I may try to figure that out.


How to apply focus for specific tab in quicktab

You can alter the search form hook_for_alter using form id.

Add a hidden field name it 'mytab' whose by default value will be channel and on click of tab its value will be toggled between channel and profile.

So when we submit the form to search the content, it will look this way ?title=hello&mytab=channel

Now on in your hook_form_alter inline js code to select the default tab based on the mytab value that you can get using $_GET.

Let me know if it works for you.


This module appears to have helped many: Logo Tool

From the Logo Tool page:

  A simple tool to display either a random logo on every page refresh, else display a specific logo on specified pages and a default set logo on all unspecified ones.


User automatically redirected to main language page

You can check your admin's modules page, for some module related to translation or the locale module.

But some modules can cause this behavior, such as Translation redirect module, part of the Internationalization (i18n) package.


Views expose filter with ajax showing validation message after reloading page?

Disable the Ajax for exposed filter, It will show only the message on form submit.


There is something wrong with your HTML:

<div id="node_container" <form="" action="/dev_v2/kw/user" method="post" accept-charset="UTF-8">

This is definitely not interpreted as form.


Easist way to moderate an image via a php GET callback request?

You can specify a path with hook_menu and let the call back point to this path. The call back method of the menu entry handles the call from the service, does any processing needed and finaly does a drupal_goto to your node.

Have a look at the commerce adyen module. It provides two entries in hook_menu which handle call backs from the adyen payment gateway.


How to implement properly a view of nodes displaying other referenced nodes with no duplications?

You can fetch the 'Parent' nodes with their 'Children' nodes with the default functionality of views and without the use of Relationships, Aggregation or other modules.

The Steps Are:

Create a view of 'Parent' content type.
In the 'Fields' section add the field 'Content: Title' and the field 'Content: Children(Appears in: node:parent)'.
In the 'settings' of the 'Format' section  select as 'Grouping field Nr.1' the 'Content: Title' field.
In the field 'Content: Children' select the display format that you want.
Finally 'Exclude' from display the 'Title' field.

Enjoy


boost only for front page with cache enabled for other pages?

All the node pages either can be added to exception list with Boost or front page.

You can inspect the cache files that boost creates (these are actually plain html files) in the cache apache root folder.


Is there any way in drupal to get all primary links through views?

Can you create a hook_menu() and then in the callback do a https://api.drupal.org/api/drupal/includes!menu.inc/function/menu_tree_all_data/7 to get the menu tree and then expose that to services or return  json.


MySQL master/slave database replication?

No, Drupal doesn't.

Master/Slave replication is the job of the database management system, not Drupal's. All that Drupal does is use it, by using the slave server for specifically marked queries.

To be able to use replication, you either need a pre-configured hosting environment which already provides this or full access to the database server so that you can configure it. Replication happens on a server to server level, not database to database. In short, Pagodabox will most likely not allow you to set up replication.


How to add a view mode caching dependency in my custom block?

Found it out :)

Using entity_get_display to actually load the display view settings of the current node and then just merge the tags:

<?php

public function getCacheTags() {
  if ($node = $this->getNode()) {
    $cacheTags = Cache::mergeTags(parent::getCacheTags(), array('node:' . $node->id()));
    $display = $this->getEntityViewDisplay(); // function which uses entity_get_display
    $cacheTags = Cache::mergeTags($display->getCacheTags(), $cacheTags);
  }
  else {
    $cacheTags = parent::getCacheTags();
  }

  return $cacheTags;
}


Content disappeared for authenticated users

Go to admin/user/permissions and then tick the check-box for authenticated users under  access content and then click save.


After "?" redirect, the url is cut, why?

Even though I haven't ever used the Anonymous Redirect module, I wouldn't be surprised if your "issue" is caused by the fact that this module does not support what you're trying to do.

However, as a possible alternative (as per your "Any solutions for this one?"), you may want to use the Rules module to perform the redirect you want to do. For an example of how to do so, refer to my answer to "How to redirect an anonymous user to the login form after a 403 error?" (the "option 2" part of it. Not sure what exact "Rules event" would fit in your case, but it'll be probably something related to a specific "path" in your site.

Not sure if it would fit your needs here also, but maybe you want to add the "Rules URL argument" module also to this. Here is a quote about it (from its project page):

  ... provides two rules conditions based on URL arguments:

  check if a URL argument is present.
  compare the value of an URL argument.

  It also provides an action that makes the value of an URL argument available as new variable to Rules.

Refer to my answer to "How to use the Rules module to implement a custom redirect for an outdated URL?" for way more details about this module also.


Apply grouping to custom views list template

Turns out the $rows object has indices that don't go from 0, counting up by 1.  It keeps only indices of the items in the current group.  That makes this code work:

<?php foreach ($view->style_plugin->rendered_fields as $delta => $item): ?>
    <?php if(isset($rows[$delta])) : ?>
         ... print out whatever necessary ...
    <?php endif; ?>
<?php endforeach; ?>


Sort view items by field collection's field value

You can use field_collection_views module which it creates a default View of field collection type. Its address is /admin/structure/views/view/field_collection_view and I recommend you clone this View and configure the rest of the options. The Fields section contains a few items that are very helpful, like Host Entity ID, Host Entity Type and ... .


Target individual items of a multi-value field in my page template

There are many ways to achieve this. Given you use a custom or sub-theme you'd follow Twig Template naming conventions and create your own field--node--MYFIELDNAME.html.twig template. And then simply adjust the markup according your needs.

See Classy's field.html.twig for reference and its for-loop you simply can customize:

{% for item in items %}
  <div{{ attributes.addClass(classes, 'field__item') }}>
    {{ item.content }}
  </div>
{% endfor %}

To target the second item in a multi-value field inside page.html.twig use the following snippet (it starts to count with 0, so that 0 is the first and 1 is the second item).

{{ node.field_MYFIELD.1.value }}


I think you want to have your node show June 12, 2012

If that is the case, you can do this:

function THEME_preprocess_node(&$variables) {
  if ($variables['submitted']) {
    $variables['submitted'] = t('Posted: !datetime', array( '!datetime' => format_date($variables['node']->created, 'custom', 'F j, Y')));
  }
}

Here's PHP documentation for date formats: http://php.net/manual/function.date.php


Drupal.t() works in this case. Have to to compile the javascript and clear the Drupal cache in order for strings to appear.

For props way:

On get_sample_props():

function getsampleprops() {
  return ['sampleval' => t('Hello World!!!')];
}

On the controller,

$build = [
  '#theme' => 'sample_react',
  '#props' => json_encode($this->get_sample_props()),
];

On the template, I did:

On the React side, I used

$val = this.props.labels.sampleval;

Volia, its done. Its bit inconvenient, but work gets done.


Sanitizing on output to avoid Cross Site Scripting (XSS) attacks

  Use Twig templates The Twig theme engine now auto escapes everything by default. That means that every string printed from a
  Twig template (e.g. anything between {{ }}) gets automatically
  sanitized if no filters are used.

  See Filters - Modifying Variables In Twig Templates for the Twig
  filters available in Drupal.

  In order to take advantage of Twig’s automatic escaping (and avoid
  safe markup being escaped) ideally all HTML should be outputted from
  Twig templates.

  API functions Use t() and \Drupal::translation()->formatPlural()
  with @ or % placeholders to construct safe, translatable strings. See
  Code text translation API in Drupal 8 for more details.

  Use Html::escape() for plain text.
  Use Xss::filter() for text that should allow some HTML tags.
  Use Xss::filterAdmin() for text entered by a admin users that should allow most HTML.

  Strings sanitized by t(), Html::escape(), Xss::filter() or
  Xss::filterAdmin() are automatically marked safe, as are markup
  strings created from render arrays via Renderer.

  While it can also sanitize text, it's almost never correct to use
  check_markup in a theme or module except in the context of something
  like a text area with an associated text format.

Source: Drupal 8: Writing secure code by: Rade, Shyamala, Robert Castelo, and Pere Orga.


It's in Drupal.ajax.prototype.eventResponse, round about line 265:

// For radio/checkbox, allow the default event. On IE, this means letting
// it actually check the box.
if (typeof element.type != 'undefined' && (element.type == 'checkbox' || element.type == 'radio')) {
  return true;
}
else {
  return false;
}

It's hard-coded, but this is JS - you can just monkey-patch Drupal.ajax.prototype.eventResponse and get it to do whatever you like :)


How to modify Drupal configuration programmatically?

Most of these configuration settings tend to be controlled by a variable, so Drupal uses variable_get() and variable_set() to retrieve and modify these values.

To find out the variable name and value you can have a look at the source page.  For example:

<label for="edit-user-register">Who can register accounts? </label>
<div id="edit-user-register" class="form-radios">
  <input type="radio" id="edit-user-register-0" name="user_register" value="0" class="form-radio">
  <label class="option" for="edit-user-register-0">Administrators only </label>

  <input type="radio" id="edit-user-register-1" name="user_register" value="1" class="form-radio">
  <label class="option" for="edit-user-register-1">Visitors </label>

  <input type="radio" id="edit-user-register-2" name="user_register" value="2" checked="checked" class="form-radio">
  <label class="option" for="edit-user-register-2">Visitors, but administrator approval is required </label>
</div>

Here you can see that in order to change the "Who can register accounts?" option, you need to change the value of the user_register variable. You can set it to 1 for visitors, so putting this code in your module will do the trick:

variable_set('user_register', 1);

Of course, this is if you're too lazy to open the source code :) .  The other way is to find out which callback generates this form, and inspect user.module:

function user_menu() {
  //snip...
  $items['admin/config/people/accounts'] = array(
    'title' => 'Account settings',
    'description' => 'Configure default behavior of users, including registration requirements, e-mails, fields, and user pictures.',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('user_admin_settings'),
    'access arguments' => array('administer users'),
    'file' => 'user.admin.inc',
    'weight' => -10,
  );

Then find the callback function user_admin_settings() in user.admin.inc:

$form['registration_cancellation']['user_register'] = array(
  '#type' => 'radios',
  '#title' => t('Who can register accounts?'),
  '#default_value' => variable_get('user_register', USER_REGISTER_VISITORS_ADMINISTRATIVE_APPROVAL),
  '#options' => array(
    USER_REGISTER_ADMINISTRATORS_ONLY => t('Administrators only'),
    USER_REGISTER_VISITORS => t('Visitors'),
    USER_REGISTER_VISITORS_ADMINISTRATIVE_APPROVAL => t('Visitors, but administrator approval is required'),
  ),
);

So there you have your variable and in fact there's some constant to set up the values: USER_REGISTER_VISITORS.


Packing taxonomy fields into one div not from SQL?

This is the content of field.html.twig in the core theme classy:

{%
  set classes = [
    'field',
    'field--name-' ~ field_name|clean_class,
    'field--type-' ~ field_type|clean_class,
    'field--label-' ~ label_display,
  ]
%}

{%
  set title_classes = [
    'field__label',
    label_display == 'visually_hidden' ? 'visually-hidden',
  ]
%}

{% if label_hidden %}
  {% if multiple %}
    <div{{ attributes.addClass(classes, 'field__items') }}>
      {% for item in items %}
        <div{{ item.attributes.addClass('field__item') }}>{{ item.content }}</div>
      {% endfor %}
    </div>
  {% else %}

Each field is packed into a div with its own class field--name-field-name. In your case field--name-field-tags and field--name-field-categories.

Steps for solution:

If you don't use classy as base theme you can put somehting similar in your custom theme or simply copy this twig from the classy theme and change as needed.

core/themes/classy/templates/field/field.html.twig -> themes/mytheme/templates/
Flush all cache.


Cloning Node with Webform and Conditional Confirmation Message

The node clone module gives you the tools to make this happen. You can have a custom module make use of hook_node_clone_alter then use the Webform Conditional Confirmation module's functions to load & copy the original messages, store them temporarily, then save them upon saving the newly cloned node.

Something like this...

function MYMODULE_clone_node_alter(&$node, $context) {
  $messages = webform_conditional_confirmation_message_load($node->clone_from_original_nid);
  foreach($messages as $msg_id => $message) {
    //@TODO: Store in some temporary spot until cloned node is saved
  }
}

function MYMODULE_node_update($node) {
  //@TODO: Retrieve messages from temp location and place into $messages
  foreach($messages as $msg_id => $message) {
    $message->nid = $node->nid;
    webform_conditional_confirmation_message_save($message);
  }
}


Do I have to delete the _responsive.scss file that comes with Zen and code my own?

Whether you delete specific files or not is incidental, but what you do need to do is replace everything in Zen's default Sass that relates to grids with your Susy-based system.

Because of the nature of Susy there's a good chance you won't need to change any of the markup Zen builds, but of course your mileage may vary depending on exactly how customised your theme is.


How do I programmatically create a view?

The classic way is to create it manually, via UI, then click "export" (path like http://example.org/admin/structure/views/view/default_demo/export), and wrap resulting code into a module using hook_views_default_views(), maybe fine-tuning details.


Display a view with exposed form programmatically

So better to say in your question more details of how it doesn't work, but I'll take a guess...

Try

$view = views_get_view('storage');
  $view->set_display('block');
$view_markup = $view->preview('block');

I've done this before to render the View, that will give you some markup...

Then I've noticed that the "action" of the form could be incorrect, so you have to do a hook_form_alter implementation and set the #action to the current page path...I'm guessing what the value of $form['#id'] will be, you will need to verify that ...

    function yourmodule_form_alter(&$form, &$form_state) {
    if($form_id == 'views_exposed_form' && $form['#id'] == 'views-exposed-form-storage-block') {
        $path = current_path();
        $form['#action'] = '/' . $path;
    }

  }


Best settings for xml sitemap, cron time and submission time?

The indexing you are having is moderate / typical indeed. Only a small percentage of sites (from the 100% existing in the web right now) are being indexed every hour or so (some sites are indexed once smaller times like 20 minutes or even less - Wikipedia for example could be indexed in 10 minutes or less in some cases).

You should use various Drupal modules to raise the both PageRank and PQS (Page quality score) of your sites pages.

Use wisely the modules MetaTag, AdvAgg, xml sitemap, pathauto, search404, redirect and others to insure you achieve that targets.

More ways to handle that many 404's - Either your could redirect all the nodes to the homepage or groups of them to some nodes with suitable context).  Moreover, if you have the spare timenergy or resources you could make redirects to NID's 1x1 for all or most of your links. You could also delete some via WMT and than via robots.txt. It is recommended by some to make redirects not in Drupal but rather directly in the main .htaccess file for better performance.


Go to "Manage Fields" link for the Blog content type (/admin/structure/types/manage/blog/fields) and add a new field:
Name it whatever you want ("blog_picture" or something) and for the Field Type select "Image"
Click "save", pick a default image if you want and click "save field settings"
On the next screen do not tick "Required", make any other changes you want and click "save settings"
Done!


Drupal 7 with Display Suite and Apache SOLR search environments

The second branch of Display Suite has full support for Apache Solr pages, it basically takes it over by default. This hasn't been committed to the first branch as it involves to much changes.

The second branch doesn't have much changes - you might get some notices first, but re-saving the Display configuration solves those.

The biggest change is the default template files which are a little different because the 'Hide empty regions' option has been removed. The logic for collapsing regions is now in the template file itself. That's why we now ship with a 2 column and 2 column fluid template for instance.


Is there a way and/or reason to unload a node after node_load?

It's advised to use node_load() rather than building your own queries.

If you worry about memory impact, you can unload it by unsetting it:

unset($node);

It would destroy the specified variable/object, however you don't have to do it as PHP should handle garbage collection internally.

Secondly the node would be only loaded in your local scope, so once PHP exits  your function, it should be automatically flushed from the memory at some point.

If you're worry about memory impact, you may:

reduce number of modules which hook into the node objects,
run PHP profiler (such as XDebug) to check the memory is used the most,
enable Devel and its performance checking, it'll show you how much memory is used per individual page,
implement memory caching (instead of using database layer), such as redis or memcached

See: How do you improve Drupal performance?


It's not like, it's un-translatable. You have to render it on some page and then clear your cache and search in "{you-domain}/admin/config/regional/translate/translate" interface.


How to delete a variable during uninstall?

The problem is probably here (from the comments):

  The variable gets set during installation when the hook_schema calls a function to iterate through an array to create database columns.

The uninstall process calls drupal_uninstall_schema(), which in turn calls drupal_get_schema_unprocessed(), which invokes hook_schema().

So the variable is being added again during uninstall, presumably at a later point in the process than your hook_uninstall() is invoked and variable_del() has run.


Enable twig_debug and you will see HTML comments surrounding the output that tell you what template suggestions are available. In this case you will get output like:

<!-- THEME DEBUG -->
<!-- THEME HOOK: 'page' -->
<!-- FILE NAME SUGGESTIONS:
   * page--front.html.twig
   * page--node.html.twig
   x page.html.twig
-->
<!-- BEGIN OUTPUT from 'core/modules/system/templates/page.html.twig' -->

Naming your template page--front.html.twig will use that template for only the homepage.


How to set default value for entity reference field in hook_form_alter

You need to first check the structure of your form. Mine worked with the following:

$form['field_image']['widget'][0]['target_id']['#default_value'] = \Drupal\node\Entity\Node::load(2);

Cheers!


{500 service unavailable (with message)} error when trying to register a user with API

Just a stab in the dark here.

It seems that you have extra square brackets. I think this is why your error message refers to field 0 -- you're sending it an array. Try it exactly as the article displays, with no square brackets?

For example:
    "pass": {
        "value": "test"
      }

Good luck.

Update

To enable setting a password, you need to change a setting which is default in the install.

Go to admin/config/people/accounts (Configuration > People > Account Settings) and uncheck  "Require email verification when a visitor creates an account":

Granted you are allowing POST to Anonymous users as described in the article above, you should be good to go and get a response such as the following in PostMan:

{
  "uid": [
    {
      "value": "5"
    }
  ],
  "uuid": [
    {
      "value": "70738718-d4e9-455e-a1f6-cf95df613507"
    }
  ],
  "langcode": [
    {
      "value": "en"
    }
  ],
  "name": [
    {
      "value": "ac@bb.com"
    }
  ],
  "created": [
    {
      "value": 1487319576
    }
  ],
  "changed": [
    {
      "value": 1487319576
    }
  ],
  "default_langcode": [
    {
      "value": true
    }
  ],
  "user_picture": []
}

Hope this helps!!


I ended up using the S3AutoPush module. I migrated it to Drupal 7 and hacked the hell out of it to make it fit my needs.

If anyone reads this and is interested, I'd be happy to share my code. I won't put it on drupal.org for now since it's a real hack-job and not worthy yet.


Rules + Button Field: getting entity object to a custom action

It turns out this was caused by the parameter type I used. I set it to "entity", whereas it should be the machine name of the entity type. Changing it to "commerce_product" has fixed the problem.


How to show/hide "printer-friendly version" link according to workflow states?

One way of doing it is by using hook_node_view_alter(). For example, you would put the following code in a custom module called hideprint (see many tutorials online on how to create a custom module). Be sure to dpm() the array $build when you are testing the module to correctly check the value of field_review_workflow.

function hideprint_node_view_alter(&$build) {
  if ($build['field_review_workflow'][0]['#value'] == TYPE_VALUE_FOR_NOT_FINISHED){
    hide($build['links']['print_html']);
    hide($build['links']['print_pdf']);
  }
}


How to test Drupal distributions and see examples

Distributions and modules can easily be installed and tested at simplytest.me


How to access data from external MS SQL database tables in a Drupal site running on MySQL

As pointed in the question, Views is currently unable to do it. It relies on Drupal's DB Layer which is currently unable to query different DB engines and doesn't support MS-SQL. Views 3 (currently in alpha) provides pluggable query backend so it must be possible to write a backend on top of PDO ODBC or an other mean to reach the MS-SQL DB. Queryin the MS-SQL DB from PHP will probably be a performance issue. Views' caching will certainly be needed to avoid unnecessary repeated queries to the server.

In order to work around this and avoid diving into Views 3, you may use Views (2) to query the Drupal's database, or another one on the same engine. And simply import the needed data into this database. This is what I recently did on a project with a small amount of daily updated data. I used PDO ODBC (with unixODBC and FreeTDS) to periodically import data from a MS SQL Server database into MySQL tables. The tables were then exposed to Views using Views' API. The Data module could also have been used for this purpose.

Another option may be to import the data from MS-SQL as Drupal's nodes. If the data are imported as nodes using a custom content-type with the needed fields (using CCK), you get Views integration as well as the tons of existing modules to leverage Drupal's nodes.

One easy solution to import external data into Drupal is the Feeds module. While initialy build as a rewrite of the Feed API to import RSS and Atom feeds, Feeds is actually a powerful framework to import data into Drupal. It can easily be extended through plugins and hooks to support different data sources, formats and processors.


How to create a view of Media images that do not have any Alt Text

There is the Filter called Thumbnail (alt) from the Media Category that is for the Alt text.
After you add the Relationship for the Image field the Is empty (NULL) Operator will become available. If the Relationship is not present only the string operators will be listed.
Add the Relationship image from field_media_image and then add the Thumbnail (alt) Filter with the Is empty (NULL) Operator.
It will filter out Media items that have the Alt field available in their structure but not filled in (empty), for example images, as opposed to Files that don't come with Alt fields in their structure.

On the other hand, using the Is less than 1 Operator/value combination can help in situations when you need to filter out different Media types to show the items that don't have the Alt field in their structure at all like File types, while Images with empty alt don't satisfy that condition.


Show content with a date after the current one on a view

Just add a filter based on the date field and the criteria should be "greater than or equal to", then select "Enter a relative date" in the drop down field and enter the word "now"

Here is a screenshot from a site that has a Register By date field and I have a list of Upcoming Events that show based on this in a homepage block.


theme_table drupal 7 issue - operator not supported for strings in theme.inc

To fix this problem you need to mention class & id values in array.
PFB, the corrections:

$row[] = array('data' => drupal_render($form[$key]['alt_name']), 'class' => array('alt-ing-name-td'));

$output = theme_table(array('header' => $header, 'rows' => $rows,'attributes' => array('id' => array('recipe-id'))));

Hope this will help.


How to modify the query that the views integration with the chart API module provides?

To create charts in Drupal, there are plenty of modules available. Refer to the comparison of charting modules for an overview. After doing so, it should be clear that the names (and namespaces) of various charting modules are pretty confusing. Therefor I suggest you add a link to the exact 'Google Charts API' module this question is about.

Moreover, if I correctly understand the question, it seems to me that this is a rather straight forward requirement that can be easily addressed with (at least) the Charts module, i.e. the views integration of it (provides a new views style plugin to transform tabular view results into a chart). I recently created quite a lot of new Charts documentation that should help to get started with it.

The Charts module ships with out-of-the-box samples which are straight forward to adapt to fit your needs, e.g. by cloning these samples in a new views display or a new view. Of course there are other alternatives in that comparison that might be a better fit for this specific case.

Be aware: I'm a new (co-) maintainer of both Chart and Charts (confusing module names, I didn't invent them), and the author of the comparison of charting modules.


Lost all JS and CSS on updating the module?

That is why you should never do any modification to a module. The proper way to do this is to add the js and css to your custom theme using the same method you have done for views.
It is strongly discouraged to modify module or add anythings to the module otherwise on update all the changes will be lost.


Pre-Populating a Form Field with something other than its default value

Figured it out on my own. The solution was:

$form['restaurant_newsletter_subscription'] = array(
    '#type' => 'checkbox',
    '#title' => t('Subscribe to Restaurant Newsletter'),
    '#return_value' => "True",
    '#default_value' => $attributes[15]->Value,
    '#prefix' => '
',
    '#suffix' => '
',
    '#ajax' => array(
        'callback' => 'ajax_replace_default_callback',
        'wrapper' => 'restaurant_newsletter_subscription_div',
    ),
);

And for the callback:

function ajax_replace_default($form, $form_state) {
    $field_name = $form_state['triggering_element']['#name'];
    $form[$field_name]['#default_value'] = "False";
    return $form[$field_name];
}

And I also kept the hidden fields in the form:

$form['existing_restaurant_newsletter_subscription'] = array(
    '#type' => 'checkbox',
    '#title' => t('Restaurant Newsletter'),
    '#value' => $attributes[15]->Value,
    '#access' => FALSE,
);

This was simpler to store the existing preference variables for comparison in my logic later on than to try to retrieve the subscriber yet again inside of that form submit handler (It already retrieved the subscriber when it loaded the form, to populate the fields....trying to minimize the number of API calls I have to make).

Implemented like this, if a box is checked and becomes unchecked, that Ajax callback function alters the default value to false, rather than returning just the pre-populated value. If you check the box again it still changes the default to false, but it doesn't matter since if the box is checked that's irrelevant.

Not the most elegant fix, you get a little loading circle thing for a second when the Ajax runs, but it works.

Note: I left the Ajax callback function generic because even though I keep using the same field on this page, there are lots of similar fields doing the same thing. Using the triggering_element allows me to just recycle this code for all of them.


Error - External URLs do not have an internal route name

Hi

After a lot of research and try and error attempts I have found what was doing that.

My problem starts when I delete some view page that I have created, it seems the path of that page is still "alive".

If I create another page with them same path the site works fine

So to fix this problem:

- Delete the page view with some path, eg "contacts" (at this point I have that error)

- Create a new content and set the same URL name, in this case "contacts" (at this point the site is working 100%)

- Then delete the content created in the step above (site is still working 100%)

This seems the URL path its no deleted by drupal on the first step and thats why I have that error.


Force redirect in submit handler even though destination parameter set

The only correct way to do this is to alter the Request object and drop the destination.

In your submit callback:

\Drupal::request()->query->remove('destination');

Depending on the context, you might want to store it somewhere, for example pass it along to the URL you are redirecting to, so that it is respected again later.

See https://www.drupal.org/node/2325463 for a core issue that is doing exactly this to fix the preview button if a destination is given.


Trying to render an array of items with the drupal_add_html_head function

if ($families) {
    $element = array(
        '#tag' => 'html',
    );
    foreach ($families as $fontString) {
        $fontclass = preg_replace('/[^\d\w]+/', '-', strtolower($fontString));
        $element['#attributes'][class'][] = $fontclass;
    }
    drupal_add_html_head($element, 'google_fonts');
}


How to output specific php depending on value of content type radio

By using @Neograph734's advice I did use conditional fields.
Within the content type structure I added a field a link field(the button I wanted to conditionally show). Then used the conditional field to show this link when needed.


This can be done via hook_form_alter

function mymodule_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {

   if($form_id == 'user_register_form') {
      $form['field_name']['widget'][0]['value']['#attributes']['readonly'] = 'readonly';
   }

}

Add some css:

input:read-only {
  background-color: #ddd !important;
}

Result:


It's a really open question, but I'll try to help you a bit.

Basic example is : I have to create "vehicules", some "cars" and some "motos". Should I create one content type (CT) with one field "type" (with "cars" and "motos" as available values") or 2 CTs "cars" and "motos".

Here is the points I look into before choosing:

fields: if the fields are the same between content types, just create one CT, if they're really different, then create 2 CTs.
display: if the display is the same, then chose 1 CT, if not, create 2 CTs.
views: will I make list of both CTs, or will they always be separated?
cross content: is it possible that a node is part of both CTs? For example, is a "can-am spyder" a moto, a car or both of them? If you have cross content, then I would suggest to have only one CT, which a multiple select for the "Type" attribute. So people searching for cars or for motos will find the spyder anyway.
how "smart"/involved are you Back-Office users? Usually when you choose to keep only one content type, you end up having a lot of extra fields to configure the theming, the little differences between your different types, etc. So the edit form can be really long and confusing. If you're the one configuring everything, that's fine. But if you need to explain the form to a lot of editors/contributors, this can be painful.

After counting the pro and cons, you can make your decision.
Usually, I give 2 points for "fields" and "display", one point for "views", "cross content" and BO users... Make the sum and decide :)


How can I prevent a user from logging in from more than one computer or browser?

If you look into the modules issue queue, you would see that there is already a very active port underway. You could help to get it to a solid release by testing it out.

See Issue #1047132: Session Limit version for D7


extend('PagerDefault') doesn't call pager_default_initialize

As documented on the See the Extenders page on drupal.org:

  To use an extender, you must first have a query object. From the query object, the extend() method will return a new object that should be used in place of the query object. For example:

$query = $query->extend('PagerDefault');

  The above line takes a select query, creates a new PagerDefault query object that contains the original select query, and returns the new object. $query may now be used as if it were the original query object but with additional methods now available.

  Note that $query is not altered in place. The new object is returned from extend(), and if it is not saved to a variable it will be lost. For example, the following will not do what you expect:

So, you first line should looks like:

$query = db_select('redagavimas', 'r')->extend('PagerDefault')->fields("r");


It's a serialised PHP array.

You would, in my humble opinion, be nuts to try to parse this with SQL.

Use PHP to unserialize, make your changes, serialize it again, and write the result to the database.


Looking at the definition of fivestar_static theme-function in fivestar.module file under fivestar_theme(), you need to provide the theme function with an array including the following keys: rating, stars, tag. A working example should look like:

$fivestar_variables = array('rating' => $your_average, 'stars' => $your_maximum);
print theme('fivestar_static', $fivestar_variables);


What is the purpose of aggregation in view?

Without aggregation, Views fetches data from the database and lists that data in individual "rows".

When you turn on Aggregation some mathematical functions can be applied to the existing results under certain conditions. That is how you might get the SUM of all the values of a field, or the AVERAGE etc.

Charts usually don't display individual "rows" of data, they display statistical data that you get from calculating some values from the entire results list. That is why charts need Aggregation - to get to the numbers that are shown on the chart.


How to format 'node reference' field values from the Views module

Interesting. Initially it would appear that the "Pagetitle" is being stored in the Last Name field. However assuming that it's not, you can use the devel_themer module to find out what and where is theming that field's output. The culpript could very likely be inside one of your own custom Views templates or theme function override. If not, devel_themer should point you in the right direction.


My thoughts in a nutshell:

Start with the Zen base theme
Sub theme this with your custom theme (there are instruction in the Zen theme on how to do this)
Use a fixed width option, and resize the main column to 520px
Add CSS to spice it up and give it colours etc (out of the box it is fairly boring colour wise)

In order to hide breadcrumbs you can override the page.tpl.php to not display them.


Activate or DeActivate requirement status of field based on another field

What you could do is make the military field not required. Then add your own validate function to the form with:

$form['#validate'][] = 'my_function_name';

Then in your function you can do a check e.g.

function my_function_name*$form, &$form_state){
  if($form_state['values']['my_gender_field'] == 'male' && empty($form_state['values']['my_military_field'])){
     form_set_error('my_military_field', 'Military field is required');
  }
}

Or you could try using #states from the form API which has a 'required' option:
https://api.drupal.org/api/drupal/developer!topics!forms_api_reference.html/7.x#states


Exclude some, not all, user profiles from search engine results

There is and there is not, there are two sides of that question.

Bad side is - external search engines are just that: external. You can send them suggestion but you cannot make sure they respect them.

Good side is - you can create a field, and if it's checked output: <meta name="robots" content="noindex" /> Some search engines, including Google, Bing and apparently Yahoo! (can't find a link for that one), will respect that.


Preventing FlexiSlider (Adaptive) to resize beyond a certain minimum height

I hope my auto-reponses to the last 3 or 4 questions I posted, serve to the rest :)

Just wrap the block where your flexislider slide views is contained in a div and give it a min-width with !important and set the height to "auto".

Have not tested this in IE yet tho. Let's see.


Field Collection fields causes errors in array_flip functions in /includes/entity.inc

In case anyone has the same problem, try to update the module to the DEV version. In the above case the php error messages mentioned disappeared.


Create a webform which creates a user account

There is a module for that.

Forms Steps provides an UI to create forms workflows using forms modes. It creates quick and configurable multisteps forms.


Why does Drupal still convert links using a non-existant url alias pattern

Home » Administration » Configuration » Search and metadata » URL aliases (settings tab)

Update action
 Do nothing. Leave the old alias intact.
 Create a new alias. Leave the existing alias functioning.
 Create a new alias. Delete the old alias.


How can I pass page variable to a form builder function in a custom module?

One way is to put either the e-mail or an ID referencing the e-mail (the NID of the node where it is stored for example) as a hidden field, which will be received by your submit handler hook.

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


Advice on CSV import with taxonomy for data sanitaztion

Store the list of states as a taxonomy and add a text field to the taxonomy called aliases. This would be an text field with unlimited values.

Now when checking if a term exists you can use:

function taxonomy_load_term_check_aliases($name, $vid) {

    // load term by name (not using taxonomy_get_term_by_name() as I want to pass in vid, not machine name)
    $tid = db_query('SELECT tid FROM taxonomy_term_data WHERE vid = :vid AND `name` = :name', array(':name'=>$name, ':vid'=>$vid))->fetchField();

    // no match - see if an alias exists
    if(!$tid) {
        $bundle = db_query('SELECT machine_name FROM taxonomy_vocabulary WHERE vid=:vid', array(':vid'=>$vid))->fetchField();
        $tid = db_query('SELECT entity_id FROM field_data_field_aliases WHERE field_aliases_value = :name AND bundle=:bundle',
            array(':name' => $name, ':bundle'=>$bundle))->fetchField();
    }

    $term = taxonomy_term_load($tid);

    return $term;
}

If you can't find a match then add an additional alias. As you list of aliases builds up it will become more and more automated.


Is it possible to disable cache on certain fields?

You need to adjust the cache context of the node.

If the cookie is a drupal session, use the predefined cache context for this:

$build['#cache']['contexts'][] = 'session.exists';

If you target another cookie, that drupal is not aware of, you would need to create your own context, more info:

https://www.drupal.org/developing/api/8/cache/contexts


Drupal method to retrieve all existing roles and all users of a specified role

You can use the user_roles() function to get a list of the roles in the system. You can even pass in specific conditions, for example if you want to get only the roles that contain a certain permission.

As far as getting a list of users by role, there is no such function, unfortunately; you'll have to write a small helper function yourself. I usually use something like this:

function users_by_role($role_id) {
  $sql = 'SELECT uid FROM {users_roles} WHERE rid = %d';
  $q = db_query($sql, $role_id);
  $uids = array();
  while ($row = db_fetch_array($q)) {
    $uids[] = $row['uid'];
  }

  return $uids;
}

That'll give you the user ids for a given role, after that you can use user_load() to get the user object for each, or simply add a join to the above query and include the data you need directly.


How to show contextual links / quick edit links for blocks

Per 'No Sssweat's comment above, this was due to a small syntax error in a custom javascript file, viewable in console. Once corrected, the contextual links worked as intended.


How to create a menu with background images for list items?

I would suggest:

Use the module http://drupal.org/project/menu_attributes (beta 1 is out for Drupal 7)
Give each menu item a CSS ID or class that needs an image
Use CSS to assign background images to the menu items

Using this method, no PHP coding is required, and the menu images become content editable by your authors (once the CSS images have been setup).


Add two items with different shipping methods to basket / checkout in drupal commerce

Currently, shipping is set on an order-basis. If you want to have per line-item shipping that would be something you'd have to build custom. Line items are entities so you can add new fields to them (including shipping profiles) and then create a shipping module or ruleset that properly configures shipping.


Reuse file uploaded via (File|Image|Whatever)Field in another node

The FileField Sources module expands the file field widget and allows the user to select new or existing files through additional means, including  re-use files by an auto-complete textfield, attach server-side files uploaded via FTP, transfer files from a remote server (cURL required) and select existing files through the IMCE file browser.

The Media module (2.x) provides and additional file field widget which use its media browser to upload or select a (media) file.


How to expose an entity reference field as a filter on a custom entity in Views?

I think there are many solutions but I resolved the same problem in the hook
hook_form_alter()
altering the form element type from textfield to select and populate the #option attribute:

  $options = _getOptions();
  $form['your_field'] = [
    '#type' => 'select',
    '#options' => $options,
  ];

Other solutions are appreciated.


How to unset CSS class for menus in the template.php?

If you want to override a core stylesheet, add it to your theme .info file.

That way, the .active class need have no CSS rules

e.g: themename.info

stylesheets[all][] = system-menus.css

  To override a core or contributed module style sheet, it must be
  specified in your theme's .info file. Drupal overrides are cascading
  and your theme's stylesheets override any that were previously
  declared. For example, system-menus.css is located at
  "modules/system/system-menus.css". If you place a file with the same
  name in your theme's folder and add the following entry to the .info
  file, the original system-menus.css file will be ignored and your
  version will be loaded in its place.

More info here: http://drupal.org/node/263967

See also hook_css_alter for a code-based solution to remove stylesheets.


What's the functional difference between the "disabled" and "external" caching setting?

External caching is just a caching system that doesn't use the database tables used by Drupal to cache data, or doesn't use any table in the database used by Drupal. Example of external caching systems includes APC, eAccelerator, Memcache/Memcached, Varnish, XCache, or even a system that uses files instead of database tables.

All those systems surely cache data, or there would not be any difference between using them, and disabling the cache completely. The only difference with the standard Drupal cache system is where the data are cached.


Placing Content Outside of Region Container

Following your structure one way could be:

Wrap your views block structure as shown below:

 #Section ends

 #Row ends

 #Container ends

        #Full width, out of container
        [View_block] #View block out of container
        #Full width ends

 #Container opens

 #Row opens

 #section opens
        # Rest of the content is in container...

This will maintain the original structure and places your views blocks outside of the container and within the main content.
Even if this block is turned off, the page will not break.

Please modify as per your final output.


You can use the View reference module.

  Defines a field type View reference which creates a relationship to a Views display and allows the view to be displayed as the content of the field.


Get webform values in page which is action for this webform

You can use hook_form_alter and add your custom submit handler.

    /**
     * Implements hook_form().
     */
    function hook_form_alter(&$form, $form_state, $form_id) {
        if ($form_id == 'WEBFORM_ID') {
            $form['#submit'][] = 'custom_webfrom_submit';
        }
    }

    /**
     * Implements webform custom handler
     */
    function custom_webfrom_submit($form, &$form_state){
        //get the values here $form_state['values']
    }


Drupal 7 Commerce: How to change cart page title?

There are probably a dozen different places you could do this, personally I'd go for hook_page_alter() in a custom module:

function MYMODULE_page_alter(&$page) {
  // Make sure you're on the right page
  if ($_GET['q'] == 'cart') {
    drupal_set_title('New title');
  }
}

You would probably get away with doing the same thing in your theme's template.php file (maybe in hook_preprocess_page()) if you're not keen on writing a custom module just for this functionality.

The alternative to this is to install the String Overrides module. I've used this module in the past to override the title for exactly the same page (/cart) and it works great. It also means you can take your translation strings out of the settings.php file, which in my opinion isn't necessarily the best place to have them (even though it's absolutely a 'Drupal' way to solve the problem).


Render commerce item page with views - how to get proper add to cart form?

Create a View of your content.

Add field "Commerce Product: Add to Cart Form" to your View.


How can I access the paragraph fields from my node via Tokens?

The token browser stops spitting out chained suggestions after a sensible level of nesting - otherwise the memory use and (lack of) UI responsiveness could easily get out of hand. That doesn't mean that chaining stops, just the available hints.
You can keep right on going, e.g.
[node:field_agent_reference:entity:field_gratification_for_agents:entity:field_foo:value]


arg() dependent hidden field in AJAX form

As suggested by @AyeshK, I checked the $form_state in the hook_form before i set the value from arg()

 $form['slideid'] = array(
  '#type' => 'hidden',
  '#value' => (!empty($form_state['input']['slideid']) ? $form_state['input']['slideid'] : arg(2))
);

This could also be done in the hook_form_submit ...

function hook_form_submit($form, &$form_state){

    if($form_state['values']['slideid'] != $form_state['input']['slideid']){
        $form_state['values']['slideid'] = (int)$form_state['input']['slideid'];
    }
   //====save the form data...

}

It looks like a crude fix, but it works for me.

Thank you for your help @AyeshK & @kiamlaluno