How to set the values of some fields depending on the value of a list box?

Below is a sample of a rule (in Rules export format) that you can use as a prototype to answer your question by using the Rules module:

{ "rules_set_field_value_based_on_value_of_selection_list_field" : {
    "LABEL" : "Set field value based on value of selection list field",
    "PLUGIN" : "reaction rule",
    "ACTIVE" : false,
    "OWNER" : "rules",
    "REQUIRES" : [ "rules", "rules_conditional" ],
    "ON" : { "node_presave" : [] },
    "IF" : [
      { "entity_has_field" : { "entity" : [ "node" ], "field" : "field_optionlist" } },
      { "entity_has_field" : { "entity" : [ "node" ], "field" : "field_free_format_text" } }
    ],
    "DO" : [
      { "SWITCH" : {
          "USING" : { "data" : [ "node:field-optionlist" ] },
          "DO" : [
            { "CASE" : {
                "USING" : { "value" : "B" },
                "DO" : [
                  { "data_set" : { "data" : [ "node:field-free-format-text" ], "value" : "B.A.S.I.C." } }
                ]
              }
            },
            { "CASE" : {
                "USING" : { "value" : "A" },
                "DO" : [
                  { "data_set" : { "data" : [ "node:field-free-format-text" ], "value" : "A.D.V.A.N.C.E.D." } }
                ]
              }
            }
          ]
        }
      }
    ]
  }
}

Some more details to further explain the above above sample:

The Rules event I'm using is "before saving content".
In my case I have these fields:

a selection list field with machine name field_optionlist.
a text field with machine name field_free_format_text.

The selection list field actually has 3 possible values, like so:

A (=Advanced).
B (=Basic).
C (=Custom).

As a sample, I decided to set the values of the text field like so:

B.A.S.I.C. if "The selection list field's value is Basic".
A.D.V.A.N.C.E.D. if "The selection list field's value is Advanced".
Leave it unchanged if "The selection list field's value is Custom"

Part of the "clue" to make this rule work is the condition Entity has field. That's also what is mentioned in the Rules UI when you're adding a "data comparison" condition: somewhere it says "The data selector helps you drill down into the data available to Rules. To make entity fields appear in the data selector, you may have to use the condition 'entity has field' (or 'content is of type')". I wouldn't be surprised if that is what you are missing in the rules conditions you tried so far ...

For a video tutorial that illustrates the importance of this Entity has field condition, refer to Data types and data selection, especially what is shown between about 13:30 and 17:30 in that video.

However, to make the above work, and to be able to get this to work with only 1 rule (instead of writing 2 rules, ie one for "Basic", and one for "Advanced"), I also used the "Conditional Rules module. That way you could expand the above prototype to say dozens of different possible values. For a sample using the Rules Conditional module (for which there is not a lot of docu available), refer to my answer to the question "How to prevent a node being saved when using the Rules module?".

Note: the Field Permissions module should help you to make such text field read only.


D8 HTML tags from field converted to special characters when printing variables

It is unsafe to print raw data from a field value.

Instead of using {{ node.field_hours.value }} put this in your node template:

{{ content.field_hours }}

This will print out the field as configured in the view mode. In the view mode you can select a text filter that matches the allowed tags of the ckeditor. In Drupal 8 all necessary text formats are predefined to be used together with ckeditor.


how to be the last hook_page_alter called?

To make your hook last called you can make use of hook_module_implements_alter
like the following:

function MODULENAME_module_implements_alter(&$implementations, $hook) {
  if ($hook == 'page_alter') {
    // Move MODULENAME_page_alter() to the end of the list. module_implements()
    $group = $implementations['MODULENAME'];
    unset($implementations['MODULENAME']);
    $implementations['MODULENAME'] = $group;
  }
}


Easy! When a new Page is created, just change its owner to a different user with appropriate role and permissions. In our case, let's say to admin.

First, install the Rules package, enable Rules and Rules Admin modules.

Navigate yourself to the Rules | Triggered rules | Add a new rule page:

Label: Detach page from creator
Event: After saving new content

Make sure the new rule is active. Save changes and on the next page Add a condition:

Select the condition to add: Content has type
Content types: Page

Save and Add an action:

Select an action to add: Load a user account
User id: 1

Save and again, Add an action:

Select an action to add: Set the content author
User, who is set as author: Loaded user

Done! This changes the node creator and the original author has control over it no more.

As you will see, this is just the quickest solution to your problem. Rules module enables you to go wild and achieve heaps of stuff that you would normally expect separate modules to be put together for. To get the idea, have a look at how I used Rules (in conjunction with Flag) to keep track of Recently viewed nodes in Drupal.

Note that the node creator always has view permission to the node, as long as they have access content, without which CMS wouldn't make much sense. Anyway, to keep track of the original creator, for display or so, you can use the CCK's User reference module.


We never implemented PayPal's direct recurring API, though there should be a patch in the queue to try out if you wanted. The thing to check will be real-time notifications of recurring charge failures and whether or not there's a user interface allowing the customer to cancel. Since it's PayPal, there very well may be from within PayPal itself.

PayPal does offer the ability to create Billing Agreements that you can charge against at later times, but while we included the ability to create Billing Agreements via Express Checkout, it was never fully integrated into the Commerce License Billing suite that we would normally recommend for recurring payment management.

In short, with PayPal your options are limited. If you are able to make use of Commerce Braintree instead, which is a PayPal company, I'd advise doing so, as that module offers a direct integration with Commerce Card on File (and therefore the license billing module).


Certainly, you can call path_set_alias()  (or path_save() in Drupal 7) and set up whatever you want.  You could call these from within nodeapi() (or node_op..... in Drupal 7) and set up your path however you want.  But, I also think that drupal isn't case sensitive, so, 'foo/bar/BAZ' is the same as 'foO/bAr/BaZ' as far as it's concerned here, so, gotta be careful.

ADDITION:

If you want pathauto to do this, quick hack would be to edit pathauto.inc and do this:

  if (true) {
    $foo=drupal_strolower(dirname($output));
    $bar=basename($output);
    $output=$foo . '/' . $bar;
  } else {
    // Optionally convert to lower case.
    if (variable_get('pathauto_case', 1)) {
      $output = drupal_strtolower($output);
    }
  }

where it does just this:

// Optionally convert to lower case.
if (variable_get('pathauto_case', 1)) {
  $output = drupal_strtolower($output);
}

but it's up to you to more refine if(true) otherwise it will do this for every alias.


How to determine reason for unprocessed files in Drupal to Drupal migration

It looks like this poster received an answer from the Drupal-to-Drupal data migration module maintainer over at drupal.org, so for convenience I will post it here:

Source:Issue#2476077: How to determine reason for unprocessed files

  Side issue first - that informational message is coming from some
  contrib module (something search-related, perhaps) and not related to
  migration per-se. Grep your codebase for "Deleted documents from
  index" to see what it might be.

  So, the unprocessed count is precisely the count of source records,
  minus the number of records in the map table (so, you will never find
  an "unprocessed" record in the map table. All processed records are
  recorded in the map table with an appropriate status.

  The first question is, are there really unprocessed records, or is the
  source count off? The most common cause of "unprocessed" records being
  reported is a malformed source query that has more than one row with
  the same primary key (fid in this case) - this can happen when joining
  to another table that has multiple rows per "base" row. Elsewhere
  you've been speaking about extending migrate_d2d classes and modifying
  their queries - could you have done that for the file query, and
  joined to another table?

  The next step is to try to identify specific unprocessed files. If
  your D6 and D7 databases are on the same MySQL server and accessible
  with the same MySQL user, you can do something like:

select d6.fid
from d6.files f
left join d7.migrate_map_myfilemigration map on f.fid=map.sourceid1
where map.sourceid1 is null

  If the dbs are not on the same server, you could try dumping the D6
  files table (or just the fids) and loading it into a temp table on the
  D7 server.


Is there a standard place 3rd party module pages report what PHP version they're tested on?

There is a route for all modules of the pattern https://www.drupal.org/node/{nid}/qa for showing testing reports.  Nightly runs, per-commit runs, and one offs should appear there.

For the module you mentioned, the page is https://www.drupal.org/node/1305958/qa, and it looks like automated tests aren't set up.

The Poll module does show tests, https://www.drupal.org/node/1896974/qa

In general, the default test (if set up) will track the min versions for PHP and MySQL for the chosen core branch.


How to do (unit) testing of Drupal specific JavaScript code?

Right now we don't have any automated testing of the UI. There have been talks about using Selenium and there is even a proposed session about it for DrupalCon London, but i don't know of any work that has been done yet.

This could be a nice contribution for Drupal 8.


Drupal 8 theme showing Uncaught TypeError: $(…).find(…).once is not a function in console

You're loading 2 versions of jquery:
assets/js/jquery.min.js: {}
- core/jquery

That's most likely your issue. Try removing the assets/js/jquery.min.js entry and flushing your cache. That will mean you're just using Drupal's core jquery which hopefully your plugin should work fine with


how to get password as submitted by the user in hook_user_insert?

Any hook that is invoked from user_save() is too late to get the password as entered from the user. In fact, the first lines executed from user_save() are the following ones.

if (!empty($edit['pass'])) {
  // Allow alternate password hashing schemes.
  require_once DRUPAL_ROOT . '/' . variable_get('password_inc', 'includes/password.inc');
  $edit['pass'] = user_hash_password(trim($edit['pass']));
  // Abort if the hashing failed and returned FALSE.
  if (!$edit['pass']) {
    return FALSE;
  }
}

What you can do is adding a form submission handler to the form used to create new user accounts. That submission handler can access the password as entered from the user in $form_state['values']['pass']. I would rather add a form submission handler that is executed right after user_register_submit(), as that submission handler contains the following code.

  if (!variable_get('user_email_verification', TRUE) || $admin) {
    $pass = $form_state['values']['pass'];
  }
  else {
    $pass = user_password();
  }
  $notify = !empty($form_state['values']['notify']);

  // Remove unneeded values.
  form_state_values_clean($form_state);

  $form_state['values']['pass'] = $pass;

I would use the following code.

function mymodule_form_user_register_form_alter(&$form, &$form_state) {
  // Add your submission handler.
  $form['#submit'][] = 'mymodule_user_register_submit';
}

function mymodule_user_register_submit(&$form, &$form_state) {
  // The password is in $form_state['values']['pass'].
}


For a form API element, just set $form['element']['#required'] = TRUE;

More info: #required

  Indicates whether or not the element is required. This
  automatically validates for empty fields, and flags inputs as
  required.

For more control, consider an #element_validate handler

Note, for a custom element using hook_element_info, #validate and #element_validate callback handlers are supported there in the element definition.


How can I reference an entity field in a template file?

Change your hook_theme code to:
function mytheme_theme() {
  return [
    'node_album_edit_form' => [
      'path' => \Drupal::theme()->getActiveTheme()->getPath() . '/scss/templates/album',
      'render element' => 'form'
    ],
  ];
}

and in your template file
{{ form.field_album_title }}


The quickest way I know of is by using Views.
I would create a special "content type" with a special image field, a text field to describe the meaning of the Tag, and a Term Reference field to include the applicable tag later. Then I would enter one image + text for each existing tag and assign it to the tag itself. Later with the help of views I would customize display-views like the one you have mentioned which would take just a few minutes to do.


Render default value of views exposed filter

This may because of the exposed form settings. Change the settings of exposed form to "Basic" if it is "Input required".


Media/file repository - asset autocomplete widget?

You can use Media module to store Images in a specific location,but you cant get the auto complete function with this module but you can select and reuse the old photos from the Image location.

The another good thing using this module is it is already integrated with the Ckeditor.


Views load the whole entity even though they only need 3 fields

Are these custom entities or from a module? If they are custom you could try to override the 'query' or 'load' function in the entity controller class (defined in hook_entity_info() ). If it is from a contributed module, there isn't anything you can do without altering the module code.

Also please note that the actual images are only loaded when the browser requests them over http via an  tag, the entity loads the fields over SQL. Agreed, this creates some overhead. But I guess you would hardly notice the difference when a few fields less are loaded.


Action attribute in forms is not a url. Why?

If you look again, I would hazard a guess that you are using pathauto, and that the default pattern for Webform paths is [node:title]. If you set it to form/[node:title] then the action attribute would look more like a path. eg. My Form would have an action attribute of action="/form/my-form".

In Drupal everything goes through the Drupal bootstrap. There are no calls to cgi-bin or the equivalent. Rendering a form or processing a form are done by calling the same url, which tells Drupal where to look for the form. What Drupal does depends upon the op associated with the call, and the rendering, validation, processing and storage are all defined by the modules underlying the form.


In a Views page with 3 arguments, 3rd argument default PHP being ignored if 2nd argument is not present

Always keep the optional args in the end otherwise define Action to take if argument is not present or at least set Provide default argument in argument configuration form.


How to create a url pattern for a specific node

To accomplish this, you can use Pathauto module. To set a specific path for a specific node, go to admin/modules/pathauto/config and set the path for that specific node in the textbox as you want. For your case use test/[node:title] in the Pattern for all test paths text field.


How add a css id selector to a views row

Solution 1:

No need to add ID for each row, you can achieve it by each row CSS class it self. Instead of document.getElementById("js-fadeInElement"); you can use document.getElementsByClassName("js-fadeInElement");

Solution 2:

You can use Views theme templates to modify the HTML output and add your id attribute.
Under the Advanced section, you will find Theme: information.

  This link will show you possible file name for templates and a sample
  content of that file.

You probably want to copy and modify the "Style output". You can put your custom template in your own theme directory. You probably want a name like views-view-list--your-view--page.tpl.php

Please follow this link to override the template.


How to remove the submit button on the form included by drupal_get_form?

If you look at the function drupal_render it will ignore all elements marked as #printed so just add that to the submit button's array.

You'll need to inspect the $delivery_information_form array to see exactly where your button is at, and when you find it you can do something like this:

  $delivery_information_form = drupal_get_form('sbsl_order_delivery_information_1_form_' . $supplier_id);
  $delivery_information_form['path']['to']['button']['#printed'] = TRUE;

before adding it to the $element array.


node/[nid]/edit does nothing. how to troubleshoot?

My first step would be to watch the request with Firefox's Live HTTP Headers.  This will tell you if the request is actually going out or not.

If it is, then you need to check server logs to see if the request is being processed.  You may also need to add some watchdog() calls in the core node.module to track it down.

If the request isn't going through, then I suspect you have some rogue Javascript that is intercepting the click.  Disable JS and retest.  Another possibility could be that you have a CSS positioned element over the tab, and that is actually catching the click event.  Go through the body with Inspect Element and double check all of that.


The following works with all standard renderers (default/IPE).

There is no preprocess possibility for the regions, so some extra work is needed.

First add the following preprocess function to your template.php of your theme or your own module (change MY_THEME accordingly).

/**
 * Implements hook_preprocess_HOOK().
 */
function MY_THEME_preprocess_panels_pane(&$vars) {
  // Determine if a panels panel (region) is empty.
  // Every pane needs to be checked for content.
  // Set the result on the panels display object.
  if (empty($vars['content']) || (isset($vars['pane']->IPE_empty) && $vars['pane']->IPE_empty)) {
    if (!isset($vars['display']->panel_is_empty[$vars['pane']->panel]) || $vars['display']->panel_is_empty[$vars['pane']->panel] ) {
      $vars['display']->panel_is_empty[$vars['pane']->panel] = TRUE;
    }
  }
  else {
    $vars['display']->panels_is_empty[$vars['pane']->panel] = FALSE;
  }
}

Then you can use the data in the $display->panel_is_empty array in your PANELS-LAYOUT.tpl.php files to conditionally add extra classes. (Change 'PANEL' to the specific region.)

<div class="panel-panel <?php print !empty($display->panel_is_empty['PANEL']) ? 'panel-panel-empty' : ''?>">
  <?php print $content['PANEL']; ?>
</div>


If you are already building a custom field type, you could add properties for the link to your field:

class MyLinkField extends FieldItemBase {

  public static function propertyDefinitions(StorageDefinition $storage) {
    ...
    $properties['title'] = DataDefinition::create('string')
      ->setLabel(t('Title'));
    $properties['url'] = DataDefinition::create('string')
      ->setLabel(t('URL'));
  }

and use it in the field formatter:

class MyLinkFieldFormatter extends FormatterBase {

  public function viewElements(FieldItemListInterface $items, $langcode) {
    $elements = [];
    foreach ($items as $delta => $item) {
      $elements[$delta] = [
        '#type' => 'link',
        '#title' => $item->title,
        '#url' => Url::fromUri($item->url),
      ];
    }
  return $elements;
  }


How do I add a JavaScript file from a module?

You will have to add the js in libraries.yml, like

dirty_forms:
  version: VERSION
  js:
    js/jquery.dirtyforms.js:{}
dirty_forms_ckeditor:
  version: VERSION
  js:
    js/jquery.dirtyforms.ckeditor.js:{}

and then include in the form via

$form['#attached']['library'][] = 'dirty_forms/dirty_forms';


How to expand/collapse text in WYSIWYG w/CKEditor

This worked for me
JS Injector
(function ($) {

$(document).ready(function() {
    // Configure/customize these variables.
    var showChar = 100; // How many characters are shown by default
    var ellipsestext = "...";
    var moretext = "Show more >";
    var lesstext = "Show less";

    $('.more').each(function() {
        var content = $(this).html();

        if(content.length > showChar) {

            var c = content.substr(0, showChar);
            var h = content.substr(showChar, content.length - showChar);

            var html = c + '' + ellipsestext+ '&nbsp;' + h + '&nbsp;&nbsp;' + moretext + '';

            $(this).html(html);
        }

    });

    $(".morelink").click(function(){
        if($(this).hasClass("less")) {
            $(this).removeClass("less");
            $(this).html(moretext);
        } else {
            $(this).addClass("less");
            $(this).html(lesstext);
        }
        $(this).parent().prev().toggle();
        $(this).prev().toggle();
        return false;
    });
$(".morecontent span").css("display", "none");
$(".morelink").css("display", "block");
})
})(jQuery);

CKeditor

      Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

      Morbi placerat imperdiet risus quis blandit. Ut lobortis elit luctus, feugiat erat vitae, interdum diam. Nam sit amet arcu vitae justo lacinia ultricies nec eget tellus. Curabitur id sapien massa. In hac habitasse platea dictumst. Integer tristique leo consectetur libero pretium pretium. Nunc sed mauris magna. Praesent varius purus id turpis iaculis iaculis. Nulla convallis magna nunc, id rhoncus massa ornare in. Donec et feugiat sem, ac rhoncus mauris. Quisque eget tempor massa.


Contextual Links not appearing for blocks

Contextual links are printed with:

print render($title_suffix);

I Have checked it on block.tpl.php

See: Working with contextual links

I would suggest not to put inline css in your template.
Here working code:

<div id="<?php print $block_html_id; ?>" class="<?php print $classes; ?> clearfix" <?php print $attributes; ?>>
  <?php print render($title_prefix); ?>
  <?php if ($title): ?>
    <div <?php print $title_attributes; ?> style="background: #044faa; color: #fff; padding: 5px 15px; font-size: 16px">
     <?php print $title; ?>

  <?php endif; ?>
  <?php print render($title_suffix); ?>

      <?php print preg_replace("/(<)[\/]?[p](>)/is", "", $content); ?>


I managed to do it using the Views module. I create a View of "Aggregator item" type.

In my view, I display each field I want to see, and for the "Aggregator:Title" field configuration, in the "Rewrite results" section, I checked "Trim this field to a maximum length". There are options to set the maximum length, to add or not an ellipsis (...), to add or not a "Read more" link... See the picture for more details (it refers to the "Aggregator:Body" field, but it works the same way).

Hope that helps,


Assuming that your template file is in a subfolder of your module folder (it looks like it's in templates), then your hook_theme needs to define the path. So it should look some thing like:

function gq_theme($existing, $type, $theme, $path) {
  return array(
    'gq_form' => array(
      'path' => $module_path . '/templates',
      'variables' => array(
        'first_name_field' => $form['field_first_name'],
      ),
    ),
  );
}

where $module_path is the path to your module.


How put a product display on the "Shop" not the "Home" page?

If I understand you correctly, you want to tell Drupal to use a different node for the home page.   If this is what you mean you can do this by going to

Home -> Administer -> Site Configuration

You can change the node for the Default front page there.


hook_libraries_info(), documented in libraries.api.php, is just a hook that informs the Libraries API module of any existing external library. Its purpose is not loading those libraries when a Drupal page is shown; for that, the module needs to call libraries_load() (defined in libraries.module) when necessary.

libraries_load_files() is the function that actually load in the page the CSS and Javascript files, respectively with drupal_add_css() and drupal_add_js().

  // Load both the JavaScript and the CSS files.
  // The parameters for drupal_add_js() and drupal_add_css() require special
  // handling.
  // @see drupal_process_attached()
  foreach (array('js', 'css') as $type) {
    if (!empty($library['files'][$type])) {
      foreach ($library['files'][$type] as $data => $options) {
        // If the value is not an array, it's a filename and passed as first
        // (and only) argument.
        if (!is_array($options)) {
          $data = $options;
          $options = array();
        }
        // In some cases, the first parameter ($data) is an array. Arrays can't
        // be passed as keys in PHP, so we have to get $data from the value
        // array.
        if (is_numeric($data)) {
          $data = $options['data'];
          unset($options['data']);
        }
        // Prepend the library path to the file name.
        $data = "$path/$data";
        // Apply the default group if the group isn't explicitly given.
        if (!isset($options['group'])) {
          $options['group'] = ($type == 'js') ? JS_DEFAULT : CSS_DEFAULT;
        }
        call_user_func('drupal_add_' . $type, $data, $options);
        $count++;
      }
    }
  }


As mentioned here drush is not yet completely compatible with PHP 5.4

And regarding the error message you will need to invoke drush from a more [error] functional Drupal environment to run this command , in general cases it means that you are running drush from a location which is not associate to a drupal instance. To be on a safer side go location-of-your-drupal-instance/sites/all/modules and run the command.


Rewrite all needed paths by hook_menu_alter. It is invoked  by menu_router_build().


How do I per-variation add to cart button In Views with no selection?

I finally found the answer from help on this post. here  Although, I still had a few issues and mine ended up being slightly different, so I will lay out what I did to achieve this.

I am using a view table but really any sort of display using fields with grids should work the same.

Install the module Add to cart link
Create a new display on your product variation called what you like I am using 'view' with only the add to cart link field.
In your view add the display type you require.
Add Relationship: variations (Relate each Product with a variations set to the product variation.)
Add Relationship: Product
Add contextual filter: Product: ID - Provide default value Product ID from URL
Add Field Rendered entity - Product variation
Select your display from the view mode.
Save, add your view and output your view to your product page.

Now you will see all the Add to cart buttons displayed for each variation on the product with the right token add to cart link for each.


How to theme all pages after a certain url

You can use THEME_NAME_theme_suggestions_page_alter to create your own template suggestions!

In your theme:

File: my_theme/my_theme.theme

/**
 * Implements hook_theme_suggestions_HOOK_alter.
 */
function my_theme_suggestions_page_alter(&$suggestions, $variables) {
  $current_path = \Drupal::service('path.current')->getPath();
  $current_path = \Drupal::service('path.alias_manager')->getAliasByPath($current_path);

  if (strpos($current_path, 'this-page') !== false) {
    $suggestions[] = 'page__this_page';
  }
}

File: my_theme/templates/page--this-page.html.twig

// Output html and stuff

Obviously replace "my_theme" with the name of your custom theme.

Here is a nice tutorial that expands more on it.


How to programmatically add a field to all product types?

The entity as defined by drupal commerce should be commerce_product:

function commerce_product_entity_info() {
  $return = array(
    'commerce_product' => array(
      'label' => t('Commerce Product'),
      ...
    ),
  );
  ...

  return $return;
}


SVG icons do not show up when remotely connected

Make sure that in your code you dont reference the icon like http://127.0.0.1/sites/default/somepath/youricon.svg but you re using a relative path instead like sites/default/somepath/youricon.svg.


How to find machine module name for `drush dl`?

According to my experience, I know machine names of some commonly used modules,
but basically when it is for new module or when I have doubt in machine name,
I google it the module name, it should provide you with link for drupal project page,

the url will be in the format   https://drupal.org/project/[project-machine-name]

drush dl [project-machine-name]

for multiple module you can do like this

drush dl [project-machine-name1] [project-machine-name2][project-machine-name2] ..


How to remove field from form and configuration?

change this line

->set('enabled_content_types', $form_state->getValue('enabled_content_types'))

to

->clear('enabled_content_types')

In Drupal, go to config form and click save.

Side Note: Alternatively, you could also delete the config via Drupal Console or Drush as mentioned in the answers here, How do I remove a configuration object from the active configuration?

Now you may now remove the relevant code.

public function buildForm(array $form, FormStateInterface $form_state) {
  $mymodule_config = $this->config('mymodule.settings');

  $types = \Drupal::entityTypeManager() // remove
    ->getStorage('node_type') // remove
    ->loadMultiple(); // remove

  foreach($types as $type) { // remove
    $content_types[$type->id()] = $type->label(); // remove
  } // remove

  $form['enabled_content_types'] = [ // remove
    '#type' => 'checkboxes', // remove
    '#title' => $this->t('Enabled Content Types'), // remove
    '#description' => $this->t('content types .'), // remove
    '#default_value' => $config->get('enabled_content_types'), // remove
    '#options' => $content_types, // remove
  ]; // remove

  ...

  return parent::buildForm($form, $form_state);
}

public function submitForm(array &$form, FormStateInterface $form_state) {
  $mymodule_config = $this->config('mymodule.settings');
    ->clear('enabled_content_types') // remove
    ->set('urls', $form_state->getValue('urls'))
    ->save();
  parent::submitForm($form, $form_state);
}


public function validateForm(array &$form, FormStateInterface $form_state) {
  parent::validateForm($form, $form_state);
  $values = $form_state->getValues();
  if ($values['your_field'] == 'some_forbidden_value') {
      $form_state->setErrorByName('your_field', $this->t('This value is forbidden!'));
   }
}

About setErrorByName().


More multiple add to cart buttons drupal commerce

It appears that you're looking for something that is decribed in detail in Multiple products per Add To Cart form (product kits/packages) also.
And that issue is what was the inspiration for the Commerce Product Bundle module (available for D7, but only as an alfa version for now). Here is a excerpt from its project page:

You can define products that consists of other products. They are all combined in one add to cart form. The form works like the core add to cart form with all the fancy selection and ajax magic. So the customers can make their selections as usual. The difference is, that the products from mulitple reference fields were presented on one add to cart form.
The bundle is then represented by one order line item. This allows the maximum compatibility with other modules such as shipping or payment modules.


Files are created in the directory whose name is returned from file_directory_temp() which returns:

The value of the Drupal variable "file_temporary_path," which is set from the setting page on admin/config/media/file-system (Drupal 7) or admin/settings/file-system (Drupal 6).
If that Drupal variable is not set, then the function checks one of the following directories; if one of those directories exists, then it is returned (and used).

the directory returned from ini_get('upload_tmp_dir')
on Windows, the directories "c:\windows\temp" and "c:\winnt\temp."
on OSes different from Windows, the directory "/tmp."
on PHP version 5.2.1 or higher, the directory returned by sys_get_temp_dir().

If the variable "file_temporary_path" is not set, and the directories I listed in the previous point don't exist, or are not writable, the function uses the value of the Drupal variable "file_public_path"; by default that directory has the value conf_path() . '/files' that is the directory "files" contained in the directory containing the setting.php file used for the Drupal site.

The function set the variable "file_temporary_path" to the directory it found.

As far as I know, any module opens temporary files using a path starting with "temporary://" (available only in Drupal 7 and higher) or uses file_directory_temp(). The directory returned from file_directory_temp() can change from system to system, but modules always use that directory.

Drupal modules don't have the permission to write the directory containing the modules; it's quite difficult a module uses that directory to create temporary files. If you find a module that uses the directory containing the modules (or any sub-directory of that directory) report that as a bug.


Use createFilter to build an advanced query using AND and OR with the search API

This should be possible:

<?php
$or1 = $query->createFilter('OR');
$or1->condition('field_last_name', 'name');
$or1->condition('field_first_name', 'name');
$query->filter($or1);

$query->condition('field_postal_code', 'zip');
$query->condition('field_city', 'city');

$or2 = $query->createFilter('OR');
$or2->condition('field_interests', 'keywords');
// if field is fulltext, the default '=' operator is interpreted as 'contains'.
// to search over all fulltext fields: $query->keys('keywords')
$or2->condition('field_hobbies', 'keywords');
//...
$query->filter($or2);
$query->sort('field', 'ASC');
$query->execute();

But IMHO and unfortunately you won’t be able to further nest queries/filters like AND ((field1 = 1 AND field2 = 1) OR (field1 = 2 AND field2 = 2)). I’m going to open another thread for this problem.


Adaptively Displaying Images Inline Drupal 7

I was finally able to get AIS working for adapting with inline images and shadow box. It can be done through Wysiwyg (see here for instructions: http://drupal.org/node/1555376)  or I just insert this code in the image tag: class="adaptive media-image attr_typeof_foaf:Image img_fid_1172 img__view_mode__media_adaptive attr_format_media_adaptive" typeof="foaf:Image". From what I can tell none of the other adaptive modules can do this. I checked it in Adaptive Image and it does not do inline images. An example of this working can be seen at: http://173.236.7.153/~ssanalyt/drupal/consulting-areas/business


Use Context to load JavaScript on certain pages

The Context Add Assets module does exactly that :)

Taken from the README

  Supports adding active theme files to page via context

I've used 7.x-1.0-beta1 with no major problems, so don't be afraid that there's no full release :)


Why did upgrading Drupal 6 cause a huge increase in database traffic?

Apart from the NewRelic suggestion, which I put in a comment, consider reproducing this issue in a second environment, I assume you do have a staging/testing environment of the site, or at least a local installation. If not, you should get one ;)

Then you can install the devel.module, enable query logging and/or xhprof profiling. Then you can actually switch between the old version and the new one and compare the difference within Drupal. Devel's query logging will tell you exactly which queries are executed and how long they took.


How to add additional "items" on a webform in Drupal 7

The module Webform Add More does similar thing,

  Webform Add More enables selected fieldsets to be initially hidden and
  progressively shown with an Add more button, mimicking CCK multiple
  fields. The approach was proposed by Bartezz, and code originally
  implemented by span and kranklin 1. This module adds a checkbox
  setting to webform fieldset components to select which should have Add
  more functionality, as well as an advanced setting to override the
  button label per Webform.


Can I use Emoji as icon in navigation bar?

Can't help with the PDO exception, but .. Have you looked at IconAPI ? It has a sub module for use with menu items which doesn't cause overlapping as you described.

You can then use Fontello as an icon provider and create a font set from the emoticons there, or import your own emoji icons into Fontello and download them as a font set.


How can I display a taxonomy term's ancestral tree on a content page?

2 possible solutions: a) programmatically via an own custom module providing a custom formatter or via a custom theme function. Or b) via contrib modules providing a field formatter to view the whole term path instead of only the end point (default).

In your case I assume you ask for the second. The module Hierarchical select used to provide this view widget (field formatter) in D7 and maybe alternative modules like SHS or CSHS in D8 will provide it? If not, you can try to work with the Custom formatter module, which enables you to build own formatters in admin UI without creating own modules for this purpose. It comes with examples showing how it works, and it can be used even if the user has no advanced module development knowledge.


The mentioned Module Composite Views Filter was extended by it's maintainer. It is still in patch-test-phase, but it is working now to bring in as much filter groups as you like.

  Allows you to create one filter condition that enables a bunch of filter conditions. Sometimes one condition isn't enough for your filter, but you still want the user to be able to change the filter (group).


Customizing taxonomy Term page with sticky articles

You can create a custom module and implement hook_menu_alter for taxonomy terms.

In your custom callback you then filter by your taxonomy and intercept the ones you want and pass the rest to the default handler.

On the ones that you intercept you then render a custom view for that taxonomy. That view will just be a normal default view (no page) with an attachment as well. You set the attachment to the top of the other view and show teasers. The other view will show links only with an offset to not show the teaser nodes as well. Your view will be constructed with appropriate contextual filters that you will pass.

Your MODULE.module file:

function MODULE_menu_alter(&$items){
  // change taxonomy view path for certain vocabularies
  $items['taxonomy/term/%taxonomy_term']['page arguments'][] =   $items['taxonomy/term/%taxonomy_term']['page callback'];
  $items['taxonomy/term/%taxonomy_term']['page callback'] = 'MODULE_taxonomy_term_callback';
  $items['taxonomy/term/%taxonomy_term']['file path'] = drupal_get_path('module', 'MODULE') . '/includes';
  $items['taxonomy/term/%taxonomy_term']['file'] = 'MODULE_callbacks.inc';
}

Your MODULE_callbacks.inc file (located at MODULE/includes):

function MODULE_taxonomy_term_callback($term, $callback) {
  $function = __FUNCTION__ . '_' . $term->vocabulary_machine_name;
  if (function_exists($function)) {
    return $function($term);
  }

  module_load_include('inc', 'taxonomy', 'taxonomy.pages');
  return $callback($term);
}

// one for each vocabulary
function MODULE_taxonomy_term_callback_TAXONOMYVOCABULARYMACHINENAME($term){
  $view = views_get_view('VIEW_MACHINE_NAME');
  $view->set_display('default');
  $view->set_arguments(array($term->tid));
  $view->pre_execute();
  $view->execute();
  return $view->render();
}

You View(s) will be as follows:

Contextual filter: Content (taxonomy in question)

When the filter value is not available

Provide default value: Taxonomy term ID from URL
Load default filter from term page.


How to create the slideshow as the background slideshow using drupal 7?

You can try using the Vegas Background jQuery Plugin module.

  Vegas is a jQuery plugin to add beautiful fullscreen backgrounds and slideshows to your webpages.

Try out the module demo.


Select previous/next nodes of same content type programmaticaly in Drupal 7

Clive is right.
But $prev_nid is looking for the first node in the table.
So you could add an ORDER BY, like this:

$prev_nid = db_query("SELECT nid FROM {node} WHERE type = 'my_type' AND created < :created ORDER BY created DESC LIMIT 1", array(':created' => $node->created))->fetchField();
$next_nid = db_query("SELECT nid FROM {node} WHERE type = 'my_type' AND created > :created ORDER BY created LIMIT 1", array(':created' => $node->created))->fetchField();


Drupal allows your site to have many Themes installed. Themes can define their own HTML structure to make your site look a certain way. Drupal has a few themes the ship out-of-the-box.

Depending on the theme you use it may or may not contain HTML classes or ids in the source to easily target specific items on the page. Typically, themes and Core html is fairly darn flexible.

Looking at the Zen Theme HTML and CSS markup you can see it has fairly specific rules to get at and theme alot of the content from Zen and also core drupal themes: Useful CSS selectors to add to your stylesheets


Registration form in a popup window (colorbox or jQuery ui)?

There's already a module for that, Ajax Login/Register:

This module provides a smooth way for the user to login, register and request new password via AJAX at any Drupal site.
Features:

This module provides a block with 2 links (Login, Register) for the anonymous user.
When the user clicks on Login or register the requested form appears in a nice ajax popup.
The login and register forms can validate using ajax and not redirect on error.
On success the module redirects to the user page.
When user is logged in, the block provides a Welcome !username message and a link to the user page and a logout link.
This module integrates the thickbox plugin with the Ajax module and provides a simple, easy to use and cool login and register block.


Change the 'insertElement' function for 'insertHtml' function

editor.addCommand('phpcode', {
  exec : function() {
    editor.insertHtml('
<?php echo "hello"; ?>
');
  }
});

Hope it will be work.


Facebook Share the older version of the article

Use Facebook Debugger to clear the cache. The title and image will updated.


It's the same as in other PHP applications with separate V layer - print and print_r, being directly PHP functions, don't know about anything in View layer of Drupal application. They cannot pass their output to theming chain, cache systems in place and so on. That said, they often works, but that's more a coincidence.

For array inspection, you should either use xdebug or, if you don't have time, patience or skill to set it up, use Devel module. Specifically, dpm, dvm, dpr and dvr functions will be useful for you. See this helpful demo page for details of their use.

TL;DR: Install Devel, replace print and print_r() calls with dvm(). Profit.


There are no entities matching. BaseFieldDefinition entity reference error for taxonomy

Change the Color to color in ['target_bundles' => ['Color' => 'Color']]) if you create a vocabulary caller Color the machine name will be color Not Color So try with:

$fields['color'] = BaseFieldDefinition::create('entity_reference')
      ->setLabel(t('Color'))
      ->setDescription(t('The color of the fruit.'))
      ->setSetting('target_type', 'taxonomy_term')
      ->setSetting('handler', 'default:taxonomy_term')
      // Target is color not Color.
      ->setSetting('handler_settings', ['target_bundles' => ['color' => 'Color']])
      ->setDisplayOptions('view', [
        'label'  => 'above',
        'type'   => 'author',
        'weight' => -3,
      ])
      ->setDisplayOptions('form', [
        'type'     => 'entity_reference_autocomplete',
        'settings' => [
          'match_operator'    => 'CONTAINS',
          'size'              => 60,
          'autocomplete_type' => 'tags',
          'placeholder'       => '',
        ],
        'weight'   => -3,
      ])
      ->setDisplayConfigurable('form', TRUE)
      ->setDisplayConfigurable('view', TRUE);


A merge query does this:

Does a record with the provided keys already exist in the database?
If no, add it with the provided field values
If yes, update the existing record with the provided field values.

Finding a duplicate isn't considered an exceptional circumstance, because that's what the query is designed to do; so no exception will be thrown.

If your aim is to support this statement:

"you can't add this record because it exists in the db"

Then a merge query might not be the right tool. db_insert() in a try...catch might make more sense in that case.

If you just want to know whether a record was added or updated, check the return value from MergeQuery::execute():

$result = $query->execute();
switch ($result) {
  case MergeQuery::STATUS_INSERT:
    // New record was added
    break;
  case MergeQuery::STATUS_UPDATE:
    // Existing record was updated
    break;
}


Under the "Contexts" tab for your page variant, add a relationship to Node:author.  This will expose the available fields from the author for your use.

However, What are you trying to do?  You might be better off to define what you want in Views and then set up a node page variant to display the view for you.


Managed File Field and file_usage_add() - what should I attach the file to?

I attached the file to user 1 and can't see any adverse effects as yet:

file_usage_add($file, 'mantis', 'user', 1);

I also OMITTED the following line from my submit function:

$file->status = FILE_STATUS_PERMANENT;

This means that the file will be deleted after 6 hours when cron runs.

If anyone has a better solution then I'll be happy to mark as answer.


How to logout a specific user programatically?

Use drupal_session_destroy_uid function.

  Ends a specific user's session(s).

Example:

drupal_session_destroy_uid($uid_to_logout);


How to set up a question/assignment pool for a course website?

You might want to start from the Answers module. Here are some details about it (from its project page):

  Answers enables the implementation of a Question & Answer system in a Drupal site. Users can post questions and other users can answer them.

Head over to its project page for more details.

At its core, this module exists of 2 typical content types:

Question.
Answers.

The Answers module comes with integrations with other modules such as:

the Rules module, to add all sorts of business logic to fit your requirements.
the Userpoints module (and supports voting).

Here is a summary of how I'd implement what you're looking for:

the Questions and Answers are 2 content types, implemented via the Answers module.
Implement the Readings as a (3rd) content type, in which you add Entity references to the various Questions that would fit.
Implement the assignment as a (4th) content type, in which you add Entity references to the appropriate readings.

Not sure if it would be a requirement here, but I can imagine you also might want to add the Group module. Some more details about that:

you can organize the various students that attend a selected course (with group type = Class, or Training), and with each specific course implemented as a "Group".
the Group roles that would make sense in this case are:

course admin.
tutors.
students.
outsiders (= anybody else who is not (yet) involved in a specific class, but for which you want to show them something about such classes, to create awareness).

Disclosure: I'm a (co-)maintainer of the Answers module.


This online video got me a good bit of the way along:

http://mustardseedmedia.com/podcast/episode34

  On this podcast, Bob shows how to import any iCal feed of events into your Drupal site and displaying them in a Views-driven calendar on your site. (This means importing your Google or Yahoo! calendars or any other calendar system that puts out a feed in iCal format) This is tasty stuff! Want to have the Drupal calendar delete nodes once they're deleted from the feed? Check out this patch and give it a try. Episode Links Feed API, iCal Parser, Feed API Mapper

I am stuck on populating the Organic Group field of the newly created node.


Does using MongoDB for field storage limit functionality?

its a cool question.

Im on my 5 week adventure of playing around with Drupal 7 and mongo,

However as Cahpabu stated and quoted.

  NO RELATIONSHIPS WHATSOEVER. EFQ Views do not support relationships
  because Mongo doesn’t support JOINs." - Under the Converting the Views
  section on this post. (Just to clarify, I'm not being argumentative,
  I'm genuinely curious) – Chapabu Sep 6 at 15:57

I think you can do a lot using mongo with Drupal, moving a lot of other stuff into mongo, like sessions, etc. simple "fields" however :

Since Views is extremly limited with Mongo db. I found out that its better(and much more timeconsuming) to rewrite some custom modules fitting into the schema of mongo.

So its for sure, a great adventure if your starting up a new project/site. But the adventure will be filled with great challenges down mystery lane.

Even the Whitehouse had to go back to Mysql from mongo.
here is a quote I found on it.

  "The current release depends on MongoDB. When we first created the
  application, we wanted to make sure we had a highly scalable
  application and database to meet our anticipated performance needs
  under high loads. We have been running MongoDB in production for over
  a year, but we have decided that the performance benefits it provides
  are outweighed by the complexity of trying to extend Drupal features
  backed by MongoDB."

However other people had great succes with mongodb and Drupal 8
Mongodb and Drupal 8

  As they state in their slide, To achieve full mongodb functionality is
  of course impossible.

But you will have to give up several modules using SQL, (which is a lot) For now, I still have the feeling that Drupal cant dance a full tango with Mongo. Even using the modules. its still a rough way.


Is it currently possible to have Views respect RSS Display settings on a Content Type?

There is a current bug in views that does not respect any changes you make to the default RSS display settings. See Issue #1301788: RSS Feed - Title plus teaser --- still grabs default node view?. There is a patch but it hasn't been rolled into a release yet.


How can I render an HTML table in a block?

You can use the table theme type to do this.  In your build section, return a render array that includes this:

return [
  '#type' => 'table',
  '#header' => $header,
  '#rows' => $rows,
];

Where header is an array of strings and rows is an array of row value arrays.

Some reference items I found:

New render element #type 'table'

Render arrays


What causes the errors in the rules that come with Commerce Coupon?

A possible reason for running into this error is because the entity metainfo for "commerce_coupon_number_of_uses" is not provided, unless you have created a 'coupon type'.

In that case, try to create such coupon type and verify if it removes those errors.


How to access the value of a referenced node's field to use it as a Rules action?

Try adding a Rules Action (as the very first action) like "Fetch entity by id", which in your case is probably something like node:node_reference:nid.

This should make the data available from the node that is referenced via your node reference field.


Can "No front page content has been created yet. Add new content" be removed totally?

Add this to your theme's template.php file

function THEME_preprocess_page(&$variables) {
  if ($variables['is_front']) {
    unset($variables['page']['content']['system_main']);
  }
}


white-space and minimum length validation in custom search

You can use hook_form_alter(&$form, &$form_state, $form_id) and extend your validation process by adding $form['#validate'][] = 'custom_validation()'


getValue() is probably returning an array, which cannot be interpreted by twig. try:

$variables['author_name'] = $variables['node']->getOwner()->get('field_full_name')->getValue()['value'];

Or search for the right key in there ..


What are recommended modules or processes which support rating based comments or reviews?

Rating

The VotingAPI module (available for both D6 and D7) offers a framework to developers of Drupal modules about voting and/or rating. It uses a standardized API and schema for storing, retrieving, and tabulating votes for Drupal content.

VotingAPI offers these key features:

Create/Retrieve/Update/Delete operations for voting data.
Whenever a vote is casted, it calculates the results and caches them. These calculations can either be the default calculations (average, total, etc), or they can be implemented via custom tallying functions.
Via its integration with the Actions module, it can trigger workflow steps whenever votes are casted and results are tallied, such as promoting a node to the front page, hiding a comment flagged as spam, or sending some eMail.
It integrates with the Views module, which allows for slice and dice of the content of a site based on user consensus. And tt provides functions to format vote data to display them to users.

Typical rating related modules with a stable release for D7:

Rate (D6 and D7).
Fivestar (D6 and D7).
Voting API Bayesian (D7).
Star Rating (D7, no VotingAPI dependency).
Raty (D7-beta2).

Views / Rules / Flag / Message

Everything above relates to "Rating" (or voting). Some more modules that you may want to consider (= add to the mix of modules you might want to consider):

The Flag module, which is typically combined with the Rules module also to create all sorts of interesting site features. If you're not familiar (enough/yet) with Rules, checkout the 32 (!!!) great, and free, video tutorials Learn the Rules framework, organized in 7 chapters. There is a similar set of 8 video tutorials about the Flag module.
If you also add the Views module, you're already pretty close to a great mix of modules to create the site you're looking for. Maybe also review the set of 30 video tutorials about the Views module.
For more details about the Message module, refer to some interesting Use Cases detailed within its Community Documentation.


Change format of webform emails via hook

The hook you are looking for is hook_mail_alter.

To modify webform submissions emails your code should look like:

function MYMODULE_mail_alter(&$message){
  if ($message['module'] == 'webform' && $message['key' == 'submission']){
    /*** Place your code here ***/
  }
}

This will alter just the webform submissions emails.


Webform save draft after each field update

Ok, I've found this http://drupal.org/node/1319926 and based on it I've managed to make it work. This is my ajax callback (it can be attached using hook_form_alter(), based on your needs):

function _my_module_js_draft($form, &$form_state) {
  global $user;
  $draft_sid = _webform_fetch_draft_sid($form['#node']->nid, $user->uid);

  $form_state['values']['details']['sid'] = $draft_sid;
  $form_state['values']['op'] = !empty($form['actions']['draft']['#value']) ? $form['actions']['draft']['#value'] : t('Save Draft');

  $form_state['save_draft'] = TRUE;
  webform_client_form_pages($form, $form_state);
  webform_client_form_submit($form, $form_state);

  return $form;
}

For having the save draft functionality available for Anonymous I've used this patch: http://drupal.org/node/1932560#comment-7185674


Why does the autocomplete return incomplete words?

Actually the issue was related with stemming algorithms as Clive mentioned first. By removing this line in fieldType name="text" in schema.xml file, autocomplete was repaired:

<filter class="solr.SnowballPorterFilterFactory" language="English" protected="protwords.txt"/>

So, after I disabled stemming everything was good with autocomplete feature (either contrib module and my custom one), but unfortunately there was a new problem with standard queries (using Search API and views module); those were no more working. Then I managed to solve all issues my changing the analyzer of fieldType name="text" to this one.

<!-- An unstemmed text field - good if one does not know the language of the field -->

<fieldType name="text_und" class="solr.TextField" positionIncrementGap="100">
  <analyzer type="index">
    <tokenizer class="solr.WhitespaceTokenizerFactory"/>
    <filter class="solr.StopFilterFactory" ignoreCase="true" words="stopwords.txt" enablePositionIncrements="true" />
    <filter class="solr.WordDelimiterFilterFactory"
            protected="protwords.txt"
            generateWordParts="1"
            generateNumberParts="1"
            catenateWords="1"
            catenateNumbers="1"
            catenateAll="0"
            splitOnCaseChange="0"/>
    <filter class="solr.LengthFilterFactory" min="2" max="100" />
    <filter class="solr.LowerCaseFilterFactory"/>
  </analyzer>
  <analyzer type="query">
    <tokenizer class="solr.WhitespaceTokenizerFactory"/>
    <filter class="solr.SynonymFilterFactory" synonyms="synonyms.txt" ignoreCase="true" expand="true"/>
    <filter class="solr.StopFilterFactory"
            ignoreCase="true"
            words="stopwords.txt"
            enablePositionIncrements="true"
            />
    <filter class="solr.WordDelimiterFilterFactory"
            protected="protwords.txt"
            generateWordParts="1"
            generateNumberParts="1"
            catenateWords="0"
            catenateNumbers="0"
            catenateAll="0"
            splitOnCaseChange="0"/>
    <filter class="solr.LengthFilterFactory" min="2" max="100" />
    <filter class="solr.LowerCaseFilterFactory"/>
  </analyzer>
</fieldType>

With this definition for my text fields, everything works perfectly. Even accented characters are correctly returned, so it fits exactly my use case, as system is indexing english and french publications.

Thanks


How do I programatically attach fields to a node defined in hook_node_info()

If you have familiarize with features module. It will be easy. You can get more idea about content type creation and it is related with field. Follow the steps to get a working example.

Create content type and related field in you site.
Enable features module and export this content type as a new module.
The system generated module, you can find the content type creation and field relateion code.
You can find documentation for creating content type and field via code in drupal.


Entity translation will do the trick :). That module allows you to point out certain fields to be translated without translation the entire node.

https://www.drupal.org/node/1280632 shows you some use cases and examples on how to configure the module.


Rendering a module's template contents in the page body

The best way to add the JavaScript in Drupal is to have an external JS file like helloworld.js in your module/theme and include it using the function,

  drupal_add_js('jQuery(document).ready(function () { alert("Hello!"); });', 'inline');
  drupal_add_js('jQuery(document).ready(function () { alert("Hello!"); });',
    array('type' => 'inline', 'scope' => 'footer', 'weight' => 5)
   );
  drupal_add_js('http://example.com/example.js', 'external');
  drupal_add_js(array('myModule' => array('key' => 'value')), 'setting');

For more info see drupal_add_js()

  How can I get the onLoad() function to fire once my Drupal page is loaded. I a normal HTML page, I could use the body onload= callback

jQuery(document).ready is similar to your onload function that you are trying to call in your HTML body.

UPDATE:

Add the "template" instead of file in your  hook_theme for using templates like,

 function hello_theme($existing, $type, $theme, $path){
    return array(
      'timeline' => array(
        'variables' => array('content' => NULL),
        'template' => 'timeline',
        'path' => drupal_get_path('module', 'hello')
      )
    );
  }


How to add a class to a List field based on the content?

Found the solution with the Field Formatter CSS Class module to get the css added, then for being able to use it on the Views module, the instructions from are (Drewpal's instructions):
'm using the views module. In order to pass the css property captured with the Field Formatter CSS Class module through to the Views module, you have to do the following:

Go to ../admin/structure/views and edit the view that's displaying the field(s) where you want the css to be applied
In the "Fields" section, add the content field that's capturing the css class (in my case it was Content: Style)
On the configuration page, uncheck the "Exclude from Display" box and set "Formatter" to Key (if using Select List as in the video), then click apply
Next, edit the field that you'll want the CSS class to be applied
On the config page, in the "styles" section, check "Customize Field HTML" and then check "Create a CSS class"
In the "CSS class" textbox enter the token from the field that holds the css class (note: the token should be the name of the field like this [feild_fieldname] - mine was [field_style])
The select apply and it will pass the css class through.

More info here:
http://codekarate.com/daily-dose-of-drupal/drupal-7-field-formatter-css-class-module#comment-7154


Automatically insert images to translated page

You should use Entity Translation module instead of core Content Translation to provide multilingual functionality into your site, then define which fields are translatable and which are not.
You can't reach your goal with Content Translation module only.


what is starting point of any drupal module.?

what is the first function that executes in .module file? - none in the C sense. If you came from C, C++ or C# environment, think of modules like you think of dll / so files. If you came from Java, think of them like you think of libraries. Piece of code that is hooked by the program if needed, and provides functions that can be called as needed.

So which function is called first? One that implements hook that, by accident, happens to be needed first.

Drupal modules provide functions that react to certain events. These functions are called hooks. Introduction to hooks is in the Develop for Drupal documentation.

Note: As  Ayesh K helpfully pointed, PHP code placed in module file will usually be executed at every call. But Drupal expects there is no code outside functions in .module files. Placing direct PHP code may cause unexpected behaviour, so please don't do it.


There are some known issues with Drupal 7.x in some server configurations particularly around PHP 5.6 and OpenSSL 0.9x due to changes in how PHP verifies SSL certificates. Acquia has some notes about the cause and options (including a core patch to try to address some instances of the problem but read the whole article before considering that option).

On shared hosting you'll likely want to try the Alternative HTTP Client module to see if it resolves the notice.


How do I connect to the database from a module?

Just execute the query, Drupal takes care of everything else.

If it doesn't work, then that's for another reason.

Also, see Given that db_select is much slower than db_query, why would I want to use it?


The webform module would work for you. It gives you a nice interface to fetch the results so you can do some meaningful post analysis on your results too.


In which file to add the cache_clear_all function

You can set the block's caching in hook_block_info, like so:

function MODULE_block_info()
{
    $blocks = array();

    $blocks["BLOCK_NAME"] = array(
        "info"  => "BLOCK TITLE",
        "cache" => DRUPAL_NO_CACHE,
    );

    return $blocks;
}


Simple subscription validates email address. It did work for me. I used the latest version of the module.
It also provides a hook hook_simple_subscription which allows modules to do something with the simple subscription form results such as sending email for subscription verification.


LoginToboggan redirect to the same page on Drupal-7

I found the answer, what did it was the Login Destination module!


Turns out I was using the wrong version of geolocation.  If you use the 8.x-1.11 when you run the upgrade script it pull over the geolocation data into your system.  Although this isn't the default that composer installed for me, I had to re-install it.

Hope it helps someone out there,

Mark.


How do I upgrade to Google's Universal Analytics using the Google Analytics module?

I upgraded to 2.0, cleared the cache several times, and then waited about an hour-- now it works!  So I guess sometimes you just have to wait a bit after upgrading.


Based on this comment https://github.com/drush-ops/drush/issues/58#issuecomment-23716869 it has something to do with your PATH variable. Fix it and the error should go away.

  Added C:\Windows\System32;C:\Windows\SysWOW64 to PATH in Environment
  Variables.  Both errors gone the 'mode' one and the other one about
  console window width.


If you'd implement those banners via blocks, then you might be able to get it to work using the Rules block visibility module. Here is a quote from its project page:

  The Rules block visibility module allows Rules components to be used to control block visibility. This provides Drupal administrators and developers extreme flexibility in controlling when blocks should be displayed on their websites, in addition to the default visibility options provided by Drupal.

  The general idea is that if you can do it with Rules, you can use it to control block visibility, so the possibilities are limitless.

  Need to show a block only for users registered more than a month ago?

  Perhaps you have a block that must be shown only between 8am-5pm on weekdays?

  What about displaying or hiding a block based on current weather conditions?

  All of this can be done by using Rules block visibility.

With that, and as per the "if you can do it with Rules, you can use it to control block visibility" above, you've reduced your question to making Rules intercept the various URLs corresponding to each of those banners.

If you're not familiar with how to do that with Rules, then have a look at my answer to the question "How to make the permissions of a module more granular?" (and pay attention to the regex-expression included in the sample rule I included there).


Trying to create a widget that submits a form and takes you to another search page

It's not clear from your question, so I will assume that you are missing the following:

/**
 * Submit handler for facet form.
 */
function resource_library_facetapi_select_submit($form, &$form_state) {
  $form_state['redirect'] = array(
    $_GET['q'],
    array('query' => unserialize($form_state['values']['select'])),
  );
}


how to use token in "Execute custom PHP code" in a rule

At the very beginning, I just saw "$commerce_line_item" can be used in php code, but I wanted to use [commerce-line-item:line-item-label] value which showed in the token place. So I tried to use token_replace to get this value.

Finally, I figure out how to get that value and use it in PHP Code.

Although it isn't showed in the variable name place, we can still use $commerce_line_item -> line_item_label in the PHP Code. This works for me.


Difference between DRUPAL_CACHE_PER_PAGE and DRUPAL_NO_CACHE

DRUPAL_NO_CACHE doesn't cache the item, ever.
DRUPAL_CACHE_PER_PAGE caches the item per page url -- this is useful for example if the block changes with a url context.


I ran into a similar situation and hacked up a solution based upon the advanced solution here: http://drupal.org/node/770782.

Addition per commentary...

Basically what I was running into here was a situation where I had node content tagged with a genre as well as a location and what I wanted was a list of all the genres in a location.

A quick description of the view would be "Filter on published content of node type X with an argument (Drupal 6) (now Contextual Filter in Drupal 7) of location and display the genre field of each found."

A difference in my solution is that I kept count of how many nodes were tagged and I sorted on that while in the link given above it was sorted alphabetically.

Doing this with Views created lots of duplicate rows obviously because it was listing each node it found with that genre.

So, basically what I ended up doing was going into hook_views_pre_render() and looping through the results and removing all duplicates, eg:

function YOUR_MODULE_views_pre_render(&$view) {

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

    drupal_set_message('<pre>' . print_r($view->result) . '</pre>'); // to get the correct $result->FIELD_NAMES for your particular View

    // what we are first going to do is go through the results of the View
    // and create an array of unique taxonomy ids that we find.
    // we are going to store that info in array $unique_tids
    // we are also going to keep a count so we can sort on "popularity"

    $unique_tids=array();
    $count_tids=array();

    foreach($view->result as $r => $result) {
      if ($result->term_data_vid != 'THE_VOCAB_WE_ARE_LOOKING_FOR' ) { // looking back, I probably could improve the View substantially by filtering on just one taxonomy vocabulary :)
        unset($view->result[$r]);
      } else {
        $count_tids[$result->term_data_tid]++;  // keep count of how many times we see this tid
        if(in_array($result->term_data_tid, $unique_tids) || !$result->term_data_tid) { // if we have already seen this tid, or it does not exist, delete this row from the results
          unset($view->result[$r]);
        } else { // we haven't seen it, so keep it in the View results
          $unique_tids[] = $result->term_data_tid;
        }
      }
    }

    // at this point we could just return and our View would contain the
    // unique genres, but it would be "sorted" based upon the order in which
    // the node it was first tagged in was created (I think) but we want to
    // get fancy and sort this listing with the most popular genres first
    // based upon how many pieces of content has been tagged with it, so...

    arsort($count_tids); // sort the counts in reverse order so the largest counts come first
    $new_result=array();

    // crude but effective ... curse you for making me look at years old bad code :)
    // but basically go through the counts and find the Views row that corresponds

    foreach($count_tids as $c => $count) {
      foreach($view->result as $r => $result) {
        if ($result->term_data_tid == $c) {
          $new_result[]=$result;
        }
      }
    }

    // we now have our unique results in the order we want so set
    // the View to it...

    $view->result=$new_result;

  }

  // any other pre_render()ing goes here...

}

And that's what I did to present unique genres in a location sorted by how many pieces of content were tagged with a particular genre.  Let me know of any/many typos in the code (I had to clean out a lot of extraneous code to get it down to the basics) and or if you would like any other explanations.  Also looking back (I wrote this in my nube stages of Drupal) I can clean up a lot of it.  Thanks Drupal Answers for making me go back and rewrite totally working two year old code the right way :)

Oh, looking at comments in my code, this created havoc with paging so in my system I just listed everyone on one page since I didn't have all that many genres to worry about.  I think if you did this in hook_views_post_execute() instead it would respect paging.


Drupal 7 use custom layouts created by Panels module

You are probably looking for Panelizer; use it along with the panels in-place editing tool

From the module's project page:

  The panelizer module allows you to attach panels to any node in the system. It is similar to the panels_node module that ships with Panels, which provides a single node type that is a panel. Panelizer, however, allows this to work for many entity types. It works by using the Page Manager template to take over the page rendering of the node. In Panelizer 7.x-3.0, you can also panelize view modes. The old-style "Page Manager" implementation is treated as a specialized view mode.


Extending a year range of a popup calendar

Provided you have a Date field, the widget you use is the "Pop-up calendar" and there is no data in the field yet, you can edit the field and it holds the settings as shown below. Increment the ending year in the field settings


Creating a new variable by combining 2 field values

You should use entity module and entity_metadata_wrapper . I already answered a similar question in here.


Showing content on pages without taxonomy

This should be fairly straight forward

Create a new view that displays all the content without a taxonomy term,
In the existing block view look under the advanced settings for no results behaviour and click add. In here you can add a view to display if there are no results so simple select your view that you created in step 1.


Multi-site setups are a little tricky due to their reliance on the same codebase. You can use a multi-site setup in this scenario, but bear in mind that when you upgrade a module in sites/all/modules, it'll affect all the sites (unless overridden in sites/$SITENAME/modules).

This leads to potential issues where one of your sites relies on N version of a module, but you want to use N+1 on another site. The module in question might not have an upgrade path, or it might've drastically changed its functionality between versions (not as uncommon as you might think, given Drupal culture towards major versions).

Additionally, if there are critical database changes needed during a module upgrade, you'll find that you need to take down multiple sites at the same time to ensure you run update.php.

So for most use-cases, multi-site isn't the way to go. Unless you're really strapped for space or you have some weird hosting restriction that prevents you from mapping each site's domain to a separate folder, you're likely better off maintaining separate code bases and using tools like Drush and version control to speed up code deployment.

The prototypical use-case for multi-site, outside of its use as a workaround for restrictive hosts, is when you're deploying a ton of sites that are extremely similar. You might be running a hosting service, or building a bunch of micro-sites for a company, or what-have-you. In those cases, you can roll your own multi-site setup, but you should also consider using Aegir, which automates and abstracts a lot of the hassles of running such a set-up.

Adding new sites to a multi-site setup is pretty straightforward: create a new folder under sites, edit sites/sites.php (Drupal 7 only), copy sites/default/default.settings.php to settings.php in that new folder, and visit the site in a browser. Drupal should begin the installation process and use the new folder. Your new site will have access to all the modules under sites/all/modules just like your exiting sites.


Customizing webform results submission page

Look at EntityForms to have more control over submissions and selecting what submissions to view.

Features
Ability to attach any Drupal Field to the Forms
Ability to use most field based and entity aware modules.
You can download submitted data to XML and / or CSV data files using View Data Export.
Rules based form submission notifications. Allows for complex notifications logic.
Rules based form access control. Allows for complex access logic.
Use Views to create to create an administrative listing of each Entityform type Submissions for fine grain control.


Drupal 8 - taxonomy term field without "title" attribute

You should be able to use template_preprocess_views_view_field to accomplish this. Create that hook in your custom theme like:

/**
 * Alter field_MY_TAX_FIELD link to add title attribute.
 *
 * Implements template_preprocess_views_view_field().
 */
function MY_THEME_preprocess_views_view_field(&$vars) {
  if ($vars['field']->field == 'field_MY_TAX_FIELD') {
    // Add title attribute to link.
  }
}

Alternatively you could create a new field formatter that extends Drupal\Core\Field\Plugin\Field\FieldFormatter\EntityReferenceLabelFormatter. Override the viewElements method. First call $elements = parent::viewElements($items, $langcode);, then traverse $elements and add your title attribute when appropriate. After you create the formatter, clear cache and then go back to your view and select your new formatter as formatter for the taxonomy field.


Call to undefined function node_mass_update()

The solution for this problem is to include the node.admin.inc file.

 module_load_include('inc', 'node', 'node.admin');
 node_mass_update($nodes,array(array('status' => 0)));


Alter form to have single radio button term reference checked by default

the way I did it now, is following - First I tried to use a hook provided by workbench access itself which supposed to be for that use case, look here
https://drupal.org/node/2019473

But it would not work for me, so I did :
this results in a select box with only one possibility. Not the best UX style maybe and later I will try to hide the element, maybe with ds module.

function workbench_access_crud_by_state_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id != 'hardware_antrag_node_form') {
    return;
  }
  //sdpm($form);
  $option_arr = $form['field_tu'][LANGUAGE_NONE]['#options'];
  // remove 'none'-option
  array_shift($option_arr);

  // look for field for workbench_access and replace options
  $wb_access_field = $form['workbench_access_fields']['#value'][0];
  $form[$wb_access_field][LANGUAGE_NONE]['#options'] = $option_arr;
}


How to edit live theme .info file (localhost)

May be the problem is of / present at the starting in your first attempt(/css/main.css), try once with:

stylesheets[all][] = css/main.css

Note: Clear the cache and check if it works.

Also you can check the following links if it helps:
https://drupal.org/node/171205
https://drupal.org/node/171209


How can I make a custom content entity ID editable on the content entity form?

You have both a widget configured and a custom form element, that results in Drupal being confused about the structure.

If you have a form element defined by yourself, don't define form display options and you should be OK.

The reason the widget show up like with other fields is likely actually a regression with the security fix in 8.3.1 that denies edit access to the entity. When we did that, we didn't anticipate a use case like this. You could override the default fieldAccess() method on the EntityAccessControlHandler to grant edit access to the id field, at least when it is new.

Or you do not make the lot number the actual entity ID but have a technical auto-increment ID, then you don't have to worry about this stuff.


Using the Global Redirect module with the default options. You can redirects all URLs without a language prefix to the correct URL with the default language prefix contained.


Automatically show one selection of a field based on the selection of another field in a view

Take a look towards conditional fields module. Hope this will helps to solve your issue.
(https://www.drupal.org/project/conditional_fields)


How to make a reference on same node without recursion problem

There is no reason you can't have an entity reference field that references the same content type, the problem only comes when you have nodes that reference each other in a loop.

For example if nodes A, B & C have these relations you cause a loop and get the error you describe:

A > B > A
A > C > A
A > B > C > A
A > C > B > C
etc.

If you create your content in a way that avoids loops you avoid the problem, however there is also another work around you can use (which is described at https://www.drupal.org/node/2301499#comment-8973869):

Have a new view mode for your nodes. This could be done in custom code as per the linked example, or by using the Entity View Modes module.
Configure your entity reference field on the product content type to display using your new view mode.
Configure the display settings for your new view mode on the product content type to not display your rendered referenced entity.

This way when you view a product it will display its referenced entity for that field but that referenced entity will not print out its rendered entity, avoiding the recursion.

That linked issue also has a patch that apparently addresses the issue but the maintainer has said it will never be committed so I would use caution if thinking about using that.


probably not really drupal realated. But here you go:

Drupal.behaviors.mywebform = {
  attach: function (context, settings) {
    $.ajax({
        url:'/devtest/sites/democities.php',
        type:'POST',
        dataType: 'json',
        success: function( json ) {
            // if #edit-submitted-info-city is not a select you will have to make it one, or take the select that is in, or create one select in it.
            $('#edit-submitted-info-city').append('<select>').attr('id', 'stackexchangeExample');

            $.each(json, function(i, value) {
                $('#stackexchangeExample').append($('<option>').text(value.city).attr('value', value.city));
            });
        }
    });
}};

you might want to make sure that you run this only once, adjust the creation of the select element accordingly. or add a once() implementation


Cannot add files to a specific folder using file resumable module

Because I was pressed by time I made the following changes:

1 I moved the whole sites folder to the extra space (after I bought
   some more)

2  I created a symlink to sites

Everything seems to be working ok.

My idea is that inside files drupal can't handle symlinks.


How can a node appear in different places?

You can do this pretty easily with views...just build a view with different page or block displays that filters nodes by the different tags (a.k.a. Taxonomy Terms). You can manually build a menu that provides links to the different pages that correspond to each tag.


Automatically change field when another field value is selected

This sounds like a bad case of data de-normalization. You shouldn't have a "Contact" field on your "Job application" content type if it's simply going to duplicate whatever is already in the "Job" content type.

If you're simply wanting to be able to see who the contact is for a given application, use the "Rendered entity" formatter for the job reference field on the application content type. (I'm assuming you're using the Entity Reference module?) In the formatter settings, choose a view mode that only displays the contents of the Contact field on the job node.

This way, if the contact ever changes for the job, it'll live-update across all job applications.


Display different icons depending on field value

This only requires one field. It sounds like it is a list (text) field to me.

This should be done as a new variable to the node template by way of using hook_preprocess_node in your MYTHEME.theme (replace any instance of MYTHEME with your actual themes name, i.e. bartik) file. Here is an example:

function mytheme_preprocess_node(&$variables) {
  $type = $variables['node']->getType();

  if ($type == 'NODE_TYPE') {
    $price = $variables['node']->get('field_name')->value;

    switch ($price) {
      case "m":
        $variables['custom_icon'] = 'icon1';
        break;

      case "h":
        $variables['custom_icon'] = 'icon2';
        break;

      case "x":
        $variables['custom_icon'] = 'icon3';
        break;

      case "f":
        $variables['custom_icon'] = 'icon4';
        break;

      case "l":
        $variables['custom_icon'] = 'icon5';
        break;

      default:
        $variables['custom_icon'] = FALSE;
        break;
    }
  }
}

Then, create a node--NODE-TYPE.html.twig file, where NODE-TYPE is the machine name (bundle) of the node in question (ex. article, page, product).

In this file, you now have a new variable available to use, which would be output with:

{% if custom_icon %}
  {{ custom_icon }}
{% endif %}

If no value, or value does not match whats expected, the switch statement will set the variable to FALSE so you can check in Twig if you should output it or not.


How do I update a node's file field from within a module?

The file field type has a fid column (file ID); you just need to save the file so an ID is populated, and add it to the node like this:

$file = file_uri_to_object('/tmp/new.zip');
$file->status = FILE_STATUS_PERMANENT;
file_save($file);

$node->field_ios_file[LANGUAGE_NONE][0]['fid'] = $file->fid;
node_save($node);


A views page as “Output this field as a link” in a block (Drupal)

Images can automatically be made to link to either their node or directly to the image itself using the 'manage display' tab on the content type: admin/structure/types/manage/content_type/display

I would simply make your view an unordered list of teasers and link each image to the file itself if you only want to display the image, or if you would like to have other fields such as a description you could select content and link it out to the node. I am not sure how you have your content type setup but best practice would be to have the fields setup similar to the screenshot below. You would have one image field per photograph and simply use the teaser display mode and image styles to display thumbnails in a listing.


%{HTTP_HOST} is the default and it usually works. The other 2 options are there in case http_host doesn't work. Every hosting environment is different; that's why there are options.


How do I show a translated the value of a content type in my template

You need to render either:

Fields
Variables created in a preprocess hook in mytheme.theme

Example, if you crated a field called Short Text (field_short_text), then in the node template for that type, you do:

{{ content.field_short_text }}

Except from the page template level (page.html.twig) you won't have access to the node render array.

If you create your own variables in a preprocess hook, you will need to call the translation service against that - it is better to let Drupal work normally for simple cases like these.

What you can do in this situation is create a View that has a node id argument, and either:

Output Views fields (meh)
Output that node in a designated view mode (best method)

Generate a Block display from that View, then place the block in the Banner region of your theme from Block Layout in the admin. If you are not familiar with Views, you should get familiar with it right now.

However, if you are trying to print the site slogan and site description, these are set under Admin > Config > Site Information, and should be available already as variables to the page template. I don't think there is a need to recreate what already exists, unless core doesn't translate site name, site slogan, site description but I am pretty sure it does.


How to Get data of Content type in a custom view

I believe you are looking for this module:
https://www.drupal.org/project/viewsnodefield


A couple of options, for example:

Provide an RSS feed of the calendar events.
Provide email notifications with something like http://drupal.org/project/subscriptions


Structure and dynamic are IMO the keywords for choosing taxonomy.
I recently had this question come to me when tagging companies with geographical regions. My first choice was to prepare taxonomy with list of regions. Soon it turned out to be over-complication. The regions almost never change their names and almost never change their structure/parents. So I tossed out the taxonomy and decided to use a flat List (Text). It's now also much easier to maneuver the regions in a View. So - if your list is static and flat - go for a list.


How to assign permissions based on user points?

Use roles.

The only problem with 10+ roles is that your permission table is going to get huge but you can solve this by limiting it per role (see link on roles list) or use a module like faster permissions.

The loading of roles is most likely much faster than doing custom checks. Also, when doing something like this, you'll certainly run into issues, for example when trying to work around existing permission checks in modules and so on. The permission system is one of the core elements of Drupal. Use it and don't try to fight it. That's not going to work.

There is a Userpoints Role module in http://drupal.org/project/userpoints_contrib, which allows you to configure how many points users require for a given role and it should just work. There are even a few tests there now. Note that it currently gives you all permissions the user has enough points for. This might not be what you'd expect but it has the advantage that it would be enough to only specify the additional permissions each role has.


How to fill select options based on previous select?

I've figured it out on how to do this...

I fill out the #options for the second <select> when I build the form.
I hide it with a #states.

When the user then selects something in the first <select> I use the populateDurationYears method to remove invalid options like this:

$options = [];
if($maxDurationYears != 0) {
  for($i = $minLoanDurationYears-1; $i < $maxDurationYears; $i++) {
    $options[] = ($i+1) . " years";
  }
  $form['loanDurationYears']['#options'] = $options;
}
return $form['loanDurationYears'];

This does the trick :-) No need for AjaxResponse or anything like the ReplaceCommand etc... Keep it simpel Stupid! ;-)


This is a case where reading the routing file is a bit deceptive.

There are actually two similar routes defined in system.routing.yml:

system.files:
  path: '/system/files/{scheme}'
  defaults:
    _controller: 'Drupal\system\FileDownloadController::download'
    scheme: private
  requirements:
    _access: 'TRUE'

system.private_file_download:
  path: '/system/files/{filepath}'
  defaults:
    _controller: 'Drupal\system\FileDownloadController::download'
  requirements:
    # Permissive regex to allow slashes in filepath see
    # http://symfony.com/doc/current/cookbook/routing/slash_in_parameter.html
    filepath: .+
    _access: 'TRUE'

After watching in the debugger, it turns out that the matched route is actually system.files, and not system.private_file_download.  But it will not match a tailed-URL at all without help.

The help needed is a "path processor", which is a routine that the router calls to let code do unusual things with route matching.  Here's the one that's used for private: and temporary: files, among other users in Core:

In core/modules/system/src/PathProcessor/PathProcessorFiles.php:

class PathProcessorFiles implements InboundPathProcessorInterface {

  /**
   * {@inheritdoc}
   */
  public function processInbound($path, Request $request) {
    if (strpos($path, '/system/files/') === 0 && !$request->query->has('file')) {
      $file_path = preg_replace('|^\/system\/files\/|', '', $path);
      $request->query->set('file', $file_path);
      return '/system/files';
    }
    return $path;
  }

}

A path processor is a service, and needs a "tagged" service definition.  Here's the one for Core's path processor for the /system/files subpath:

In system.services.yml:

  path_processor.files:
    class: Drupal\system\PathProcessor\PathProcessorFiles
    tags:
      - { name: path_processor_inbound, priority: 200 }

Once I'd added the correct route and service definitions, my custom URL scheme works the same way the Core file scheme URLs work.


How to set the language to Swedish when users visit example.se and to French when visiting example.fr?

On admin/config/regional/language/configure/url change the Part of the URL that determines language to Domain.

Then set up domains to all languagues: admin/config/regional/language/edit/LANGCODE


In drupal website how to create multiple sitemap for each content types?

There's now the module to do that: XML Sitemap per node type

The XML Sitemap Per Node Type module provides the additional context for XML sitemap module that allows creating sitemaps per content type.


Prevent Drupal from auto-caching pages in all translations

So there is a function called drupal_page_is_cacheable() which you can call, on a site, in order to avoid the caching, so you could for example call that on your uncachable filter.


How do I fetch versions of a module compatible with latest core version?

You can use https://updates.drupal.org/release-history/search_api_solr/current to get the versions either prefixed with 8.x- or without an API compatibility prefix. (The latter is the case for SEMVER versions.)

The output from that URL contains information about this release, for example.

<release>
<name>search_api_solr 4.1.1</name>
<version>4.1.1</version>
<tag>4.1.1</tag>
<status>published</status>
<release_link>https://www.drupal.org/project/search_api_solr/releases/4.1.1</release_link>
<download_link>https://ftp.drupal.org/files/projects/search_api_solr-4.1.1.tar.gz</download_link>
<date>1591714636</date>
<files>
<file>
<url>https://ftp.drupal.org/files/projects/search_api_solr-4.1.1.tar.gz</url>
<archive_type>tar.gz</archive_type>
<md5>7f2dbc01229b118c02c66f4ac210d430</md5>
<size>3207604</size>
<filedate>1591714636</filedate>
</file>
<file>
<url>https://ftp.drupal.org/files/projects/search_api_solr-4.1.1.zip</url>
<archive_type>zip</archive_type>
<md5>511e33c0b0ae47a0bd455109f87d07d1</md5>
<size>3792678</size>
<filedate>1591714636</filedate>
</file>
</files>
<terms>
<term>
<name>Release type</name>
<value>Bug fixes</value>
</term>
</terms>
<security covered="1">Covered by Drupal's security advisory policy</security>
<core_compatibility>^8.8 || ^9</core_compatibility>
</release>

It also contains data for this release. (This shows that the URL doesn't return information only for SEMVER versions.)

<release>
<name>search_api_solr 8.x-3.9</name>
<version>8.x-3.9</version>
<tag>8.x-3.9</tag>
<status>published</status>
<release_link>https://www.drupal.org/project/search_api_solr/releases/8.x-3.9</release_link>
<download_link>https://ftp.drupal.org/files/projects/search_api_solr-8.x-3.9.tar.gz</download_link>
<date>1581700341</date>
<files>
<file>
<url>https://ftp.drupal.org/files/projects/search_api_solr-8.x-3.9.tar.gz</url>
<archive_type>tar.gz</archive_type>
<md5>5050a8e2bd6b4965d414cade7aae3dc8</md5>
<size>1052117</size>
<filedate>1581700341</filedate>
</file>
<file>
<url>https://ftp.drupal.org/files/projects/search_api_solr-8.x-3.9.zip</url>
<archive_type>zip</archive_type>
<md5>140f15134d4e8f2239b96e682186e021</md5>
<size>1278054</size>
<filedate>1581700341</filedate>
</file>
</files>
<terms>
<term>
<name>Release type</name>
<value>Bug fixes</value>
</term>
<term>
<name>Release type</name>
<value>New features</value>
</term>
</terms>
<security covered="1">Covered by Drupal's security advisory policy</security>
<core_compatibility>^8.7.7 || ^9</core_compatibility>
</release>

Unfortunately, there isn't a way to get all the versions that are compatible also with Drupal 9 and not just with Drupal 8, using an updates.drupal.org URL. For that, you need to parse the XML output and filter those versions containing ^9 in the <core_compatibility> tag.

As side note, the all, 8.x, 7.x end-points are considered legacy. I guess that means they could be removed in the future.

References

Update status XML


Can I use Corolla theme as a fixed width layout?

Though I have not used that theme myself, it indicates on the project page that it's 'Responsive' so the sidebar is doing what its supposed to do when the browser is resized to a narrower width -- it's using a Media Query. I tried the demo and this was my experience as well. Though that might have seemed odd in the old days, now it's actually what you want for the site to work with multiple devices and screen widths. You will note that if you resize even narrower, the other sidebar goes underneath as well and this is as expected.

From the project page:

  "The new 7.x-2.x version is a subtheme of Adaptivetheme which includes
  a powerful new responsive layout engine with full support for mobile
  devices."

You may want to take a look at this for a primer on Responsive Design: http://www.alistapart.com/articles/responsive-web-design/


Most of the time it is the memory_limit setting in your php.ini. Drupal 7 needs a bit more memory and depending on how many modules you are using, it must be set to a higher value. 64M or 128M should be enough for moderate sites.


How to manually uninstall/purge modules?

This is a known bug. Replace the module with the most recent DEV version, update, and then try uninstalling again


How do I properly pass values from PHP to JavaScript?

You first JS snippet executes before the page is done loading.  Is it not the same syntax as the shorthand for declaring the document.onready event handler.

You working example runs from an onready, but the Drupal best practice is to use a behavior, eg:

(function ($, Drupal, undefined) {
  Drupal.behaviors.mymodule = {
    attach: function (context, settings) {
      console.log(settings.mymodule);
    }
  };
})(jQuery, Drupal);

Take a look at Managing JavaScript in Drupal 7 for more information.


To get the CSRF Token, do a GET on:

?q=services/session/token

Please note that 'services', is not the path to your endpoint, its a built in path provided by the Services module.

After grabbing the token, you then pass the token along in the header for any POST, PUT, and DELETE requests from authenticated users:

X-CSRF-Token=abcdefg123456789

jDrupal may be of use in this scenario as well, it's a JavaScript API for the Drupal Services module


Multiple values in creating a new field instance

Hopefully this will prove useful: To create a field that allows multiple values, you set the cardinality to -1 when using field_create_field.  Then all instances will allow multiple values (provided the widget supports that).

Example:

field_create_field([
  'cardinality' => -1,
  'field_name' => 'field_unlimited',
  'type' => 'special_content',
  'entity_types' => ['node'],
]);


Tooltip issue with tipsy and views tooltips

I got around this with some CSS and custom field HTML for the title and other info that I wanted to display in the tooltip, so there's no need for tipsy anymore