Why can't I update core from 8.6.16 to 8.7.1?

There seem to be some version dependency issue with that email-validator.

I solved it by updating the composer.json to the newer version before updating Drupal:

composer require drupal/core:~8.7.0 --no-update
composer require webflo/drupal-core-require-dev:~8.7.0 --no-update
composer update drupal/core webflo/drupal-core-require-dev --with-dependencies --dry-run
composer update drupal/core webflo/drupal-core-require-dev --with-dependencies
cd web
[../vendor/bin/]drush updatedb
[../vendor/bin/]drush cr

YMMV, here is the Issues where you can get more help if this doesn't work (check the related Issues as well):

Cannot update to Drupal 8.7.0 from 8.6.15 -- egulias/email-validator version conflict

Don't forget to attach your composer.json and composer.lock there so the problem can be properly diagnosed.


How to redirect all images in the files folder to a default file?

You could use the stage_file_proxy module or cdn module


That resource has an optional type parameter, so you should be able to get away with requesting:

http://example.com/rest/privatemsg/?type=inbox

Or ?type=sent, etc


500 error when deleting node with 300,000 comments

I think you could delete the comments via database, limiting the deletion to those attached to the involved node.

It might be a simple as this:

DELETE FROM comment
WHERE nid = <the involved node id>

To ensure avoiding any issue (or in case there is something subtle I missed) you can first execute the equivalent SELECT and control its results:

SELECT * FROM comment
WHERE nid = <the involved node id>

And obviously you shouldn't execute the DELETE query without previously getting a backup.

EDIT: as a non-expert, I only proposed what seemed obvious when examining the comment table.
But thanks to @MPD comment, I realize that there are some linked data to also consider.

Regarding fields, after looking at the tables definition I think that an additional DELETE query should be executed first (before deleting comments themselves), something like:

DELETE FROM field_data_comment_body
WHERE entity_type = "comment"
AND entity_id IN (
  SELECT cid
  FROM comment
  WHERE nid = <the involved node id>
)

If unfortunately supplemental comments had been added, a similar query should be executed also for each of them.

Regarding "The node won't be reindexed." and "Node statistics won't be updated.", I'm not expert enough to understand what is involved.
So I hope @MPD will be able to bring its own complementary information.


How can I display all levels in Simple hierarchical select

I had the same problem and found the answer was to create a custom module and not use SHS. Here's how I did it with Drupal 8 ... and some info on how done with D7: https://drupal.stackexchange.com/a/269296/18513


Are there Drupal modules that help process e-mails dynamically

Inmail is designed to be the low level framework to receive mails within Drupal. We proposed in D8 to also implement Mailhandler on top of Inmail and there's good chance this will happen to reduce complexity.

Inmail "works" and you can write plugins to handle the mails.

What you need is a system that supports dynamic mail addresses (through e.g. address expansion). They then need to be redirected / forwarded to the site. This is more a mail server (MTA) configuration than inmail on its own. Through this, every reply is sent to a unique mail address (defined when sending). You can then while handling the mail easily lookup the reference / know the origin.

We plan to add more support for common mail configuration to consider these dynamic situations through configuration only at some point.

Check the issue queue, open feature requests if you can't find a proper issue and start contributing to it! ;-)


Where can I find the save destination path for a filefield? (via code)

It's part of the instance settings of the file field, but it supports tokens. You want to call  file_field_widget_uri($field, $instance), that will give you a URI you can use to save the file.


How do I programmatically add a new search page to the search page list?

After you've configured the plugin in UI, export the config and look for the configuration file search.page.[search_plugin_id].yml.

Remove the uuid and hash line and place the file in the directory config/optional/ of the module.

You find examples in the core modules Node and User, see http://cgit.drupalcode.org/drupal/tree/core/modules/user/config/optional/search.page.user_search.yml


You can use relationship settings to add in the taxonomy, and then add a contextual filter on "user:uid" with taxonomy value fetched from currently looked-in user.

Have a look at this refrence: https://drupal.org/node/1111722#comment-4315620

Copied here in case that node goes away:

Create a user view.

Add a contextual filter on user: uid. If no filter value is present,
build a default value using the currently logged in user. (This will
give you exactly one user object in your view -- the logged in user.)

Add a relationship, using the relevant taxonomy reference field on
the user accounts. This will bring you information about the
"interest" term for the logged in user.

Add another relationship, called "term: nodes marked with term" (or
something like that). This will bring you information about all nodes
marked with the interest term for the logged in user.

Either set the view to display node teasers, or select a number of
fields to display.

Add a display as usual. Done!


Primary Links Not Showing Up On Certain Themes

There are two ways to show primary links: through the theme settings or through a block placement. Check your theme's settings to see if it has a setting for display of primary links. If it does not, your only configuration option is to place the primary links block into a region through block administration.


In uc_attribute.module file comment out from line number 1360 (starts at if ($adjustment != 0) {) to 1363 and add the bellow code

if ($adjustment != 0) {
    //$display_price = $adjustment > 0 ? '+' : '-';

    //this variable is used to flag your custom discount on minus values
    $set_discount = false;

    if($adjustment > 0){
        $display_price = '+';
    }else{
        $display_price = '(';
        $set_discount = true;
    }
    if($set_discount){
        $display_price .= uc_currency_format(abs($adjustment)). ' off)';
    }else{
        $display_price .= uc_currency_format(abs($adjustment));
    }
}


How to create block with unapproved comments for dashboard?

If you need a simple solution, such as a link for approving a comment (no bulk operations), you can achieve this simply with Views.

Add a new field to your view of comments and select 'Comment: Approve link'. This will provide a link for approving the comment.


Can I use hook_css_alter inside of hook_form_alter

You can't use a hook function inside of a hook function. If you are in the css alter hook you have to get the information you need from where you are in code. For example you could check for the route name of the form because the current route match is available in a service. So this could work (not tested):

function mymodule_css_alter(&$css) {
  $user = \Drupal::currentUser()->getRoles();
  $route = \Drupal::service('current_route_match')->getRouteName();
  if (in_array('administrator', $user) && $route == 'entity.node.edit_form') {
    ...


drill down taxonomy node count using views

FYI. For those who have the same issue above. I managed to do this in Drupal 7 and it's called facet search primarily using Apache Solr or without Apache Solr here


Finally, I decided to use the Autocomplete Deluxe module as tagging widget.

  This is an enhanced autocomplete element, that uses the JQuery UI autocomplete. It will also implement a widget for taxonomy and lists.
  There is also an implementation for the References module: Autocomplete Deluxe for References.


I want to override theme node.tpl.php file with node--[content-type].tpl.php in my custom module

This can be done by providing Drupal with a content type template suggestion through hook_theme. It uses the same 'node--contentname' formalism you are used to in theme templates. This method is IMHO preferred if your module also creates the content type you're theming.


You should look into menu position. You can set active menu trails based on path or node type and they have a simple api for extending the functionality.


Directly changing a theme causes a "Functional environment bootstrapping" error

I wasn't inside the sites' folder! I didn't notice that for some reason - Here is a possible explanation why, that might be nice for you to read:

In the similar time period, I also ran a few general Drush commands inside the root folder just to check if Drush itself is working because of Environment Variable (Path) value setting mistakes I made earlier and tried to fix; I could run drush in each session only after manual var export, but I than went to home/.profile, and added export PATH="~/.composer/vendor/bin:$PATH" in the end of file and it fixed it.


point a subdomain to a page without using domain module

I'm going to assume 1) you already have the proper DNS records set up and 2) you want a redirect (tells the browser to go to URL node/12664) and not a proxy rewrite (i.e. serve the page at node/12664).

Your best option would be to handle this in your .htaccess with mod_rewrite:

# Handle request for subdomain
RewriteCond %{HTTP_HOST} ^test\.mysite\.local$ [NC]
RewriteRule (.*) https://mysite.local/node/12664 [L,R]

If you do want to try to handle this as a redirect in your settings.php you could try something like this:

if ($_SERVER["HTTP_HOST"] == 'test.mysite.local') {
    // Tell the browser to redirect to the HTTPS URL.
    header("Location: https://mysite.local/node/12664");
    exit;
}

If you want to serve a page from a different subdomain/host, without changing the URL, you'll have to delve into the hell of Apache ProxyPassReverse


Drush won't clear uploaded temporary files

Simply make CRON run drush as _www user. /etc/cron.d suppotys it, it's format is:

#<timing>   <user> <command>

Just make entry for your drush:

11 * * * *    _www   drush

Details, of course, may vary a little.

I used this answer.


How can i use bootstrap js library in my theme?

Yes i fixed this problem by using jQuery with more higher version.


How to set same filter value to be searched to the different filters on the same page?

You should enter the same identifier for all views, if you want to use one exposed value for all views in current page.


Combined Fields filters and missing custom search api fields

It's kind of a beginner error here but in case it's useful to anyone the solution is you want to use the Search API Search filter rather than the combined filter.

It handles the search of the provided index all as a single input field by design.


your module should be like this:

function yourmodule_menu()
{
    $items = array();
    $items['path/to/form'] = array(
        'title' => 'Page Title',
        'description' => 'Page Description',
        'page callback' => 'drupal_get_form',
        'page arguments' => array('yourmodule_form_function'),
        'type' => MENU_NORMAL_ITEM,
    );
}

function yourmodule_form_function()
{
   //build form api here as array
   //return array
}

Hope this helps you!


Getting a list/array of all organic groups a user is part of

Assuming you are using Drupal 7 and latest OG you can use og_get_groups_by_user().

  Get the group IDs of all the groups a user is an approved member of.


Can't get module configuration form into modal

You need to add your configuration form using the hook_block_configure instead of making it a page. Add your information to the form as you would any normal drupal form api along with your validate and submit functions. You will also need to hook into hook_block_save for save functionality.


How do I programmatically generate an entity form?

You can use the entity form builder service.  I was able to load the user form this way (with $entity being the current user):

$entity = User::load($uid);
$user_form = \Drupal::service('entity.form_builder')->getForm($entity, 'default');

If you want to get the user register form (which is basically an entity form without a saved entity), you can just use the create method on your entity class before passing it to the form:

$entity = User::create();
$user_form = \Drupal::service('entity.form_builder')->getForm($entity, 'default');


How to add HTML class to main menu list?

One way to achieve this to create a theme key in your template file like this:

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

    $items['custom_main_menu'] = array(
      'variables' => array('links' => array()),
  );

  return $items;
}

And then use the function below

function THEMENAME_custom_main_menu($menu){
  $menu['links'][367]['#below'][526]['#attributes']['id'] = "news_ma_international";
  // this will add id to link # 367
}

Now to print the main menu in your page.tpl.php use something like this

 <?php $main_menu_tree = menu_tree(variable_get('menu_main_links_source', 'main-menu')); ?>
                <?php print theme('custom_main_menu', array(
                  'links' => $main_menu_tree,
                  'attributes' => array(
                    'id' => 'main-menu-links',
                    'class' => array('links', 'clearfix'),
                  ),
                  'heading' => array(
                    'text' => t('Main menu'),
                    'level' => 'h2',
                    'class' => array('element-invisible'),
                  ),
                )); ?>

I hope this will help!


Add header and footer for every pages printed

you can do it to inset html tag in header ot footer file in tpl.php

enter your header

print $content of your page

enter your footer


You can use hook_preprocess_commerce_product like so:

function mymodule_preprocess_commerce_product(&$variables) {
  $product = $variables['elements']['#commerce_product'];
  ...
}


Aggregator offer the possibility to add custom fetch/parser/process to update/override/remove actions on the global process.

For example I managed to make aggregator deal with enclose url image.
Their are several ways to do it with Drupal 8. I used a very simple one : Annotation.

/**
 * Defines a default parser implementation.
 *
 * Parses RSS, Atom and RDF feeds.
 *
 * @AggregatorParser(
 *   id = "xxxxx_aggregator",
 *   title = @Translation("XXXX parser"),
 *   description = @Translation("Custom parser for RSS enclosure tag.")
 * )
 */
class CustomParser extends DefaultParser {

  /**
   * Override default parser to add the enclosure attribute to feed item
   * {@inheritdoc}
   */
  public function parse(FeedInterface $feed) {

    parent::parse($feed);
    // your code...
  }

}

In this given example, using @AggregatorParser, I allow Aggregator to detect and use another PARSER, my custom, which is extending the aggregator's default.

Do not forget to add it in the correct needed path. Here its : namespace Drupal\xxxxx_aggregator\Plugin\aggregator\parser;

You will be able to see and enable it on the aggregator feed admin page.

For deeper informations you can analyse the aggregation process throught the module's files, this contrib module use plugin management and hooks api. AggregatorPluginManager.php


I was able to solve this using the following code:

function bikebike_ajax_form()
{
    if (isset($_POST['url']))
    {
        $url = $_POST['url'];
        $menu_item = menu_get_item($url);
        $form = call_user_func_array($menu_item['page_callback'], $menu_item['page_arguments']);
        if (isset($form['#action']))
        {
            $form['#action'] = url($url);
        }
        $html = drupal_render($form);
        die($html);
    }
    die('');
}

As you can see, instead of rendering the page using file_get_contents, I simply grabbed the elements from the function defined in hook_menu. I needed to change the 'action' parameter of the resulting form structure.

If anyone has a better solution to this problem, I'll happily give you the answer.


twig if Term ID is something, then do something

The original question is how to use the term id in a twig condition. You find the term id in the property target_id of the reference field:

{% if node.field_term_reference.target_id == '1' %}

The value is Bass

{% else %}

The value is Gold

{% endif %}


Prevent name collisions on form value flattening?

While it's good practice to use unique field names in your form, you can use the #tree property to preserve the group nesting of parent -> same child name there.

$form['#tree'] = TRUE;

That will preserve the nesting of group -> field values in the form $form_state['values'] so instead of being flattened it will be

$form_state['values']['details']['admin'] = 'foo';

and

$form_state['values']['more_details']['admin'] = 'bar';


In the Features module, what does "Recreate" do?

Recreate allows you to re download the feature, including any changes made to config along with the option to add new config.


How to display elements responsively side by side using Bartik theme, similar to bootstrap grid?

I ended up working around it by extracting the relevant css classes of bootstrap into my custom css file. Now I can use the bootstrap grid without disturbing the normal Drupal theme:

.row {
  margin-right: -15px;
  margin-left: -15px;
  box-sizing: border-box;
}
.row:before, .row:after {
  display: table;
  content: " ";
}
.row:after {
  clear: both;
}

.col-md-1, .col-md-2, .col-md-3, .col-md-4, .col-md-5, .col-md-6, .col-md-7, .col-md-8, .col-md-9, .col-md-10, .col-md-11, .col-md-12 {
  position: relative;
  min-height: 1px;
  padding-right: 15px;
  padding-left: 15px;
  float: left;
  box-sizing: border-box;
}

.col-md-12 {
  width: 100%;
}
.col-md-11 {
  width: 91.66666667%;
}
.col-md-10 {
  width: 83.33333333%;
}
.col-md-9 {
  width: 75%;
}
.col-md-8 {
  width: 66.66666667%;
}
.col-md-7 {
  width: 58.33333333%;
}
.col-md-6 {
  width: 50%;
}
.col-md-5 {
  width: 41.66666667%;
}
.col-md-4 {
  width: 33.33333333%;
}
.col-md-3 {
  width: 25%;
}
.col-md-2 {
  width: 16.66666667%;
}
.col-md-1 {
  width: 8.33333333%;
}


Mutliple rewrites/redirects in settings.php on a Pantheon hosted site

If you have a reverse proxy service/server sitting in front of your Pantheon instance, it seems like that's the place to place your redirect rules. Rewriting/redirection is a common feature of reverse proxies.

For example, CloudFlare supports redirect patterns under its Page Rules manager. Pantheon has a few doc pages that bring up using CloudFlare so it looks to be a common configure they see used with their service.

If you have a Varnish instance in front your Pantheon instance, you can configure rewrite/redirects in VCL.


Can the Flag module be used to lock content while editing to prevent concurrent edits?

You can do it by using the node_validate function.

Your relevant part code is that :

if (isset($node->nid) && (node_last_changed($node->nid) > $node->changed)) {
    form_set_error('changed', t('The content on this page has either been modified by another user, or you have already submitted modifications using this form. As a result, your changes cannot be saved.'));
  }


Clone product display with referenced product

Try  https://www.drupal.org/project/replicate  and https://www.drupal.org/project/replicate_commerce

The Node Clone module focus on cloning using the administration interface and is designed only for nodes replication, whereas Replicate can clone any entities (nodes, taxonomy terms, users, ...).


Commerce Discount Extra

  Provides a number of common discount condition and offer types:

  Order discounts

  Condition types

  Order-owner role
  Total items in order

  Offer types

  Fixed amount per-quantity discount (Buy X product get Y (or X)    product at discount up to some number of (or unlimited) times)
  Percent per-quantity discount

Ubercart Discount Coupons

  A checkout pane, a cart pane and a block are available for customers
  to enter coupon codes, each of which can be enabled or disabled
  separately. Discounts can be shown as an item in the cart or applied
  on the checkout page.


How to add JavaScript code to a webform?

The recommended way to add a JS to any form in Drupal is using #attached to the $form element.

In order to add the JS to a webform, you would have to implement hook_form_alter or hook_form_FORM_ID_alter, and add the #attached

function MODULE_form_webform_client_form_3_alter(&$form, &$form_state) {
  $form['#attached']['js'] = array(
    drupal_get_path('module', 'MODULE') . '/MODULE.js',
  );
}

Then create the MODULE.js file inside the module directory, and write your JS there.

Refer to The Drupal JavaScript API, to see how to work with JS in Drupal way.


How do I redirect users and show a message?

Set the repeat parameter in drupal_set_message() to TRUE and it will work:

$response = new RedirectResponse($url);
$response->send();
drupal_set_message(t('My message after redirect'), 'status', TRUE);


Should I use the Activity or Message module?

Heartbeat and Activity are both specifically intended for showing user activity (like on Facebook, Twitter, etc.)

Heartbeat is going to be deprecated in favor of Message.  According to the Heartbeat module page:

  This project will be deprecated. The future would be in the module
  Message. It's much smaller and it cannot be compared to heartbeat when
  it comes to features. However the possibilities as API would be the
  same.

Note "the API possibilities are the same."  This means that you will have to write custom code to get Message to do what you want, but as a result you will have more control than the Activity module.

Use the Activity module if you want a solution that works mostly out-of-the-box; use Message if you want to have a highly custom configuration.


How can I differentiate between third-party and custom modules in the list of modules?

You can just do this by looking at sites/all/modules folder - if the sitebuilder was a good one you will see two folders "custom" and "contrib". In modules administration page there is no simple way to differentiate between them.


Found the best way of doing this was using ajax_command_invoke() instead.

By using this you can make a call to a custom jQuery function, in which you can then do what you want.

    ...
    // Prepare an ajax command to insert the node html into our ajax wrapper.
    $commands = array();
    $commands[] = ajax_command_html('#deck .deck-creator', $thumbnails);
    $commands[] = ajax_command_invoke(NULL, array('customAction'));

in a jQuery file

(function($) {
    $.fn.customAction = function() {
        // do my code
    }
})(jQuery);


Why does my user signup request have no response back?

was able to resolve this. The problem was with the incorrect configuration of SMTP relay host which was blocking the sending email part while signing up, due to which the request was incomplete with no response. If anyone has the same problem it should probably be with the SMTP configuration settings on the server


jquery integration issue when attempted to execute on load

As @Kevin mentioned

  Drupal 8.4 introduced jQuery 3.x

And according to jQuery Core 3.0 Upgrade Guide  the "ready" event has been removed.

What you should do is to implement your functional code in Drupal.behaviours. This would have the similar effect as $(document).ready() but with more benefits.

(function ($, Drupal) {

  Drupal.behaviors.myHandler = {
    attach: function (context, settings) {
      // do something
    }
  };

})(jQuery, Drupal);


What are the appropriate configurations for the Subdomain module on Window 7 running XAMPP?

I think you have to setup a virtual host in XAMPP having a different IP, like 127.0.1.2 and adjust your host file by adding 127.0.1.2 sub.ideastar.

More here (but in german.)


In Drupal 7 Commerce, is there a way to populate an anonymous user's profile billing/shipping address data during checkout?

It sounds like you're wanting to set the default billing / shipping customer profiles for the newly created user to be the ones that were just used in checkout. I don't know if there's a Rules action for that, but if not, that sounds like a good feature request for the Commerce Addressbook module. If there is, then you just need to add a checkout completion rule to make it happen.


Services 7.3 - Simple Resource Example works only with GET not with POST from Poster

You need separate callbacks for each of the CRUD operations. You've only implemented 'retrieve', which is the GET callback, you need to implement a 'create' callback for POST to function.

Reading the docs really helps:
https://drupal.org/node/783460


check the hook

function hook_preprocess_oa_user_badge(&$vars) {
  if (user_access('YOUR PERMISSION')) {
    $vars['links']['#links']['YOUR BUNDLE'] = array(
      'title' => t('ITEM TITLE'),
      'href' => 'ITEM URL',
    );
  }
}


how to change address bar by its content-type/title of node

Install Pathauto
Visit the URL Alias Patterns page at /admin/config/search/path/patterns
Choose an appropriate token-based pattern for your content type in the relevant text field, before saving. (e.g. [node:content-type]/[node:title])
Visit the "Bulk Update" tab and generate all Content aliases.

From now on any time you (or anyone else) creates a node of that type, the URL alias will be automatically set.


You can set permissions to users under permissions tab of people module in admin  .Please check below screenshot.Hope it helps


Views - get nodes flagged or created by me

Views 3 supports groups of filters joined by OR.

Edit your View.
Under "Filter criteria" click the little down arrow next to "Add" and select "And/or, rearrange".
Create a new filter group with the filter(s) you want.
Change "operator" to "OR".
Save.

If you're using Drupal 6:

  Views Or allows Views to
  combine filters or arguments with OR and fields with COALESCE.


Is there any alternative way to add CCK field for Drupal 6

Do you mean you're adding over 200 fields to a content type?! Yikes!

If so, I'd strongly recommend you look into:

Breaking the content type up into several smaller ones and using Node References to join them.
Making sure you're using multi-value fields where at all possible.
Using one or two 'Extra specification'-style free text/WYSIWYG fields to store unimportant data from many fields, provided you don't need to filter on those fields.

The issue comes down to practicality and future development... Imagine the size of your edit forms! Huge forms can actually cause problems for people's computers due to memory limitations. Imagine trying to debug or style such forms...

By breaking up the content type into groupings of fields, and collapsing discrete fields into text areas you can better normalise the data and, for a little extra work up front, save yourself a lot of pain later.

Drupal fields have entries in several tables and need many settings created, so I'd avoid using SQL to do it as it'd probably be much more work than just manually adding them.


How to add css class attributes to the anchor element inside the links of a given menu by theme function

I am probably looking at this upside down or backwards but, are you rendering this menu yourself, eg, you are calling theme('links', $variables) somewhere and can easily modify $variables?

If so, a quick look at the theme_links() function itself reveals the following comment...

/**
 * Returns HTML for a set of links.
 *
 * @param $variables
 *   An associative array containing:
 *   - links: An associative array of links to be themed. The key for each link
 *     is used as its CSS class. Each link should be itself an array, with the
 *     following elements:
 *     - title: The link text.
 *     - href: The link URL. If omitted, the 'title' is shown as a plain text
 *       item in the links list.
 *     - html: (optional) Whether or not 'title' is HTML. If set, the title
 *       will not be passed through check_plain().
 *     - attributes: (optional) Attributes for the anchor, or for the <span>
 *       tag used in its place if no 'href' is supplied. If element 'class' is
 *       included, it must be an array of one or more class names.
 *     If the 'href' element is supplied, the entire link array is passed to
 *     l() as its $options parameter.
 *   - attributes: A keyed array of attributes for the UL containing the
 *     list of links.
 *
 *  (rest of comment deleted)
 */

showing that what you need to do is put in an attributes key with each link, as, further on down in the code, when it is creating the link itself, it does, as the comment above also mentions, adds in the full $link as the $options parameter, eg...

$output .= l($link['title'], $link['href'], $link);

So, if you create an attributes key that points to an array with a key of class for whatever link needs a special class, and that key itself points to an array containing that name, this class will be added to the anchor.


Just a couple of ideas:

Alter the email template to include the external link to the purchased files.
Create a tab on the user profile with the links of of the files on the external site.
Create a module to allow the default "File download" module on Ubercart to link to external files and not only to upload ones.

Other readings:

Creating an E-Commerce Site Using Drupal & Ubercart

Selling Digital Goods (Mp3's, Photos, Movies, etc)


Flags - show a flag marker even if user cannot modify it

You could add a new boolean field Answer to comments which has a default value of 0. Next, create a Rule that changes the boolean value of a flagged comment to 1. The rest is theming; use the following code in your comment.tpl.php file:

<?php if ($comment->field_answer['und'][0]['value']): ?>
  <mark>This is the answer</mark>
<?php endif; ?>


Is it to possible add placeholder text for link fields?

You could do something like this in

function formalter(){
$form['#after_build'][] = 'mytheme_after_build';
}
function mytheme_after_build(&$form, &$form_state){
    $form['field_twitter_link']['und'][0]['url']['#attributes']['placeholder']=t('my new');
    return $form;
}

Taken from here https://drupal.org/node/1002560


Drupal 7 Comments Alternating Row Colors

Looks like you can use the $zebra class in the comment template.

Add it in the preprocess hook as a class:

/**
 * Implements hook_preprocess_comment
 */
function THEME_preprocess_comment(&$variables) {
  // Zebra classes are added in the default template_preprocess function
  if (!empty($variables['zebra'])) {
    $variables['classes_array'][] = $variables['zebra'];
  }
}

You can then style the 'odd' and 'even' comments with CSS

e.g, something like:

.comment.odd{
  background-color: #efefef;
}
.comment.even{
  background-color: #ffffff;
}


So, I've written a preprocess function to do this:

/**
 * Prepares variables for link fields.
 */
function mymoduleortheme_preprocess_field__link(&$variables) {

  // If the link is a reference to an internal entity and there was no
  // link title provided by the content editor, then use the entity
  // label as the link text.
  $i = 0;
  foreach ($variables['element']['#items'] as &$item) {
    if (empty($item->get('title')->getValue()) && $item->getUrl()->isRouted()) {
      $parameters = $item->getUrl()->getRouteParameters();
      if (!empty($parameters)) {
        foreach($parameters as $entity_type => $id) {
          if ($entity = \Drupal::entityTypeManager()->getStorage($entity_type)->load($id)) {
            $variables['items'][$i]['content']['#title'] = $entity->label();
            break;
          }
        }
      }
    }
    $i++;
  }
}

This is working with both the standard Link field formatter as well as the "Separate link text and URL" formatter provided by Drupal 8 core.

My only doubt here is that I'm not sure how safe it is to assume getRouteParameters() will always be keyed with an entity type name and a value of the entity id.

Would appreciate your help to review and vet this. Thanks!


"Page not found" or "Forbidden" when submitting form Is it a problem with Apache?

Based on the given error message, the issue is definitely about file and/or directory permissions or ownership. Make sure all the files and directories belong to the username under which your website runs. Also fix the permissions per https://www.drupal.org/node/244924.


Customizing the node create form using a template file

If you want to design the form then use hook_form_alter you will get form array. If you want to design the node page then user node--content_type.tpl.php.


How to programmatically add a facet to Facet API based on returned facet values?

If you used Search API, this code should help you:

$delta = facetapi_hash_delta(facetapi_build_delta('search_api@INDEX_MACHINE_NAME', 'block', FACET_NAME));
print render(module_invoke('facetapi', 'block_view', $delta));


To use Views Bootstrap module you need to have theme that based on Twitter Bootstrap. If your theme is not based on it, you may take a look to similar modules, such as Nivo slider


Group result and display count in a view

My example is based on 1 Content Type and 1 field (City).

FIELDS. Add 2 same fields in fields area you wanna group and show counter.
FORMAT. Group by required field

PAGER. Set 0 in Pager area.
ADVANCED.
Enable aggregation in advanced settings

COUNT. Enabled 'count' for second field (which is not used to group)

Sorting. Set sorting as your group field.

FINAL

This is how looks my view

RESULT


Accessing a FieldItemList value within Twig

To get the value you've highlighted in the debug output in Twig:

{{ content.field_latitude['#items'].0.value }}

You can see this follows the path you've shown in the screenshot, but missing the protected values array. Instead it uses .value on the field item, which calls a magic method __get('value') to retrieve the protected property.

But as @MarioSteinitz commented it's better to use the node object:

{{ node.field_latitude.value }}

Because content is not an API like the methods of the node object. It is a render array which can change when you configure the field display differently or install a layout module.

And never use the |raw filter on user input!


$node = node_load($nid);
$node_wrapper = entity_metadata_wrapper('node', $node);
$node_wrapper->field_myfield->set(1);
$node_wrapper->save();

Entity metadata wrapper is a great way for set or read values of fields in the node!


Get domain logo in views (using Domain Access module)

I don't think you can do that with views only. You'll need to do some coding.
The point is that your logos are not linked to your Domains, but to your themes.

So you need to get your theme based on the domain_id, and then print the logo of the theme.

[EDIT]

If you look at the api of theme_get_setting, then you can see that you can pass as a second parameter the name of the theme you want the logo.
So it should be something like:

$MY_THEME_ID = domain_theme_lookup($MY_DOMAIN_ID);
$logo = theme_get_setting("logo", $MY_THEME_ID);


Solution found :

//appel de la variable user
global $user;

//recuperation de lapercu
$apercu = $_SESSION['image_generate'];
//creation de lobject file
$file_apercu = new StdClass();
$file_apercu->uid = $user->uid;
$file_apercu->uri = $apercu;
$file_apercu->filename = basename($file_apercu->uri);
$file_apercu->filemime = file_get_mimetype($file_apercu->uri);
$file_apercu->status = 1;
//sauvegarde en base
$file_apercu = file_save($file_apercu);

//recuperation du pdf
$pdf = $_SESSION['pdf']->uri;
//creation de lobject file
$file_pdf = new StdClass();
$file_pdf->uid = $user->uid;
$file_pdf->uri = $pdf;
$file_pdf->filename = basename($file_pdf->uri);
$file_pdf->filemime = file_get_mimetype($file_pdf->uri);
$file_pdf->status = 1;
//sauvegarde en base
$file_pdf = file_save($file_pdf);

//recuperation du numero de commande
$form_panier = $_SESSION['form_state_panier'];
$sql = db_query('SELECT MAX("order_id")
                FROM commerce_order
                WHERE uid = '.$user->uid.'')->fetchAssoc();

//creation de lentity
$values = array(
            'type' => 'commandeflyer',
            'uid' => intval($user->uid),
            'status' => 1,
            'comment' => 0,
            'promote' => 0,
        );

//creation dentity sans limage et le pdf
$entity = entity_create('node', $values);
$ewrapper = entity_metadata_wrapper('node', $entity);
$ewrapper->title->set('commandeflyer'.$sql['MAX("order_id")']);
$ewrapper->field_numcommande->set(intval($sql['MAX("order_id")']));
$ewrapper->save(true);
entity_save('node', $entity);

//chargement de lentity
$commandeflyer = node_load($nid = $entity->nid, $vid = NULL, $reset = FALSE);

//ajout image
$commandeflyer->field_flyer_image_commande[LANGUAGE_NONE][] = array(
    'fid' => $file_apercu->fid,
    'uid' => $file_apercu->uid,
    'uri' => $file_apercu->uri,
    'filename' => $file_apercu->filename,
    'filemime' => $file_apercu->filemime,
    'status' => $file_apercu->status
    );

//ajout pdf
$commandeflyer->field_pdf[LANGUAGE_NONE][] = array(
    'fid' => $file_pdf->fid,
    'display' => '1',
    'uid' => $file_pdf->uid,
    'uri' => $file_pdf->uri,
    'filename' => $file_pdf->filename,
    'filemime' => $file_pdf->filemime,
    'status' => $file_pdf->status
    );

//save entity
node_save($commandeflyer);


Is there a limit of tags to associate with content?

It's a simple you must follow this 2 Steps :

First Step :

Create a views that will list your users that you want to reference
Add a Reference display to your view make your filters then Save

Second Step :

Download entity reference module
Add new entity reference field  "Users that will access this content"
Chose the target type : User
Choose the mode "Views: Filter by an entity reference view"
Select the views that you've build on the first Step (the display type must be Reference and not page or block)

Now you will be able to select the users like a tags on content type but without any access permission

To restrict the Permission to the referenced user :
download the user reference access module

Then configure it under the user entity reference field settings of your content type


Running multiple Drupal installations on one URL: is it advisable?

Not only is it not a problem but it's actually a quite common practice!

Check out this link for some tips: multisite howtos

The only suggestion I have is to give each site a subdomain rather than a subfolder, in my experience this works a lot better:

dept1.domainname.org
dept2.domainname.org
dept3.domainname.org

(with all 3 hosts pointing to the same directory)

Setup

To set this up, just add a separate configuration folder under sites for each one:

/sites/dept1.domainname.org/setings.php // dept1 production
/sites/dept1.stagingdomain.org/setings.php // dept1 staging
/sites/dept1.domainname.local/setings.php // dept1 development
and so on...

Also, you should have separate files directories for each site and you can place site-specific (custom) modules on a modules subdirectory under the respective site's settings folder, to keep the /sites/all/modules directory uncluttered!


entity:file:undefined" plugin does not exist upload using curl to jsonapi

The usual troubleshooting step when it seems to work for others is to spin up a minimal D8 app and see if it occurs there. The minimal app worked as expected, which points to a module conflict. For me, the contrib module file_entity was causing this trouble. It took several efforts to get it uninstalled, and only by following the #8 comment on https://www.drupal.org/project/file_entity/issues/3060204 where I try to install it would I be able to finally uninstall it.


What would be the best way to setup a mobile theme for an existing domain with domain access module?

You need these two modules to do this:

https://www.drupal.org/project/simple_mobile_redirect
(detects mobiles and redirects them to pre configured paths)
&

https://www.drupal.org/project/themekey
(serves any theme (e.g. a customized mobile theme) under any pre configured path)


The problem you are facing is that Drupal is so versatile that you may feel swamped by the many ways to accomplish this goal.

The things you need to do:

provide the correct body class
override the correct theme template at the appropriate context
inject the correct style sheet at the appropriate context (optional)

This is how you do it:

You must make sure that you have a body class that identifies the page you want to CSS style. Front page already has 'front' class. You can inject body class via template_preprocess_html (example here). Your CSS can then target the body class in the same style sheet (no need for separate style sheet).

To provide separate style sheets you need to inject different style sheet for different contexts. When using the info file the style sheet is always loaded. To do it conditionally, you will need to use drupal_add_css, and as you wish to do it at a page level you need to add that function probably in template_preprocess_html. You will need to detect the page that you are on by inspecting the url, then load the CSS file that you need. Example here: Adding style sheets

Style sheets can also be removed/altered via hook_css_alter

To target different layouts for different pages, look at Drupal 7 Template (Theme Hook) Suggestions. You can use the available theme suggestions, and you can also add your own (by ading to the theme_hook_suggestions key in an appropriate preprocess_function.)

If some of this sounds too complicated, just go with the Context module. That module has a slew of plugins that can do everything I described above. There are many tutorials, as in Drupal 7 Context module - Daily Dose of Drupal episode 72.

There are also many video tutorials available on theming with Drupal Zen and Zen Grids


Need help adding an action to registration and user form submit

You must implement hook_form_alter, like this:

function MODULENAME_form_alter(&$form, $form_state, $form_id) {
  if ($form_id == 'user_register_form') {
    $form['#submit'][] = 'name_of_callback_function';
  }
}

NOTE: You can also implement this hook in your theme. Remember to clear the cache.


Writing image value to field_collection object

The column name for an image field is fid (not value), so you just need to change this bit of your $values array:

'field_bp_image_file' => array( LANGUAGE_NONE => array(array('fid' => $fid)), ),


How can I alter bundles of commerce_order_item entity type using custom module

add_to_cart_confirmation needs to be a a defined entity form mode, that's most likely the error in your case. Provide it as default configuration in your module or check its existence or create it if necessary.

See how node defines the teaser view mode as an example, or user the register form mode.


How to create charts based on content types items?

Using the Charts module
Step 1: Getting started
To create charts in Drupal, just use the Charts module. It comes with a sample view which will give you a chart for each of your content types.
Just clone and refine that view, and check how close you are to make it fit your needs. Refer to Create charts using Views (and its subpages) for more details.
For a sample of such chart (derived from the delivered sample view), have a look at this demo sample.
Step 2: Create the tabular format of the view
A common mistake when creating charts, is that the data to be charted is (not yet) correct. So you really need to first work on getting the tabular format of the view created correctly. That's also what's recommended in the Bonus tip within Steps to create charts using the views UI, i.e.:

You may find it easier to start with a "Table" display and convert it to a chart display after setting up the data. It can be easier to visualize what the result of the chart will be if it's been laid out in a table first. ...

Step 3: Add the chart to your view
Do not try to start this step if you didn't first complete the prior step.
There is an issue which might help to answer this question, or at least to understand the challenge here. I.e. Graph node input over time (support date formatting on a continuous axis).
In Comment #3 of that issue is stated: 'The trouble here is that neither Views nor Date modules provide aggregation options for date-based fields.'.
Using the Quant module
If using the Charts module you can't get it to work (or don't want to consider the suggestions above), then you may want to look at the Quant module as an alternative. Here are some excerpts from its project page:

... provides an engine for producing quantitative, time-based analytics for virtually any Drupal component. Quant takes raw data about normal Drupal actions, such as node creation, and plots the activity over time, with the selected time being configurable. See the screenshot provided for a better understanding.
Provided charts:

Content creation
Comment creation
Content creation by type
Aggregate content creation
User creation
Page views (requires Statistics)
User shouts (requires Shoutbox)
User point transactions (requires User Points)
Group creation (requires Organic groups)
Group joins (requires Organic groups)
Invites sent (requires Invite)
Invites accepted (requires Invite)
Statuses shared (requires Facebook-style statuses)
Private messages (requires Private message)

Especially the "Page views* chart that is provided might be close to what you're looking for.
Evaluating other charting modules
If none of the above modules would work in your case, then you might want to look at the "Comparison of Charting modules" documentation.
Disclosure: I'm a (co-)maintainer of all modules mentioned above (and original author of the comparison).


How to allow a role to add user without adding user name, password, roles, etc

It sounds like these people you're adding should not be added as users to the system.  You should only add users if they are going to be actually logging into Drupal.

If you're just trying to keep a record of clients then you should store them as nodes.  Configure a new content type called something like "customer" and add and configure the appropriate fields that you wish to store about these customers.


Update image tags using entity metadata wrapper

You must pass in a node object as the second value, instead of a node ID.

$node = node_load($node_id);
$wrapper = entity_metadata_wrapper('node', $node, ['bundle' => 'hub_page']);

That might be your problem. Check out the docs: Entity metadata wrappers.


How to filter a view on a property of optional entityreference-related content (table join / views relationship)?

It seems we cannot use the
  field_data_field_language.field_language_target_id value as a
  condition on the first LEFT JOIN without having another JOIN first,
  which would defeat the purpose - or am I missing something?

Why would adding the column defeat the purpose? Add field_data_field_language.field_language_target_id from your Word and exclude it from the Views display.

Then in your view under Advanced Options add a tag to the query such as concept_word_lang_matrix_view

Then in a custom module implement hook_query_alter() to add your custom join (but not muck with the View fields or anything directly persay -- your Join is just refining results fetched by your View configured in the Views Admin UI)

A sample implementation of hook_query_TAG_alter looks like:

/**
 * Implements hook_query_TAG_alter for the Submission Is Open authentication
 * check of my business logic.
 */
function MYMODULE_query_SubmissionIsOpen_alter(QueryAlterableInterface $query) {
  #dpm(_MYMODULE_get_raw_sql_string($query));
  #dpq($query);
}

/**
 * This is a helper function to output the raw SQL from a db_select() type
 * query.
 *
 * Found via:
 * http://drupal.stackexchange.com/questions/51333/print-the-query-which-is-built-using-db-select
 */
function _MYMODULE_get_raw_sql_string(SelectQueryInterface $query) {
  $string = (string) $query;
  $arguments = $query->arguments();

  if (!empty($arguments) && is_array($arguments)) {
    foreach ($arguments as $placeholder => &$value) {
      if (is_string($value)) {
        $value = "'$value'";
      }
    }
    $string = strtr($string, $arguments);
  }
  return $string;
}

dpm() and dqp() are from the Devel module, they let you preview the SQL running from Views from within your module (where you're tweaking it).

Without having your server/DB I cannot just give you the SQL (nobody can do your homework for you). Writting the correct SQL is the hard part; altering the Views SQL is somewhat tricky but outlined here. goodluck.

EDIT
you may also find this documentation helpful:
https://drupal.org/node/1705998


If you try using filters via the UI on the page itself (not via a services endpoint request), check how the URL changes. If you are not using AJAX in your view, the URL should append all filter values to itself. Then in your services request (poster), try sending in that same URL pattern with the filter arguments in it.

For example, when I used a node title filter on my view and submitted it, I got this URL returned .../testpage?title=testfilter. Then try sending the poster request to this URL with the filter value of your choice.


How do I store URL parameter in user registration field?

Using hook_form_alter you can set the default value of your field to be this query parameter.

function MY_MODULE_form_alter(&$form) {
  $q = drupal_get_query_parameters();
  $form['parameter_field']['default value'] = check_plain($q['aid']);
}


Count of nodes filter in views for a taxonomy with depth

There are several ways to do it, based on how you are going to manage your content.
But for your problem I guess the solution can be this:
1. In Fileds: add Taxonomy term: Name
2. In Relationships, add a Taxonomy term: Content with term
3. Add a contextual filter for Taxonomy term: Name
    3a. Choose 'Display a summary'
    3b. Choose 'Display Record count with link'.

Here is several resources that can help:
Views and node count for taxonomy terms
How to display number of nodes with current term?
Showing how many nodes are associated with a term
Display node count per node reference field


Create a view to display the list of content created by user

Yes, the easiest way to list content created by user is with Views.

Basically, create your view, with the relevant filters for content type, fields etc..

Then add a contextual filter for current user.

Click "Advanced" > "Contextual Filters"
"Add" > "Content: Author uid"
"Provide default value" > "User ID from logged in user"
Save


What is the purpose of Translation field in form display mode?

This is an extra field (Drupal term for a pseudo field not stored in the database you can move around in UI), which is added when Content Translation is enabled:  content_translation_entity_extra_field_info()

See this issue:

  content_translation_entity_extra_field_info is obsolete

  Problem/Motivation

  content_translation_entity_extra_field_info is adding the extra field
  "Translation" but it is not used by content_translation in the form
  alter hooks and it only confuses when we are on the form display
  configuring the fields and reordering it doesn't change anything on
  the edit page.

  Proposed resolution

  Remove content_translation_entity_extra_field_info
  and remove the "translation" component from all saved form display
  configs.

https://www.drupal.org/project/drupal/issues/2856551


Switching to mobile theme while cache is enabled

ThemeKey does support the Drupal cache.

However, the Drupal cache cannot perform device specific cacheing on a single domain since page caches are organized by absolute URLs. See this discussion for an explanation: https://www.drupal.org/node/2242303

The solution is to have a device redirect at the server level to a mobile subdomain (ie. m.mysite.com) which shares the same docroot and switches the theme there. The Boost module is recommended and the process is outlined here:

https://www.drupal.org/node/1214890


Get/print current Ubercart currency via template.php

/**
 * Implements hook_node_load().
 */
function NAME_OF_MY_MODULE_node_load($nodes, $types) {
    $language = $GLOBALS['language']->language;

    if($language == 'en') {
        $variables['uc_currency_code'] = 'EUR';
        $variables['uc_currency_sign'] = '€';
        $variables['uc_currency_thou'] = ' ';
        $variables['uc_currency_dec'] = ',';
        $variables['uc_currency_prec'] = '2';
        $variables['uc_sign_after_amount'] = 1;

        variable_realm_switch('currency', 'eur', $variables);

        // increase price by 1000
        foreach($nodes as $key => $value) {
            if(isset($value->price)) {
                $nodes[$key]->price += 1000;
                $nodes[$key]->sell_price += 1000;
            }
        }
    }
}

Requires Variable module. I hope it helps


Ranking items (groups, nodes) by the number of Facebook likes

This question recently came up at work (small world), my thoughts:

Render the Facebook like button using the XFBML version of the button
Attach a handler to the click event (see the docs)

FB.Event.subscribe('edge.create',
  function(response) {
    // do some AJAX stuff here
    alert('You liked the URL: ' + response);
  }
);

In the above callback, fire an AJAX request back to drupal, to update either a custom table, or alternatively you can use the core statistics table. If you wish to use the core statistics table (or even create your own table) you can leverage the code from my module https://drupal.org/project/statistics_ajax

One advantage of using core statistics, is that it has views integration out of the box, although in saying that writing custom views data sources for your table is easy too.


How can I query and order nodes with multiple date field values within a specific range?

Are the date/time values stored as a varchar in your database? If I'm not mistaken, in that case the ordering is performed by comparing the String values (which is inline with the outcome of your example, i.e., A:2, B:5, C:6).

You could alter your query, using hook_query_alter(), and cast/convert the datatype to datetime (not sure whether every database supports this).

The easiest solution would be to sort the query result afterwards, using the usort() function and in your comparison function you can use PHP's DateTime object or the strtotime() to compare the values.


How know what theme/theme name a Drupal site is using?

You can get it from source of any page. Have a look for the javascript array at the top/bottom of the page that begins with:

jQuery.extend(Drupal.settings, {...

There's a setting in that array called "theme" which contains the name of the theme being used for that page.


How to limit a custom views filter to a certain display type?

This works, you can use a form alter hook to check the display plugin, and then remove options from the AddHandler form.

/**
 * Implements hook_form_FORM_ID_alter().
 */
function entity_browser_form_views_ui_add_handler_form_alter(&$form, FormStateInterface $form_state) {

  // Hide 'entity_browser_bundle' filter plugin for displays other than
  // entity_browser.
  $display_id = $form_state->get('display_id');
  $display_plugin = $form_state
    ->get('view')
    ->get('storage')
    ->get('display')[$display_id]['display_plugin'];

  if ($display_plugin != 'entity_browser') {
    foreach ($form['options']['name']['#options'] as $key => $value) {
      if (strpos($key, 'entity_browser_bundle') !== FALSE) {
        unset($form['options']['name']['#options'][$key]);
      }
    }
  }
}


Drag ad drop images to make a customised gallery

This is actually a nice idea but probably not so easy to implement.

jQuery UI could help you with the drag and drop features. http://jqueryui.com/demos/droppable/
Drupalgardens does some galerie configuration through drag n drop - so there you may be able to get some inspirations on this. Especially since you can export the site and then look how exacly they do it. http://drupalgardens.com


How to add CSS classes to buttons of Drupal Commerce checkout forms?

According that you have default views_form_commerce_cart_form_default form for your cart, this should do the job. Put the following lines in a custom module:

function MYMODULE_form_views_form_commerce_cart_form_default_alter(&$form, &$form_state, $form_id) {
  $form['actions']['checkout']['#attributes']['class'] = array('btn-success');
}

If not ok, check the ID of your form with

function MYMODULE_form_alter(&$form, &$form_state, $form_id) {
  drupal_set_message("Form ID is : " . $form_id);
}

and apply the same above snippet with function MYMODULE_form_FORM_ID_alter.

EDIT : to apply btn-success to Continue buttons of the cart, checkout, review pages:

function MYMODULE_form_alter(&$form, &$form_state, $form_id) {

  switch ($form_id) {

    case 'views_form_commerce_cart_form_default':
      $form['actions']['checkout']['#attributes']['class'] = array('btn-success');
      break;

    case 'commerce_checkout_form_checkout':
    case 'commerce_checkout_form_review':
      $form['buttons']['continue']['#attributes']['class'] = array('btn-success');
      break;
  }
}

To do it yourself next time : in your hook form alter() module, check the form_id, dsm($form); and browse the dsm tree to find your needle...


How can a view in DrupalGap, which is used by a custom module, NOT be cached but instead be called each and every time?

DrupalGap 7 is a multi-page application, which means as you navigate around, pages that you previously visited remain in the DOM. Then when you navigate back to that page, it is already in the DOM, so it isn't rebuilt.

All you need to do is add the reloadPage option to your link and that'll force the page to be reloaded upon navigation: http://docs.drupalgap.org/7/Pages/Reloading_Pages

/**
 * Implements hook_menu().
 */
function my_module_menu() {
  var items = {};
  items['foo'] = {
    title: 'Foo',
    path: 'foo-bar',
    options: {
      reloadPage: true
    }
  };
  return items;
}


Best method to enable/disable modules depending on the environment

One possible answer is the Environment module (the 7.x dev release works just fine). It allows you to define arbitrary environments (comes configured with "Development" and "Production", but you can have more if necessary). It then provides drush environment-switch to switch between environments. You can then implement hook_environment_switch() to do anything you want when the environment is switched. There's no built-in support for enabling and disabling modules, but that's easy enough to do in code, as you demonstrate above. It's also convenient for doing things like changing variable values and blocking development users.

You then put something like drush environment-switch production in your deploy steps.

This also has the benefit of being able to switch back to Development easily. For instance, I have views_ui disabled in Production, but enabled in Development. If I need to urgently check a view in the ui on the production site, I can switch the environment to Development, do what I need, and switch back.

It's also nice that since it's implemented in hooks, you can keep different types of functionality in different modules, and you can keep these things in the code base and under version control.


Users can't use a name in comments that is equal to the username of a registred user

It is not possible. The form validation handler for the comment form (comment_form_validate()) doesn't allow to the anonymous users to choose a username that has been already used by a registered user. The function contains the following code:

  elseif ($form_state['values']['is_anonymous']) {
    // Validate anonymous comment author fields (if given). If the (original)
    // author of this comment was an anonymous user, verify that no registered
    // user with this name exists.
    if ($form_state['values']['name']) {
      $query = db_select('users', 'u');
      $query->addField('u', 'uid', 'uid');
      $taken = $query
        ->condition('name', db_like($form_state['values']['name']), 'LIKE')
        ->countQuery()
        ->execute()
        ->fetchField();
      if ($taken) {
        form_set_error('name', t('The name you used belongs to a registered user.'));
      }
    }

The code avoid the confusion there could be between anonymous users that reports the link to
their homepage and an authenticated user, when the anonymous users would use a username already in use.

To remove that limitation (which I don't think it's a good idea), you should implement hook_form_comment_form_alter() to add your own validation handler (with $form['#validate'][] = 'mymodule_comment_form_validate', or similar code. Your form validation handler should be a copy of the one used from the Comment module, except the part that reports an error when an authenticated user is already using that username.
There is another problem, though; the form validation handler used by the Comment module contains the following code:

  if (!empty($form_state['values']['cid'])) {
    // Verify the name in case it is being changed from being anonymous.
    $account = user_load_by_name($form_state['values']['name']);
    $form_state['values']['uid'] = $account ? $account->uid : 0;
    // …
  }

In your case, if an anonymous user would use "Christoffer" as username, and that is already used by an authenticated user, the code would load the user object for the authenticated user, and the comment would be attributed to the authenticated user, not the anonymous user.

There could be also other code in the Comment module that takes the assumption there cannot be two users with the same username, which is a restriction present in Drupal.


Is there a way to trigger an action on a php exception in Drupal 7?

I'm glad this question was asked some time ago, and Thanks to @coderama for offering a bounty for this. I make questionnaires/challenges to Druplars in my local community, and this was a question there.

PHP allows you to set error and exception handlers. This similar to how you register class autoloaders and shutdown functions.

See set_error_handler

  Sets a user function (error_handler) to handle errors in a script.

  This function can be used for defining your own way of handling errors
  during runtime, for example in applications in which you need to do
  cleanup of data/files when a critical error happens, or when you need
  to trigger an error under certain conditions (using trigger_error()).

Also, you can set an exception handler to handle uncaught exceptions. See set_exception_handler

  Sets the default exception handler if an exception is not caught
  within a try/catch block. Execution will stop after the
  exception_handler is called.

Drupal takes over these two when it initializes the environment. even before bootstrapping advanced bootstrap levels, such as the database, variables, and full bootstraps.

If the error happens in Drupal-handled request, it will be handled by either of these handlers (error or uncaught exception handler) unless it was overriden by other modules (Devel's error handler, and other error handling modules or server-side implementations, possibly New Relic).

Both of these functions call _drupal_log_error() to proceed to the logging behavior in Drupal.

The default error handling (and other logging) functionality is based on the watchdog() function.

watchdog() function invokes hook_watchdog(), which the db_log module implements hook_watchdog to store them in the database. watchdog() function itself is not storing them in the database. Similarly, there is syslog module that can store them in the system log (instead of, or in addition to the database log).

If you want to call your own logging/reporting tool, you can simply create a module and implement hook_watchdog() to log them. Note that watchdog() is called to log events that you probably don't want to log, such as users logging in, node CUD events, user registrations, etc. You can filter them down by inspecting the parameters passed for the hook implementation.


Getting the number pad to show up for text fields

hook_field_widget_form_alter

  Alter forms for field widgets provided by other modules.

or use hook_field_widget_WIDGET_TYPE_form_alter to hook into the Number field specifically.

/**
 * Implements hook_field_widget_WIDGET_TYPE_form_alter().
 */
function mymodule_field_widget_number_form_alter(&$element, &$form_state, $context) {
  $element['#type'] 'number';
}


In git, the terms "branch" and "tag" always applies to the whole repository, not to the individual files.  A branch denote is a series of commits (so you always use an "x" instead of specific version number for a branch). A tag is a label for a specific version, so you specify the version number (e.g. 1.0 for the first released version, 1.1 for the next, and so on.)

The command git branch -v will give a verbose listing of the current head.  It should, in the case of Drupal 7, start with a line * 7.x-1.x.  If it says master on the first line, you've not set things up right.

Before adding tags, you need to get your project on a 7.x-1.x branch.  In your local repository, do the following to checkout branch 7.x-1.x and delete branch master, and push those changes to the remote:

git checkout -b 7.x-1.x
git branch -d master
git branch -v
git push origin 7.x-1.x
git push origin :master

After you've made sure the branch is 7.x-1.x, you can go ahead and add a tag to your release.

You can use the commands you refer to, to tag.  To see all the tag(s) in the local repository:

git tag

After pushing to the remote, if you've done this correctly, you should be able to click on the Version control tab and find the 7.x-1-x branch in the Version to work from: pull-down menu.  If you retain the master branch, make sure that you make the 7.x-1.x branch the default.


How do I set up a view to filter on URL path?

To be able to filter nodes by their path you will have to use menu_link. (i havent used it though).

As far as i know there is no simple way of displaying content of the menu related tables, which is what you would have to do to include the views in the result. Some discussion and a direction of coding is here : http://groups.drupal.org/node/22731 Unfortunately the module suggested there wouls help you neither - it is again just for nodes.


What does #optional mean for a "details" form element?

This is handled in the render element Details:

Details.php:

  public static function preRenderDetails($element) {
    ...
    // Do not render optional details elements if there are no children.
    if (isset($element['#parents'])) {
      $group = implode('][', $element['#parents']);
      if (!empty($element['#optional']) && !Element::getVisibleChildren($element['#groups'][$group])) {
        $element['#printed'] = TRUE;
      }
    }
    return $element;
  }

If #optional is TRUE and there are no visible children, then the element is not rendered.


This is actually pretty complicated.  The major problem is that both the region and the zone that it is in have the grid classes on them.

You need to implement a template_process_zone() in your theme, and then remove the grid classes from $variables["content_attributes_array"]["class"].  You then need to implement a template_process_region() and remove them from $variables["classes_array"].

Any other regions in that zone will then have grid problems, and the containing zone won't have a grid container definition.

Your other option is to use CSS to override the grid definitions for the zone and region.  Depending on your site and the theme, you may be able to get away with using a full zone wrapper around things, and then using positioning on the region to make it appear full width.


How can I create bidirectional node references?

There has been a lot of movement around this subject lately.

The state of the art module seems to be Entity Reference.

It may lack some functionality you're asking for, so cnr may be of help too.


Display term description below a field widget based on the selected option on node edit form

You can add an #ajax property to the state field in a hook_form_alter() and then include the taxonomy term description as a form item below the state field if state is set.
See the ajax examples in the examples module or post here is you have any problems.

I don't think there is any need to use a block.


Search Form block not displaying in Home Page

have you looked at the block settings to see if it has something like "display on these pages" or "don't display on these pages" checked and if so it's saying to not show it on ?


Applied Image Styles Cause Failed Image Render

These aren't private files, right? There is an open issue for something that sounds a lot like this. We applied patch #34 and it resolved the problem for us.


You can use the admin/content page as a reference to combine forms. There, the filter form and overview form are passed as elements in a new $form array.
Coming from the content administration callback function in the node.admin.inc file:

/**
 * Menu callback: content administration.
 */
function node_admin_content($form, $form_state) {

  $form['filter'] = node_filter_form();
  $form['#submit'][] = 'node_filter_form_submit';
  $form['admin'] = node_admin_nodes();

  return $form;
}


Sorry missunderstood your questtion, I think ->

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

is what you are looking for.


Why is this extremely simple form not getting an upcast entity from its route?

It seems entity routes (beginning entity.), like those in the user module, get the Drupal\Core\ParamConverter\EntityConverter converter automatically applied; other routes don't.

You should be able to apply it yourself easily enough:

my_job_board.user_register_form:
  path: '/my-job-board/register/{user_role}'
  defaults:
    _form: '\Drupal\my_job_board\Form\UserRegisterForm'
    _title: 'Register for My Job Board'
  requirements:
    _access_user_register: 'TRUE'
  options:
    parameters:
      user_role:
        type: entity:user_role

See Parameter upcasting in routes for more info.


Showing a node edit page with drupal_get_form() and hook_menu()

hook_menu() is only evaluated when the caches are rebuilt, so the call to module_load_include() won't be called when the path is actually visited.

That hook is only meant for declaring menu items, if there's any logic that needs to be added for a path it should happen in the access callback/page callback like so:

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

  $items['test/test'] = array(
    'title' => 'Edit this node',
    'description' => 'Edit this node.',
    'page callback' => 'control_center_test_callback',
    'page arguments' => array('page_node_form', $node),
    'access callback' => TRUE,
  );
  return $items;
}

function control_center_test_callback() {
  module_load_include('inc', 'node', 'node.pages');
  $nid = '4';
  $node = node_load($nid);

  return drupal_get_form('page_node_form', $node);
}

Since you're forwarding to a static node edit page though, it might be easier just to set the page callback to drupal_goto() and hardcode the URL:

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

  $items['test/test'] = array(
    'title' => 'Edit this node',
    'description' => 'Edit this node.',
    'page callback' => 'drupal_goto',
    'page arguments' => array('node/4/edit'),
    'access callback' => TRUE,
  );
  return $items;
}


This can be solved by changing your Views filters to be connected using an OR instead of an AND. This option can be accessed by through the Views interface using the steps below.

1.

2

3


Cannot access Administration > People page

I'm not sure 100% if my solution will solve your issue or not but give it a try

first set base url in settings.php

$base_url = 'http://baseurl.com/Drupal/htdocs';

then check if clean urls enabled from

/?q=admin/config/search/clean-urls

just in case try to clear Drupal cache from

/?q=admin/config/development/performance


Using drush into remote host is showing me local data

It'd be interesting to see what results you'd get if you modify your script above by removing the domain.com: (in 'root'), to make it look like so:

<?php
$aliases['lws'] = array(
    'root' => '/home/user/public_html',
    'uri' => 'domain.com',
    'remote-user' => 'user',
);
?>

At least that would make it look more like the samples for 'dev' and 'prod' as documented in https://www.drupal.org/node/1401522 .

Curious to hear if this helps somehow ...


Embedded images not shown in Google Chrome

Is that an exact copy-and-paste?  It isn't valid HTML.  Try

I think I fixed everything...

Whenever you have browser differences, run your page through http://validator.w3.org/ and fix the errors first.


My drupal 7 messed up after installing a module and I just get an error, how do I debug it and trace the source of that error?

You can use the debugging methods mentioned in the comments, especially ddebug_backtrace.

Another, more manual option, is, to disable other enabled modules one by one, until the error goes away. Once you know the culprit, search the issue queue of that module (and the new module) and/or use the debug statement (or drupal_debug from the devel module) to narrow down the problem.

Some pointers on how to debug:
https://drupal.stackexchange.com/questions/545/how-do-i-debug-drupal
How do I debug my Feeds import not importing a field

And then of course, you should look at the web-server logs (apache, etc).
Another way to debug issues like that, when you get the white screen of death, is, to execute a drush command on the command line - like cc or something like that. Often, the error message gets printed to STDOUT.


Hum... Classic "I am sure I tried that before and it wasn't working"... I spent an entire day looking for the solution, and find it 5 minutes after posting here :)

$query = db_query("
  SELECT n.title, SUM(q.quantity_value)
  FROM {node} n
  JOIN {quantity} q
  ON q.entity_id = n.nid
  WHERE EXISTS (SELECT *
    FROM {tags} t
    WHERE t.entity_id = n.nid
    AND t.tid IN (12, 15))
    HAVING COUNT(DISTINCT t.tid) = count(12,15)
  GROUP BY n.title
");
$results = $query->fetchAll();

Subquery was the way to go (if anyone has something better to suggest, I would love to hear it).

Thanks,

Ed


How do I redirect to an external URL without caching it?

Disable caching in responses

You can build the cacheable metadata and put max-age = 0 in it:

$build = [
  '#cache' => [
    'max-age' => 0,
  ],
];
$cache_metadata = \Drupal\Core\Cache\CacheableMetadata::createFromRenderArray($build);
$response->addCacheableDependency($cache_metadata);

If you want to put this in one line:

$response
 ->addCacheableDependency((new \Drupal\Core\Cache\CacheableMetadata())->setCacheMaxAge(0));

Disable caching for anonymous requests

Also you have to disable the page cache for anonymous requests

\Drupal::service('page_cache_kill_switch')->trigger();

This is necessary no matter if you use a normal redirect response or one with drupal caching.


Moving drupal site to the root of the server

I guess you can upload the new .htaccess file and change back the line #RewriteBase if you have modified only one line of the .htaccess file, there won't be any problem and even if the file exists there it will give you a option to replace.

Few things that you have remember while moving your site to root folder are:

Put the site into maintenance mode so that user's posts, comments etc. doesn't gets lost.
The #RewriteBase is uncommented when we use the drupal from the subdirectory. So if you are moving it to the root folder than I guess no need to modify this line. (Anyways you try you way also).
If you have modified/using the $base_url in setting.php than don't forget it to update as well.log
Clear the complete cache, and check the watchdog table data (dblog) at "/admin/reports/dblog" to make no page or anything is having issue.


Predefined field collection items in node edit form

I do not think that this will work in the way you wish, since Field Collections are entities rather than normal fields.

It sounds to me like you need to use form_alter to update your input form.

Checkout this link on Drupal.org for one method that might work:
Finally - found a solution... (D7)


Can Drupal built-in search or Apache Solr find comments on the site made with Disqus?

Looks like it may be possible on the server side via the Disqus API PHP wrapper - I widened my answer outside of Drupal to get more input: https://webmasters.stackexchange.com/a/52159/3738

Though I still have concerns about not fully controlling the comment data and if the API changes. I'd have to see real benefits for our situation for Disqus to be able to outweigh these potential issues. Another issue is that of usability (UX/User Experience): having already logged in to the Drupal site, the user has to log in yet again to use disqus, unless the well supported Facebook login to the Drupal site can be "carried" into the Disqus login automatically. Though some user testing has revealed some would prefer the Disqus approach to be simpler.


how to alter exposed form values before submit for filters in drupal7 view

function example_form_alter(&$form, &$form_state, $form_id) {
 array_unshift($form['#validate'], 'example_request_validate');
}

function example_request_validate(&$form, &$form_state) {
  if (isset($form_state['values']['text_field']) && !empty($form_state['values']['text_field'])) {
    $request_id = $form_state['values']['field_request_id_value'];
    if (strchr($request_id,''))) {
      $request_id = ltrim(strchr($request_id,''), '');
    }
    form_set_value($form['text_field'], $request_id, $form_state);
  }
}


It seems that "I am unsure on what action to call this rule" is your remaining issue, and that by using the rules module you are already close.

However, when talking about Rules and its Event-Condition-Action concept, your issue is about what Event to use. With that in mind, I would try to use the Rules Scheduler submodule of Rules, to schedule the rule to be executed at the moment of the purchase already.

Makes sense?


How can I move a node type's configuration into a custom module?

Configuration Management did not replace Features completely, Features still has its place.

My understanding is that:

Configuration Management should be used to manage your configuration for a specific site/project.
Features should be used to export configuration to custom modules as you develop them if they're going to be re-used on another site.

The configuration in your custom module goes into 2 directories (install or optional).

Configuration in the install directory is considered required and only gets imported when your module is installed.
Configuration in the optional directory is optional and will import during your module install if all the dependencies are present. (I think it also gets imported if all dependencies are later installed.) E.g. If you define a View in your module's optional directory, that configuration would be installed only in two instances: 1. when you install your module, if Views is installed, or 2. when Views is installed later, sometime after your module is installed.

The Features module page lists several additional resources to help understand the differences between Configuration Management and Features.


Language code and country code on the URL

I achieved this using Persistent URLs: https://www.drupal.org/project/purl and a custom LanguageNegotiation plugin


Add translation files to custom module doesn't work

You might need to uninstall the module completely and reinstall it again, in order to be able to import the translations. Otherwise, they are not picked up automatically. There are a couple of threads in the Drupal forums mentioning this issue: https://www.drupal.org/node/220341 , https://www.drupal.org/node/435706#comment-2711736

Hope that helps,


Panels doesn't output views content pane title

The $title variable for the views_view theme hook is added only for the administrative preview. Here is the section of code in template_preprocess_views_view() that adds the title: http://cgit.drupalcode.org/views/tree/theme/theme.inc?h=7.x-3.11#n85

If you want to add that variable to your template override, you can do so with an additional preprocess.


Custom basic .js from theme dir prevents Splashify module from working

Looks like simple syntax error :

(function ($) {
  /* Slideshow */
  Drupal.behaviors.MYSITE = {
    attach: function (context, settings) {
      $(".carousel").jCarouselLite({
        btnNext: ".next",
        btnPrev: ".prev"
      });

      /* Rollover info */
      $(".block1").hover(function(){
        $(this).find("span.info").stop(false, true).fadeIn("fast");
      }, function(){
        $(this).find("span.info").stop(false, true).fadeOut("fast");
      });

      // Class for every 3rd row.
      $(".view-flavor-listings .views-row:nth-child(3n-3)").addClass("diff-margin");
      $(".view-content-inner .views-row:nth-child(5n-4)").addClass("diff-mrg");

      /* slidePager */
      $('.pages').slidePager({
        last:6,
        borders:1,
        change:function(n){
          var els=$('.thumbs li').removeClass('mrk');
          els.eq(n).addClass('mrk');
          els.eq(n+1).addClass('mrk');
          els.eq(n+2).addClass('mrk');
          $('.thumbs li').css('opacity',1);
          $('.thumbs li:not(.mrk)').css('opacity',1);
        }
      });

      // Make Plupload default.
      $('.filefield-sources-list').each(function() {
        $('a.filefield-source-plupload', this).trigger('click');
        $(this).hide();
      });
    } // attach
  } // behavior
})(jQuery);


Notice: Undefined index: allowed_values in list_allowed_values()

This can happen if you delete a field from the definition of a custom content type and that field is still referenced by a View.  Even if you added a new field with the same name as the one you deleted the problem will persist. You need to remove the old field from the View definition and then add the new field to the View.


Negative number of stock after order many products

Solution of this problem is Ubercart Out of stock Notification module.


Printable Templates for Views using Print Module

I faced a similar issue quite a while back and below is how I solved it:

Create another display of the same view (clone page)
Choose 'Remember last selection' in the Views exposed filters' settings in the original page view
In the cloned page view, set 'Expose form in a block' to 'Yes'
Use the regular 'print/view-url' wherever you want but remember that 'view-url' in this case is the path of the cloned page view.

Hope this helps,

Regards,
Supriya Rajgopal


I've seen this problem when as unprivileged user you call drush cc all and drush tries to delete cache files created by the web server process. Those files are owned by the web server user and they don't have the 'all other users" write permissions enabled (the last three permissions group).

Fixing this is a file permissions issue. One fix is to put web server user and drush user in the same group and assure that files created by the web server process are writable by its group members.


You can check if the form failed validation by calling form_get_errors

You could try using drupal_form_submit instead, which I think will also validate the form (seen via form_get_errors)


I believe that groups are a feature of the migrate_plus module. In order for them to be recognised, the file needs to be named migrate_plus.migration_group.<group_name>.yml. The actual migrations also need to be formatted like this migrate_plus.migration.<migration_name>.yml.

One other issue I see is that your id: wprdpress should be id: wordpress. (Just in case that typo is in your code :) )

The last thing is that migrations are only defined on module install. This means that you have to uninstall and re-install every time. (Or you can implement some drush commands to do it for you. Check out this tutorial.)


Month Year granularity on views exposed filter for a custom table exposed to view

In order to get month, year granularity we can use date handler as defined by date module so while exposing field to use it will be all about choosing the right filter handler so I used "date_views_filter_handler_simple" handler.

Code while exposing the custom table field with proper filter handler.

$data['jh_report']['date_of_purchase'] = array(
    'title' => t('Date of purchase'),
    'help' => t('Date of last purchase for current month'),
    'field' => array(
      'handler' => 'views_handler_field_date',
      'click sortable' => TRUE,
    ),
    'sort' => array(
      'handler' => 'views_handler_sort_date',
    ),
    'filter' => array(
      'handler' => 'date_views_filter_handler_simple',
    ),
  );


Aegir / drush alias issue: profiles specified at command line get forgotten

I tweeted this to Mig - he says:

  probably a bug. Workaround is to not hosting-import the site but re-verify the platform & let it autoimport site by itself

HTH! =)


Command to list all media entities in console?

If you use Drush, you can try drush sql-query like this :
 drush sql-query "Delete from name_table weher condition"


How to get the current active DB in Drupal 6?

Doesn't look like drupal allows it inherently, so I'm posting my hack in the meantime. I'm open to any suggestions on improving this:

global $db_url;
$activeDBName = db_result(db_query('select database()'));
$mode = '';
foreach ($db_url as $key => $url) {
    if(strpos($url, $activeDBName) !== FALSE) {
        $mode = $key;
    }
}

$mode will then be whatever the active db is.


Advance Poll block keeps caching results

You can try to use Lazy Pane or Block Lazyloader modules to output your poll block. Your block will be loaded from the client side, on demand, via AJAX.


Create user login programmatically in Drupal 7

It's not going to be possible to list all of the functions involved as your mileage will vary depending on what you need to do.

Basic steps:

Read up on and understand the Form API; try out a few examples so you're familiar with it.
Create a form function in your module, to be delivered in whatever method makes sense (a menu callback or embedding directly, for example). This will involve using drupal_get_form(), and viewing the user login form code will be useful here.
Create a validate handler for the form which does any validation you need. See user_login_default_validators() for the login form defaults.
Make use of user_login_finalize() in your form's submit handler to log the user in. You'd be best off copying the logic from user_login_submit() almost directly.


Why is an entity reference view field only showing one view result?

I was having this issue as well, and it came down to the view returning a different entity_id than the one(s) I thought it should be returning. This happens because of incorrectly formed relationships.

A way to check this is to add a "dpm($options);" (if you're using the devel module) in the entityreference_options_list function of entityreference/entityreference.module file (just after the $options are returned from entityreference_get_selection_handler) to see what options it is retrieving from the view.

I started a new Entity Reference view that just returned the entities that I wanted, and then I built my relationships backwards from there to finally get the correct number of entities in my form.

I hope this helps!


Should a site be in maintenance mode when running the Drush Up command?

The first bit of advice here is to always run drush up on a dev or staging site first, before running it on a production site.  Sometimes, due to bugs or incompatibilities, upgrades can break a previously-working site.  It is therefore always best to test your upgrade before bringing it live.  After testing, it is also best if you move the exact files that you tested from dev to live rather than run drush up again.  You never know, someone might publish a new release while you are testing!

When you run drush up on your test site, you will notice at the end that Drush will report either "No database updates", or it will run an updatedb, and you will see a report on the database changes that you made.

If there are no database updates required, then generally speaking, it is safe to update your code without putting your site in maintenance mode.  Note, however, that there is a small risk that a web request might be processed when only some of the files in your site have been upgraded.  Since it only takes a small amount of time to git pull or rsync your files, this is only likely to be a problem if your site gets a lot of traffic.  If you are concerned about this, you could put your site into maintenance mode, or better yet, put up an 'in progress' page by adjusting your web server's configuration.

If database updates are required, it is a good idea to put your site into maintenance mode before updating it.  After copying the files to your production system, run drush updatedb to run the database updates.  When database updates are required, it is common for them to do operations such as add new columns or tables to your database.  The new code in core or your contrib modules may assume these schema changes have been made, and may crash if run prior to the completion of the database update.  drush updatedb can take a little while to run, so it is more likely that you might serve a web request before it finishes.

Note that if there ever is a problem, it would only be observed by a small number of clients, and would be fixed with a simple page refresh in the browser.  Since you are probably watching your updatedb run, you would probably never see these failures yourself.  It is best to keep your site clean from transient failures, though, so maintenance mode is the safer option.

It is a good idea to script the update operation, so that it will run smoothly and easily every time.  See drush_deploy  and upgradepath for two example projects that do this.


I don't question that the suggested answer (from NishantP) might answer the question. But the "Goto ... & open taxonomy.module ..." looks like hacking this module. If you just do that, then be prepared for the issue potentially coming back in the next module upgrade (because such upgrade might wipe out your edit).

As an alternative, how about filing an issue for this module (if such issue doesn't exist already), and attach a patch to it corresponding to the suggested edit (hack). It might (and probably will) get accepted to be committed to the module in the next reease of it). From then on no more issue with future upgrades of that module. And if it doesn't get accepted, you can still use that same patch to re-apply in further module upgrades (assuming you don't have to re-roll them then).

Edit: looks like NishantP's answer is no longer there (deleted?). Not sure (yet) if that implies that I should now also delete "my" answer. Since I'm sure there was something in it like that "Goto ... & open taxonomy.module ...", I'll leave my answer here for now, just in case anybody else ever has similar hacking-suggestions ...


Go to Administration -> Structure -> Content Types, select the name of your content type, then click on Manage Fields.  Find the image field, click edit for that field, then scroll down until you see the Image Field Settings section.  Click the default image button, and select what image you want to show by default.


How can I list all the terms of a given vocabulary using Views?

You need to build the view from a taxonomy base as shown in this screenshot (I'm showing Tags; you would need to show Colors):


How can I give the permission to edit, update, or delete a comment or a user profile to specific roles?

There's the Comment Permissions module:

  The Comment Permissions module enables control of commenting by user role and by node type. Additional user permissions for selected node types are added to the user access system so you can configure commenting with more control than Drupal core provides.

It does have a (dev) Drupal 7 release, it's just not listed on the module page for whatever reason. You can find the archive here.

It will need testing before you can use it in a production site, but it's a very small module and a cursory glance at the code suggests it should work. I used that code as the base for a more advanced comment permissions module (including soft-deleting etc) some time back and don't remember finding any problems with it.


How can I change the name attribute to "email" in the user login form?

This is a variation of a frequently asked question.

The user login form for Drupal is built using Drupal Form API.

In Drupal 7 core, the user login form is declared in user.module:

https://github.com/drupal/drupal/blob/7.x/modules/user/user.module#L2111

  // Display login form:
  $form['name'] = array('#type' => 'textfield',
    '#title' => t('Username'),
    '#size' => 60,
    '#maxlength' => USERNAME_MAX_LENGTH,
    '#required' => TRUE,
  );

  $form['name']['#description'] = t('Enter your @s username.', array('@s' => variable_get('site_name', 'Drupal')));
  $form['pass'] = array('#type' => 'password',
    '#title' => t('Password'),
    '#description' => t('Enter the password that accompanies your username.'),
    '#required' => TRUE,
  );
  $form['#validate'] = user_login_default_validators();
  $form['actions'] = array('#type' => 'actions');
  $form['actions']['submit'] = array('#type' => 'submit', '#value' => t('Log in'));

And in Drupal 8 core, it's declared in UserLoginForm.php:

https://github.com/drupal/core/blob/8.8.x/modules/user/src/Form/UserLoginForm.php#L94

    // Display login form:
    $form['name'] = [
      '#type' => 'textfield',
      '#title' => $this->t('Username'),
      '#size' => 60,
      '#maxlength' => UserInterface::USERNAME_MAX_LENGTH,
      '#description' => $this->t('Enter your @s username.', ['@s' => $config->get('name')]),
      '#required' => TRUE,
      '#attributes' => [
        'autocorrect' => 'none',
        'autocapitalize' => 'none',
        'spellcheck' => 'false',
        'autofocus' => 'autofocus',
      ],
    ];

    $form['pass'] = [
      '#type' => 'password',
      '#title' => $this->t('Password'),
      '#size' => 60,
      '#description' => $this->t('Enter the password that accompanies your username.'),
      '#required' => TRUE,
    ];

    $form['actions'] = ['#type' => 'actions'];
    $form['actions']['submit'] = ['#type' => 'submit', '#value' => $this->t('Log in')];

If you need to customize it, you should not edit the code in core. Instead, you should do it using hook_form_alter() in a custom module.

This is a classic example of one of the first exercises new developers can do to learn how to build Drupal modules, and a web search should reveal many tutorials.

As @Jaypan pointed out in the comments above, you probably want to change the label on the field ($form['name']['#title']) rather than its name.

Here's an example of how to do that with hook_form_alter() in Drupal 7:

function YOUR_MODULE_NAME_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id=='user_login') {

     // This will change the field label from "Username" to "Email".
     // The t() function marks the string as translatable by Drupal.
     $form['name']['#title'] = t("Email");

  }
}

In Drupal 8, it's almost the same, but $form_state is now an object and must be type hinted as an instance of \Drupal\Core\Form\FormStateInterface:

function YOUR_MODULE_NAME_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {
  if ($form_id=='user_login') {

     // This will change the field label from "Username" to "Email".
     // The t() function marks the string as translatable by Drupal.
     $form['name']['#title'] = t("Email");

  }
}


How to display external data using custom form in a Drupal page?

Not sure why you want to create a custom module for this, since ... there is a module that can "*display JSON results in a Drupal page" ... i.e. the Views JSON Query module. Some details from its project page:

  JSON Query is a Views 3 plugin that adds native JSON query generation. It allows you to parse JSON using Views' graphical query builder.
  It works much like Views XML Backend but with JSON.

And a screenprint from that same page:

For more details, read about it in the article about "Show external JSON data in Drupal Views".

PS: Similar solution if your input format is XML (instead of JSON), using Views XML Backend.


Creating line item of specific type programmatically

Never mind. I just realized that the commerce_product_line_item_new() function has a $type parameter that defaults to Product. Not sure how to delete the question, but maybe it will help someone else.


***EDITED****

How about if you add the js into the HEAD tag .

This goes into your default Theme that is being used and you need to add this hook to the template.php file ; if it doesn't already exist.  Remember to Clear you cache afterwards also.

/**
* hook_preprocess_html
*/

function yourtheme_preprocess_html(&$variables, $hook) {

   drupal_add_js(drupal_get_path('theme', 'yourtheme') . '/js/common.js');

}


Setting up a download page requiring a user to fill a form before downloading anything

There is Webform Protected Downloads. But it will result to quite a different structure from yours. Webform Protected Downloads allows someone to download a "protected" file after filling out a webform. You can add more than one file and have the download links expire after a certain time.

When also looking for something like your issue I also found another module (don't remember the name) that added a page before redirecting you to a node. So maybe you could add a webform page to send the user before reaching the download page. But if he knows the link he could bypass it of course.


Show custom page while the server processes a form

Checkout the module loader , it may solve your problem

A similar module hide_submit


You don't actually create hooks. You use helper functions such as module_invoke_all(), module_invoke() or drupal_alter() to invoke all functions matching the expected name pattern. The invoked functions are usually found with  module_implements().

Even if it is not needed for the hooks to work, the best practice is to document them in MODULE.api.php by creating empty stubs hook_NAME functions with documentation comments.


Access denied for user anonymous for node retrieve service

It was issue with domain module. Domain strict module was enabled. After disabling, it started working.


Are you using Views? If so, you could try using Views arguments for exposed filters: https://www.drupal.org/node/54455


Where is the setting saved when I modify a configuration setting?

https://www.drupal.org/developing/api/8/configuration/simple

See the section on Interacting with configuration and Reading configuration.

E.g. $config = \Drupal::config('system.performance');

I'm assuming the saved settings are configuration.