how to add "access callback" function to a path defined by a view?

Reminder: Views module allows you to set the access from Views UI

If you want to create your own logic; this is how your code should look like:

function MYMODULE_menu_alter(&$items){
  $items['client/place/%']['access callback'] = 'MYMODULE_custom_callback';
}

function MYMODULE_custom_callback(){
  $isValid = false;

  /* your logic */

  return $isValid;
}

Make sure your module is called after the Views module. Usually Views module wight is 10; so your module wight should be 11 or more.

Also, don't forget to clear your cache.


Common meta tag description for a particular content type

Visit /admin/config/search/metatag
Click on "+ Add default meta tags" button
On the next page, select the content type or entity you want
Define your defaults there


You can implement hook_commerce_cart_product_add()
The product which user is adding to cart and the line item is available with in this hook. you can fetch the Time(Interval) field value from product and save it to line item.

function my_module_commerce_cart_product_add($order, $product, $quantity, $line_item) {
   $commerce_line_item = commerce_line_item_load($line_item->line_item_id);
   $product_time = $product->time_interval['und'][0]['value'];
   $line_item->default_time = $product_time;
   commerce_line_item_save($line_item);
}


You could use panels. Heres a good guide to setting up page manager with panels.

http://drupal.org/node/1582906

or you could use templates...

taxonomy-term--[vocabulary-machine-name|tid].tpl.php
base template: taxonomy-term.tpl.php

  Theme hook suggestions are made based on these factors, listed from
  the most specific template to the least. Drupal will use the most
  specific template it finds:

taxonomy-term--tid.tpl.php
taxonomy-term--vocabulary-machine-name.tpl.php
taxonomy-term.tpl.php

  Note that underscores in a vocabulary's machine name are replaced by
  hyphens.

See: http://drupal.org/node/1089656


Composer packages changed, even though same version used

composer update without any argument tries to update everything.

If you want to use the packages specified in composer.lock, run composer install instead.


I would suggest a small trick with contextual filters.

After adding a filter:

You could simply select and fill the 'Provide default value' field.
Here you have many options to mention the default value. The one which should work for you is: "Raw value from URL"

Alternative:

Set 'WHEN THE FILTER VALUE IS NOT AVAILABLE' to (Display contents of "No results found")
Select 'Allow multiple values' option at the bottom (by clicking on more)
Now you should pass two filter with the URL

Your default filter
Filter which user will add to url.

So your default url should always include the default parameter (filter).
Once this is done, when there is no value for the user's filter view should filter the results based on the default filter.


You might be looking for [site:url]. Alternatively, there is also [site:url-brief]


How to Remove '-None-' option from Select List Field?

Edit the filed and make one of the option as default value in the select list and Make it required field.


Why EVA display of views is added to the manage display of content type?

From the EVA project page:

  "Eva" is short for "Entity Views Attachment;" it provides a Views display plugin that allows the output of a View to be attached to the content of any Drupal entity.

(...)

  The placement of the view in the entity's content can be reordered on the "Field Display" administration page for that entity, like other fields added using the Field UI module.

Apparently it did just what it claims it does.


Backup table from custom module using backup and migrate

I've had a look at the Backup and Migrate code and I've come up with a solution, one that works for me at least.

I've created a function that gets the default profile data, then alters that to save only the tables I want. It seems to work well but if anyone can see any possible problems with this solution please do let me know.

The function:

<?php
/**
 * @param $tables
 *  An array of table names that will be backed up.
 * @param $filename
 *  Text prepended to the date when naming the backup file.
 */
function _MYMODULE_backup_custom_tables($tables, $filename = 'custom-backup') {
  module_load_include('module', 'backup_migrate');

  // get default profile settings
  backup_migrate_include('files', 'profiles');
  $settings = _backup_migrate_profile_saved_default_profile();

  // set the destination to our private folder
  $settings->destination_id = 'manual';
  $settings->source_id = 'db';

  // get a list of all tables from the database
  $schema = drupal_get_schema();
  ksort($schema);
  $drupal_tables = array();
  foreach ($schema as $table => $table_schema) {
    $drupal_tables[$table] = $table;
  }

  // remove from the database table list the tables we would like to save
  foreach ($tables as $table) {
    unset($drupal_tables[$table]);
  }

  // alter default filters so only the tables we want will be backed up
  $settings->filters['destinations']['db']['nodata_tables'] = array();
  $settings->filters['destinations']['db']['exclude_tables'] = $drupal_tables;

  // change the filename so we can identify the backup in the directory
  $settings->filename = $filename;

  // backup tables
  backup_migrate_perform_backup($settings);
}
?>

The function can then be used like this:

<?php
// the names of the tables we want to save
$tables = array(
  'custom_table_one',
  'custom_table_two',
);

// the text to use when naming the backup file
$filename = 'my-custom-backup';

_MYMODULE_backup_custom_tables($tables, $filename);
?>


How to print the timestamp of date in a Views fields?

There is a way:

Go to Configuration > Regional and language > Date and Time > Formats (Tab)
Then click "add format" to add a new date format and just type "U" in the textfield. The "U" is actually the timestamp.
Go back to "Types" tab and add the new date type you just created and give it some name like "Timestamp".
In your view select your date field and select your custom date type in "Choose how users view dates and times"

Hope this is what you were searching for.

Otherwise: If you just look for the MySQL like timestamp just select "Plain" as the formatter in your views field.


How to unfocus button after ajax form was rebuilt?

You can solve this by setting focus to another element on rebuild.

I don't know how to do it in Drupal 8, but here's Drupal 7 code to focus an element:

In the form_alter:

  // Focus the first element on rebuild.
  if ($form_state['rebuild']) {
    $first_element = array_keys($form['entry_fieldset']['entry_ids'])[0];
    $form_state['focus_id'] = $first_element;
  }

  // Allow a form element to be focused.
  if (isset($form_state['focus_id'])) {
    // Pass the element ID as a variable to the JS.
    $settings = array('focus_id' => $form_state['focus_id']);
    $form['#attached']['js'][] = array(
      'data' => array('example' => $settings),
      'type' => 'setting',
    );
  }

JS:

  /**
   * Focus a form element.
   */
  Drupal.behaviors.exampleFocusElement = {
    attach: function(context, settings) {
      if (settings.example && settings.example.focus_id) {
        // Focus the element having the ID passed in.
        $('#' + settings.example.focus_id, context).focus();
      }
    }
  };


How to pre-fill form fields with data from the node?

You could use Prepopulate module to prefill fields in subscriptions. But:

I would redesign the model in order not to save the same information you already have in courses again with the subscription. It's redundant to store title, date, place, etc. twice, with all the implications changes of the primary information in courses would have.

Said this content type "subscription" only should save a entity reference to courses. I propose to add a link to each course in Views which allows to subscribe to it. To do this, follow this steps:

Add field "ID" and check "Exclude from display".
Add "Global: Custom text" to your fields and put a label like Subscribe.
Under Rewrite results, check "Output this field as a custom link".
In field "Link path" enter node/add/subscription?edit[course]={{nid}} - where "course" is the name of entity reference field in content type subscription and "nid" is the replacement pattern for the course id.
Install and activate Prepopulute module

Clicking a subscription link in Views should now open subscription form and prefill the referenced course field. Making a custom module would allow you to create this content type without showing the form to the user.


Loop over first three items of a list in Rules

Install Conditional Rules so that you can add "conditions" between " rule actions". After that you can create a variable which iterates and use that to stop after the third elements.


Pulling components out of a Features module into a Drupal site

Use the Feature Tools module. The main goal of the module is to give the ability to remove elements from a feature and put them back to the DB.
It adds a "Safe Create Feature" button to the recreate feature form, that detects the element that has been removed from the feature and saves them in an unlink file.
In order to save the elements to the DB you need to go to the admin/build/features/unlink page, check the element you need to import and submit.


How do you configure a Drupal linux dev system for sending email?

Here is another attempt to answer the now questionable question...

Drupal core uses the php mail() function by default. See /modules/system/system.mail.inc

Context

Do you have a Linux based Drupal dev system? Does a fresh install of Drupal (6,7 or 8) appear to work? If an anonymous user attempts to create a new account, does it appear that an email is sent but NEVER received? Yes to all of the above?

A brief history. It was in the Fall of 2010 that I downloaded and installed this thing called Drupal (version 6). After creating a new account the system sent an email with a keyed link to set the new member password. I was impressed.

I was using a Windows XP laptop at the time.  Mail systems are not my speciality but I had managed to get websites to send emails. The sum total of my expertise at the time was this -- I was using some kind of SMTP thingy.

In the Spring of 2013 I switched to Ubuntu 12 for Drupal development. I recently discovered that the linux configuration did not send a new user email. The Win system (Windows 7) works like it always has since the XP days - it just works.

Most of us use email systems managed by our ISP, employer, or internet offerings such as Hotmail or Goggle's gmail.

I have since discovered I configured an smtp relay. A Drupal call to mail() will relay the message (with authentication if necessary) to my preferred mail server.

Windows install

On a windows (WAMP) system, there is a "window only" section in the php.ini file that allows the setting of a mail server.

Linux install

A search for 'mail' using the Synaptic package manager revealed that the default lsb-invalid-mta package was installed (Linux Standard Base sendmail dummy).

Linux has many mail systems available, sendmail, ssmtp, postfix, qmail  exim or nullmailer, to name a few.  They can get complicated. Most everybody with any experience prefers something other than sendmail.

Postfix

The postfix package seems to be the most popular. The trick here is to configure postfix as an SMTP relay. This means a call to mail() will relay the request to the mail server of your choice.

Here is a suggestion on how to configure your Drupal development system using postfix as an SMTP relay:

Step 1 - Prepare system

Uninstall and remove each mail package that you have tried but have failed to get working:

sudo apt-get remove --purge [mail package that did not work]

Rinse and repeat as necessary. I have read somewhere that this is a good idea. If all goes well, sendmail for dummies (lsb-invalid-mta) will be left.

Step 2 - Install postfix (again if necessary)

sudo apt-get update
sudo apt-get install postfix

Step 3 - Configure postfix

Cut and paste the following code into your editor. Replace every occurrence of mailserver:port with something that works. Modify username and password accordingly.

Note the 'myorigin' setting does not include a port number.

You may then cut and paste these commands onto the command line. It is recommended that it be done in steps, one line at a time, just to see how things go.

# Open up a sudo session so you don't have to preface every
# command with 'sudo' - remember to exit when done!
sudo -s

The following commands work as s when logged in as 'root':

# postconf is a program that can modify the postfix config file /etc/postfix/main.cf
postconf -e 'relayhost = mailserver:587'
postconf -e 'myorigin = mailserver'

postconf -e 'smtp_sasl_auth_enable = yes'
postconf -e 'smtp_sasl_password_maps = hash:/etc/postfix/sasl_passwd'
postconf -e 'smtp_sasl_security_options ='

# Authentication -- Substitute mailserver, username and password here:
echo "mailserver:587   username:password" > /etc/postfix/sasl_passwd

# Protect this password file
chown root:root /etc/postfix/sasl_passwd
chmod 600 /etc/postfix/sasl_passwd

# update the sasl_password.db file using the new password file
postmap /etc/postfix/sasl_passwd

# Restart
service postfix restart

# and exit the sudo session
exit

Step 4 - Test

If everything goes well, a variation of this command:

mail name@whatever.com

should work. You should be prompted for a Subject. After entering the subject line, follow with the body of the text (i.e. "Hello world!"). There is no prompt for "Body". I am not sure why.

Use Ctrl-D to complete the command.

Now check the email address for the message.

Acknowledgements

Maybe I should acknowledge Google because I used it to find these links, but the search was exhausting. Here are some of the pages I bookmarked. Some of them are quite old.

http://developernote.com/2012/07/how-i-configured-sendmail-for-php-on-ubuntu-server-12-04/#comment-27377

http://www.howtoforge.com/postfix_relaying_through_another_mailserver

http://www.howtoforge.com/how-to-relay-email-on-a-postfix-server

http://lenss.nl/2009/01/making-php-mail-work-on-ubuntu-through-postfix/


How to add a profile cover with a user field image in a view?

You need to install the Image URL Formatter module

Then in your view, click on your image field and select url as the formatter, so it prints the url rather than the image.

Views doesn't allow to use the style attribute in re-write results.

Therefore, you will need to use a template file. views-view-fields--[view-name]--[machine-name].tpl.php). This file needs to be in /sites/all/themes/THEMENAME/templates folder.

put this inside it:

<div class="profile-background"  style="background-image: url('<?php print $fields["field_image"]->content; ?>');">

<?php print $fields["field_other"]->content; ?>

...

Clear/Flush all caches to see changes.


The Node Export tab points to a link, so I was able to get this working by setting 'Actions' to 'Page redirect', and pointing it to the page that the Node Export tab points to, a page within the node called 'node_export', e.g. '../node/1602/node_export', where '1602' is the node id (nid). So I entered 'node/[node:nid]/node_export' as the Value of the URL to which it is to be redirected. I also left 'Force redirect' checked. Now when I click the Save button it performs the node export to XML after updating.


The website encountered an unexpected error. Please try again later

The issue was created by rules.

I had read somewhere on two or three occasions that the Rules module could generate such error but I thought disabling the module would be enough to show if rules were involved or not. It didn't. Apparently, the rules are still active when the module is disabled (a diehard, at least in my case!)

I also had to disable the rules one by one until I found the culprit. It was a rule automatically making the new authenticated user a member of a welcome group. Somehow, the data in the rule had shifted and it was no longer the account but the site:logged-in-user that was made a member of the group.

The lesson here is about Rules and that the rules need to be disabled. Disabling the module alone is not enough. I hope this helps someone.


Have a look at the Views Accordion module, and its related Community documentation.

By "grouping fields", the group header can be used as accordion header. And Views allows for one field to include the content of multiple fields, so you can utilize this views feature for this purpose (Combined fields).

Does this help somehow?


I have used profiling 7.x-1.0-alpha1, as it was alpha release there were some issues. I hope those have been fixed in the beta release, so maybe you can use it. I would recommend not to use the beta version either; it can break anything.

However, if you are willing to learn how to use this module, just use it; it is not too risky.


You can set a class to the title field using Style Settings as shown below screen. You can user token replacements in style settings to set class to the title field.

Using small javascript or jquery read the class of title field and set the color same as class name using CSS property.


How to make a hierarchical categories of a view's nodes?

If you want to display your taxonomy as tree, and insert nodes having given term, into that tree, you'd need Views Tree. This adds a display plugin for Views. You just need to create a node listing view which accepts a term argument.

If you mean to format the term attached to a node, as a hierarchical tree, try Term Reference Tree.


Figured out a workaround.

With having the views_php module https://www.drupal.org/project/views_php , I went into the view I was working on and clicked "add" in the fields section.

I chose Global: PHP and the field that would be pulling my database (descr in this case).

For the field that would be pulling from my database (descr), I chose to "Exclude from Display" and in the Global:PHP field, I choose the available variable (which was $row->descr).

There are probably better ways to do this but after spending close to a week, this works for me.


Custom 500 Error page: Is there a way to theme a fatal error?

Symfony's HttpKernel uses the event dispatcher to allow subscribers to handle exceptions and send custom responses. Only if no subscriber does so will it throw the exception further up and let it reach the global error handler. (At which point it's indeed too late to do anything else.)

Drupal already comes with such a subscriber (or rather several of them, which check particular conditions) for HTTP exceptions (These are implementors of \Symfony\Component\HttpKernel\Exception\HttpExceptionInterface, such as NotFoundHttpException.)

If you absolutely need to intercept non-HTTP exceptions wherever they happen, and return custom responses, you can create your own subscriber (see  Drupal\Core\EventSubscriber\HttpExceptionSubscriberBase), and give it a very low priority (< -128) to avoid interfering with the core HTTP exception subscribers.

However, architecture-wise I would suggest this is not a good way to go. If you have a controller that triggers a particular exception, then it should catch it and throw the appropriate HTTP exception instead. This also requires much, much less code than messing around with event subscribers. ;)

If need be, you can even throw a ServiceUnavailableHttpException (503) or set a custom status like new HttpException(500) if there is no class for it.

Drupal core's exception subscribers don't actually handle 5xx errors, but you can create your own that does, which would probably look something like the following:

class Custom5xxHtmlSubscriber extends HttpExceptionSubscriberBase {
  public function on5xx(GetResponseForExceptionEvent $event) {
     // Do stuff
     (new Response())->send();
  }

With a corresponding service definition like the following:

  custom5xxsubscriber:
    class: ...
    tags:
      - { name: event_subscriber }


How can i configure the core search module to also show results for incomplete words?

Actually there's a quick way to set this up with the Search API and the Search API Database Search modules. No need for Solr.

Enable both the modules and go to the Search API configuration page
(admin/config/search/search_api)Add a server and give it a recognizable name (such as "MySQL"), make sure it's enabled.

Choose the following service class: Database service (normally the only option. If you don't see it, make sure that the "Search API Database Search" module is enabled).

Selecting this service class will provide you the option Search on parts of a word (make sure you enable it). Now hit "Create server".

Next, go back to the Search API configuration page, and add an index. Again give it a recognizable name, such as "Contentindex", and make sure it's enabled.
Select the server you recently created (in this example "MySQL").
Datasource options: check the content types you want to index (the description of this field may be a bit confusing, but make no mistake: you should check the content types you want to index, not the ones you want to leave out).

You could check "Index items immediately", but that depends on the size of your content. This option is alright for smaller websites. In the other case: let cron take care of it. Hit "Create index".

Next, you want to enable the fields (in the fields tab) to that very index, e.g.: content type, title, status and author - and hit "Save changes" (we'll take care of the related fields later).

Then you want to configure the filters (in the filter tab). Here you can enable the bundle filter, if you want to finetune the content types once again (probably won't need to).
Down below you'll find the highlight filter, to highlight the search word in the results.
Now return to the fields tab and unfold the "Add related fields" tab. Add all the fields of which you want to get the content indexed, and hit Save.

Finally go to the "view" tab of the index, and index now all the items.
The last step is to create search results page and search block in Views, which only takes a few minutes.

Make sure the submodule Search Views is enabled and create a view page which will show "Contentindex" (select the name you gave to your index configuration instead of "content" which is selected by default.

Add all the fields (make sure your format is "fields") that every search result should consist of (title [link to content], body, …).

You'll notice that these fields look like this Indexed Node: Title
Add an exposed filter: Search: Fulltext search; and select the following in its settings: Contains any of these words, and use as: Search keys.

You're done!


Rules: how to create variable with PHP and $_SERVER['HTTP_REFERRER']

Turns out I just had to look harder and change my expectations a little.

Click Add a Variable
Select text (for my scenario)
In the Value field, you can then use php to echo out a value for a single variable

I was hoping to be able to create a variable with a type of 'object' (or similar) so that I could use the url values like [url:param1] or [url:param2].

I have not found a way to do that - I just created a different variable for each of the two parameters I needed off the query string.


Try https://www.drupal.org/project/geo_block. It will allow you to add your video to a block and choose which countries should or should not see it.

Keep in mind however that this, like most other region blocking/detecting tools can be tricked.


What is the syntax for l.d.o translations in a drush make file

The post beta9 dev version of drush_make also supports downloading drupal core translations with, for example:

projects[] = nl

Source: http://drupal.org/node/644916. (There's also a documentation patch there.)


How to change the date format in the date field as a select list?

If you want to alter the way this component is shown globally, you can implement hook_preprocess_datetime_form(), eg. like this:

function mymodule_preprocess_datetime_form(&$variables) {
  // Ensure there's a month field and it's a select.
  if (isset($variables["content"]["month"]) && $variables["content"]["month"]['#type'] === 'select') {
    foreach ($variables["content"]["month"]['#options'] as $monthNum => $label) {
      if ($monthNum) {
        // Convert month number to unabbreviated name.
        $dateObj = DateTime::createFromFormat('!m', $monthNum);
        $monthName = $dateObj->format('F');
        $variables["content"]["month"]['#options'][$monthNum] = $monthName;
  }
}

}

The code for the day select will be similar.


Yes, use the --no-backup option with your command.

drush --no-backup up myproject

If you're you're looking to make this a default option, you can do something like Bash aliasing and just run that alias instead:

alias drush-no-bup='drush --no-backup'

Then run:

drush-no-bup up myproject


I could not access a page as administrator user

From hook_menu():

  "access callback": Defaults to user_access() unless a value is inherited from the parent menu item; only MENU_DEFAULT_LOCAL_TASK items can inherit access callbacks. To use the user_access() default callback, you must specify the permission to check as 'access arguments'

Emphasis mine.

So if you don't provide an access callback explicitly, user_access() is used, which, unless you're logged in as user 1 which is a special case, returns FALSE if you don't provide it with any access arguments. That's why passing in access arguments fixed it.

You can't change this default behaviour without changing core Drupal files. Being explicit about your access is better than being implicit anyway - default should always be to deny.


Send private message - Subject and message filled in

One way to do this is to use the Prepopulate module.  This solution is not specific to Privatemsg.

As the module page notes:

  For example, the following URL,

  http://www.example.com/node/add/blog?edit[title]=this is the title
  will automatically fill the Title field on a new blog post with the
  words "this is the title". Any field can be prepopulated this way,
  including taxonomy and CCK fields. You can prepopulate more than one
  field at a time as well.


How do I display username in a custom block?

You can do this in sevaral ways, one of this could be use a preprocess function. In your custom module in the .module file or your custom theme in the .theme file (recommended) write this:

/**
 * Implements hook_preprocess_HOOK().
 */
function [my_module_or_theme]_preprocess_block(&$variables) {
  $variables['username'] = \Drupal::currentUser()->getUsername();
}

and then in your template suggestions of block.twig.html print the variable {{ username }}


Strange error in status reports en unable to safe my taxonomy term url-alias

You can safely ignore this.

See https://www.drupal.org/node/2661178 and the core issue linked there for details.

Nothing is broken, the entity definition change tracking just gets a bit confused.


show image field twice with different image style

If you're displaying your field programmatically you've to use:
For Large :

<?php echo theme('image_style', array(
    'style_name' => 'large',
    'path' => $node->field_image['und'][0]['uri'],
    'alt' => t('Image'),
    'title' => t('Title'))); ?>

For Medium :

<?php echo theme('image_style', array(
    'style_name' => 'medium',
    'path' => $node->field_image['und'][0]['uri'],
    'alt' => t('Image'),
    'title' => t('Title'))); ?>

Your can also call any format you added on back office his name


I simply needed to install and configure a proxy server and point my iPhone to it.  I installed squid on the ubuntu box via apt and then on the iPhone under the wireless settings pointed it to the proxy.


How to add tags to View-created RSS feed?

You can include them in the fields for the view display. If they are taxonomy terms, you can add them from the views fields list.


If your node contains Date field than you can set start and end date (you can turn on/off end date field in field settings). Both are available in Views so instead of building your Views filter on start date, build it on end date.


Cannot Change Max Upload Size in File Field From 8mb

There are three variables in php.ini that could be limiting your upload size.

Look for the following in php.ini:

memory_limit = 32M
upload_max_filesize = 10M
post_max_size = 20M

I imagine one of these is set to 8M in your case.

Also, you will most likely have to restart apache after making the change to php.ini.


Hide Group audience/content visibility in node

In the OG content type, you will see a field for group audience. You can simply hide it in the Manage Field tab. Or, you could use CSS. In both cases, you are not hacking the core code.


How to create view of taxonomy terms and then once clicked on taxonomy term another view will be opened displaying all content having that term?

I get it working. It was not that hard :)

First I create the view of taxonomy term. In that view I add contextual filter "Taxonomy term : term ID".

And in the next view I add contextual filter "Content: content_type_name"

Thats it. Got the desired result.


How To Display Image instead of Taxonomy name using Views to display my nodes?

Create a view of the appropriate nodes
Set the view output type to be "table"
Create a "relationship" in the view between node and taxonomy term
Now you can add the image field from the term to your views output
If you use multiple vocabularies, add a filter to select just the vocabulary you are interested in.

If you don't already have the imagecache module installed, I recommend it as it will let you control the size of the displayed image.


altering them for node edit page not working

Its working on my site, although i haven't made a template but it should work with a template too. here is my code

function modulename_theme(){
     $items['article_node_form'] = array(
    'arguments' => array('form' => NULL),
    'render element' => 'form',
  );
    return $items;
}
function theme_article_node_form(&$var){
    $form=$var['form'];
    $output = '<h2>' . t('Please enter your information below') . '</h2>';
    $output .= drupal_render_children($form);
    return $output;

}


Render the first image of an image field which allow to enter multiple images

It's all about the structure of the image field. You're automatically going to the 0 index, but I bet if you were to do a dump of that variable, you'd find you were at the wrong position in the array. You'll need to loop through it or target the very specific element you're looking to render.
Check out this documentation comment for details and modify for your example. That comment shows the following code to loop through the images.
$node = node_load($nid);
$image = field_get_items('node', $node, 'field_NAME');
foreach ($image as $key => $value) {
  $output = field_view_value('node', $node, 'field_NAME', $image[$key], array(
    'type' => 'image',
    'settings' => array(
      'image_style' => 'thumbnail', //place your image style here
      'image_link' => 'content',
    ),
  ));
  print render($output);
}

That code is showing how to loop through the images in a different context, but the foreach() loop is the same that should be used in your code.
For that reason, it could be worth taking this up to template.php inside  hook_preprocess_node() to avoid adding logic in a template file.
function mytheme_preprocess_node(&$variables) {
  if($variables['node']->type == 'blog' {
    // My crazy logic to assign my image variable.
    $variables['blog_image'] = render($somevalue);
  }
}

The template file then just needs a single code line.
print $blog_image;


The t function's first argument is a string, and the second is a keyed array of arguments (search => replace).

The string your passing in is:

token_replace(variable_get('listing_edit_free_activated_page', 'Your free content has been activated. Thanks!'))

And the replacement your searching for it @link.

As the string @link does not appear in the string your passing in no replacements are made.

Here is an example where a replacement will be made:

$text = t("@name's blog", array('@name' => format_username($account)));


Is there a rule condition to check if the url is the front page?

I dont think there is such a rule, but you can do this: add a rule for User is going to view page and in condition add PHP snippet and check for drupal_is_front_page() based on this add actions as desired.


Get value from twig tweak without additional markup

A field formatter stores the field object inside of the render array for reference later, so that you can still access the raw values:

{% set field = drupal_field('field_example', 'block_content', 1) %}
{% set value = field['#items'].0.value %}
{{ value }}

This is the same for all field formatters.

Your approach might also work, if you |render the field first and then apply |striptags:

{{ tab1visibility|render|striptags }}

But not in a consistent way, because it depends on the specific field type and the configured field formatter.


Add pagination to the results in custom module after split the row to many sub rows

I find the solution here

$limit = 10;
$rows = pager_array_splice($rows, $limit);
$form['tablesort_table'] = array(
    '#theme' => 'table',
    '#header' => $header,
    '#rows' => $rows,
    '#empty' => t('Sorry, there is no results to show'),
);

function pager_array_splice($data, $limit = 10, $element = 0) {
    global $pager_page_array, $pager_total, $pager_total_items;
    $page = isset($_GET['page']) ? $_GET['page'] : '';
    // Convert comma-separated $page to an array, used by other functions.
    $pager_page_array = explode(',', $page);
    // We calculate the total of pages as ceil(items / limit).
    $pager_total_items[$element] = count($data);
    $pager_total[$element] = ceil($pager_total_items[$element] / $limit);
    $pager_page_array[$element] = max(0, min((int)$pager_page_array[$element], ((int)$pager_total[$element]) - 1));
    return array_slice($data, $pager_page_array[$element] * $limit, $limit, TRUE);
}


What's the best way to maintain templates for standard pages and a front page?

To avoid duplication, creating separate PHP files might work, but the best answer is to you do everything in your MYTHEME_preprocess_page(&$variables) function, in your template.php file.

MYTHEME_preprocess_page(&$variables) {
  if($variables['is_front']) {
    //set variables to X
  }
  else {
    //set variable to Y (or just leave them)
  }
}

Now you probably won't even need page-front.tpl.php

Also, if you are using page.tpl.php and/or page-front.tpl.php you do have the variable $is_front available


What you're looking for is often called "siblings".

When sharing the same Taxonomy terms there are Contextual filters Has taxonomy term that can be used and this can work in a lot of cases.

But there are cases even with shared Taxonomy that needs to go a different route (possibly when using Aggregation or Multilingual sites). That second "sibling" route is also what you need to use when the connection is done through an Entity Reference field that isn't Taxonomy, like it is in your case.

The solution is done with the help of two Relationships and one Contextual filter.

Create the Content type Views showing Admin nodes. You first add the Relationship for your ER Location field, this introduces info about the referenced node into the Views. In your case this is the info about Location node referenced from Admin nodes.
Then you add the reverse Relationship to the first one, it will use the first Relationship by default, this is where the matching happens. The second Relationship introduces info about the content that is using that ER field. In your case this is all the Activity nodes that point to the same Location.
Add the Contextual filter for Node ID and make it use the second Relationship. Set it the usual way, default value and ID from URL, validate against Activity Content type.
If this is a Block Display set it to display in a theme region on Activity nodes and adjust its Contextual filter settings. Now when you visit an Activity node you will see listed all the Admin nodes that share the same Location ER.

Repeat the procedure for the second ER field Sport type. You will have 4 Relationships and 2 Contextual filters in the end. Don't build everything at once, test step by step and build it all for only one ER field first.

When building for the second ER field you can use the keyword all in Views Preview to "shortcircuit" the first Contextual filter so you can test the second one directly, without interference from the first one (you enter values into Preview separated with / for each Contextual filter you have, for example all/34 to bypass the first Contextual, all/all to bypass both Contextuals, or 34/34 to test for the Activity node with the NID 34).

This answer has a bit more details for a similar example:  Entity Reference widget selctor in view referring same reference


How to show views calendar by node field_date

Just configured your Contextual filters like below snapshot.


You need to run token_replace on the email body and pass in the user object for the target user. In your function:
$global $user;

$emluser = user_load($user->uid);
$body = "Hello [user:name], blablablala -- Team [site:name]";
$body = token_replace($body, array('user' => $emluser));

You don't need to pass anything for the site tokens to be replaced.


How to debug what module/process is requesting a file?

It is possible that the previous server was suppressing errors entirely and this error would have shown up had error reporting been turned on. In general, you can debug such errors by using the dsm() function from devel module. If you need to know where a functional call is coming from, you can use debug_backtrace().


Set entity reference target_id in migration yml

Old question, but I'm guessing you need to add the array for the item list. I was successful with:

field_something/0/target_id: YOUR_VALUE_HERE

I haven't found documentation on the slash in the field id, but it is an array notation. The above is equivalent to something like:

$destination_values['field_something'][0]['target_id'] = YOUR_VALUE_HERE


How to hide node/add and */edit page titles

Try with hook_preprocess_page_title

function myModule_preprocess_page_title(&$variables) {
  //- Get the Current route name
  $route_name = \Drupal::routeMatch()->getRouteName();
  switch ($route_name) {
    //- Add node Page
    case 'node.add' :
      $variables['title'] = t('New add page title');
      break;
    //- Edit node Page
    case 'entity.node.edit_form' :
      $variables['title'] = t('test');
      break;
  }
}


Field contains list and values of it are shown in one symbol

You need to have the allowed values settings in the following format:

allowed_values:
  -
    value: '1'
    label: A
  -
    value: '2'
    label: 'Bb'
  -
    value: '3'
    label: Ccccc

The quotes don't matter for single word strings. I hope this helps.


Can a subgroup of a public group be private and hidden?

I recently experienced this same "Undefined index: field_mode in OgBehaviorHandler..." error when trying to set the og_group_ref field widget to select list. It appears that it doesn't work if it's not set to "OG Reference". In the "Additional behaviors" field, you can set it to select there, but the widget needs to be left as the default value. Try that and see if it's of any help.


Can't log in to Drupal instance after duplicating database

First check whether $cookie_domain is set to localhost or not?

If it is set as the URL of the live site then it might not work. I faced this issue previously.

Other cause might be clean urls. You can check whether clean URL is enabled in your localhost or not.

You can check whether mod_rewrite is on or not here. If clean url is causing problem then you can disable from your database. If you want to disable clean url goto your database find variables table, find clean_url variable and set it to 0.


Total count of two different content types in one View?

The table in the screen capture is similar to this one:

The Views Calc module can be used to transform that table so that the calculations in the last rows (with Count, Sum and Max) get added to it.

By replacing the columns like '# Fish' and 'Weight' with 'Total Demonstrations' and 'Total deliverable ...' (as in the question), and by asking for only the 'sum' to be added, it should answer the question.

To ask for the 'sum', just select it from the selection list, similar to what is shown in this screenshot:

For more details (step-by-step instructions), refer to the community documentation about the Views Calc module.

Disclosure: I'm a co-maintainer of this module,
I hope this does not violate the site's policy on self-promotion.


OAuth token parameter missing when configuring Google Analytics Reports

The Linux server running my.example.com which was giving problem had time lag of 45 minutes. The moment I corrected it .. it worked.


Added a new field to user profile, how do I set a value for existing users?

Use Views Bulk Operations Module to update field values

  This module augments Views by allowing bulk operations to be executed
  on the displayed rows. It does so by showing a checkbox in front of
  each node, and adding a select box containing operations that can be
  applied.

Create a view of type users
Add Bulk operations: User field and choose Modify entity values checkbox to select your boolean field


What is the best way to start from scratch?

This question is difficult to answer. Check your Drupal versions first, 7.xx, etc, i.e., if you use 7.18 at your home, the same version should be used at your work.

If the versions are same and you still encounter the problem, I would do personally this by copying everything from my home instance to my work instance.

Copy the whole drupal site folder to my work PC.
Dump the database via phpMyAdmin (including DROP TABLE IF EXIST statements) and import it to my work PC. As a side note, I normally export cache tables with structure only in a separate dump file for the sake of smaller dump file.

That should be fine. This is the usual way I do for site cloning.


D7 images not loading from css or from direct urls

Have you tried

<img src="/sites/default/files/StMaryDedication_1_20121202.jpg">

and

.section-contact div#header {
  background-image: url('../images/contact_banner.png');
}

where images is a folder in your theme dir e.g: images/contact_banner.png relative to css file in e.g: css/style.css.


How can I create a view that lists users who have NOT completed an order?

To save to anyone else the trouble, this is the view I created to achieve the above.

$view = new view;
$view->name = 'Spambots';
$view->description = '';
$view->tag = '';
$view->base_table = 'users';
$view->core = 6;
$view->api_version = '2';
$view->disabled = FALSE; /* Edit this to true to make a default view disabled initially */
$handler = $view->new_display('default', 'Defaults', 'default');
$handler->override_option('relationships', array(
  'uid' => array(
    'label' => 'Order user',
    'required' => 0,
    'id' => 'uid',
    'table' => 'uc_orders',
    'field' => 'uid',
    'relationship' => 'none',
  ),
));
$handler->override_option('fields', array(
  'mail' => array(
    'label' => 'E-mail',
    'alter' => array(
      'alter_text' => 0,
      'text' => '',
      'make_link' => 0,
      'path' => '',
      'absolute' => 0,
      'link_class' => '',
      'alt' => '',
      'rel' => '',
      'prefix' => '',
      'suffix' => '',
      'target' => '',
      'help' => '',
      'trim' => 0,
      'max_length' => '',
      'word_boundary' => 1,
      'ellipsis' => 1,
      'html' => 0,
      'strip_tags' => 0,
    ),
    'empty' => '',
    'hide_empty' => 0,
    'empty_zero' => 0,
    'hide_alter_empty' => 1,
    'link_to_user' => 'mailto',
    'exclude' => 0,
    'id' => 'mail',
    'table' => 'users',
    'field' => 'mail',
    'relationship' => 'none',
  ),
  'created' => array(
    'label' => 'Created date',
    'alter' => array(
      'alter_text' => 0,
      'text' => '',
      'make_link' => 0,
      'path' => '',
      'absolute' => 0,
      'link_class' => '',
      'alt' => '',
      'rel' => '',
      'prefix' => '',
      'suffix' => '',
      'target' => '',
      'help' => '',
      'trim' => 0,
      'max_length' => '',
      'word_boundary' => 1,
      'ellipsis' => 1,
      'html' => 0,
      'strip_tags' => 0,
    ),
    'empty' => '',
    'hide_empty' => 0,
    'empty_zero' => 0,
    'hide_alter_empty' => 1,
    'date_format' => 'small',
    'custom_date_format' => '',
    'exclude' => 0,
    'id' => 'created',
    'table' => 'users',
    'field' => 'created',
    'relationship' => 'none',
  ),
  'login' => array(
    'label' => 'Last login',
    'alter' => array(
      'alter_text' => 0,
      'text' => '',
      'make_link' => 0,
      'path' => '',
      'absolute' => 0,
      'link_class' => '',
      'alt' => '',
      'rel' => '',
      'prefix' => '',
      'suffix' => '',
      'target' => '',
      'help' => '',
      'trim' => 0,
      'max_length' => '',
      'word_boundary' => 1,
      'ellipsis' => 1,
      'html' => 0,
      'strip_tags' => 0,
    ),
    'empty' => '',
    'hide_empty' => 0,
    'empty_zero' => 0,
    'hide_alter_empty' => 1,
    'date_format' => 'small',
    'custom_date_format' => '',
    'exclude' => 0,
    'id' => 'login',
    'table' => 'users',
    'field' => 'login',
    'relationship' => 'none',
  ),
  'edit_node' => array(
    'label' => 'Edit link',
    'alter' => array(
      'alter_text' => 0,
      'text' => '',
      'make_link' => 0,
      'path' => '',
      'absolute' => 0,
      'link_class' => '',
      'alt' => '',
      'rel' => '',
      'prefix' => '',
      'suffix' => '',
      'target' => '',
      'help' => '',
      'trim' => 0,
      'max_length' => '',
      'word_boundary' => 1,
      'ellipsis' => 1,
      'html' => 0,
      'strip_tags' => 0,
    ),
    'empty' => '',
    'hide_empty' => 0,
    'empty_zero' => 0,
    'hide_alter_empty' => 1,
    'text' => '',
    'exclude' => 0,
    'id' => 'edit_node',
    'table' => 'users',
    'field' => 'edit_node',
    'relationship' => 'none',
  ),
  'delete_node' => array(
    'label' => 'Delete link',
    'alter' => array(
      'alter_text' => 0,
      'text' => '',
      'make_link' => 0,
      'path' => '',
      'absolute' => 0,
      'link_class' => '',
      'alt' => '',
      'rel' => '',
      'prefix' => '',
      'suffix' => '',
      'target' => '',
      'help' => '',
      'trim' => 0,
      'max_length' => '',
      'word_boundary' => 1,
      'ellipsis' => 1,
      'html' => 0,
      'strip_tags' => 0,
    ),
    'empty' => '',
    'hide_empty' => 0,
    'empty_zero' => 0,
    'hide_alter_empty' => 1,
    'text' => '',
    'exclude' => 0,
    'id' => 'delete_node',
    'table' => 'users',
    'field' => 'delete_node',
    'relationship' => 'none',
  ),
));
$handler->override_option('sorts', array(
  'uid' => array(
    'order' => 'DESC',
    'id' => 'uid',
    'table' => 'users',
    'field' => 'uid',
    'relationship' => 'none',
  ),
));
$handler->override_option('filters', array(
  'order_id' => array(
    'operator' => 'empty',
    'value' => array(
      'value' => '',
      'min' => '',
      'max' => '',
    ),
    'group' => '0',
    'exposed' => FALSE,
    'expose' => array(
      'operator' => FALSE,
      'label' => '',
    ),
    'id' => 'order_id',
    'table' => 'uc_orders',
    'field' => 'order_id',
    'relationship' => 'none',
  ),
  'rid' => array(
    'operator' => 'not',
    'value' => array(
      3 => '3',
      6 => '6',
      4 => '4',
      5 => '5',
    ),
    'group' => '0',
    'exposed' => FALSE,
    'expose' => array(
      'operator' => FALSE,
      'label' => '',
    ),
    'id' => 'rid',
    'table' => 'users_roles',
    'field' => 'rid',
    'relationship' => 'none',
    'reduce_duplicates' => 0,
  ),
));
$handler->override_option('access', array(
  'type' => 'role',
  'role' => array(
    3 => 3,
    5 => 5,
  ),
));
$handler->override_option('cache', array(
  'type' => 'none',
));
$handler->override_option('header', 'The following accounts have no orders associated with them and are not assigned a specific role. Therefore it is safe to assume they are spambots.');
$handler->override_option('header_format', '1');
$handler->override_option('header_empty', 1);
$handler->override_option('use_ajax', TRUE);
$handler->override_option('items_per_page', 20);
$handler->override_option('use_pager', '1');
$handler->override_option('style_plugin', 'table');
$handler->override_option('style_options', array(
  'grouping' => '',
  'override' => 1,
  'sticky' => 0,
  'order' => 'asc',
  'summary' => '',
  'columns' => array(
    'mail' => 'mail',
    'login' => 'login',
    'uid' => 'uid',
    'delete_node' => 'delete_node',
  ),
  'info' => array(
    'mail' => array(
      'sortable' => 0,
      'separator' => '',
    ),
    'login' => array(
      'sortable' => 0,
      'separator' => '',
    ),
    'uid' => array(
      'sortable' => 0,
      'separator' => '',
    ),
    'delete_node' => array(
      'separator' => '',
    ),
  ),
  'default' => '-1',
));
$handler = $view->new_display('page', 'Page', 'page_1');
$handler->override_option('path', 'spambots');
$handler->override_option('menu', array(
  'type' => 'none',
  'title' => '',
  'description' => '',
  'weight' => 0,
  'name' => 'navigation',
));
$handler->override_option('tab_options', array(
  'type' => 'none',
  'title' => '',
  'description' => '',
  'weight' => 0,
  'name' => 'navigation',
));

It will need tweaking to your needs because I've got it set up to filter based on user role too but should give you a good base to start with.

Also the SQL is:

SELECT users.uid AS uid, users.mail AS users_mail FROM users users  LEFT JOIN uc_orders uc_orders ON users.uid = uc_orders.uid LEFT JOIN users users_uc_orders ON uc_orders.uid = users_uc_orders.uid LEFT JOIN users_roles users_roles ON users.uid = users_roles.uid AND (users_roles.rid = 3 OR users_roles.rid = 6 OR users_roles.rid = 4 OR users_roles.rid = 5) WHERE (uc_orders.order_id IS NULL) AND (users_roles.rid IS NULL) ORDER BY uid DESC


How to check which node should be posted on which domain?

Consider using the Domain Access module. Here's an excerpt from its project page:

The Domain Access project is a suite of modules that provide tools for running a group of affiliated sites from one Drupal installation and a single shared database.
The module uses Drupal's Node Access system to determine what content is available on each site in the network. Unlike other multi-domain modules for Drupal, the Domain Access module determines user access based on the active domain that the user is viewing, rather than which group or site the user belongs to.


jQuery Once has changed with jQuery 2.x, see the Drupal changelog for info.

I ran into the same issue and that fixed it for me:

Essentially now you are going to want to do:

...once('mybehavior').each(function()...


combining messages and content types in views

Workaround:

Use Drupal hooks on create/edit/delete of node, then create a custom message type that just takes text field (no entity reference).

Then in your hooks create the new message type and add for its field value the message text constructed from the node fields. Embed links to node if node is still available.

$message = message_create('general_alert');
$wrapper = entity_metadata_wrapper('message', $message); // populate with node data

// Set necessary fields to use with tokens.
$wrapper->field_message_text->set(array('value' => $text));
$message->save();

Or even better, include both an entity reference field for your message and a text field. Add the entity reference when creating/updating the node, and populate the text field when deleting the node.


Form storage is cleared after ajax submission

You say this is about building the form. If you display a form on a page, then this form is rendered, but the form object is not stored yet. This happens later when the form is submitted, then you can use $form_state.

Generally when you build a form this is the same like rendering of non form content. Put the initial values in HTML (in the form elements). Similar to default values for visible fields use hidden fields for other values. You also have to add the correct cache metadata to the form so that the render cache varies by the data and is invalidated when the data is modified.

If you don't want to transport data in a rendered form then use a session or tempstore. This kind of storage is not restricted to form requests, so strictly not connected to this issue, but for logged in users these are easily available and for anonymous you can start a session, which you need to do anyway if you want to personalize a form.


Get a 404 page already when calling with trailing slash

Most likely you have a written rule htaссess 301 redirect. Possibly it is written in the code or via modules.


How to delete all data when uninstalling a module without going in manually in PHPmy Admin?

Modules should clean up after themselves. If they aren't, you should report it in the module's issue queue.

But, at least with D7, there isn't really much that should be left in the database. Most modules that create tables delete them when they are finished. The biggest area where things are left behind is in the variables table - many modules don't clean these out. You can safely delete them after module uninstall though.


Import users into Drupal with data from a CSV file

I think that I can make an import directly with a MySQL script but is
  it possible with Drupal (I know I can insert datas directly into
  database but U don't know if Drupal system will allow that method)?

Instead of MySQL this would be a Drupal method to insert users by using the Entity API:

$user = User::create([
  'name' => 'foobar',
  'mail' => 'foobar@example.com',
  'status' => TRUE,
]);
$user->save();

So if you don't want to use Migrate there are other ways for such a simple import task. You can use a php library of your choice to fetch the data and then add the user entities one by one. I answered a similar question for importing nodes at a time when Migrate was still in alpha: Is there a way to migrate only nodes?


The first variant that "passes" will be the one that is shown.

So if the first (top) variant does not have any conditions limiting when it is displayed, it will always be the one that is shown.


CKEditor placeholder text doesn't work (config.js)

I'm assuming you are using wysiwyg with ckeditor.

The problem is that wysiwyg pass the configuration to the editor, in our case ckeditor, based on the options selected on the wysiwyg profile in use.

The solution i found sure it's not the best buts works for me. It's about modifying the wysiwyg file thats sets the configuration for ckeditor.

Open site/all/modules/wysiwyg/editors/ckeditor.inc and find the function wysiwyg_ckeditor_settings, then, before the code implode the $extra_plugins array add your extra plugins.

before:

if (!empty($extra_plugins)) {
  $settings['extraPlugins'] = implode(',', $extra_plugins);
}

add:

$extra_plugins[] = 'confighelper';

result:

$extra_plugins[] = 'confighelper';
if (!empty($extra_plugins)) {
  $settings['extraPlugins'] = implode(',', $extra_plugins);
}

Hope it helps.


Access Denied when I try to flush cache or change theme

I have no idea why, but I disabled clean-urls and reenabled it and now I can flush cache and switch themes without access denied.

I had installed the Boost module which also involved putting some stuff in the .htaccess and turning on clean urls (although I was using it anyway).

This problem took me about 4 hours to solve and was completely unintuitive.


How can I embed view results right in the content region as if it's part of the content?

Try adding Entity Views Attachment (EVA) in your view, then use it as a block-field in DS.


Drupal commerce: how to force user to pay with specific payment method?

You've already realized that you need a rules condition, since the available payment methods are determined through rules.

The selected shipping method is stored on the order entity ($order->shipping_rates), so you can just check that.
You might need to write a custom Rules condition (which is just a PHP function declared by an implementation of hook_rules_condition_info()).


How to view and inspect a Commerce Billy invoice pdf template as HTML, before it's passed to the PDF generator?

If you check the page callback of PDF URL (i.e. "invoice-pdf/%commerce_order"), the HTML output of Invoice PDF is generated using commerce_billy_pdf_html($order) function. Same function is used by Print Invoice URL (i.e. "invoice-pdf/%commerce_order/print") to generate Printable output of Invoice. Since print page render HTML output you can inspect the output easily.

So for example, if your order number is 1 and your Invoice PDF URL is "invoice-pdf/1", then you can see the HTML Structure of PDF Output by going to "invoice-pdf/1/print" page.

Hope this helps.


How large is the original image? It could be your production server php memory limit is being reached. Have you checked the error logs on the server?

Drupal needs to put the original image into memory to create the styled version so if this image is quite large it can cause memory to run out. Especially if you're on a cheap hosting


D7 form field #ajax callback not called on autocomplete field

I think the problem is that $form['field_video_reference'] is a container and you want to attach the ajax event to the actual text field element.

If you inspect the $form array you should see the correct place to put it. In needs to be at the same level as the #type => 'textfield' (or entity reference) property.

I think the path will be something like:

$form['field_video_reference'][LANGUAGE_NONE][0]['value']['#ajax'] = array(
    'callback' => 'mymodule_video_ajax_callback',
    'wrapper' => 'my-path-div',
);


How can I programmatically reset a user's password

You can use the _user_mail_notify() function, along with a user object, to invoke the password reset email:

// Load a user (admin in this case).
$account = user_load(1);

// Invoke the email. It will be queued along with other system mail to be sent during cron
_user_mail_notify('password_reset', $account);

A one time login URL with a 24 hour expiry is included by default with that particular email.


Unpublish blog content after a certain time

https://drupal.org/project/scheduler

  This module allows nodes to be published and unpublished on specified
  dates.

  Dates can be entered either as plain text or with calendar popups. To
  use calendar popups you need to install the Date Popup module, which
  is part of the Date module.


Nothing changes because you are setting a hook argument, but the value to which you set that argument isn't kept.
hook_views_query_alter() is invoked from Sql::alter(), which is called from ViewsExecutable::build().
// ViewsExecutable::build()
// Let modules modify the query just prior to finalizing it.
$this->query->alter($this);

// Sql::alter()
\Drupal::moduleHandler()->invokeAll('views_query_alter', [$view, $this]);

The only way to alter the query is using the methods made available from QueryPluginBase (including its parent classes), not replacing an object passed to the hook with another object. See for example workspaces_views_query_alter(), an implementation of that hook done from a Drupal core module. The relevant code altering the query is the following one (ViewsQueryAlter::alterQuery() and ViewsQueryAlter::alterQueryForEntityType()). (I copied only the comments that could help in understanding the changes done to the query.)
public function alterQuery(ViewExecutable $view, QueryPluginBase $query) {
  if (!$this->workspaceManager->hasActiveWorkspace()) {
    return;
  }

  if (!$query instanceof Sql) {
    return;
  }

  $entity_type_ids = [];
  foreach ($query->relationships as $info) {
    $table_data = $this->viewsData->get($info['base']);
    if (empty($table_data['table']['entity type'])) {
      continue;
    }
    $entity_type_id = $table_data['table']['entity type'];

    $entity_type_ids[$entity_type_id] = $entity_type_id;
  }
  $entity_type_definitions = $this->entityTypeManager->getDefinitions();
  foreach ($entity_type_ids as $entity_type_id) {
    if ($this->workspaceManager->isEntityTypeSupported($entity_type_definitions[$entity_type_id])) {
      $this->alterQueryForEntityType($query, $entity_type_definitions[$entity_type_id]);
    }
  }
}

protected function alterQueryForEntityType(Sql $query, EntityTypeInterface $entity_type) {
  $table_mapping = $this->entityTypeManager->getStorage($entity_type->id())->getTableMapping();
  $field_storage_definitions = $this->entityFieldManager->getFieldStorageDefinitions($entity_type->id());
  $dedicated_field_storage_definitions = array_filter($field_storage_definitions, function ($definition) use ($table_mapping) {
    return $table_mapping->requiresDedicatedTableStorage($definition);
  });
  $dedicated_field_data_tables = array_map(function ($definition) use ($table_mapping) {
    return $table_mapping->getDedicatedDataTableName($definition);
  }, $dedicated_field_storage_definitions);
  $move_workspace_tables = [];
  $table_queue =& $query->getTableQueue();
  foreach ($table_queue as $alias => &$table_info) {
    if ($table_info['table'] == 'workspace_association') {
      break;
    }

    if ($field_name = array_search($table_info['table'], $dedicated_field_data_tables, TRUE)) {
      $relationship = $table_info['relationship'];

      if ($table_info['join']->field != 'entity_id') {
        continue;
      }

      $new_table_name = $table_mapping->getDedicatedRevisionTableName($field_storage_definitions[$field_name]);

      $workspace_association_table = $this->ensureWorkspaceAssociationTable($entity_type->id(), $query, $relationship);

      // Update the join to use our COALESCE.
      $revision_field = $entity_type->getKey('revision');
      $table_info['join']->leftFormula = "COALESCE({$workspace_association_table}.target_entity_revision_id, {$relationship}.{$revision_field})";

      // Update the join and the table info to our new table name, and to join
      // on the revision key.
      $table_info['table'] = $new_table_name;
      $table_info['join']->table = $new_table_name;
      $table_info['join']->field = 'revision_id';

      // Finally, if we added the workspace_association table we have to move
      // it in the table queue so that it comes before this field.
      if (empty($move_workspace_tables[$workspace_association_table])) {
        $move_workspace_tables[$workspace_association_table] = $alias;
      }
    }
  }

  // JOINs must be in order. i.e, any tables you mention in the ON clause of a
  // JOIN must appear prior to that JOIN. Since we're modifying a JOIN in
  // place, and adding a new table, we must ensure that the new table appears
  // prior to this one. So we recorded at what index we saw that table, and
  // then use array_splice() to move the workspace_association table join to
  // the correct position.
  foreach ($move_workspace_tables as $workspace_association_table => $alias) {
    $this->moveEntityTable($query, $workspace_association_table, $alias);
  }
  $base_entity_table = $entity_type->isTranslatable() ? $entity_type->getDataTable() : $entity_type->getBaseTable();
  $base_fields = array_diff($table_mapping->getFieldNames($entity_type->getBaseTable()), [
    $entity_type->getKey('langcode'),
  ]);
  $revisionable_fields = array_diff($table_mapping->getFieldNames($entity_type->getRevisionDataTable()), $base_fields);

  // Go through and look to see if we have to modify fields and filters.
  foreach ($query->fields as &$field_info) {
    // Some fields don't actually have tables, meaning they're formulae and
    // whatnot. At this time we are going to ignore those.
    if (empty($field_info['table'])) {
      continue;
    }

    // Dereference the alias into the actual table.
    $table = $table_queue[$field_info['table']]['table'];
    if ($table == $base_entity_table && in_array($field_info['field'], $revisionable_fields)) {
      $relationship = $table_queue[$field_info['table']]['alias'];
      $alias = $this->ensureRevisionTable($entity_type, $query, $relationship);
      if ($alias) {
        // Change the base table to use the revision table instead.
        $field_info['table'] = $alias;
      }
    }
  }
  $relationships = [];

  // Build a list of all relationships that might be for our table.
  foreach ($query->relationships as $relationship => $info) {
    if ($info['base'] == $base_entity_table) {
      $relationships[] = $relationship;
    }
  }

  // Now we have to go through our where clauses and modify any of our fields.
  foreach ($query->where as &$clauses) {
    foreach ($clauses['conditions'] as &$where_info) {
      // Build a matrix of our possible relationships against fields we need
      // to switch.
      foreach ($relationships as $relationship) {
        foreach ($revisionable_fields as $field) {
          if (is_string($where_info['field']) && $where_info['field'] == "{$relationship}.{$field}") {
            $alias = $this->ensureRevisionTable($entity_type, $query, $relationship);
            if ($alias) {
              // Change the base table to use the revision table instead.
              $where_info['field'] = "{$alias}.{$field}";
            }
          }
        }
      }
    }
  }
}

The code is also wrong because it replaces an instance of a class that extends QueryPluginBase with an instance of a class that implements StatementInterface. Those objects aren't interchangeable, as their methods and properties are different.


Problem with migration from Apache to IIS

You need to translate the Apache server's rewrite rules into their IIS equivalents, in the root web.config.

For reference, see what is reported in the Windows Download Instructions.

  IIS7: Create/modify web.config file. Drupal distributions come with .htaccess files for *nix use; IIS7 users should convert this file to a web.config file for their site. If you have used the IIS Manager to create a new site, a basic web.config file will exist in your site's root directory.


Why does using '#type' => 'text_format' change the position of the field's description?

text_format is not a single form element that is rendered like textarea, textfield checkbox etc. Instead, it is several form elements (you get two form elements, one to select the filter, and a textarea to enter the actual text).

What you need to do is use the #after_build property to define a function that will enable you to alter the element after it has been built (the two form elements has been created). You can define custom theme function here and move data around in order to output the description and other data exactly how you want to.

Look at the FAPI documentation for more info.

Update

The #after_build on text_formats works a bit differently than expected, as it gets called twice. What you could is:

$form['text_format'] = array(
  '#type' => 'text_format',
  '#title' => t('Body'),
  '#my_description' => t('The text you enter here appears on the page.'),
  '#after_build' => array('after_build'),
);

And then

function after_build($element) {
  if ($element['#type'] == 'textarea') {
    $element['#description'] = $element['#my_description'];
  }
  return $element;
}

The idea is that you create a value for the fake description and convert it to the real description on the text area. What will happen with the normal description value is that is will be added to the filter form element only which is why your theme overrides doesn't work.


I am not sure what you are trying to do, but I recently tried a module that allows you to upload your videos via your website to Youtube. Check it out:

http://drupal.org/project/video_upload

On the other hand, if you simply want to integrate existing Youtube videos to your website (as fields), simply use the Media modules:

First of all, you need Embedded Media Field module:
http://drupal.org/project/emfield

Then install Media: Youtube to integrate your videos:
_http://drupal.org/project/media_youtube

You can list, sort, filter all your nodes (that contain your video field) very easily with views.

I hope this help, feel free to ask some more details.


I had to do something similar recently. The extremely simple answer I came up with was to simply keep track of the last time the function was run with a db variable.

So, in psudo code, I ended up doing something like this:

function hook_cron(){
  $now = new DateTime(date(DATE_ISO8601));
  $last_checked = new DateTime(variable_get('last_checkedvar', date(DATE_ISO8601, '0')));
  $diff = $now->diff( $last_checked );

  if ($diff->days >= 1){
    //do your stuff
  }
}

Works well for me. And it also doesn't interfere with any of the other cron tasks I have running on my site.


Try implementing hook_theme_registry_alter() and see how that goes.

function mymodule_theme_registry_alter(&$theme_registry) {
    $theme_registry['commerce_product__full']['path'] = drupal_get_path('module', 'mymodule') . '/templates';
}

Your module presumably will have a folder named templates. And inside the folder you have a file called commerce-product--full.html.twig


Ajax webform: refresh page on a successful submission

Thus topic has its own issue in the module's issue queue:
Need to get the redirect message of successful webform submission via ajax with ajax_disable_redirect.module

There's a patch but nobody tested it. Maintainer is waitinig for some confirmation. If you need it go for it.


The directory sites/default/files is not writable on Mac OS X

The files directory in your site must be writable by the webserver. In the finder, do a Get Info on the files directory and assign read & write permissions to staff. (Make sure that this applies to any directories inside files as well.) Alternatively, in the terminal you could "chmod -R 775 my-site-path/sites/default/files" to take care of files and any contained subdirectories.


$body_data = [
  '#theme' => 'something',
  '#somearg1' => 'somevalue1',
  '#somearg2' => 'somevalue2',
];
$body_content = \Drupal::service('renderer')->render($body_data);
$message['body'] = explode("\n", $body_content);


Why is my theme function not called (not in template file)?

arguments was for Drupal 6, you need to use variables for Drupal 7.  One of variables or render element is required, hence nothing is showing up at the moment as the item isn't making it into the theme registry.

function activit_theme() {

  return array(

      'activit_package_teaser' => array(
          'variables' => array('node' => NULL),
          'type' => 'module'
      ),

  );
}


People have been facing issues with Theme Developer module. If you installed this module just to get template suggestions, you might want to uninstall it and use theme_debug (only for d7) variable instead.

Enable this variable by adding $conf[theme_debug] to your settings.php or drush vset theme_debug 1

Then Perform a element inspect (or) view page source to get template suggestions. You may find this article on drupal and the answer in this post helpful- self promoting my answer.


Entity Reference Colorbox Format Display

In the manage display change the format for the referenced image to rendered entity. Then select the gearbox and select colorbox view.

You will need to edit this view mode.So go to biblio content type and manage display. Select colorbox view and change the image field format to colorbox.


Form data not being entered into the SQL statement

Drupal flattens the form values array so the element set at $form['info']['first'] will be available in $form_state['values']['first'].

If you want it to be available in $form_state['values']['info']['first'] you need to set the #tree attribute on the parent element:

$form['info'] = array(
  '#type' => 'fieldset',
  '#title' => t('Personal Information'),
  '#collapsible' => TRUE,
  '#collapsed' => FALSE,
  '#tree' => TRUE
);

There's more info available on the #tree and #parents documentation page if you're interested.

The alternative is to change your db_query() call to use the "default" method:

db_query("INSERT INTO {subscription_info} (first, last, email, phone) VALUES ('%s','%s','%s','%s')",
  $form_state['values']['first'],
  $form_state['values']['last'],
  $form_state['values']['email'],
  $form_state['values']['phone']
);


the reason the sorting that comes with drupal core doesnt work is that it only works for query based content.  If the content is static or otherwise not query based that you need to sort you have the use the client side tablesorting.js as explained here http://tablesorter.com/docs/


How to override subtheme settings (inheritance)?

Assuming you've cleared the cache and all that before trying to inspect any changes, it sounds like your base theme (the theme you've based your sub-theme on) is one of those themes where the configuration is for a large part done by means of the administrative interface. This means that edits done to the .css fileshave no effect, as they're overridden by settings the administrative interface.

A number of popular themes has this property, including the Adaptive Themes family and Omega 3.

To check out if this is the case, navigate to Administration » Appearance » Settings for your theme (or sub-theme).  If there is a lot of settings for fonts, etc., hacking the .css files will not help much and you need to use the administrative interface for styling.


AJAX auto on views (without clicking submit button)

If you enable AJAX in Views, you can also edit "Exposed Form Style" settings. There is a checkbox in there that says "Autosubmit" which will react whenever a user changes an exposed filter.

Edit: sorry, that is for Drupal 7. I see you have listed Drupal 8. For Drupal 8, this was removed and is now being added in an effort in the CTools module. You can see the updates here: https://www.drupal.org/node/2475595

According to this comment, you can apply the latest patch in that thread to CTools 8.x beta1 release, enable "CTools Views" module to add the functionality back in.


Backtracing an SQL error shown in drupal set message with no specifying information

turn on error reporting for php. turn on mysql query log and inspect new queries -- add a simple parameter you can lookup like SELECT ..., 'IS-THIS-BROKEN-1' as debug_key to easily find your quer(ies) in the mysql log file. ... Views offer such a debug parameter for views sql queries too ... my point is there are better ways to tackle this that strictly form your PHP code and drupal_set_message.


How do I create a page (with a url) that displays only views blocks

One way of solving your issue is by installing the following modules:

Empty Page

  The Empty Page module is a simple empty page solution. It provides an interface that assists in managing "empty" menu callbacks, mostly used for pages that only consist of blocks.

Path Access

  The Path Access module gives site administrators an additional layer
  of access control to all pages of a Drupal site.

Chain Menu Access API - required by Path Access module

  Chain Menu Access API allows your module to chain its own menu access
  callback functions into other modules' menu router entries.

After installing all the above modules, try to implement the following steps:

Add new empty page from admin/structure/empty-page/add.
locate blocks you need to display on the created page using Context with Path condition and Blocks reaction.
Now from Access Path settings admin/config/people/pathaccess specify who should access the created page and who should not per user role.

I hope this will help you.


Use hook_feeds_after_save( $source, $entity, $item, $entity_id)
for parsing for links the document and execute command after the importing of each feed.


Adding indexed field to Search API query in code

$query->fields(array('title'));

Doesn't do what you think it does/should, this tells Search API that this is one of your fulltext fields that you want querying against the string you passed to keys()

$query->keys($text);

What backend are you using for Search API, in my experience Solr returns all indexed non empty fields. Make sure the Title is indexed so that it is available to your Search API's backend.


In Drupal 7 They are not using the datetime field. instead of that you can use the int field and add your date in unixtime stamp format.

You can expose the data using hook_views_data hook. Check following URL for more help:

https://api.drupal.org/api/views/views.api.php/function/hook_views_data/7


Would changing the permissions implemented by a module require a new version of the module?

If it changes significant behaviour from previous version I recommend changing the major version. Even if its just a single adjustment like permissions. Wrong or missing permissions may cause huge problems on a site running your module.


Determine whether module is enabled / disabled

This code will list all non core enabled modules:

drush pm-list --pipe --type=module --status=enabled --no-core


how can i get path vocabulary based taxonomy term with node title using views?

Try to change alias pattern for products. Install Entity Token + Pathauto, and on Pattern tab in alias settings (admin/config/search/path/patterns) try to use something like:

[node:field-category:parents:join:/]/[node:field-category:name]/[node:title]


How to create a email notification to subscribers and the author who posted a comment programmatically in drupal 7?

I do not see a way to allow users to subscribe to comment notification, is that your issue?

In case it is you might have to do something like
Create a menu item as 'Subscribe to comments' check this link to ajaxify for menu item. On page callback of your custom menu subscribe the current user(global $user) to the comments, to hold the data you can simply use a custom table let's name as mymoudle_comment_subscription with columns as record_id|uid|comments_on_type|flag update this table in the subscription menu callback,

Rest is what you have covered in your code, i.e. implement hook_comment_update to notify on existing comment update, hook_comment_delete notify user on comment delete, hook_comment_insert notify user on new comment is added. In your hook Implementation query your custom table 'mymoudle_comment_subscription' fetch all uids get user mail by uids or in case you do not allow user to change emails you can store email directly in your custom table and use drupal_mail as your code shows to mail all users.


You have a few options here.

For the short term, you can disable database logging on /admin/modules/uninstall until you can get the full situation under control.

You can disable assertions.  Search yout settings file(s) and set

assert_options(ASSERT_ACTIVE, FALSE);

You should also edit your php.ini file to set zend.assertions=0.

You can then enable database logging again.

That said, it seems like you are running an old version of Drupal.  PHP 7 changed the way assertions work, this was fixed in core in late 2017 and was part of Drupal 8.5.  You should update your site to fix this, and get the security updates that have been made since then.


How to use helper/private methods with a .module file?

I always follow Symfony standards when it comes to helper functions. I normally have one module for developer-central stuff where I add a class under src/Utils for that and then call it everywhere I need it. Also in *.module or *.theme files.

web/modules/custom/my_module/src/Utils/MyHelperFunctions.php

namespace Drupal\my_module\Utils;

/**
 * Class MyHelperFunctions.
 */
class MyHelperFunctions {

  /**
   * Get current multisite directory name.
   *
   * @return string
   *   The basename of the matching multisite directory.
   */
  public function getMultisiteAlias() {

    $site_path = \Drupal::service('site.path');
    $site      = explode('/', $site_path);

    return $site[1];
  }

}

web/modules/themes/custom/my_theme/my_theme.theme

use Drupal\my_module\Utils\MyHelperFunctions;

/**
 * Implements template_preprocess_html().
 */
function my_theme_preprocess_html(&$variables) {

  // Add multisite body class.
  $site = MyHelperFunctions::getMultisiteAlias();

  $variables['attributes']['class'][] = 'site-' . $site;
}

@NoSssweat suggested that the more Drupalitically correct way to do this would be to create a service to let that method be called by other modules via dependency injection as well.

web/modules/custom/my_module/my_module.services.yml

services:
  my_module.helper_functions:
    class: Drupal\my_module\Utils\MyHelperFunctions

And then you wouldn't need to use the namespace anymore, but just can call the service wherever you want:

\Drupal::service('my_module.helper_functions')->getMultisiteAlias();

Read more: When should I create a service or a utility function?


When the rule is ran a certain role is granted to the user. So in your rule's condition add a PHP (or any other way) and check for the number of users who have this role.


How to create a view to count comments per user?

I got it! Sharing my way ;)

What I did:

Created a view of comments of my type.
As fields, I added Author uid twice.
Set aggregation (COUNT) on the second Author uid.
Added a sort criteria for aggregated (Count) Author uid as descending.

woala... Wasn't that hard after all :)


Show/hide menu link based on changing custom $tempStore value

You can try to add the custom cache tag to the access result:

return AccessResult::allowed()->addCacheTags(['custom_cache_tag']);
return AccessResult::forbidden()->addCacheTags(['custom_cache_tag']);


Email Notification to Store Owner When Order Complete

You didn't mention the versions so I assume you are using Drupal 8 with Commerce 2.
You can use Commerce Reaction module as it allows you to select the Commerce event and have a reaction when it is dispatched.
It provides a plugin to send HTML, and twig template emails with nice integration with the Token module.


how it's possible to load nodes by taxonomy terms

In Drupal 7 conditions are deprecated, it is preferable to use EntityFieldQuery to retrieve a list of entity IDs. You can see more here:
About EntityFieldQuery

In this answer you can see an example: What's the proper use of EntityFieldQuery?

In Drupal 8 you can do something like that:

$nids = \Drupal::entityQuery('node')
->condition('your_taxonomy_field', 'your taxonomy id')
->execute();
$nodes = \Drupal\node\Entity\Node::loadMultiple($nids);

I hope it helps


Need help with taxonomy term creating a users view

You can create a View or Views with pages to accomplish this. The presentation of nodes connected to a taxonomy term on its display page is baked into Drupal separately from Views, I think. I'm not positive about that; I never use it. I'm more likely to go around it for reasons similar to what you're describing.

One page can easily present a list of of your location taxonomy terms. I would use a field-based view, and show the name of the term from the list. Uncheck the box that has the field link to the term directly, and instead check the box for the field to function as a custom link (under "Rewrite Results"), put in some URL that will include the location name, e.g., /user-location/{{ term_name }}. Scroll further down and you'll see "Replacement Patterns". Use what seems appropriate there.

The other page may be field-based or entity-based dependent on your specific needs. It keys off users, and makes use of a contextual filter. That contextual filter is the location term name taken from the URL. The page URL will use the one you set in the first page. Thus this page will present user info filtered by the location term.


Changing Button Text on Content Type form

You cannot target only the video_node_form with an existing hook in D7, but you can target all node forms and then check against the node type to alter the form. Take a look at the documentation and comments on hook_form_FORM_ID_alter(). It may also help to check out how the Book module implemented this hook in D7.

function df_video_form_node_form_alter(&$form, &$form_state, $form_id) {
  $node = $form['#node'];
  if ($node->type == 'video') {
    $form['actions']['submit']['#value'] = t('Upload');
  }
}

With regard to your second question, you generally want to place your hooks in the .module file so that they are guaranteed to be picked up by Drupal. There are some cases where this is not necessarily necessary, like in hook_views_api() where you can points to a file containing other views-specific hooks.


What are the alternatives to Features module in Drupal 8

There are multiple options available but please note that all of them are still in active development.

Config Inspector
As the name suggests it lets you inspect the configuration under a menu item in Administration > Reports

Config Devel

This module lets you both import and export the configurations code. You have settings page where you need to enter the absolute path of the files that will be imported or exported. If you want to get an idea of the filenames you can do a full site export from admin/config/development/configuration/full/export and checkout the file names. Please make a note that you need to give the full path of the files here.

If you have entered the file names correctly in Export Configuration, then whenever the respective settings are changed the changes will be written to the respective yaml file.

If you have entered the file names correctly in Import Configuration, then whenever the respective yaml files are changed the changes will be imported into the active storage.

This module can be helpful to track the configuration changes during the development stage and play around with them.

Config Tools

If you want to save the configurations of the site in code and be able to track it using git, you can use this module. It is very similar to the Config Devel module. I would prefer config devel module personally.

Config Update Module

  The main use case is: You update a module, and it has either changed
  default config that it provides, or added new config items. You want
  to be able to import the new items, view the differences between the
  site config and the changed config, and possibly "revert" (or it may
  be an update) to the newly-provided default config.

Config Reset Module

This module is similar to Config Update Module. Personally I would prefer Config Update Module as it is being used by Features Module.

Configuration Synchronizer Module

This module is similar to Config Update Module. Personally I would prefer Config Update Module as it is being used by Features Module.

Features Module

This module is actively being developed and I feel it has made some good good progress recently. As of now all the features are programmatically created. It has good drush integration. If you want to create a custom feature you must use drush features-add command.

Foot Note : If you are trying to export all the settings from one cloned site to other check out What are cloned sites in Drupal 8?

Bonus Links : If you have not yet understood CMI check out Alex Pott's articles:

http://www.chapterthree.com/blog/principles-of-configuration-management-part-one
http://www.chapterthree.com/blog/principles-of-configuration-management-part-two
http://www.chapterthree.com/blog/principles-of-configuration-management-part-three


Statistics module not logging content views after upgrade

There was a problem with missing php file in theme folder and that caused the issue. When we added the file then the counter worked as expected.


Display latest three news on a custom template

I used the Twig Tweak module and I embedded a custom view, showing latest news, inside my Twig template with:

{{ drupal_view('view_name') }}


You can try

Method I - Using Cron and queue

Cron will run the query and push the list of nodes to the queue
queue will pick the items one by one and Unpublish them

Method - II Using Cron and batch

Cron will run the query and push the list of nodes to the Batch process
Batch process will be launched programmatically using background_process module

References

Batch API
How to create a batch operation in Drupal 7
SE Answer
D.ORG post


How to get a count of number of nodes created per week in views and show the week

Contextual Views Summary

You can show weekly results using a Contextual filter.

In D7 you can add a new Contextual filter Content: Created week and configure it with these options:
    When the filter value is NOT available
    Display a summary
    Sort by Date
    Format List
    Base path (you must enter the Page path if this isn't the first Page Display in your Views)
    Display record count with link
    Override number of items to display to 0 to have an infinite number of weeks show. Use this if you want the Pager to control the number of nodes shown for each week (if there are many). Otherwise, the Pager will apply to the number of weeks as well as nodes!

This way you get a list of weeks by their number, each week links through to a list of nodes created during that week:

The Sorting criteria you add to the Views will affect the list of nodes you see after you click through a summary week link. If you add the Content: post date criteria, the nodes will show as the oldest first if you set it to ascending.

Aggregation

For more control, you can use Aggregation to count the results, but it involves a lot more steps to recreate the Summary like above.

After you turn on Aggregation simply change one of the Fields that is unique (for example Node ID) to Count DISTINCT and it will show the number of results.

You'd have to combine it somehow with the Contextual weekly filter if you wanted to display something different from the Summary, possibly create one Views display for the first node of the week, then in an Attachment do the counting and attach it to the week.

Adding a set query to Views is a bit of an overkill since the purpose of Views is to build queries (through an interface).


Add a last edited by column to find content results

You are looking Extra Columns

  This module allows additional columns/data to be added to the node,
  comment, and user tables in administration area. It provides a list of
  fields defined in your drupal installation as well as a few custom
  fields to choose from.

Alternatively you can try Administration Views module.


So try to use

function jms_industry_lens_form($form, &$form_state) {
    $values = array();

    // Load the vocabulary and collapse into an array that form api understands
    $vocabulary = taxonomy_vocabulary_machine_name_load('industry_lens');
    $terms = taxonomy_get_tree($vocabulary->vid);

    foreach($terms as $term) {
        $values[$term->tid] = $term->name;
    }

    $form['industry_lens'] = array(
        '#type'             => 'select',
        '#options'          => $values,
        '#default_value'    => 0,
        '#required'         => TRUE,
        '#ajax'             => array(
            'callback'  => 'jms_industry_lens_form_ajax',
            'wrapper'   => 'edit-industry-lens-term',
        ),
    );

    $form['industry_lens_term'] = array(
        '#type'     => 'item',
        '#markup'   => _jms_render_term($terms[0]->tid),
        '#prefix'   => '
',
        '#suffix'=> '
'
    );

    return $form;
}

/**
 * Ajax callback to change the rendered industry lens taxonomy term
 */
function jms_industry_lens_form_ajax($form, &$form_state) {
    $form['industry_lens_term']['#markup'] = _jms_render_term($form_state['values']['industry_lens']);

    return $form['industry_lens_term'];
}


drush not able to download and enable modules whenever executing drush en  on Windows OS

First, use composer require for module installation.

Second, I don't use windows long time, but as I remember, there is a PATH variables that need to be configured so drush can work properly.

Take a look at this: https://modulesunraveled.com/drush/installing-drush-windows


Sounds like you're simply missing the dependency on core/drupal (and posibly also core/jquery) in your library, so that Drupal and JQuery get loaded, which by default it doesn't for anonymous users.


how to connect to database for form submission

I think there is problem with the condition in the query. Try changing it

$result = db_select('users', 'u')

->fields('u',array('uid'))

->condition('u.name', $name,'=')

->execute()

->fetchField();

You better use Webform Module to create a form without any issues!!

  Webform is the module for making surveys in Drupal. After a
  submission, users may be sent an e-mail "receipt" as well as sending a
  notification to administrators. Results can be exported into Excel or
  other spreadsheet applications. Webform also provides some basic
  statistical review and has and extensive API for expanding its
  features.


Knowing where any block is displayed can be tricky; you would need to keep a nontrivial database table in order to do that (Boost 6.x does this with nodes that are in panels and views). A better option would be to output the block via AJAX or ESI.

http://drupal.org/project/esi/ (has ajax output option)
http://drupal.org/project/ajaxblocks/
http://drupal.org/project/ajaxify_regions/


Theme preprocess for module's template variables using dynamic path

I figured it out. There was already a preprocess function with the name template_preprocess_MODULE_block in the module file. Declaring the same function a second time has no effect.


How can I make a link from user account page to its content profile node?

Probably content_profile_load is the way to go.

The relevant issue here : http://drupal.org/node/680356


Commerce Product Display or just Views Display of line items?

You can't see products because the permission to see products is disabled by default.
Just enable it at /admin/people/permissions. E.g. enable View any product of any type if you want to permit users to see directly entities.

But also have a look at the module Inline entity form. you can edit both node display and attached product entities in one form.


Best way to register a new Drupal user via a 3rd party application

I may be biased b/c I am the Services module maintainer, but, You don't want to be directly inserting things into the database.

You could REALLY break Drupal by doing this.

If you didn't want to use services module(which why wouldn't you?) you should really use Drupal's apis to put things in the database, like, node_save, or drupal_form_submit(which is what services does).

This ensures that Drupal actually enters the data and will lead to a cleaner overall integration with less problems.

In Drupal 6.x this json actually creates a user when POSTed to SERVER/ENDPOINT/user.

{"uid":"1","name":"admin","pass":"1a1dc91c907325c69271ddf0c944bc72","mail":"kyle@workhabit.com","mode":"0","sort":"0","threshold":"0","theme":"","signature":"","signature_format":"0","created":"1286571725","access":"1294792121","login":"1293782855","status":"1","timezone":null,"language":"","picture":"","init":"kyle@workhabit.com","data":"a:0:{}","roles":{"2":"authenticated user"}}


Views Slideshow gives duplicate row classes

You could easily achieve what you need with a small workaround using css pseudo classes :first-child and :last-child, apply them to the surrounding div and easily get the paddings for first and last elements. See this and this.


This is the result of a flexible content management that tries to be everything to everyone. Adding more divs upon request would be difficult, so it provides everything anyone will ever need.

Every template can be overridden as you see fit. For an example of a theme that really clears out a lot of cruft, see Mothership.


hook_node_insert, hook_entity_insert, hool_node_presave not triggering

Only certain theme-related hooks, and alter hooks, can be implemented by a theme. The hooks you're trying to implement aren't in that list, as they're unrelated to theming.

You'll need to create a custom module and implement he hooks there instead.


Change layout of views page based on taxonomy term field

What you can do is in the hook_preprocess_page use the following code :

$arg = arg();
if (count($arg) == 3 && $arg[0] == 'taxonomy' && $arg[1] == 'term' && is_numeric($arg[2])) {
  $term = taxonomy_term_load($arg[2]);
  if ($term->vid == $my_vocab_id) {
    # code...
  }
}

Then change the value of the header as you want in the # code... part.

Basically you check if the URL is a taxonomy term page and then  you can check that the term vid correspond to its proper vocabulary id.

Hope that will help you.


How to login into Drupal 8 using Ajax (REST API)

Your POST data isn't correct, you should be using "user" and "pass". For a a more complete response, see my answer here.


Restrict a role to administer certain vocabularies and terms, and remove the access to creating vocabularies

"Creating a new vocabulary" is what you do using the URL admin/structure/taxonomy/add, while "Editing existing vocabularies" (say with machine name demotags) is done using the URL admin/structure/taxonomy/demotags/edit.

A possible solution to "restrict" access to these URLs (which seems to be the missing piece you are looking for) is to use the Rules module for this. To do so, have a look at my answer to the question "How to make the permissions of a module more granular?". It includes a rule (in rules export format), which you should be able to use if you apply these minor tunings to it:

Check the Rules Condition about which roles this validation should be applied for (if any, if not remove that condition).
Adapt the Rules Condition with the URLs containing visitors (to match the taxonomy related URLs like in my first paragraph).
You probably don't need the Rules Condition with the "regex" in it (you only have a few URLs to be validated). In that case, you don't need the "OR" part either.
Review the Rules Action (the message you want to show, and the redirect you want to force).


Create an exposed filter block from a BLOCK display output

In Drupal 7+ ensure that in the "advanced settings->other" in your block view, Use ajax=YES.