Best Way to Handle Variables Per Environment

You can create a new setting in your settings.local.php or settings.php file like:

$settings['event_base_url'] = 'https://www.example.com';

or some people are adding switch block based on the server host, e.g.:

switch (@$_SERVER['HTTP_HOST']) {
  default:
  case 'dev.example.com':
     $settings['event_base_url'] = 'http://dev.example.com';
     break;
  case 'stage.example.com':
     $settings['event_base_url'] = 'https://test.example.com';
     break;
  case 'www.example.com':
  case 'preprod.example.com':
     $settings['event_base_url'] = 'https://live.example.com';
     break;
}

Then reference it in the code like:

use Drupal\Core\Site\Settings;
$baseUrl = Settings::get('event_base_url', '');

So your code would look like:

use Drupal\Core\Site\Settings;
class EventSuggestionForm extends FormBase {
  private $baseUrl;
  private $apiUrl = '/api/v1/';

  function __construct() {
    // Read value from the settings file.
    $this->$baseUrl = Settings::get('event_base_url', '');
  }
...

Then change this setting per environment in the settings file, similar as you've different database credentials per different environment. This is the same concept as it's used for the existing $settings['file_public_base_url'] parameter.


How to send a vote using Advance Poll and Services Voting Api?

Ok, I figured out how this is supposed to work. The required JSON document to POST to the set_votes service must be this:

{
  "votes":[
    {
    "entity_id":"1328",
    "tag":"f5a8bb465",
    "value":"1"
    }
  ]
}

entity_id is the nid of the Advance Poll, tag is the choice_id of the Poll Choice you want to cast the vote for, and value must always be 1, it's the vote.

In case you need to know those IDs, it may be a good idea to expose them through the node or the view services. Or use the Devel module


How do I remove the term ID from the view URL?

Perhaps you can do this using htaccess rules.

You can probably apply the patch from this issue and than according to the reports you will be able to create a path alias from within drupal that accept url parameters (as in your case)

But you can also try views_url_path_arguments which seems to be usable in Drupal 8 judging from the amount of downloads.

Perhaps you can also give this sandbox module Query Parameters To Url a try

Note: I have not tested the above 2 modules


Page where I can see my user's managed files

I do not think there is a pre-made page for this, but you can make one using Views.  Create a new view of type Files.  Under the Advanced section, add a Relationship for the user who uploaded the file.  Then add a filter "User: current" using this relationship.


Manage Display of Entity Reference Field: How to link to nodes instead of plain-text?

On the Manage Display page for your Releases content type, select "Rendered Entity" for your entity reference field.  Then, to the right of the control that contains "Rendered Entity" you will see a little gear.  Click on the gear, and you will get another page with a "View mode" control.  The view mode has options such as "full content" and "teaser".  You can select exactly which view modes appear in this list by going to the Manage Display page for your Scenes content type, and open the "Custom Display Settings" field group.  If "Teaser" is not checked, then check it and click "save".  After you turn on "Teaser" in this way, you will have a "teaser" button at the top-right if the Manage Display page for your Scenes.  Click on this and you can control exactly what appears in a scene teaser.  If you want your scene teasers to hold different fields than scenes embedded in releases, then perhaps you could use "tokens" instead of "teaser" for your entity reference view mode.

Edit:  Sorry, I only answered the second part of your question.  If you want to render just a link to your scene, then select "Label" for your entity reference field, click the gear next to the control again, and turn on the checkbox "Link label to the referenced entity".


How to attach variables to drupalSettings with ajax?

Use the SettingsCommand
$settings=['ajax_forms_test' => ['foo' => 42]]; /* An array of key/value pairs of JavaScript settings. */
$merge=TRUE; /* (Optional) Booleen Whether the settings should be merged into the global drupalSettings. */
$response->addCommand(new SettingsCommand($settings,$merge));

So your code would become something like this:
public static function AddAJAXResponseCommands(AjaxResponse $response = NULL, array $params = []) {

  $modalSettings = [
    'id' => 1,
    'status' => true,
  ];

  $sample = [
    '#type' => "html_tag",
    '#tag' => "div",
    '#attributes' => ['class' => ['context-menu']],
    '#value' => "Dashboard",
  ];

  $sample['#attached']['library'][] = 'mylibrary/dashboard-js';
  $merge = TRUE;
  $settings['dashboard']['myVariables'] = $modalSettings;
  $response = new AjaxResponse();
  $response
    ->addCommand(new ReplaceCommand('.context-menu', $sample))
    ->addCommand(new SettingsCommand($settings, $merge));
  return $response;
}


How to display the user name that created the profile (the owner or author of the profile)?

You can get from getOwner() method

  {{ profile.getOwner().name.value }}
  {{ profile.getOwner().mail.value }}


Modal Dialog not Opening when not authenticated or in incognito mode

Ajay is correct, the javascript dependencies wont load by default for anonymous users. Here's what I added to my theme.libraries.yml to get it working:

dependencies:
  - core/jquery
  - core/drupal.dialog.ajax


You could do this several ways, the easiest from a hook standpoint might be to use views_pre_render(), eg, something along the lines of...

function YOURMODULE_views_pre_render(&$view) {

  if ($view->name=='THE_VIEW_YOU_ARE_LOOKING_FOR') {

     drupal_set_message('<pre>' . print_r($view->result, TRUE) . '</pre>'); // to see what you have to work with

     foreach($view->result as $r => $result) {
      if ($result->node_data_field_status_field_status_value) { // or whatever the $result field is you are looking to change from 0 or 1 to Pending or Approved
        $result->node_data_field_status_field_status_value='Approved';
      } else {
        $result->node_data_field_status_field_status_value='Pending';
      }
    }

  }

}


Changing block content based on user input


How to use the Rate module to rate things inside the content?

I was also looking how to use the Rate module until I found how. Just:

Go to Structure > Rate Widgets.
Select the type of rate you want to create and click on Next
Enter the information. It allows you to select what type of content will have the new type of rate.

Hope it helps anybody else.


This function

  ebanq_transfer_preprocess_user_accounts_form(&$vars)

must be called

  template_preprocess_user_accounts_form(&$vars)

So the Drupal bootstrap / hook system will know that.


How can I show referenced terms on other term page with view

You have to create a list of all School terms, and then use a Contextual filter to feed Views with information about the City term you're currently viewing (City page), so the School terms results can be reduced to show only the School terms that are related to that particular City.

Build Views that list Terms that reference another Term

Create a View of type Taxonomy term, you only need the Block Display, and choose only the School terms vocabulary
Add a Contextual filter from Taxonomy term Category named after the reference field you're using on the School term Vocabulary to reference Cities
Configure it with these options:
When the filter value is NOT available
Provide default value
Taxonomy term ID from URL
Load default filter from term page
When the filter value IS available or a default is provided
Specify validation criteria
Taxonomy term
City
Filter value type: Term ID
Save the View (adjust other options if you wish) and place the Block in a region of your theme, limit Visibility to show only on City term pages.

You should now see the list of School terms on city pages that relate to that City.

Test Contextual filter from Views UI

To test the Contextual filter while building Views you can use the Preview with contextual filters: field.

Enter all and press the Update preview button to see all results irrespective of the Contextual filter.

Enter the number of a City term TID to see the School terms related to it. For example if the term newyork has the TID 16 enter 16 into the Preview field, and you'll see the School term list is reduced to only those which reference newyork.


Change the site name programmatically for a specific page

I think you mean page.tpl.php (not system.tpl.html, which isn't a standard Drupal file).

That said, you need to put your code in a hook_preprocess_page() function inside template.php, and actually alter the template variables that are passed in. At the moment you're just creating a variable called $site_name in the local scope, and Drupal has no way to pick that up.

Try this:

function MYTHEME_preprocess_page(&$vars) {
  $path = drupal_get_path_alias();
  if ($path == 'about_us') {
    $vars['site_name'] = 'New title';
  }
}

Have a look at Setting up variables for use in a template for a bit more info.


Mystery "test" text showing on page after views module update

I can see there is some jquery script adding the string 'Test' for each view row . Look into your code base for the string '.view-id-blog .views-field-body' and you'll find out from what file is it coming.

You may also want to disable javascript aggregation for sometime, and then see the exact file name in the developer tools directly.


Ok, I've found the answer.
Files and tmp folders were owned by root, so I changed in www-data ( web user ) and everything works now.


Automatically fill fields taking value from user profile

use the form api and hook_form_alter http://api.drupal.org/api/drupal/modules%21system%21system.api.php/function/hook_form_alter/7 and set the values of the form items to the items you specify
WIth form api you can specify a default value which you can set to what is in the user profile.


To start with, just enable the top_content default view which comes with the VotingAPI module. Its Fivestar display has the sorting set up as follows:

Relationship: Vote results
Add sort criterion: Vote results: Value, Relationship: Voting results


Remove All Unwanted js and css files from theme

Drupal only has one sanctioned mechanism for removing specific assets, regardless of the motivation for doing so.

For CSS:

hook_css_alter

For JS:

hook_js_alter

To remove all style and scripts except .info style and script use below codes:

function hook_css_alter(&$css) {
    $themes=list_themes();
          foreach($css as $key=>$item) {
            if (!in_array($key, $themes['yourthemename']->stylesheets['all'])) {
                unset($css[$key]);
            }
        }
}

function hook_js_alter(&$js) {
    $themes=list_themes();
    foreach($js as $key=>$item) {
        if (!in_array($key, $themes['yourthemename']->scripts)) {
            unset($js[$key]);
        }
    }
}

If the theme/module is custom, then obviously you can just remove the offending code manually if that makes more sense.


On User Creation, send user registration email in his language preference

I think you need to change the way drupal detect the language of the current user.

You can do so by going to /admin/config/regional/language/configure and check "Follow the user's language preference.". You may need to move this option as the first detection method.


Do I need to install Drupal using Drush in order to use Drush?

No, you do not need to install Drupal using Drush in order to use Drush. All you need is to make sure that while running drush cc all, you are in the Drupal directory.

For example, if your Drupal lies under /var/www/Projects with root name as drupal then first you need to move inside /var/www/Projects/drupal and then run the drush cc all command.

The reason being, Drush can be executed inside a Drupal environment only.


Setting a field readonly rather than invisible from hook_field_access()?

Try something like that :

Replace FORM_ID with the real form ID.

function MYMODULE_form_FORM_ID_alter(&$form, &$form_state) {

  if(!user_access(ADMIN_USER)){
      $form['your_field_name']['#disabled'] = TRUE;
    }

    $form['your_field_name']['#access'] = TRUE;
}


Make new content [typeA] out of existing content [typeB]

It is possible all right. In your custom module use node_load and node_save:

$abstract = node_load($abstract_id);
$event = new stdClass();
$event->type = 'event';
node_object_prepare($event);

$event->title = $abstract->title; // and so on

node_save($event);

$event_id = $event->nid;

Just wrap it in a function and expose it to the framework you are using - most of them provide good examples in their documentation.


How to use hook_form_alter to hide a form field for certain users?

You can clean up the code a bit by using hook_form_FORM_ID_alter:

function mymodule_form_regester_node_form_alter(&$form, &$form_state, $form_id) {
  global $user;
  $node = node_load(arg(1));
  $num  = $node->field_node_reference['und'][0]['nid'];
  $val  = node_load($num);
  $event_noderef_uid = $val->uid;

  if($user->uid == $event_noderef_uid){
    $form['field_NAME']['#access'] = FALSE;
  }
}

Other than that, if field_NAME exists in the form and the condition is true, access will be set to FALSE. If you are testing this as user 1, you may not be seeing the results you desire as that is the superuser. It would help if you posted the form you are trying to alter and what its structure is for field_NAME. Probably a really good case to write an automated test for as well.


The pattern field_data_field_ refers to Field storage. This data is attached to an entity of some kind, most likely a Node. You can learn more about content management on drupal.org, Nodes, content types and fields.

You should edit the node that you want to modify (admin/content or click Edit on a node if the tab hasn't been styled out of existence), and find the field that someone added there. Then you can change the value. You can check what fields are used in which entity types by going to /admin/reports/fields. Each field usage has a link to its respective Field Management page where you can learn more about how that particular field is configured.

Modifying field_data_field_ directly in the database is incorrect because data retrieval happens in field_revision_field_ tables.


How to get the node title of a refernced node

You could use entity_label() function.

The function takes the entire entity as an argument, and it should already be loaded.
I would just load the node. As the other author suggested, it is very likely to be already cached in a hook_node_presave() call.


How to change the content moderation state in a custom submit handler?

To change the moderation state you need first to get the entity:

$entity = $form_state->getFormObject()->getEntity();

and then change the state:

$entity->set('moderation_state', 'submitted');

and save:

$entity->save();

All the code:

/**
 * Submit callback to submit for approval
 */
function draft2submit_callback(array &$form, FormStateInterface &$form_state) {
  // Getting the entity.
  $entity = $form_state->getFormObject()->getEntity();
  // Changing the moderation state.
  $entity->set('moderation_state', 'submitted');
  // Saving the entity.
  $entity->save();
}


You cannot run any code after a return statement. By definition the return will exit the function. Try moving the dpm call to just before the return statement.

As an aside, I believe that best practices say that $block->content should be a render array and not straight up html...


The problem is links are generated by Google. I assume Google tools does not suffice, and you can't generate report of enough quality using Google Analytics - if you could, you wouldn't ask here.

You cannot alter links. If what you display is not what Google provided, you are not getting any money. So the only sure way - generate link like http://example.org/count_ad_click/123dwe324), record click and redirect user - is closed for you.

You could cover ads with transparent link to your counting address, to avoid altering the real one. That counts as click hijacking and can hurt your reputation, badly. Browsers can start to display "possible malware" alerts, SEO position will drown and so on. Oh, and of course no money.

You still can use jQuery to append onclick to those links, and either push events to Analytics or to your own counting mechanism. Both are prone to manipulation, as they happen on a client side and user can fake those clicks all he wants, so you can get any number of false positives. On the other hand, if your reader will have javascript turned off, it will not count him at all, and some anty-hijacking plugins can prevent click count, too. Last but not least, that's the way AdSense module works now, anyway.


Awarding points with Rules for uploading a user picture

Have a look at the "User Points" (https://drupal.org/project/userpoints) module.
It has rules integration (among many other modules) so this may be the one you're looking for. It also provides a hook API by the looks of it, so if you need more custom functionality than what it offers by default, you should be able to perform actions from within a custom module.


Strategy for upgrading large Drupal 6 site to D7

Although both methods are valid, #2 can be painful if you have a lof of custom code in your app. I would consider option #1.  Migration is quite straightforward using migrate module.

There is a little more overhead than doing a straight-up upgrade but the process is very well documented and well integrated with Drush.  With migrate you can even have roll-backs and migration reports out of the box, all scriptable and quite easily automated.

I have done some pretty large migrations myself with this module and it works like a charm once in place.

PS: No worry for your entity id's, migrate uses the same nid when it imports the nodes.


There are multiple ways you can add an extra column or a field to each row of your views output. And you can choose what is best for your use case.

For a Drupal 7 site you can use -

https://drupal.org/project/computed_field
https://drupal.org/project/views_php
for extra fields in plain text, you can refer this answer.

If you need to pass any kind of dynamic context to your custom extra field, say a node id, there are multiple ways to do that too.


Webform submit button disappearing if I change it from default

If you have a custom twig template for your webform the custom submit button needs to be referenced differently than the default.
Default Submit Button reference:
{{ element.actions }}
Customized Submit Button reference:
{{ element.elements.actions }}


Create a link to user/logout. It can be a menu item or an HTML link in a block.


Form API multiple select drop downs in a paragraph

You can try a combination of wrapping the whole form in a div, so:

form['#prefix]='
';
  $form['markup1'] = array(
    '#type' => 'markup',
    '#markup' => 'Hello this is a pulldown '
  );
  $form['pulldown1'] = array(
    '#type' => 'select',
    '#required' => TRUE,
    '#options' => array('option1', 'option2', 'option3'),
  );
  $form['markup2'] = array(
    '#type' => 'markup',
    '#markup' => ' and this is another pulldown '
  );
  $form['pulldown2'] = array(
    '#type' => 'select',
    '#required' => TRUE,
    '#options' => array('option4', 'option5', 'option6')
  );
form['#suffix]='
';

then use theme_form_element to remove the field wrapper divs that Drupal injects automatically around each field, see this post. Once these individual divs around each pulldown are removed then the pulldowns will render inline with the markup.


The key directories are modules, themes, and profiles. You also want to backup all settings.php files, and uploaded files as well. Although, I would separate the two into two backup files, since, depending on the site, the uploaded files directory could be in the low MBs or hundreds to even GB of files. Give them both a readable date timestamp for a filename.

Also, backup your composer.json and composer.lock files. If you control your site build using Drupal Project or Acquia BLT which has a composer driven approach, composer.json will contain the information needed to rebuild your site (this does not include data, only code). Then it's just a matter of backing up custom modules and custom themes, since composer can fetch all the code and rebuild core.


Themekey with mobile detect not working properly

The mobile detect module had some issue with caching. The Drupal 7 Core caching have been supported since few weeks ago by a sub-module call "Mobile Detect Caching."

However, the developer mention that he boost probably would not work.... Here is what the developer said:

  It will only work with Apache(?). I doubt it will work with Varnish,
  Boost, or similar. I suspect it will work with {cache_page} in
  alternate caches, but I didn't test this.

In the comments you mention that you are using a Shared Hosting and you depend on the boost module and what you should do ?

Well, I would recommend you to follow the issue Drupal Cache + Mobile Detect Conflict where the still discussing this module caching issue. In addition to follow you should ask for boost support or an alternative. They might try to implement this module with the boost module.

In the mean time, I would recommend to used a free CDN called CloudFlare and let them generated the caching instead of the boost Module. However, you probably would not get the same results as the Boost module.


Split an array returned by menu_tree_output

Just in case someone needs this: I found a solution altering menu_build_trees output:

$menuTree = menu_build_tree('my-menu');

// flatten out the hierarchic menu tree
foreach ($menuTree as $key=>$value) {
    // if the item has children
    if (count($value['below']) > 0 && $value['link']['hidden'] != 1) {
        $flatMenu[$key]['link'] = $value['link'];
        // add a custom class to the first level items
        $flatMenu[$key]['link']['localized_options']['attributes']['class'] = array(
          'first-level-item',
        );
        // override nested menu items
        $flatMenu[$key]['below'] = array();
        // and add those to the new array
        $flatMenu = array_merge($flatMenu, $value['below']);
    // if the item has no children
    } elseif ($value['link']['hidden'] != 1) {
        $flatMenu[$key] = $value;
        $flatMenu[$key]['link']['localized_options']['attributes']['class'] = array(
          'first-level-item',
        );
    }
}

$markup = '';
$chunk = 5;
// split the new array in chunks and wrap them each with a numbered class
foreach (array_chunk($flatMenu, $chunk, true) as $key=>$value) {
  dfb($value);
  $markup .= '
';
  $markup .= drupal_render(menu_tree_output($value));
  $markup .= '
'."\n";
}

$block['content'] = array('#markup' => $markup);
return $block;

It is a bit hacky but with some extra lines of CSS it works perfectly well!


Create a view pulling in content that matches user profile

With Drupal 7 and Views 3 you can match on multiple taxonomy terms using contextual filters. I posted about this on drupal.org here. Maybe it can be adapted to your particular situation.


I think you answered yourself :).  If you want to redirect back to the page the user invoked it from, set $path to current_path() when calling confirm_form.  Otherwise set $path to wherever you want them to go on cancel.


How to customize the user profile page with views

Create a view and add a "page" display.
Use "user/%" as the page path.
Add a contextual filter "user uid" and select "provide default value" user ID from URL.

You are done. This view overrides each user's profile page.

You can also add another display "attachment" to this view. Or add another views block as a view area into the footer of that view.


Here are few tips:

make sure your Drupal core has all the files in the right place (especially node module),
make sure your imported database is in UTF-8 format,
upgrade your Drupal core to the latest version (drush fr && drush up drupal)
clear all your caches (drush -y cc all), including your memcached (killall memcached),
rebuild your registry by using Registry Rebuild (which you already did),
if you're using modules which are implementing drupal_bootstrap() (such as Secure Site), disable them,
try disabling your PHP cache engines (such as XCache, Zend optimizer) to see if that's the problem,
test it on different environment/machine,
eventually restore your database from the point where it was working before


How to display User profile fields to anonymous visitors?

Normally this is simply done within the permissions admin section (/admin/people/permissions if I remember right). Simply give anon users the permission to view profiles and those fields.

Maybe the module you are using causes the fields to be hidden. Check the permissions of that module as well.


The node module is marked as

required = TRUE

in the node.info file, so the developers are basically saying that as far as they're concerned the node module is imperative for Drupal 7 to function correctly.

You could try patching the info file to remove that line, then disabling the node module to see what happens...in fact if you do that you should write a blog post about it or something, it would be very interesting to find out the effects; I've never heard of anyone trying to do this before :)


You can apply GROUP BY or DISTINCT by enabling views aggregation settings to remove duplicate records.

Go and edit your view
In Advanced » OTHER section by enabling Use aggregation: Yes
In FIELDS or FILTER CRITERIA section, select and apply Aggregation
settings for which fields you want to group by or distinct.


How to change field value from a Views block?

You can use Editable Views Module. The module provides a field to be editable when displaying using views.


Here is a working example taken from the Rules Examples module, which is a submodule of D8 Rules Essentials.
langcode: en
status: false
dependencies:
  module:
    - tr_rulez
  enforced:
    module:
      - tr_rulez
id: redirect_to_home
label: 'Redirect to home on Login'
events:
  -
    event_name: rules_user_login
description: 'Issue #2975452-6: Redirect all users to "/" on login, except for when a one-time login password is used.'
tags:
  - login
  - redirect
  - rules_examples
config_version: '3'
expression:
  id: rules_rule
  uuid: 7263942c-3847-460d-af3f-6c78f80fbcc1
  conditions:
    id: rules_and
    uuid: a8c1bb95-b783-4238-a7e1-9b4b9fb96ca4
    conditions:
      -
        id: rules_condition
        uuid: f35e2d95-850d-455d-99e2-629e37b17cb7
        context_values:
          text: reset
        context_mapping: {  }
        context_processors:
          text:
            rules_tokens: {  }
        provides_mapping: {  }
        condition_id: rules_path_contains_text
        negate: true
  actions:
    id: rules_action_set
    uuid: d17285ef-4de4-498a-8b78-654cf79566ee
    actions:
      -
        id: rules_action
        uuid: a529b090-e6f3-4421-aede-75489267d888
        context_values:
          url: /
        context_mapping: {  }
        context_processors:
          url:
            rules_tokens: {  }
        provides_mapping: {  }
        action_id: rules_page_redirect


Modify checkbox event on custom line item type to hide show div

I think the Conditional Fields module should do the job.

It allows you to create rules to hide or show fields based on another fields value - so perfect for you.


EntityQuery not returning content based on language

Content entities have an active language concept. If load them, they by default return values for the default translation.

With your query, you know it has that translation, so you can do $node = $node->getTranslation($language);. If you're not sure it exists, you can use $custom_tag = \Drupal::service('entity.repository')->getTranslationFromContext($node, $desired_langcode);. That will return the node in the matching translation if it exists, or the best alternative. You can also leave out the langcode, then it defaults to the current content language.


Why `GROUP BY` in hook_views_query_alter() doesn't work?

Use add_field() with array('function' => 'groupby') parameter.

$query->add_field('node', 'nid', 'node_nid', array('function' => 'groupby'));
$query->add_groupby('node.nid');

Aditional information:

After using add_groupby you might see the next code after GROUP BY:

GROUP BY node.nid, nid

See the next issue: https://drupal.org/node/1578808

To avoid unnecessary GROUP BY conditions add:

$query->distinct = TRUE;


You can convert the script in a Drush shell script.

  A drush shell script is any Unix shell script file that has its "execute" bit set (i.e., via chmod +x myscript.drush) and that begins with a specific line:

    #!/usr/bin/env drush

  or

    #!/full/path/to/drush

Drush scripts are better than Bash scripts for the following reasons:

They are written in PHP
Drush can bootstrap the site before running the script

The following is the example you can find on helloword.script.

#!/usr/bin/env drush

//
// This example demonstrates how to write a drush
// "shebang" script.  These scripts start with the
// line "#!/usr/bin/env drush" or "#!/full/path/to/drush".
//
// See `drush topic docs-scripts` for more information.
//
drush_print("Hello world!");
drush_print();
drush_print("The arguments to this command were:");

//
// If called with --everything, use drush_get_arguments
// to print the commandline arguments.  Note that this
// call will include 'php-script' (the drush command)
// and the path to this script.
//
if (drush_get_option('everything')) {
  drush_print("  " . implode("\n  ", drush_get_arguments()));
}
//
// If --everything is not included, then use
// drush_shift to pull off the arguments one at
// a time.  drush_shift only returns the user
// commandline arguments, and does not include
// the drush command or the path to this script.
//
else {
  while ($arg = drush_shift()) {
    drush_print('  ' . $arg);
  }
}

drush_print();

You can made the script executable, so you can  execute it with <script file> <parameters> where <script name> is the script name, and <parameters> are the parameters passed to the script; if the script is not executable, you call it with drush <script name> <parameters>.


Core Update: Which Is Safer, Patching or Drush?

At the end of the day, by whatever method you use, what you have accomplished is changing the code on your Drupal site.  In theory, both methods you mention should produce the same result.

What I recommend is that you first upgrade and test on a dev machine, and then, once you have tested everything and are convinced that the set of code files that you have is correct, move those exact files to production.  There are a number of ways you can do that.  Some people like to commit all of the files to git, and then use git push / git pull to deploy.  Rsync is another common way to move the code files over.  Then, you just need to run updatedb (unless you determined in testing that there are no updates required), and bring your site back online.

So, in summary, "safer" depends on your deployment plan, not your upgrade technique.


Hiding Superfish Dropdown on Specific Menu Item

I ended up solving my problem by setting the url pattern for Articles to "news/[node:title]". I then used Menu Trails to highlight the News menu item based on the url path.

Now the "News" link will automatically be highlighted when viewing individual articles. Hopefully that helps someone else!


How to correctly remove a module in a staged environment?

Be very careful about keeping your database and code in sync; as you mention in your question, the modules to be uninstalled need to stay in the code base until their uninstall hooks are run on the live database.  This is a limitation of Drupal that a git pull workflow alone is not going to solve.

I would recommend that instead of attempting to adjust your process, you instead look for ways to reduce the downtime required to process your updates.  I would recommend setting up a ying / yang multisite staging environment to solve this problem.  n.b. I have not used the scripts contained in the preceding link; you may wish to set things up differently, following the same idea that you can swap your live and stage sites during deployment.

Continue to follow the same procedure you outlined in your question with the following adjustments:

a. Sync from dev to stage (yang) as usual. Test by doing an uninstall of the modules to be removed followed by code removal, etc.  Git workflow notes: create a tag or note the hashid of the different states of your code: all modules in place prior to uninstall, code modules removed, your overrides & c. removed, etc. as needed.  Perhaps only two references are needed.

b. When testing is complete and accepted, restore the code on stage (yang) to the state of live (ying).

c. Prepare the live (ying) site for update by disabling any user's ability to change content on the system. An sql update to the permission table will usually do here. At this point, users will still be able to read content on the live site, but will get a permission denied error if they try to update content. (If you are cool, perhaps you could change the permission denied handler to print an appropriate notice that the function is temporarily unavailable).

d. Now push the live (ying) database back to stage (yang) database, excluding the permissions table from the update.

e. Repeat step a. again.  If you have your hashtags handy, it should be easy to restore to the state where the modules to be removed exist, run the uninstall hooks on the database, and then advance back to the state of the code where your items from step 1 are merged back in.

f. You are now ready to swap ying and yang. Do this by adjusting your Apache configuration directives. Note that if you do an /etc/init.d/apache restart, some connections may be dropped, but /etc/init.d/apache reload will allow for a clean swap.

g. Live is now 'yang'; the permissions table is unmodified here, so users can create content.  If you automate steps e. and f., the time unavailable should be very low.

h. Push live (yang) back to stage (ying), both code and database -- or push from dev, as needed. You now have a clean environment ready for your next iteration.


I can't comment yet, or I would to inquire further about your use case.

Instead, I'll just provide an answer in hopes it helps.

Do you absolutely need to use a template file? In Drupal 7 Views 3, there are options for each field to customize the html for the field label and value if desired. See attached view field style settings to see how this is configurable.

Optionally, you can set the html to none and rewrite the output to include your specific markup. See second attachment.

Hope that helps, Jason.


I found from my seniors that these configurations (in this case GMap configurations) are stored in variables and Strongarm module can be utilised to export them. After enabling Strongarm module, these variables will be available for exporting under Strongarm Feature Component in Features UI. The other system/environment on which these variables need to be imported will also need to have Strongarm module enabled.
Though these configurations were exported from my system and imported on the other system properly, the map still didn't show up on the other system, the reason being that the devel generate module which we were using to generate content of Contact content-type was unable to generate dummy latitude and longitude for the Location field (enabled through Location module). I entered those latitude and longitude values manually, saved the changes and vola! the map was rendered.
Note: In my case, I wasn't using a Google Maps API key so that wasn't a problem.


How do I use a newer version of jQuery with Ubercart shipping quote (Ajax)?

As it turns out, Ubercart will NOT work with jQuery after 1.2.6 unless you make a small change to an Ubercart module

ubercart/shipping/uc_quote/uc_quote.pages.inc

Go to around line 70 which should be the end of the uc_quote_request_quotes function

comment out or replace the broken drupal_json($return_quotes);

replace it with the standard PHP json encoder
print( json_encode($return_quotes) );


Convert Acquia Clear Varnish For One URL Curl Command to Drupal::httpClient()

I found the solution: https://docs.acquia.com/cloud-platform/performance/varnish/manually-purge/#manually-clearing-caches-for-applications-using-ssl
PHP way:
    $varnishUrl = 'https://bal-' . $elbDomain . '.prod.hosting.acquia.com' . $nodeUrl;
    $curl = curl_init();
    curl_setopt($curl, CURLOPT_URL, $varnishUrl);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($curl, CURLOPT_CUSTOMREQUEST, 'PURGE');
    curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
    $headers = [];
    $headers[] = "X-Acquia-Purge: {$xAcquiaPurge}";
    $headers[] = "Host: example.com";
    curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
    curl_exec($curl);
    $code = curl_getinfo($curl, CURLINFO_HTTP_CODE);
    if ($code == 200) {
      return $code;
      curl_close($curl);
    }
    $errorMsg = curl_getinfo($curl);
    \Drupal::logger('module_name')->error(json_encode($errorMsg));
    curl_close($curl);

Drupal way:
    $varnishUrl = 'https://bal-' . $elbDomain . '.prod.hosting.acquia.com' . $nodeUrl;
    $options = [
         'verify' => false,
         'headers' => [
           'X-Acquia-Purge' => $xAcquiaPurge,
           'Host' => 'example.com',
         ],
       ];
       try {
         $client = \Drupal::httpClient();
         $response = $client->request('PURGE', $varnishUrl, $options);
         $code = $response->getStatusCode();
         if ($code == 200) {
           return $code;
         }
       }
       catch (RequestException $e) {
         watchdog_exception('module_name', $e);
       }


Display Suite Extras module (part of Display Suite) has an option to do that.


This video should sort you out. You need to use the hook form alter
http://www.youtube.com/watch?v=xYMd6WDqxKY


How do I change the uploaded file name after the node has been saved?

Perhaps this will help you.  Last night I wrote a code which is meant to auto-generate a file and attach it to the node.  When the node is about to be saved, the function removes the uploaded file from the node and creates and attaches the new file.

In your case, you might be able to just update the file name with file_copy and resetting the filefield.

    function MODULE_node_presave($node) {
    /*
    *  Out with the old - detach file object
    */

    if (isset($node->field_filefieldname['und'][0]['fid'])) {
     file_delete(file_load($node->field_filefieldname['und'][0]['fid']));
    }
    unset($node->field_filefieldname['und'][0]);  //just for good measure

    /*
    *  In with the new
    */

    $filename = 'newfilename.dot';
    $filepath = conf_path().'/files/yourpath/';
    $touchout = $node->title;

    $tempFile = file_directory_temp().'/'.$filename;

    file_put_contents($tempFile, $touchout);

    $file = (object) array(
        'uid' => 1,
        'uri' => $tempFile,
        'filemime' => file_get_mimetype($tempFile),
        'status' => 1,
        'display' => 1,
      );

   /*
   *  File save operation, puts file in /sites/default/files and records update in db
   */

    if (file_prepare_directory($filepath, FILE_CREATE_DIRECTORY)) {
     $file = file_copy($file, 'public://path/'.$filename, FILE_EXISTS_REPLACE);
    }

   /*
   *  Reattaches our severed file, good as new.
   */

    $node->field_filefieldname['und'][0] = (array)$file;
    }
    ?>


How do I post JSON data on a remote resource?

Quite a few ways to do that, but here's one approach using the queue api, for async processing:

Add the items to a queue on save.
Add a queue worker to process the queue and send the items to the remote service.

If you use a cron queue, you can process them automatically via cron.
More info:

https://api.drupal.org/api/drupal/core!core.api.php/group/queue/8.8.x
https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Annotation%21QueueWorker.php/class/QueueWorker/8.8.x


How to active payment pane in Commerce Kickstart?

I think you are looking for Commerce Checkout Pane Payment or Commerce Checkout Pages.

Commerce Checkout Pane Payment Module Feature:

This module creates a Checkout Pane that shows the selected payment method on the review page of the checkout. This is a contrib module for Drupal Commerce.
Drupal Commerce Contrib. This module creates a Checkout Pane that shows the selected payment method on the review page of the checkout.

Commerce Checkout Pages Module Feature:

Commerce Checkout Paages gives site administrators the ability to create additional pages for the checkout process through the admin user interface.


Currently, Commerce Discount doesn't support specific times in it's discount rules.

You could use PHP evaluation to make this work, though.


How to create a related page or content type with in an existing custom content type?

If your concern is merely visual, you can use Fields to separate the different buying options then use Field Groups to separate them using, for instance, an accordion. You could then use javascript to control/open/close the items on the tabs.


How can I set specific download URI for file?

The proper solution is a hook_menu, which I believe is also going to be a requirement to make this reasonable when several sites want separate names.

I workaround would be to just symlink it to your Drupal root.

ln -s sites/example.com/files/somefile.xml some.xml

But if it's a requirement to have each filename only available on one domain, apache would need to have logic to block the "wrong" names, which is inconvenient.

A third possibility would be to rewrite the URL in apache, but I don't exactly know the syntax for this.


change RegEx in filter_url for text field

I think, I got the answer. I added "\$" to the $trail RegEx pattern.

$trail = '[a-zA-Z0-9:%_+*~#&\[\]=/;?!\.,\-\$]*[a-zA-Z0-9:%_+*~#&\[\]=/;-]';

Are there any drawbacks with this solution or is there a better way solving it?


You can achieve this with the Migrate module.  As it has a 'destination' class that deals with User imports for you.

The easiest way is to import into your database and use the 'MigrateSourceSQL' class as your 'source.

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


Memory-saving cache-clearing strategies for large sites?

Is there any intelligent and graceful way to clear all caches with Drupal besides simply clicking the button in the UI, or using drush cc all?

The cache actions module does that. It depends on rule. For exampple, you can setup a rule to clear a specific view when a node of type "x" has been added or updated. Checkout the docs for more details.

Also take a look at the cache graceful module - haven't tried it yet but looks interesting.


How to get 'base theme' information about a theme?

You can get the details of a theme by using ThemeHandler::listInfo().

$child_theme = 'bartik';

$base_theme = \Drupal::service('theme_handler')->listInfo()[$child_theme]->base_theme;

$base_themes = \Drupal::service('theme_handler')->listInfo()[$child_theme]->base_themes;


Remove duplicate data in revision tables in database

You can't unfortunately.

The concept of storing field data and revision data in two different tables is hard coded into entities at the very lowest level.

If you want to change this behaviour you're looking at a major rewrite of the entity and field systems, and I very much doubt there's any way to do it without hacking a fair few of the core files.

The best thing to do is just accept that this is how Drupal stores its data and try to work with it rather than try to get around it.


Module is reported to be missing, but it's present and active

You can not install a Drupal 7 module on Drupal 8. That's not possible.

The module needs to be converted to Drupal 8. Drupal reports the module as missing because the .info file is now info.yml, so Drupal does not find a able_player.info.yml file anywhere and correctly reports the module as missing.


How can I print a referenced media extension

{% set extension = node.field_event.entity.filemime.value|split('/') %}
{% set extensionDot = '.' ~ extension[1] %}

// File name
{{ node.field_event.entity.filename.value|replace({extensionDot : ''}) }}

// File size
{{ node.field_event.entity.filesize.value / 1000|round }}KB

// File extension
{{ extension[1] }}


I am not sure that i fully understood what you want; but if what you need is to give special attributes(ID, class etc.) to menu items, Menu attributes module may help. You also could use CSS3 :nth-child() selector.


Why /Drupal\Core\Form\FormBuilder->renderPlaceholderFormAction is taking so long?

Pretty sure that report is bogus.

That's just an arbitrary method, not a controller. They somehow identify that as the controller for that request but of course that doesn't make sense. That page lists transactions, so complete requests, not single method calls. So some requests take 2s which it incorrectly identifies as this.

Looks like new relic still can't reliably detect the route/controller for a request. Try our new relic module: https://www.drupal.org/project/new_relic_rpm. It reports the route name for the controller, then you'll see what kind of request this actually is.


I need a function to set a menu item's class to active based on if a keyword is in the URL

Something like this in your theme template can work:

function MYTHEME_preprocess_menu_link(&$variables) {
  if (menu_get_object()) {
    $parsed_path = explode('/', drupal_get_path_alias());
    $parsed_link = explode('/', drupal_get_path_alias($variables['element']['#href']));

    if (some_compare_func($parsed_path, $parsed_link)) {
      $variables['element']['#attributes']['class'][] ='active-trail';
    }
  }
}

You will have to implement some_compare_func yourself, or use a regular expression instead of exploding items, to do whatever matching needs to be done.

You can also check which menu the link belongs to (['#original_link']['menu_name'])

This is just a primer to get you going.


Testing Email locally? Could i reroute email to watchdog?

Yes, you can use the Maillog / Mail Developer module.

  Maillog provides an easy possibility to log all Mails for debugging purposes. It's possible to prevent the mails to being sent, so there is no need for an extra mail server to test the mail functionality of other modules or the Drupal core. Additionally you can immediately display the mail through the devel dpm() facility.


What you can do easily is configure how many records are kept at /admin/config/development/logging, you can set it up to 1 million, which is quite a lot.

To disable it completely (which I would not recommend), you could use a module like ultimate cron, which allows to control how often the cron job of each module is called separately.


How to print rest of the form using "without" function in twig while printing custom user field present account array?

try to print it this way it gives you more control :

{# 1.use the attribute to set the form action and other attributes #}
<form{{ attributes }}>
 {{ title_prefix }}
 {{ title_suffix }}

     {# 2.print the form elment using : {{ element.elements.key }} #}

       {{ element.elements.nom }}

       {{ element.elements.telephone }}

     {# 3.print the captcha if you have a cpatcha #}
     {{ element.captcha }}

     {# 4.you need to output a couple of hidden form elements that is required for the form to be submitted properly and securilly#}
     {{ element.form_token }}
     {{ element.form_build_id }}
     {{ element.form_id }}

     {# 5.output the form action (submit) at the end of the form link  #}
     {{element.actions }}

 </form>


I would definitely start by looking at the Migrate module. It has a plugin for MSSQL. Then, with writing some code to extend the module, you can tailor your migration to fit your needs. You can define data sources and targets, extend the migration classes, hook into the migration function, run batch migrations to test, and many other cool stuff. It is also well documented and has a few examples and case studies. You can read the documentation here on how to use and extend the Migrate module to build and/or enhance your migration process.


Does drupal have another module that have the same feature as media watermark?

Try ImageCache Actions Module. I think this will help you...


How do I dynamically include ouput from an external file?

There are a couple of modules that can help with this:

Web widgets (http://drupal.org/project/web_widgets): Embed any other web site content in a widget with a simple widget API.

Iframe_filter (http://drupal.org/project/iframe_filter): you just need to add this filter to an input format and the content you create using that format will be displayed inside an iframe created dynamically.

And other iframe projects: http://drupal.org/project/insertFrame, http://drupal.org/project/iframe_page (only dev version available right now for d7).


Debugging panels visibility rule with custom access check plugin

I found it within a few minutes of posting this question. The issue was in my summary function and my use of placeholder values. Once that was fixed, it was working fine.


No, there is no way you can change theme on this location using themekey.

You might consider to do this in your custom module. Something like this:

function YOUR_MODULE_NAME_init()
{
  global $custom_theme;
  if($_GET['q'] == 'admin/build/blocks'){
    $custom_theme = 'your_theme_name';
  }
}


The best way to migrate content is the Migrate module, in the module page you can find many Case studies with code inside and in the documentation page you will find all the information that you need.

Inside the Migrate module folder you can find the Beer.inc file, which is an example of how you can do simple mappings. For more complicated migrations you can look into Wine.inc.


Filling compound field programatically fails with EntityMetadataWrapperException

I am posting this here in case someone is having the same issue:

I use the tutorial located here to create my compound custom field with multiple columns what I didn't noticed was in the hook_fields_field_info() implementation I should define the type of data the entity will take. To make things worse in the tutorial the author use the example where all the fields he created are text fields, but in my case I have date, decimal and text fields so I had to define each type. I found the solution in this post.

In a nutshell in my hook_fields_field_info() implementation I have to declare the entity property type, but since I am using multiple columns on the field I have to implement a call back function that will allow me to define the property type for each of my columns.

/**
* Implements hook_field_info().
*
* Provides the description of the field.
*/
function field_example_field_info() {
  return array(
  // We name our field as the associative name of the array.
    'field_example_rgb' => array(
      'label' => t('Example Color RGB'),
      'description' => t('Demonstrates a field composed of an RGB color.'),
      'default_widget' => 'field_example_3text',
      'default_formatter' => 'field_example_simple_text',
      'property_type' => 'field_example_rgb', // we add the propert type here
      'property_callbacks' => array('field_example_rgb_property_info_callback'), // we add the callback
    ),
  );
}

Call back function to define each columns type:

function field_example_rgb_property_info_callback(&$info, $entity_type, $field, $instance, $field_type) {
  $property = &$info[$entity_type]['bundles'][$instance['bundle']]['properties'][$field['field_name']];

  $property['getter callback'] = 'entity_metadata_field_verbatim_get';
  $property['setter callback'] = 'entity_metadata_field_verbatim_set';
  unset($property['query callback']);

  $property['property info']['rgb'] = array(
    'type' => 'text',
    'label' => t('RGB'),
    'setter callback' => 'entity_property_verbatim_set',
  );
  $property['property info']['someothervalue'] = array(
    'type' => 'text',
    'label' => t('Some other value'),
    'setter callback' => 'entity_property_verbatim_set',
  );
}

After doing that the following code:

$node = entity_create('node', array('type' => 'MY-CONTENT-TYPE'));
$entity = entity_metadata_wrapper('node',  $node);

$data = array('column_1'=>'value 1', 'column_2'=>'value 2', 'column_3'=>'value 3');

$entity->field_custom_compound_field = $data;

$entity->save();

Worked like a charm.


In modules check for the hook_user_admin_settings_alter, check the form action and change it for the modules implementing those function

$form['#submit'][] = 'module_user_admin_settings_submit';

For reference sample forgot_username module

Instead of this
$form['actions']['submit']['#submit'][] = 'forgot_username_user_admin_settings_submit';,

use this
$form['#submit'][] = 'forgot_username_user_admin_settings_submit';

In my case, forgot_username module breaks the account savings.

Reference : https://www.drupal.org/project/private_message/issues/2905184
Patch : https://www.drupal.org/files/issues/private_message-admin_settings_submit_handler_beta18-2905184-3.patch


How can I set frequency of each content type with the XML sitemap module?

As far as I can see, the priority form field is added to the content type form from xmlsitemap_add_link_bundle_settings(), which is called by xmlsitemap_node_form_node_type_form_alter().

The first function, in the development snapshot, is using the following form field definitions.

  $form['xmlsitemap']['status'] = array(
    '#type' => 'select',
    '#title' => t('Inclusion'),
    '#options' => xmlsitemap_get_status_options(),
    '#default_value' => $bundle_info['status'],
  );

  $form['xmlsitemap']['priority'] = array(
    '#type' => 'select',
    '#title' => t('Default priority'),
    '#options' => xmlsitemap_get_priority_options(),
    '#default_value' => $bundle_info['priority'],
    '#states' => array(
      'invisible' => array(
        'select[name="xmlsitemap[status]"]' => array('value' => '0'),
      ),
    ),
  );

The form field for the priority is invisible when the "status" field is set to 0.


The problem was not that the modules failed to act correctly.  The problem was that the theme I was using did not have any CSS for the active-trail class that is provided.

To be thorough, there are two classes that get applied to menu items.  The active is only for the exact menu that you're at.  The active-trail class gets applied to all the parents of the current menu.


How to emulate all the AJAX functionality when the form is rendered after an AJAX callback?

The #ajax['wrapper'] property includes the HTML ID of a page section that should be replaced (or altered in some other way).
The #ajax['callback'] tells the Form system what callback should be called after the Ajax call happens and the form is rebuilt.

https://www.drupal.org/docs/7/api/javascript-api/ajax-forms-in-drupal-7


Search results only for the current language

The "Advanced" core search has this built in. If you prefer to do this from a theme - you could do it with form_alter. This basically hides the advanced search settings and sets current language as the only language to get results from, in the search block and search page.

Alternately you can just allow users to control which language they want to get results from and simply allow them to use advanced search.

Code for theme:

/**
 * Implements hook_form_FORM_ID_alter().
 */
function hook_form_search_form_alter(&$form, &$form_state) {
  $form['help_link']['#access'] = FALSE;
  $form['advanced']['#access'] = FALSE;
  $form['basic']['keys']['#title'] = '';
  $manager = \Drupal::languageManager();
  $form['advanced']['lang-fieldset']['language']['#default_value'] = [$manager->getCurrentLanguage()->getId()];
}

/**
 * Implements hook_form_FORM_ID_alter().
 */
function hook_form_search_block_form_alter(&$form, &$form_state) {
  $manager = \Drupal::languageManager();

  $form['advanced-form'] = [
    '#type' => 'hidden',
    '#value' => 1,
  ];
  $form['f[0]'] = [
    '#type' => 'hidden',
    '#value' => 'language:' . $manager->getCurrentLanguage()->getId(),
  ];
}


//My code for custom button
function garden_form_alter(&$form, &$form_state, $form_id ){
    if ($form_id == 'webform_client_form_4208') {
        $form['actions']['garden_quote']  = array(
            '#type' => 'submit',
            '#value' => t('Get online estimate'),
            '#submit' => array('garden_custom_submit'),
        );
        $form['#validate'][] = 'garden_custom_validate';
    }
}

//Custom submit handler
function garden_custom_submit($form, &$form_state) {
    $query = db_select('gardenvalue', 'f');
    $query->fields('f', array('total_cost'))
        ->condition('f.meters', 2, '=');
    $result = $query->execute();
    dpm($result);
}

You have spacing errors and identation errors, the condition is not pointing to a field in the table, and you have to dig into the results array to extract the value, as far as I know you only can print results in a form with

drupal_set_message(t('your message', 'success'); instead of dpm hope this help you a little bit...


Remove lingering configuration data in block plugin

There are several options.

You can unset the configuration 'row' in submit:

unset($this->configuration['row']);

You can load each block, remove the item from settings and save it. See https://drupal.stackexchange.com/a/224362/47547 how to load blocks. You can do this in an update hook.

You can export the configuration, remove the lines you don't want from the yaml files and import the configuration again. This would be the best option for a site owner who wants to clean up a single drupal installation.


Getting error 'The requested page could not be found' after https is enabled

The link to my content is lost

So you enabled HTTPS and you can no longer see your Drupal website? It sounds like you have uploaded your Drupal installation in public_html and are now serving content from the private_html folder.

If you are on a Direct Admin installation you can toggle the symlink private_html to public_html configuration That should make sure the correct files are served via HTTPS as well.

Enabling HTTPS

The rewrite rules that ship with Drupal are intended for mix-mode HTTPS (in which case your site supports both HTTP and HTTPS).

If you want the best security, just redirect everything to HTTPS. See the 3rd bullet point of Enabling HTTP Secure (HTTPS):

  For best possible security, set up your site to only use HTTPS, and
  respond to all HTTP requests with a redirect to your HTTPS site.
  Drupal 7's $conf['https'] can be left at its default value (FALSE) on
  pure-HTTPS sites. Even then, HTTPS is vulnerable to man-in-the-middle
  attacks if the connection starts out as a HTTP connection before being
  redirected to HTTPS. Use the HSTS module or Security Kit module, or
  set the Strict-Transport-Security header in your webserver, and add
  your domain to the browser HSTS preload list, to help prevent users
  from accessing the site without HTTPS.

  You may want to redirect all traffic from http://yourdomain.com and
  http://www.yourdomain.com to https://youdormain.com. You can do that
  by adding this to your .htaccess file:

RewriteCond %{HTTPS} off [OR]
RewriteCond %{HTTP_HOST} ^www\.example\.com*
RewriteRule ^(.*)$ https://example.com/$1 [L,R=301]

  Put that below RewriteEngine on.


I strongly recommend you (as a current best practice), to use Drupal8 Composer project

In this case, the root folder is going to contain "web" and "vendor" directories, so you will have to set your apache/nginix vhost for looking the index.php for one directory deeper.


There is a setting in the XMLSitemap admin configuration that lets you set the base domain. Update that value, clear cache, and regenerate the sitemap.


Boost. What does "Minimum Cache Lifetime" mean?

Check out this handbook page describing all settings (for 6.x but still relevant to 7.x):

"On high-traffic sites, it may be necessary to enforce a minimum cache lifetime. The minimum cache lifetime is the minimum amount of time that will elapse before the cache is emptied and recreated, and is applied to both page and block caches. A larger minimum cache lifetime offers better performance, but users will not see new content for a longer period of time."


How to access boolean field in content node template?

Probably the same way as other fields: http://api.drupal.org/api/drupal/modules!node!node.tpl.php/7


You can use Link module to create facebook or twitter url field for your content type.

  The link module can be count to the top 50 modules in Drupal
  installations and provides a standard custom content field for links.
  With this module links can be added easily to any content types and
  profiles and include advanced validating and different ways of storing
  internal or external links and URLs. It also supports additional link
  text title, site wide tokens for titles and title attributes, target
  attributes, css class attribution, static repeating values, input
  conversion, and many more.

For facebook or twitter icon, you need to manage this through css or need to add extra field for icon and display node.tpl.php if there is value for the link field.


Customize admin content type page design

See Drupal 7 Template (Theme Hook) Suggestions

You can do something like page--node--edit.tpl.php or page--node--1.tpl.php

See the available variables in page.tpl.php

Also you can try hook_preprocess_page

<?php
function themeName_preprocess_page(&$vars, $hook) {
  if ((arg(0) == 'node') && (arg(1) == 'add' && arg(2) == 'product')) {
    $vars['template_files'][] =  'page-node-add-type';
  }
}
?>


Create commerce product through web services

I've found the error. Firstable, my drupal commerce installation hasn't product_display content type. I have to add it manually. I don't know why, but It's missing after clean installation. Secondly, the right JSON structure for commerce price section is:

"field_product":{ "und" :
            {  "form": {
                   "commerce_price": {
                        "und": [ {
                           "amount": "1234.34",
                           "currency_code": "EUR",
                           "data": { "components": [] }
                            } ]
                      },
                   "sku":"eeaafe3231aa"
          }

After this change, I can create products display and I can see it on product manage page. Hope It could be useful for other who has the same problem.


View of nodes grouped by tag including not tagged elements

not really sure how you're getting your lists, you mention custom code, and views.... if you just need a list of nodes that have no taxonomy term:

$nodes=db_query('SELECT * FROM node AS n LEFT JOIN taxonomy_index AS ti ON n.nid=ti.nid WHERE ti.nid IS NULL')

will give you that.

you could add a join to the taxonomy_term_hierarchy table and a WHERE clause to determine if the node has a term associated that is part of your vocabulary


Drupal 7 Form API not returning all values into $form_state

Submitted values are flattened by default. To change that, set the #tree property on the container (in this case the form):

$form['#tree'] = TRUE;


Maintaining libraries on a live site without Composer

Well, turns out it is possible, at least in terms of getting modules like Webform and Entity Print working.  Both of these require libraries and many guides on installing them are emphatic that you MUST use composer for them to work.

I managed to get both of them working without using Composer:

Regular libraries such as those used by the Webform module can simply be extracted to the /Libraries folder. Simply create the directories specified in the admin/reports/status report after you instal the Webform module and put each library there.

Here is a great guide on manually installing dompdf (to use with modules like Entity Print) in the /Vendors directory: https://www.drupal.org/project/entity_print/issues/3081358#comment-13667896.

So far, at least, not so hard after all...


Display a block based on the term reference field of the current node

There's possibly an easier way with the References module. In that case it wouldn't even require NAT, but just a View with contextual filter based on the Reference field.


Rules - anonymous users redirected to user/login prevents request new password link from working

Try adding a condition to your redirection rule like this :

Path has url alias
Value : user/password
Negate : True

Edit :

It must be something like this :


hook_preprocess_page for mobile detection

You could use panels and create a variant for mobile and other for non mobile.

the mobile detect module provide a selection rule for that by using
mobile_detect_ctools


Can't modify Content Access in Media Gallery Module

Check the admin/structure/types/manage/media_gallery/access settings page on your site and ensure that the Enable per content node access control settings checkbox is checked and then save.


Can I run bulk update for URL aliases at command line?

You can also use Drush for the bulk update, see this article.


How to restrict node access based on viewer use role and node author user role?

Just tried this in my sandbox.
You can do this by using Content Access together with Rules.
The configuration would go like this:

Activate the following modules: Rules, Content Access and Content Access Rules Integrations (a submodule of Content Access)
On your content type - Event - under Access Control, activate "Enable per content node access control settings"
Create two new Rules:

For content created by a member of the Men role:

Event: After saving new content of type Event
Condition:  User has role(s), Parameter: User: [node:author], Roles: men
Action: Revokes Access to the newly created node for the role men. To do that check all but "women" in the "Role-based access control settings" > "View any content" acl group

For content created by a member of the Women role:

Event: After saving new content of type Event
Condition:  User has role(s), Parameter: User: [node:author], Roles: women
Action: Revokes Access to the newly created node for the role women. To do that check all but "men" in the "Role-based access control settings" > "View any content" acl group

Once these Rules are in place, any new content of type Event will have an ACL configuration (per node) that will block members of the same role and allow members of the opposite role to view it. You would probably need to tweak this more to match your goals but this should get you going.

Hope it helps!


If you are using Taxonomy Menu then definitely there is a bug in it. And here is a the Link to define the reason.


Printing the correct date value in a view

Double check that your site's timezone is accurate at: Site Configuration > Date & Time
Double check that your user timezone is accurate in your profile. Perhaps turn off user timezones (on the same admin pages as above.)
Confirm how timezones are handled on the specific CCK field. There are 5 options:
Site's time zone, Date's time zone, User's time zone, UTC, and No time zone conversion.


How to edit a custom region from an Omega subtheme in Drupal 7

You don't need to create another region for that.

You just have to copy the Omega file omega/templates/region--menu.tpl.php
to your subtheme's template folder: MYTHEME/templates/region--menu.tpl.php.

There you can make whatever changes you need.


Add these two date formats (in admin/config/regional/date-time/formats):

M d H:i

Y M d H:i

After that choose above created date formats (in admin/config/regional/date-time)
in

Privatemsg: Current year & Privatemsg: Other years  respectively.


Need rule: if Giftcard used to pay order, then skip PayPal, if Giftcard not used then goto PayPal

Payment methods are enabled via Rules. One of the Rules conditions is to check the balance of an order. Have you not tried adding this to your rule that enables PayPal as a payment method?


Does trusted_host_patterns support sub-directories?

Those patterns are used to check the host passed in the headers, so they cannot contain a subdirectory, since that is not passed as host. See the code in Request::getHost().

public function getHost()
 {
  if ($this->isFromTrustedProxy() && self::$trustedHeaders[self::HEADER_CLIENT_HOST] && $host = $this->headers->get(self::$trustedHeaders[self::HEADER_CLIENT_HOST])) {
    $elements = explode(',', $host);

    $host = $elements[count($elements) - 1];
  }
  elseif (!$host = $this->headers->get('HOST')) {
    if (!$host = $this->server->get('SERVER_NAME')) {
      $host = $this->server->get('SERVER_ADDR', '');
    }
  }

  // trim and remove port number from host
  // host is lowercase as per RFC 952/2181
  $host = strtolower(preg_replace('/:\d+$/', '', trim($host)));

  // as the host can come from the user (HTTP_HOST and depending on the configuration, SERVER_NAME too can come from the user)
  // check that it does not contain forbidden characters (see RFC 952 and RFC 2181)
  // use preg_replace() instead of preg_match() to prevent DoS attacks with long host names
  if ($host && '' !== preg_replace('/(?:^\[)?[a-zA-Z0-9-:\]_]+\.?/', '', $host)) {
    throw new \UnexpectedValueException(sprintf('Invalid Host "%s"', $host));
  }

  if (count(self::$trustedHostPatterns) > 0) {
    // to avoid host header injection attacks, you should provide a list of trusted host patterns

    if (in_array($host, self::$trustedHosts)) {
      return $host;
    }

    foreach (self::$trustedHostPatterns as $pattern) {
      if (preg_match($pattern, $host)) {
        self::$trustedHosts[] = $host;

        return $host;
      }
    }

    throw new \UnexpectedValueException(sprintf('Untrusted Host "%s"', $host));
  }

  return $host;
}


How do I pass an organic groups GID to a view in a pane?

Solved it like this:

Create a "Content pane" view mode of your view, and set "Argument input: Input on pane config".
Create a contextual filter in your view that expects a group ID value.
Enable the "Tokens" display mode for content type with the og_group_ref field. According to here:

Go to "Structure → Content Types → [your content type] → Manage Display".
Click "Custom Display Settings" below the field list, enable the "Token" option and save.
Go to the new "Token" display mode in the horizontal tabs on the top.
For yourog_group_ref field, set "Format: Entity id" and save.

In the Panels configuration of your list, insert your View pane.
In the View pane config form, there will be a single input field expecting a gid value and saying "You may use keywords for substitutions." below. Enter %node:og_group_ref.

How I think it works: Panels allows CTools context keywords when supplying arguments to panels. These context keywords are automatically available for all fields (%node:nid works out of the box) and all defined tokens (examples). But for fields, they evaluate to the formatted field value, such as your group's name. We could change this behavior by defining a token of the same name, and choosing a formatter that outputs the raw value (the number) when that token is evaluated.

References:

This Drupal SO question, providing the basic technique.


PHPUnit errors occur when running drupal-check

The first warning could make you think PHPUnit isn't installed, but since drupal-check is able to tell you that the declaration of Drupal\Tests\BrowserTestBase::setUp() is not compatible with the declaration of PHPUnit\Framework\TestCase::setUp(), that is not the case. If PHPUnit weren't installed, drupal-check would report more missing classes.

PHPUnit is installed, but it's version 9.0.0 or higher version, where:

The PHPUnit\Framework\MockObject\Matcher\InvokedRecorder class doesn't exist (but it's defined in PHPUnit 8.0.0)
The PHPUnit\Framework\TestCase::setUp() method is defined as setUp(): void, while PHPUnit 7 defines it as setUp() (The difference is enough to cause the fatal error.)

So, in short:

The installed version of PHPUnit is at least 9
The Drupal version you installed still requires PHPUnit 7

Notice that, so far, only Drupal 9.x has been updated to PHPUnit 8, and in future it will support PHPUnit 9. Previous Drupal versions still need PHPUnit 7, and eventually they will be updated to support PHPUnit 8.


Issue using search_api_ranges with search_api_ajax

The issue is related to Search Api ranges module. There is already a patch for similar problem.

Kindly check patch at https://drupal.org/node/1987232 or use the updated module. I hope it will help for you.


Use Color Field Value in Views Field Template File

In this use case, I believe inline styles are the way to go. There are methods to write a CSS file in your module or theme, for example, but since users can select, and update at any time, any color code, all situations would be very difficult or messy to manage. Inline styles are not ideal in the grand scope of things, but with multiple users, and multiple hex values reaching the millions, sometimes requirements make our choices for us. And plus, we just want to get it done.

Below assumes the view shows nodes, both fields are on the content type, and the title being styled is the node title, not the views title. This is best achieved setting the view to display content, and utilizing template files for your chosen display mode such as node--content-type--teaser.tpl.php.

node--content-type--rotating-hero.tpl.php:

<section>
  <h1
    title="<?php print render($title); ?>"
    alt="<?php print render($title); ?>"
    <?php if (isset($content['field_background_colour'])) : ?>
      style="color: #<?php print $content['field_background_colour']['#items'][0]['value']; ?>;"
    <?php endif; ?>
  >
    <?php print render($title); ?>
  </h1>
</section>

Here, each .views-row will contain an individual node display, and you can focus your javascript and CSS on those for the slider.

*multiple h1 tags on the same page need to be wrapped in a <section> tag, otherwise, use h2 tags.

*Templates are related to structure and usage. Views templates are for the structure and layout of content aggregation, node templates are the structure of individual entities. Wherever the field (or desired data) resides is the best place to theme template files.

Below assumes you need to style the views title itself...

will need more info about where the color field lives. If user profile, for example, you will need to load the user object to access the field value.

MYMODULE.module:

function MYMODULE_views_pre_render(&$view) {
  if ($view->name == 'view_name') {
    $view->build_info['title'] = "custom title";
  }
}

template.php:

function MYTHEME_views_pre_render(&$variables) {
  if (&$variables['view']->name == 'view_name') {
    &$variables['view']->build_info['title'] = "custom title";
  }
}


Creating a new Workbench view showing recently updated content and its state

I think I figured this out, actually.

Create a new View which lists "Content revisions" (not just "Content"). "Save & continue."
On the View edit screen, open up the "Advanced" right-hand column, remove the "Content revision: Content" relationship from the "Relationships." This causes the View to query the node_revision table, but join the node table in the vid field, which isn't what we want (because node.vid will not always point to the latest revision). Instead, add the "Content revision: Content: The revision NID of the content revision" relationship. Even though this one is also labeled "Content revision: Content," it'll join on node.nid instead of node.vid.
From the Filters section, remove the "Content: Published (Yes)" filter. Replace it with a "Workbench Moderation: Current" filter, set to Yes. Don't relate it to the new relationship we just made ("Do not use a relationship").
When adding entity fields, use the "Content (historical data)" ones instead of just the "Content" ones.

This approach seems to be working for my needs so far.

EDIT: In retrospect, I wasn't quite having the same problem as you were after all, since it doesn't sound like you were wanting to show only one revision per node. But I'll leave my answer up in case someone else eventually finds it useful.


Migrate to node content type with the right user id (migrate module)

You use the sourceMigration() method of the migrate module. You should:

1) Write one migration to migrate old users to the new version of drupal.
2) Then write a migration that moves an old table to the new version of drupal.

In (2) when you setup your field migration it sounds like you've written:

# Field Mappings Docs: https://www.drupal.org/node/1133448
# this maps new <= old field.
$this->addFieldMapping('new_user_id_field', 'old_user_id_field');

When you want to write:

# Search for sourceMigration on this page:
# https://www.drupal.org/node/1133448
$this->addFieldMapping('new_user_id_field', 'old_user_id_field')->sourceMigration('MigrateLegacyUsers');

This then uses a previously run MigrateLegacyUsers migration I described in (1) as the lookup for the new user ID in the new drupal site from the mapping table stored by Migrate for the old_user_id_field created during the MigrateLegacyUsers migration task.

Also note if you possibly have multiple users migrated into the system, say from a drupal legacy system, a wordpress system or LDAP you could write:

`->sourceMigration(array('MigrateLegacyUsers', 'MigrateWordressUsers', 'MigrateLDAPUsers'));`

This means: Find the legacy user id among all these possible prior migrations of Users. The first user_id that matches the requested legacy ID will be used by migrate (so be careful to assure all the user_ids are unique across multiple sources).


CCK field migration reproducibly results in server error on node display

We have now identified the source of the error. The content-migrate process seems to sometimes generate invalid display settings for fields. We have now seen this for two different fields. To identify the offending field, we did the following to debug:

if possible, (you getting at least a drupal error) get a call stack, so that the offending field type and field name can be searched for (grep for 'field')
to repair offending settings: go to admin/structure/types/manage/<data type>/display
set each field <hidden> in the Label column (yes that is odd, but I guess this setting is enough to trigger generating fresh display settings)
Save
set each field back to original Label settings
Save

If you want to find the culprit without stack trace, one could switch each field off, and reload the content.

I am not sure about the reason for why this works, but I suspect serialized data. Drupal uses a lot of serialized strings to store settings in the database, and the deserialization might not be robust against corrupted settings. I don't think this is really a bug in the migration code, but corrupted settings can occur at any time.

So I guess it might be a good idea to re-generate settings, in any case of a display error of custom content.


What is the variable for the human readable name of the node type?

You can use the node_type_load() function to load up the node type object, and then extract the name:

$type_obj = node_type_load($type);
$name = $type_obj->name;

You can integrate with your current code like so:

<?php
  $type_obj = node_type_load($type);
  $human_readable_type = $type_obj->name;
?>

<?php if ($display_submitted): ?>

      <?php print $human_readable_type; ?>

    <?php print $name; ?>

    <?php print $date; ?>

    <?php print $comment_count; ?>

<?php endif; ?>


How do I get product variations in a preprocess function?

$product = $variables['elements']['#commerce_product'];

  $variations = $product->getVariations();

  foreach ($variations as $variation){
      $list_price = $variation->getListPrice();
    // Do something with the variation list price here...
  }


If you have the Locale module enabled, you can translate the string on the page admin/config/regional/translate/translate - just search for Download and the string should appear in the translatable strings.

In order to translate the string you have to open the actual page once to let drupal register the translatable string.


Independent search box for views taxonomy page

You can achieve this in Drupal 7 and 8 using a mixture of modules such as:

Search API

  This module provides a framework for easily creating searches on any
  entity known to Drupal, using any kind of search engine. For site
  administrators, it is a great alternative to other search solutions,
  since it already incorporates facetting support and the ability to use
  the Views module for displaying search results, filters, etc. Also,
  with the Apache Solr integration, a high-performance search engine is
  available for this module.

Then you can use: Search API Autocomplete to accomplish the auto complete functionality you require

  The Search API Autocomplete module in action. This module provides
  autocomplete functionality for Search API searches.

And all of this is managed and is customizable via Views module and having a Search API Server that indexes what you want (Here are taxonomy terms for your case)

If you want to make it easier setting things up you can try Search API Pages

  This module is for creating simple search pages for the Search
  API project, not using Views or any other modules. They can be used
  when a view would be unnecessarily slow or complex, or for quickly
  testing out functionality. They also provide search blocks for
  starting a search from anywhere on the site.


The easiest way to do that in my situation was just adding to node.tpl:

hide($content['language']);


Easiest way to do this would be in a content-type template. You want to create a template for your content type, ex. node--[type|nodeid].tpl.php and add this in your theme folder. In your template, for displaying the boolean field you could use logic like this:

<?php
if ($node->field_boolean_field[$node->language][0]['safe_value'] == 0) {
    print "";
} else {
    print "";
}
?>

This similar question may help as well:

Optionally add image/icon after node title based on boolean content type field?


There are a couple of ways I could think I would approach this issue:

If the changes made by me in the old database are reproducible easily to the new database, I'd go for it first. And in most of the cases if you follow Drupal best practices like using update hooks, alter functions, etc. they could be easily done to the new database by (sometimes) running only update.php
So, I'd recommend to move all the custom changes to the update hooks if you have time. Because, considering that the site is live, you could expect more changes to the database. And your code should be flexible enough; unless off course if you could convince the client to stop updating the live site.
If you are sure no database level changes would be done (which I doubt, Drupal being a database driven framework), you could use some tools for comparing the changes between the two databases. Check this stackoverflow question for list of tools that could be used. Take a diff of the database, find out the tables which have differences. From the tables, find out which entities are added/removed from the database. And then make the changes to as required.
I would not recommend this method over the first.


Large file uploads stop immediately, 404 error

From: https://www.drupal.org/node/97193

  Drupal's limits on upload file size are determined by your server's
  PHP settings (as well as Drupal specified settings that can be set at
  Admin > Site Configuration > File Upload). The default values for PHP
  will restrict you to a maximum 2 MB upload file size.

  On the settings page for the upload module, Drupal calculates and
  displays the maximum file size that you can set based upon two PHP
  settings: 'post_max_size' and 'upload_max_filesize'. Since
  'post_max_size' is the limit for all the content of your post, many
  people choose 'post_max_size' to be a multiple of
  'upload_max_filesize' to allow multiple files to be uploaded, but this
  is not essential. The upload module limits the size of a single
  attachment to be less than either post_max_size, or
  upload_max_filesize, whichever is smaller. The default PHP values are
  2 MB for upload_max_filesize, and 8 MB for post_max_size.

  Depending on your host, changing these two PHP variables can be done
  in a number of places with the most likely being php.ini or .htaccess
  (depending on your hosting situation).

  For example, to increase the limit on uploaded files to 10 MB:

Add the below to the relevant php.ini file (recommended, if you have access). Note that for some hosts this is a system-wide setting.

  However, for hosts running PHP as a CGI script with suexec (for
  example) you may be able to put these directives in a php.ini file in
  your Drupal root directory.
          upload_max_filesize = 10M
          post_max_size = 10M
      Add the below to your .htaccess file in your Drupal root directory.
          php_value upload_max_filesize 10M
          php_value post_max_size 10M

  The PHP documentation states that the memory_limit setting also
  affects file uploading. Generally speaking, memory_limit should be
  larger than post_max_size. If this is an issue, see the page on how to
  Increase memory available to PHP (3 methods)

  Drupal also allows/enforces its own size limits, independently of what
  PHP allows. These are found in Drupal 6 at "Administer » Site
  configuration » File uploads" ( /admin/settings/uploads ). In Drupal 7
  size limit is controlled on per-field basis. The Drupal settings
  cannot be larger than those permitted by PHP, but may be smaller if
  you haven't updated them, so remember to check there also, after
  updating the php.ini.

Also, make sure your permissions are set correctly from your public/private folders you've set Drupal for file handling. The folders are located at /admin/config/media/file-system


There's a section in the docs explaining how to print blocks even if they are disabled. Maybe that's your problem.

Disabled blocks won't be printed unless you suppress access control as follows.
{{ drupal_entity('block', 'block_id', check_access=false) }}

Is working on D9 for me.


Customize login block's position in page.tpl

You can do it like this:

if(!user_is_logged_in() ){
    $userLoginForm = drupal_get_form('user_login');
    print drupal_render($userLoginForm);
}

because drupal_render receives argument as reference..


How do I find out which module handle a GET/POST/PUT?

Menu items (in code)

Drupal module register endpoint with hook_menu(). You can search the endpoint within the project, such as abc. It should stay inside hook_menu() with type MENU_CALLBACK.

You may find something like below.

function mymodule_menu() {
   $items = array();
   $items['abc'] = array(
     'title' => 'Ajax endpoint',
     'page callback' => 'mymodule_ajax_callback',
     ...
     'type' => MENU_CALLBACK,
   ),
   return $items();
}

Menu items (in database)

In database, table menu_router saved all registered menu items. You can lookup the endpoint on path column and find the corresponding callback function on page_callback column.

Modules

There is a number of module which provide UI or APIs for developer creating endpoints. Such as services and RESTful Web Services.


Is there a way to get Views Bulk Operation to place field options in the main VBO exposed dropdown

If you check the "Skip confirmation step" box below the "Change the author of content" action, you can remove the confirmation step.

As for making it a one-click change, that would probably require either extending VBO with another module, or somehow invoking ctools modal windows with VBO. I haven't found any success stories with the latter, but there's this: Ctools Modal + Views Bulk Operations? (drupal.org)


Truncating text instead of wrapping in a view

If you are using Views to do this:

In the Node : Title field, there is a setting to limit the number of characters labeled Trim this field to a maximum length.


how do i create a subscribe or join group link in drupal 7?


Luckily you have figured the harder part, counting the 14 products on user's cart. Second part is easily done, and it's called 'dynamic price calculation' or similar terms if you would like to find further information on google.

Create a rule
Event: Calculating the sell price of a product
Condition 0: (which is very important) Entity is of bundle or Entity has field or else you wont see the second price field added to the product type. It's rules assertion internal stuff and is needed, but somehow it's name is confusing.
Condition 1: If there are 14 or more products in cart
Action: Set the unit price to a specific amount
The value you pass to the action above is simply the price value in the second field!

This page could be useful, Sell Price Calculation / The life of a Price Calculation


Backup & Migrate scheduled backup silently fail

It is because you are using buggy module with known issues. This has nothing to do with BOA nor Aegir. There is a reason why we have removed this notoriously buggy module from BOA recently. You should report any such issues in the backup_migrate issue queue on drupal.org - and you may find them reported already, in fact.

This module may still be useful, but only if you follow its issue queue and use release which happens to work. The regressions rate in this module is way too high for us, so we no longer include it by default. Just one example:
https://drupal.org/node/1997354
and a fix:
https://drupal.org/node/1997354#comment-7426824


Is there a way to exclude the addthis module's output in the $content variable?

You can unset or alter items in $node->content by implementing hook_nodeapi() and using the 'alter' $op.


The only function that invokes hook_library() is drupal_get_library(), which is then called by drupal_add_library(), the function that modules call to add a library during a page request. Until one of those functions is not called, hook_library() is not invoked.


Using a view result as allowed_options in a text(list) field

Here's what I ended up with...

function hnbuilder_fheq_allowed_values(FieldStorageConfig $definition, ContentEntityInterface $entity = NULL, $cacheable){
    $node = \Drupal::routeMatch()->getParameter('node');
    //kint($node->bundle());
        if ($node instanceof \Drupal\node\NodeInterface) {
            $thisnid = $node->get('nid')->value;
            if($node->bundle() != 'qualification'){
                $nid = $node->get('field_qualification')->target_id;
                }
        }
        $args=[$nid];
        $values = [];
        $view = Views::getView('outcomes');

        if (is_object($view)){
            $view->setArguments($args);
            $view->setDisplay('default');
            $view->execute();
            foreach($view->result as $rid=>$row){
                foreach ($view->field as $fid => $field ) {
                    $values[$rid][$fid . '-value'] = $field->getValue($row);
                    $my_options[$values[$rid]['field_fheq_code-value']] = "[".$values[$rid]['field_fheq_code-value']."]- ".$values[$rid]['field_fheq_description-value'];
                }
            }
        return $my_options;
    }
}


D8 makes fewer assumptions about what you need in the page, so the Drupal JS library isn't included unless it's specified.

Just add

- core/drupal

as one of your library's dependancies, rebuild the cache, and all should be well.


Why would all theme background colors disappear after moving to different server?

First , Check Administrator -> Configuration -> Media -> File System to personalize your tmp path. Make sure to use relative paths and have the right privileges for your webserver.

After than Check permission of the /sites/default/files and make sure it's writeable by your web server.


how to add cck field to a content type Programatically in drupal 7?

The main functions of the Content Creation Kit (CCK) have migrated into core in Drupal 7. Now every object used by Drupal (users, nodes, even taxonomy terms) are "fieldable entities." What does this mean? Simply that you can add fields to most objects in Drupal out of the box, no CCK required!

If you're building a module that alters pre-existing node types, you'll need to check out the Entity API. I'm not too familiar with it myself, however, it doesn't seem that hard to programmatically add fields. As Bojan Zivanovic mentioned, there are many other answers dealing with this on Drupal StackExchange, here are a few for you to peruse:

- Programmatically Creating Fields in Drupal 7

- Assign Fields Programmatically to Custom Node in Custom Module

If you're just adding fields to nodes for site building purposes, I'd just use the UI.

To do so...

Go to the "Structure" menu.
Select "Content Types."
Click on "Manage fields" next to the content type you want to add fields to.

You should then be presented with an interface to add new fields to your content type, much like you did with CCK in Drupal 6.


how to select different colorbox styles for different content types in drupal 7?

There is no way to do it from admin UI.
Formatter settings also has no option to select style for current image display.

But you can try the following:

function [themename]_preprocess_node(&$vars) {
  if ($vars['type'] == 'node_type' && $vars['view_mode'] == 'full') {
    variable_set('colorbox_style', 'stockholmsyndrome');
  } else {
    variable_set('colorbox_style', 'default');
  }
}

Yep, it's dirty hack, but it can helps... maybe... =)


There is already a Gravatar module out there. I think you would be better off using a vetted, bug tested code than having to build it yourself. Once you have it installed, you can use the function gravatar_get_gravatar($mail, $options = array()) to do exactly what you're wanting.


Create a log when user join/abandoned in a og group in Drupal 7

Heartbeat module is the one to try.

I didn't tested it myself, but I read in its description that it's "an API to log activity".

It seems to support OG activity.


What is the best way to update/add paragraphs with REST on a node

https://www.drupal.org/project/entity_reference_revisions/issues/2848878 is an issue that allows to embed paragraphs on a field directly into the main resource.

We developed and use it exclusively for the use case of default_content with hal_json. It will likely not work out of the box with REST and patching/updating entities. But you're welcome to use it as a first step towards that, patches based on that are welcome.


How to re-publish nodes after unpublishing with hook_cron?

Try to disable access checking in the second run, because after unpublishing the node you might no longer have access to them (depending on the user account the code runs with):

$nids = \Drupal::entityQuery('node')
  ->condition('type', 'event')
  ->accessCheck(FALSE)
  ->execute();


To keep it simple,
Content types, Feeds, Webforms are like data input.
Views is like data output.

Views are specifically used to display the content nodes, feeds, etc. in various formats and can generate reports and exports. But You may also embed views in content types for example to keep track of previous data while entering new data.
Content types are used to input the data and we may also use feeds to import bulk data from csv or other file formats.


You should be able to log in by going to http://example.com/user directly (or http://example.com/index.php?q=user if clean URLS are turned off).


I think the theme key module might be just what you need. From the module's page:

  ThemeKey allows you to define simple or sophisticated theme-switching
  rules which allow automatic selection of a theme depending on current
  path, taxonomy terms, language, node-type, and many, many other
  properties. It can also be easily extended to support additional
  properties exposed by other modules. In combination with Drupal's
  theme inheritance you can easily achieve features like:

individually-styled channels
a front-page / "splash" screen a
date/time-selected Christmas
theme mobile themes for different auto-detected mobile devices
special themes for "limited" or "old" browsers
content, user, or role -specific themes indicating your
environment (production, staging, testing, sandbox, … ) testing your
redesign safely on a live server

And many more. https://www.drupal.org/project/themekey


How to SimpleTest a module's use of drupal_alter() or module_invoke_all()?

You can create a test module and place hidden = TRUE in the .info file.

This will hide the module in the user interface but you can still enable it in your setUp() method.

See http://drupalcode.org/project/drupal.git/blob/refs/heads/7.x:/modules/file/tests/file_module_test.info for an example.


Response comes after 6 min while creating user using services module of Drupal 7?

It's unlikely that your site needs 6 minutes of CPU time to create a user but you can confirm that checking the system load during the process.

When I've faced that kind of problems the reason was one or more timeouts when trying to connect to an external service from the server.

For example, imagine that when you create the user the site querys an external database via an HTTP connection checking for the user usual nickname (Abigail → Abbie, Peter → Pete, etc). If that external service is down your site happily will launch the connection, waiting patiently the answer until the timeout is reached and connection is closed. If your site tries to connect six times and system timeut is 30 seconds then there you have your six minutes for use creation.

Check your installation for modules that may conenct to external services, check dblog for timeouts errors messages, check system log for similar messages. Disable any suspicious module and try to create a user.

If this only happens when using Services (not in the regular user creation form) narrow your search to any Services related modules or custom code.


How to change the day and month language?

For multilingual you need to import .po file in your setup. Download .po file from this link just add language prefix at here language_prefix (/en, /hi, /de etc..).

https://localize.drupal.org/translate/languages/language_prefix

Now, add <?php print date('j F Y', $created) ?> simple php data function and add your data formate here.

After you will able to see day and month in your language.

If you wish to make a different format for both language just add this.

<?php if($language->language == "language_prefix") {
  print date('j F Y', $created);
}
else {
  print date('F j Y', $created);
}

Thank you.