How to theme Profile 2 fields for anonymous?

You can create a View of page display of type Profile types

Then in this View add curriculum_vitae as Relationships, It causes the fields of  curriculum_vitae profile be added to the Fields.

Now create a Contextual Filter of any field you want (it might be name, ID, ...).

So you can easily theme this View to display the information of the selected user.  If the View name be profile, Then using views-view-fields--profile--page.tpl.php you can theme the output.


You need to do it with JQUERY,there is another way as patching colorbox,but by default color box dont support link as title

   $('#cboxTitle').html('title');


Views filter handler for user authored from Custom Form

As pointed out by 4k4 there is no user authored data in the tables, so I thought I would add what I did to output a view of users the author created.

For me, I needed to do some of this in my custom module you might be able to do this in the configuration if your use case is easier.

 1. Create user reference field in /admin/config/people/accounts/fields
 2. Install https://www.drupal.org/project/cer/
 3. Add a corresponding reference in /admin/config/content/cer for your field and the user entity.
 4. Create a relationship for your view from the user field.
 5. Output your view as a block list on your user account page.

Now when a user creates a reference the view will shorten to a list of your users.

I took this a step further and created a custom form module to register a user and in code populate the user entity reference field with a form submit for the current user's id. This bit took me a while to work out so hope this helps someone else. :)

$userCurrent = \Drupal::currentUser();
$uid = $userCurrent->id();
$user->set("field_your_field_name",$uid);


Drupal 8: Prevent webform from saving IP

You could override the save function of webform/src/WebformSubmissionForm.php, but as you specifically ask for a hook and because this is probably also the easiest solution you can remove the field value set by the form before the entity gets saved:

use Drupal\webform\WebformSubmissionInterface;

/**
 * Implements hook_ENTITY_TYPE_presave() for webform submissions.
 */
function mymodule_webform_submission_presave(WebformSubmissionInterface $webform_submission) {
  $webform_submission->remote_addr->value = '';
}


The answer from @leymannx stops git from recognizing and pushing file permission changes to the repository.

Yet, it doesn't stop Drupal from denying write access to the configuration files after your cache cleared, and thus a git pull to fail if it can't write changes to these files.

As the permissions set automatically by Drupal still allow write access for the file owner, the easiest solution would be running git pull with the same user that is running the local webserver.

If that is no option, your developers may try to use access control lists (setfacl) for advanced write permissions to their local sites folders on Linux systems.

Another option would be to wrap the git executable with a custom shell script in their local binary paths, that ensures proper write permissions (unfortunately there's no pre-pull git hook).

As a last resort, you can patch the core. There is lots of discussion of whether and how to allow developers to circumvent file protection for setting files. None of the proposed solutions made it to core yet. But the patch from this issue for Drupal 7 allows a custom setting in your local development environment settings (e.g. in settings.local.php) to disable file permission changes.


Different product prices per line item options

If I understand what you're trying to do here correctly, you may need to create some custom Rules.

Event:  Calculating sell price of product.

Conditions:  This is where it gets tricky.  If the date range is not on the product entity, you'll need a way to get the values from the product display node, that could be annoying in and of itself.
Now, if pricing for date ranges are statically calculated (ie: a 3 day trip ALWAYS adds $50), you could set up some custom code to dynamically do things like that.
On the flip side, if those range rates are different per product, it seems it would be necessary to define those on the product entity.  And furthermore, you would probably need to create products for each variation (as in, variation for every combination of departure city AND date range).

Action:  Add amount to product price (or something like that, I'm not looking at Rules directly).


Emails sent via a Rules action contain arbitrary line breaks

You are most likely up against the hard limit of line length (77) for plain text emails, defined in a Drupal core function _drupal_wrap_mail_line. It quotes RFC 3676 as the reason for this.

If you want the one line of text you might be able to do it using a HTML formatted email rather than plain text. Alternatively you may want to reformat your email so it suits the available width. The third option of altering core or making a plugin to let you make long lined emails is probably a little overboard.


It looks like this is currently not possible for Drupal 8, using community maintained modules. The Feeds Extensible Parsers module is not ready, which means the services+feeds method is not feasible, and the Deploy module is not ready. (Though methods may become available in the future for this particular workflow.)


Custom exposed filter with single on/off checkbox doesn't respect the default value and the $_GET parameter

Views doesn't handle the default checkbox state because when you load your view page for the first time (or if the user clicks the Reset button), the URL doesn't have any parameter in it, so that the $_GET parameter is useless. Here is a complete form definition that will handle the checkbox, whether the URL has parameters or not:

class my_module_helper_handler_filter_timetracking_children extends views_handler_filter {

  /*...*/

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

    $params = my_module_get_params();

    // First time the view is loaded (or user click the Reset button), URL doesn't have parameters
    if(!$params) {
      $value = 1; // checkbox checked by default
    }
    // If URL has parameters
    else {
      // If our filter is present in the URL as parameter and its value is '1'
      if (isset($params['timetracking_children']) && $params['timetracking_children'] == 1) {
        $value = 1;
      }
      else {
        $value = 0;
      }
    }

    $form['value'] = array(
      '#type' => 'checkbox',
      '#title' => t('Show subtasks'),
      '#default_value' => isset($this->value) ? $this->value : NULL,
      '#value' => $value,
    );
    return $form;
  }

  /*...*/

}

function my_module_get_params() {
  global $base_url;
  $query = array();

  $url = $base_url.request_uri();
  $url = parse_url($url);

  if(isset($url['query'])) {
    parse_str($url['query'],$query);
  }

  return $query;
}


Adding Node-Fields to query with db_select();

To my knowledge, db_select() isn't aware of entities or fields (fields, in the context of field that are added to nodes etc.)

I imagine you'd need to do the joins to field tables yourself. I found a little example from dbtng_example--dbtng_example.module, but as per my hunch and comments below - EntityFieldQuery is actually the only correct way to do this. Fields can define their own storage which would completely break your db_select, so...

With a bit of a performance hit (which is negligible for most) you really should do it the Drupal 7 way...

Drupal 7 now has Fields in core, and with that came the EntityFieldQuery which is a querying class for finding entities (like nodes, terms, etc) by their properties (like published status) or fields (like field_page_photo or any other fields you add via UI or otherwise)

or from API:

  This class allows finding entities
  based on entity properties (for
  example, node->changed), field values,
  and generic entity meta data (bundle,
  entity type, entity id, and revision
  ID).

Some good examples and discussion here:

What's the proper use of EntityFieldQuery?

and I find myself referencing Do we need an EntityFieldQuery example? as well.


What is the basic concept behind revisons in term of performance?

Drupal essentially stores a copy of the node each time a revision is created. So if you're making alot of text edits it will be your database size that will mainly increase because of enabling revisions. (But drupal will also keep any files uploaded that are associated with previous revisions)

So normally for nodes you have about 3 core tables with a row for each node. Then you have a table for each field you add to content types e.g. "node__field_my_field" which holds the live content for that field.

So with a million nodes you'd expect 1 million rows in the core node tables and up to 1 million rows in each of your field tables for each node (If you populate every field for every node)

If you enable revisions a few new tables get created to start tracking each revision, I think its 2 extra core tables and then a revision table for each field. But this time every time you make a revision it add a row to all these tables. So with your 1 million nodes with 3 revisions you will effectively quadruple your database storage requirement

But in terms of site performance it shouldn't really have too much effect as databases can scale well


How do I get the taxonomy term name of the current taxonomy term page.tpl.php?

Try..

http://api.drupal.org/api/drupal/modules--taxonomy--taxonomy.module/function/taxonomy_term_load/7

$term = taxonomy_term_load(arg(2));
$title = $term->name;

arg(2) should return the tid of the taxonomy page (taxonomy/term/tid).


Validate upload size before starting upload with Filefield?

The only easy way to check a file upload's size on the client-side that I know of is with Flash.

You should see if the Uploadify module  works for you. I haven't used the module, but I have used Uploadify a lot, and it works great.


How to put select option value into particular category in webform module?

I think you want to store this a 2 separate fields however present it to the user as 1 field.

One solution would be to use hook_form_alter() to combine the 2 selects into 1, and then put the values back where it should be after the form is submitted.

For this example lets call the first select field A, and the second field B, and the new field that combines both A and B, C.

So - first combine the fields and add an additional submit handler:

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

  if($form_id == 'webform_client_form_<ADD WEBFORM ID HERE>') {

    // Make a new field which will have both options. Base in on the existing
    // field A.
    $form['submitted']['field_c'] = $form['submitted']['field_a'];

    // Combine the options of field A and B for the new field.
    $form['submitted']['field_c']['#options'] = array_merge($form['submitted']['field_a']['#options'], $form['submitted']['field_b']['#options']);

    // Hide field A and field B.
    $form['submitted']['field_a']['#access'] = $form['submitted']['field_b']['#access'] = FALSE;

    // Add an additional submit handler to put the values back where they
    // should be. Add this before the existing submit handler so we can make
    // our changes before anything is saved.
    array_unshift($form['#submit'], 'split_combined_select_values_out');

    // Add a validate function to make sure only 1 option is selected from each category
    $form['#validate'][] = 'combined_select_validate';

  }

}

In the new validation function make sure that only 1 option is selected from each category:

function combined_select_validate($form, &$form_state) {

  $count_a = $count_b = 0;

  foreach($form_state['values']['submitted']['field_c'] as $val) {
    if(array_key_exists($val, $form['submitted']['field_a']['#options'])) {
      $count_a++;
    } elseif(array_key_exists($val, $form['submitted']['field_b']['#options'])) {
      $count_b++;
    }
  }

  if($count_a > 1 || $count_b > 1) {
    form_set_error('submitted][field_c', 'Can only select 1 option from each category');
  }

}

And then in the new submit handler put the values back where they should be:

function split_combined_select_values_out($form, &$form_state) {

  foreach($form_state['values']['submitted']['field_c'] as $val) {
    // Check if the value  selected is from field A or field B
    if(array_key_exists($val, $form['submitted']['field_a']['#options'])) {
      $form_state['values']['submitted']['field_a'][$val] = $val;
    } elseif(array_key_exists($val, $form['submitted']['field_b']['#options'])) {
      $form_state['values']['submitted']['field_b'][$val] = $val;
    }
  }

  // Unset the value from field C.
  unset($form_state['values']['submitted']['field_c']);

}


For showing nodes of particular domain on a particular domain, you dont need avaliable on current domain. First you have to see, if you are able to see the list of nodes on a particular node without applying the filter on a normal view.

If you cant see the content, then you will have to change some settings by going to link.

admin/structure/domain/settings

Under Advanced Settings, in Search Settings, check Search content for the current domain only

Under Domain Specific Settings >> Domain Settings Behaviour >> Use the active domain


How to make use of the render placeholder system for cacheablejsonresponse?

The only trade-off I have found is to implement custom tags (per user) and put the response data array in cache so I have control over the conditions of cacheability at the controller level. I build the cacheability metadata (context + tags) with the help of a service which registers the metadata of the content which is currently normalized. And when the normalization ends, I merge the metadata onto the response and put the response in a cache backend.

And when the controller is called again, I try to retrieve the cached response and returns it if not invalidated.

Internal and dynamic page cache still works for the other controllers (i.e. standard rendered pages) without removing the high invalidation tags from the services.yml file.

Feel free to add better answers than this one.

Tested on Drupal 8.6.7.

Side note

Because I was using flag, I have had to implement cache tags pairs: userid+flaggingid. This way, we will not invalidate the caches of all users whenever a single user flags or unflags a content. This does not answer this question, but I thought it could be useful to include in your reflections for your own cache system.


The most searched keyword of the default search?

You can check the "Top Search Phrases" report at "/admin/reports/search". This will give you a count of the search phrases used. It doesn't make it out by individual keyword, but at least gives you an idea of what people are searching for.


Having issues getting solr search facets to appear on non-search pages

This is also something I want whereby the search facets are visible alongside a content type.

This problem applies to search facets in general (e.g. for those who don't use solr but use 'database search' - a "poor man's" version with less demanding requirements, suitable for shared hosting.)

Facets are generated from search results - so on a page with no search results the facets will not appear. That appears to be the design, as explained here:
Show facet filter even if there is no result

There are several possibilities that you (and I) could consider:

How do I allow facets on my full content display page? - here
the answer is not to display faceted search on a content page /
non-search page but rely on breadcrumbs to link back to a search page
My preferred approach (not yet implemented): is to put search results
on the same page as the content. These search results will be the
same as those that one clicked through before the content page. In
other words, the same list of results that contained the link to the
content item are displayed on the page of the content item itself.
These will of course be focused search items ("drill down"ed)
results. These would serve a purpose for the user as "related" and
follows convention - if you look at this site
drupal.stackexchange.com you'll see related results. But we would
probably want to display them in a smaller space, using a different
view with theming and the view could restrict the number of items
shown.


Field with unique and auto-increments values

You can achieve it yourself in your custom form submit, lets suppose your field name is  myfield ( machine name will be field_myfield and it is text) and your content type is news ( change them with your data)
first in form alter you can hide it ( it you don't want user see it )
Get idea from my code

function yourmodule_form_alter(&$form, &$form_state, $form_id) {
    if($form_id == 'news_node_form'){
        if($form['nid']['#value']){
          // if we are in adding new node hide that field and add custom submit handler
                hide('field_myfield');
                $form['#submit'][]='_my_autoinrement_submit_handler';
            }
    }
}

function _my_autoinrement_submit_handler($form, &$form_state) {
$lastValue=0;
// search for the last value
$query= db_select("field_data_field_myfield","mf") ->fields("mf")
 ->condition('bundle', 'news','=')
    ->condition('status', 1)
    ->orderBy('field_myfield_value', 'DESC')
     ->range(0,1);
     $result = $query->execute()->fetchAll();
     if($result){
         //get last value entered before this
        $lastValue= current($result)->field_myfield_value;
     }
     // increment last value ( biggest one )
     $lastValue ++;
   //set it in node
    $form_state['values']["field_myfield"]['und'][0]['value']=$lastValue;

}


How can I add entity base field with unique constraint if some entities already exist?

I think you'd need to write an update hook to first add you new base field via the EntityDefinitionUpdateManager (an example here since automated entity updates were removed.)

function example_update_8701() {
  // Add the unique constraint, etc.
  $entity_definition_update_manager = \Drupal::entityDefinitionUpdateManager();
  $field_storage_definition = $entity_definition_update_manager->getFieldStorageDefinition('hostname', 'comment');
  $field_storage_definition->setDefaultValueCallback(Comment::class . '::getDefaultHostname');
  $entity_definition_update_manager->updateFieldStorageDefinition($field_storage_definition);
}

Then in a post_update hook, you would load each entity and populate the new field with values in whatever manner makes sense and re-save.

The two methods mentioned in your question shouldn't be called since you're updating the existing entities rather than creating new ones.


How do I sort the field value by null in Search API Solr?

I also had this issue, I couldn't find an easy way to sort by null in a query alter (although Solr does have sortMissingLast, I just couldn't figure out how to inject it through Search API). Instead, I added a processor to check the field in question and add another field to identify whether it's there or not. Then you can sort by that.

<?php

namespace Drupal\my_module\Plugin\search_api\processor;

use Drupal\Core\Annotation\Translation;
use Drupal\search_api\Annotation\SearchApiProcessor;
use Drupal\search_api\Datasource\DatasourceInterface;
use Drupal\search_api\Item\ItemInterface;
use Drupal\search_api\Processor\ProcessorPluginBase;
use Drupal\search_api\Processor\ProcessorProperty;

/**
 * Checks for my field.
 *
 * @SearchApiProcessor(
 *   id = "my_field_null",
 *   label = @Translation("Has My Field"),
 *   description = @Translation("Adds a check for null field to index."),
 *   stages = {
 *     "add_properties" = 0,
 *   },
 *   locked = true,
 *   hidden = false,
 * )
 */
class MyFieldNull extends ProcessorPluginBase {

  /**
   * Machine name of the processor.
   * @var string
   */
  protected $processor_id = 'my_field_null';

  /**
   * {@inheritdoc}
   */
  public function getPropertyDefinitions(DatasourceInterface $datasource = NULL) {
    $properties = [];

    if (!$datasource) {
      $definition = [
        'label' => $this->t('Has My Field'),
        'description' => $this->t('Does this have my field?'),
        'type' => 'string',
        'processor_id' => $this->getPluginId(),
      ];
      $properties[$this->processor_id] = new ProcessorProperty($definition);
    }

    return $properties;
  }

  /**
   * {@inheritdoc}
   */
  public function addFieldValues(ItemInterface $item) {
    $entity = $item->getOriginalObject()->getValue();
    if (method_exists($entity, 'hasField') && $entity->hasField('field_my_field')) {
      $has_field = TRUE;
    }
    else {
      $has_field = FALSE;
    }

    $fields = $this->getFieldsHelper()
      ->filterForPropertyPath($item->getFields(), NULL, $this->processor_id);

    foreach ($fields as $field) {
      $field->addValue($has_field);
    }
  }

}


How do I print the {{messages}} variable?

By default the messages are in the highlighted region, put this in your page twig:

{{ page.highlighted }}

If you changed the block layout, go to

admin/structure/block

and check in which region you placed the status message block. When it is disabled, move it back into a region.


Where is the "Generate automatic URL alias" setting stored?

I was under the impression the "Generate automatic URL alias" setting would be saved in the database for each node. That's not the case.

Instead I just had to change the pathauto setting from "Create a new alias. Delete the old alias."   to "Do nothing. Leave the old alias intact."  (credits)


Not exactly. Field Collection main purpose is to make a field that holds other fields so the data can be logically grouped. So, no, you can't really "convert" it to an entity reference field - they store different data. An entity reference points at another entity; so you'd need an entity to be a container for that data. You can either achieve this via Entity API, or use ECK. I suppose you could write a migration/batch script to port over the data, but I really don't see the point unless the entities were going to be viewed on their own page.

You shouldn't have any issue with the number of rows in the database, the issue will arise when it comes to operating with that data. If you have an entity that has 1500 field collection items, and you load them for display, yes, you will have very severe performance issues. Think of it like calling entity_load 1500 times.

This usually rears its ugly head when you try to make some Views to display field collection items. Pro tip there - disable automatic preview in the Views config.

Here are some resources that may help:

https://drupal.stackexchange.com/a/105397/57
https://www.computerminds.co.uk/drupal-code/you-should-use-entity-cache
https://blog.openlucius.com/en/blog/drupal-field-collection-vs-drupal-compound-fields

This thread also has some good history on a group of people looking for performance improvements with Field Collections: https://www.drupal.org/node/1268620

Edit:

Forgot to link to Entity Cache, which you can bolt on to Field Collection.

In the past, I had came up with two solutions to solve performance bottlenecks revolving around Field Collection.

In one case, I would prime the cache with a nightly cron run, render the field collection field into a variable and cache that variable. If the cache item exists, I pass that as the template variable. This bypasses loading and rendering the field and rendering the data (entity_load) for every user requesting the page.

This works, until your cache item grows to over 1MB in which case it can still cause MySQL to slow down. You may also want to look into adding Memcache or Redis on top as the caching backend to alleviate that. Ultimately, MySQL will be your bottleneck - so you should try to offset that work and cache as much as possible in a caching backend.

In another case, I wound up storing the data in Solr. When the node was preprocessed, I would query Solr for that item. I was also storing the rendered result in Solr, so that my result already contained the rendered HTML. This was the fastest solution for end users, but came with a bit of work to keep it up to date. This is also beneficial if you also have to search through that data elsewhere, since you'd already (read: should) be working with Solr in that case.


Why not add a Text area view footer field?

You can set it to full HTML and just add an HTML anchor there. Optionally there is checkbox to 'Display even if the view has no results'.

This adds a custom link below your view.


Theme suggestion template is not being picked up

After you add your theme suggestion:
function discount_theme_suggestions_field_multiple_value_form_alter(array &$suggestions, array $variables) {
    if ($variables['element']['#field_name'] == 'user_discount'){
      $suggestions[] = 'field_user_discount';
    }
}

You need to tell Drupal in this hook you should pick my template by implementing hook_theme like the following.
/**
 * Implements hook_theme().
 */
function MODULE_theme($existing, $type, $theme, $path) {
  return [
    'field_user_discount' => [
      'base hook' => 'field_multiple_value_form'
    ],
  ];
}

Now just put your template in you templates module folder clear cache and it will be picked.
Note: if you want to use a different name from the suggested one (field-user-discount) of your template like field-user-discount-something.html.twig just tell the hook_theme the name of template like:
 /**
 * Implements hook_theme().
 */
function MODULE_theme($existing, $type, $theme, $path) {
  return [
    'field_user_discount' => [
      'base hook' => 'field_multiple_value_form',
      'template' => 'field-user-discount-something'
    ],
  ];
}


Image gallery with mobile view optimization

You may try out the Photoswipe module (dev).


Book revision page showing access denied if no revision present

If I understood this right, you have a (Nice) menu on node pages, and you've added the node/[node:nid]/revisions item to that menu. You're not actually listing revisions, just making a link to the revisions page, right?

If so, the problem is that the access callback for that menu item is hardcoded to return access denied if a node doesn't have revisions. Actually looks like this is being fixed for D8. Normally the tab wouldn't show, but it is in your case because you're creating the menu item in a different way, and the access is not checked when the link is printed. The solutions I can think of:

Replace the page with a view listing node revisions. Easy, but I don't know if you can replicate all the core revisions page functionality.
Create a wrapper menu item around the core revisions page using hook_menu(). Call it something else, like node/%node/revs. In the callback for that menu item, check if the node has revisions. If so, return the output of node_revision_overview($nid), the core function that generates that page. Otherwise, return 'No revisions'
Use hook_menu_alter() to take the existing revisions menu item (node/%node/revisions) and move it to your menu. Take a look at the definition of the menu item in node.module line 2043. You'll need to change it to not be a LOCAL_TASK and then use the menu_name property to tell it to get into your custom menu. I'm pretty sure this can work.


How to remove custom module provided entity instances by the time the module being uninstalled?

A potential duplicate.

The short answer (as I can see), you CAN'T right now remove content by the time you uninstalling the module. That makes you (us) to do it in two steps:

Write a update_hook where you remove all the content of the custom entity
You uninstall the module.
(drush cex, which removes the module from
    core.extension.yml)


You can use Views Flipped Table module.

  This module provides a views table style with rows and columns
  flipped. This is useful for views showing few entities with many
  fields, such as product comparison.


Yes see the Pager Options for your Block or Views Page:

EDIT:

Allow me to clarify. This gets the - All - text option into the configuration of the View. If you want custom business logic that says if there is 5 or more results I want to show/hide the Next and Previous and include the All options I recommend you look at hook_views_pre_view() or other Views hooks to implement hiding/removing options as needed. For ease I recommend hiding/showing the options using CSS or Javascript.

Again, this option builds the option into the page -- but doesn't really enforce your business logic.

EDIT 2:

The module Pagerer might get you a little further, but probably not all of your custom logic is possible out of the box with that module. It has an API to fine-grain it's custom pager views.


Unfortunately this is a bug in Facet API Pretty Paths module.
take a look at https://www.drupal.org/node/2423029 and ask maintainer to solve or suggest a solution for it.


Custom taxonomy; link with two content types

Drupal 7

Go to Structure > Content types, select "Manage fields" for the post content type. Either add the existing taxonomy field to it or add a new one. For a new one, choose which vocabulary should be used for this field.

Drupal 6

Go to Admin > Content > Taxonomy, edit your vocabulary. Then under content types, select the content types for which this vocabulary should be displayed.


The value of $form_state['values']['csv_file'] is empty (0) when you remove the file. You need to do a sanity check on $file after file_load not only for that reason but also as a good coding practice.

function custom_admin_form_submit(&$form, &$form_state) {
  // Saving the file, setting it to a permanent state, setting a FID variable
  $file = file_load($form_state['values']['csv_file']);
  if ($file) {
    $file->status = FILE_STATUS_PERMANENT;
    file_save($file);
    variable_set('csv_fid', $file->fid);
  }
  else {
    variable_set('csv_fid', '');
  }
}


is there a way to overwrite the views Sort criteria?

Sure, just use hook_views_query_alter().
You can intercept the view's query object and make any changes you need to it, including (but not limited to) adding/removing sort criteria.

Better WHERE's for your Drupal forums with hook_views_query_alter and Using hook_views_query_alter to change your views sort order give some examples of how to alter a view query.


Add basic page title and its teaser view in basic page

You can try Node Embed module.

Node Embed provides an input filter for CKEditor & FCKEditor integration allowing a content editor the ability to embed the rendering of nodes within the body/fields of another node.

Nice documentation for this module can be found here.


How to port vertical tabs functionality for custom node module to Drupal 7?

While driving me nuts yesterday, I started over again today and cleaned up the module a bit.
During that I tried to add another vertical tab again (#4) and this time it worked. By accident, I did re-use a group name and by this I finally was getting fully aware of how this is intended to work.

My mistake was to create a form element of type "vertical_tabs" for each first-level fieldset. But it is sufficient to only have on "vertical_tabs" form element and assign all fieldsets to that group (they actually are grouped then).

So, everything is fine with my code above but the last three lines are only required once.


Somehow, edit/delete has been changed to node->title/edit or node->title/delete for one of my project. Can anyone have idea what could be a reason?

On one of my projects, for this kind of functionality I have used Sub-path URL Alises module. Maybe it's enabled on your project ?


Custom 404 page in a theme doesn't work as expected,

Do what @jdu said and check the theme's template files for an error page template.  It will probably have the name page--error.tpl.php and probably be in /sites/all/themes/md_magnum/templates/

After that set your new error page URL in admin/config/site-information to the node you created.

To verify it is set you can check in your database under the variables table for site_404 to be set to that URL.

Make sure after you make these changes you clear cache completely and refresh your page.  If you are in Chrome, you may have to clear browser cache as well if you are using the same URL.


Does disabling a views features module remove the view from the DB

Disabling features will not disable all views in that features.
Feature is only used to export configurations,views etc to avoid manual work. You need to disable view from its UI page.


I would use CSS for that, and adjust CSS directives through the specific taxonomy vocabulary class, as appear in DOM.

I prefer CSS instead modularity as I think it would simplify the process and probably give you faster control over what vocabulary terms get what color, and on what circumstances.

Code example:

.field--name-field-categories .field-items {color: green}

Notes:

.field-label stands for the label.
.field-item stands for each vocabulary field-item.
.field__items stands for the whole row containing each vocabulary field-item.


What to enter into browser-sync command to run it on Aquia Dev Desktop?

You need to specify the hostname and port (patch.dd:8083) and the path to the CSS files you want to watch. Using the values in your example, you should therefore run:

browser-sync start --proxy "patch.dd:8083" --files "C:\patch\sites\all\themes\bootstrap_subtheme_local\css\style.css"


How to limit db_update() to update first n rows

It doesn't look like it's possible I'm afraid.

db_update() uses the UpdateQuery class, which doesn't support the range() method that a SelectQuery does.

You could probably subclass UpdateQuery and add that behaviour, but for the amount of work that would take you might be better off just using a raw SQL statement with db_query() like you've suggested.


Use replacements ..
You can simply edit the field and tick the box Next to "Exclude from display" this will hide the field, then you can Add a new field of type "Custom text"
In the "Text" section scroll until you see "REPLACEMENT PATTERNS" expand that and grab the {{ field_name }} < the field you want to use.
then in the text section put
{{ field_name }} your additional text.


Modify form elements based on current select box value in same form?

Certainly, you can utilize the #states setting.  Information can be found in the Drupal Forms API as well as in the drupal_process_states() API where you can see examples and documentation on how you can toggle your fieldset based upon the value of that select box.


How to have different displays for the same node type using Display Suite?

You can easily do this with display suite but you need to enable the DS extras module.

First create 2 different view modes using different layouts to cover your specific use case.

Next go to admin/structure/ds/list/extras and enable 'View mode per node'.

Now when you create content you can choose which view mode you would like the content to use.

This is a great way to give your content editors control over layout choice.


How I can give a particular style to maps in drupal site based on gmap module

I managed to do it by changing a little bit the gmap.js file. At the line 358

obj.bind("boot", function () {
    obj.map = new google.maps.Map(elem, obj.opts);
});

Add these line:

obj.bind("boot", function () {
     obj.opts.styles = [
                                        {
                                            "featureType": "water",
                                            "stylers": [
                                                { "color": "#808084" }
                                            ]
                                        },{
                                            "featureType": "road",
                                            "stylers": [
                                                { "color": "#c8cacc" }
                                            ]
                                        },{
                                            "featureType": "landscape.man_made",
                                            "stylers": [
                                                { "color": "#b0b3b4" }
                                            ]
                                        },{
                                            "featureType": "road",
                                            "elementType": "labels.text.fill",
                                            "stylers": [
                                                { "color": "#000000" }
                                            ]
                                        },{
                                            "featureType": "poi",
                                            "stylers": [
                                                { "color": "#9c9ea2" }
                                            ]
                                        },{
                                            "featureType": "poi",
                                            "elementType": "labels.text.fill",
                                            "stylers": [
                                                { "color": "#000000" }
                                            ]
                                        },{
                                            "featureType": "administrative",
                                            "elementType": "labels.text.fill",
                                            "stylers": [
                                                { "color": "#808080" }
                                            ]
                                        },{
                                            "featureType": "landscape.natural",
                                            "stylers": [
                                                { "color": "#808084" }
                                            ]
                                        },{
                                            "featureType": "transit",
                                            "stylers": [
                                                { "color": "#c9c9cc" }
                                            ]
                                        },{
                                            "featureType": "transit.station.rail",
                                            "stylers": [
                                                { "color": "#838080" }
                                            ]
                                        },{
                                            "featureType": "road.arterial",
                                            "stylers": [
                                                { "color": "#adaeb1" }
                                            ]
                                        },{
                                            "featureType": "poi",
                                            "elementType": "labels.icon",
                                            "stylers": [
                                                { "color": "#3e3d3a" },
                                                { "visibility": "off" }
                                            ]
                                        },{
                                            "featureType": "transit.station",
                                            "elementType": "labels",
                                            "stylers": [
                                                { "visibility": "off" }
                                            ]
                                        },{
                                        }
                                    ];
    obj.map = new google.maps.Map(elem, obj.opts);

});

Also check this thread:

drupal.org


How can we find the js file is included before or not in drupal

A. You should not be including jQuery manually in Drupal. Also, jQuery is always loaded on every page. If you need to include a different version of jQuery than the version that is included in Drupal core, you should utilize the jQuery Update module.

B. Secondly, you should be adding your javascript files using the drupal_add_js() function. Utilizing this function will take care of a lot of potential issues involved in managing many javascript files across many pages on your site.

C. drupal_add_js() returns an array of all javascript files. You could load a javascript file conditionally based on the presence of another javascript file, like this:

  $scripts = drupal_add_js();

  if(!isset($scripts['path/to/script.js'])) {
    drupal_add_js('path/to/script.js');
  }

D. Be sure to thoroughly read the Drupal.org documentation about using javascript in Drupal. This will answer many of your questions and solve many of your issues regarding javascript in Drupal.


"View recent blog entries" only showing on admin's page but other users have blogs

In the permissions page (under 'People' in Drupal 7), 'create new content' has to be checked for the users.


I finally made it work.

function mymodule_commerce_commerce_cart_order_refresh($order_wrapper) {
  foreach ($order_wrapper->commerce_line_items as $delta => $line_item_wrapper) {
    $line_item = $line_item_wrapper->value();
    $type = $line_item_wrapper->commerce_product->value()->type;
    if ($type === 'insurance') {
      $package_price   = $line_item_wrapper->commerce_product->field_package_ref->commerce_price->amount->value();
      $warranty_price  = $line_item_wrapper->commerce_product->commerce_price->amount->value();
      $amount = _mymodule_commerce_calculate_policy_price($warranty_price, $package_price);
    }
    elseif ($type === 'little_product') {
      $amount = $line_item_wrapper->commerce_product->commerce_price->amount->value();
    }
    else {
      return TRUE;
    }
    $qty = $line_item->quantity;
    // This sets the unit price by adding a component price 'base_price'.
    mymodule_commerce_line_item_price_amount($line_item, $amount, 'commerce_unit_price');
    mymodule_commerce_line_item_price_amount($line_item, $qty * $amount, 'commerce_total');
    commerce_line_item_save($line_item);
    entity_get_controller('commerce_line_item')->resetCache(array($line_item->line_item_id));
  }
}


Is Migrate module supposed to be used for imports too?

Of course! That's why we split migrate_drupal and migrate. The latter is the API, it has the destinations, like the entities you are asking for. Handbook page is at https://drupal.org/node/2127611 useful article at http://webikon.com/cases/migrating-to-drupal-8


You can install Views Bulk Operations, create a View of those entities, and set up a delete operation. It should have configuration options to execute in batches. I have done this before to delete 100,000 records.

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


Your function is telling drupal to move $file->filename to public://abc and hence renamed to abc. Drupal is doing what you are asking to do.

your $destination should be - 'public://abc/' . $file->filename

file_move($file, $destination, FILE_EXIST_REPLACE );

Below code should work (though not tested):

 $file = file_load($fid);
 $destination = 'public://abc/';
 if(file_prepare_directory($destination, FILE_CREATE_DIRECTORY)) {
   file_move($file, $destination . $file->filename, FILE_EXIST_REPLACE);
 }


How to to render a webform (or any configurable form) in a node edit form?

In this instance it sounds like the paragraphs module solves your problem. However to answer your original question...

I would use entityform, not webform to do this.

Once you added all of your field to your entity form then you can use Inline Entity Form to embed the child form.


How to check if maintenance mode is enabled in Drupal 8?

The maintenance mode of the site is a boolean value stored in a state. You can access it like this:

$state = \Drupal::state()->get('system.maintenance_mode');


WYSIWYG+CKEditor outputting span with style attribute

So i might not have the most informed answer, but i think i have a solution:

I face the same problem on our D7 site.

It turns out, if you use Chrome, content you paste in the WYSIWYG usually gets these strange line-spacings. (Regardless of if you choose "paste as plain text", or copy-paste from Notepad).

Use Firefox - and you wont see any <span style="line-height: 1.538em;"> stuff in the HTML!

If anyone knows how to use Chrome and not have these span elements show up - please let me know!

Cheers,

R


Drupal behind a SSL offloading reverse proxy -- is this config correct?

You don't have to indicate $base_url = 'https://staging.example.com'; , you can have something like this:

server {
    listen              80;
    server_name         staging.example.com;
    return              301 https://$host$request_uri;
}

server {
    listen                  443 ssl;
    server_name             staging.example.com;
    ssl_certificate         $chained_cert_path
    ssl_certificate_key     $private_key_path;

    location / {
        proxy_pass          http://$backend_ip;
        proxy_set_header    Host $host;
        proxy_set_header    X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header    X-Forwarded-Proto $scheme;
        proxy_set_header    X-Real-IP $remote_addr;
    }
}

and in your Drupal settings:

$conf['reverse_proxy'] = TRUE;
$conf['reverse_proxy_addresses'] = array($proxy_ip);

// from http://devblog.more-onion.com/using-drupal-behind-reverse-proxy
if (
  isset($_SERVER['HTTP_X_FORWARDED_PROTO']) &&
  $_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https' &&
  !empty($conf['reverse_proxy']) &&
  in_array($_SERVER['REMOTE_ADDR'], $conf['reverse_proxy_addresses'])
) {
  $_SERVER['HTTPS'] = 'on';
  // This is hardcoded because there is no header specifying the original port.
  $_SERVER['SERVER_PORT'] = 443;
}


How to get node's title and send list of it to mail

You need to create custom module and implement hook_cron().

See:

https://drupal.org/developing/modules

Also check this post:
 How to create a task which run at cron time and send emails to users?

function get_node_titles() {
    $result = db_query('SELECT n.title FROM {node} n');

    $titles = array();
    foreach($result as $item) {
        $titles[]  = $item->title;
    }

    return $titles;
}


Restrict core to generate taxonomy terms' URLs

My approach to this previously has been to ensure that there are no links within the site to taxonomy terms and that they are removed from the XML sitepath (using https://www.drupal.org/project/xmlsitemap) so they don't get into the search engines' database in the first place.

I would also recommend a module such as https://www.drupal.org/project/rabbit_hole which can force either a redirect, page not found, or access denied for taxonomy pages (and others) automatically.

I don't think there's any sense in trying to remove taxonomy links from the system when you can use the modules above to achieve this automatically for you.


How to implement content access for groups of users?

The Organic Group module will come to your rescue. Read the documentation about how to use the module.
More about the module:

Enable users to create and manage their own 'groups'. Each group can have subscribers, and maintains a group home page where subscribers communicate amongst themselves.
They do so by posting the usual node types: blog, story, page, etc. A block is shown on the group home page which facilitates these posts. The block also provides summary information about the group.
Groups may be selective or not. Selective groups require approval in order to become a member, or even invitation -only groups. There are lots of preferences to configure groups as you need.


Accessing translation and language URL from hook_preprocess_menu()

I found the answer myself.

if($variables['menu_name'] == 'navigation') {
  $langcode = \Drupal::languageManager()->getCurrentLanguage()->getName();
  // Add the logic here.
}


more fields on a content type or more content types

My personal preference is to limit the amount of content types, for user friendly reasons. Clients can get confused when you throw a whole list of content types at them. Unless your products are very different to each other (car, washing machine, house), I'd go for the fields.

Maybe the Field Group module can help to keep things tidy in the backend part of a product node.


How do I modify the teaser products display page in Kickstart Commerce?

You'll want to look into Display Suite. Its a great module which allows you to not only create new view modes, but use special layouts for each view mode and content type. If you also have the Omega theme installed, Display Suite will give you some fluid, responsive layouts to choose from as well.

To be clear, Display Suite will create a layout within your page layout. It is specific to the view mode and that content type. I say this because styling might get muddy if you use it too much or inappropriately. That said, it's a great tool :)


Depending the field type, it could be:

For exemple for plain text:

$form['field_p_cert_fqdn']['widget'][0]['value']['#default_value']

or

$form['field_p_cert_fqdn']['widget'][0]['#default_value'];

or

$form['field_p_cert_fqdn']['widget']['#default_value'][0];

or for entity reference:

$form['field_p_cert_fqdn']['widget'][0]['target_id']['#default_value'];

or some other thing

I would recommend you to use the devel module: https://www.drupal.org/project/devel (with the kint submodule enable). With this, you can add

dpm($form);

in you alter function to get the structure of the $form.


What is the proper way to uninstall a module that adds a content type

You should not delete content types in hook_disable(). Instead, you should make sure callbacks are left sane, and all data you will need on hook_enable() is properly archived and secured from modification by other modules. Good idea is to use drupal_set_message() to warn about content type that should no longer be used or displayed, but that's site admin's responsibility.

On hook_uninstall() you are supposed to left the database as if your module was never there. Thus, feel free to delete content types that was created using node_type_save(), if there are any. The ones created with hook_node_info() will be deleted automatically. Again, setting message about orphanted content is good idea, but it's site admin's responsibility not to uninstall module he is still using, after all.

If your hook_node_info() defined content type is not deleted, just disabled, you can decide to explicitly delete it, but you are responsible for cleaning all the mess it may cause, like orphaned content. You risk serious site failure if you don't.

Edited to incorporate information from Clive's comments under other answer


How to correctly start a website using Git/Drush/Composer workflow?

Because my dev environment was Windows and the staging environment was Linux, the temporary folder differs.

I had to fix it using the admin pages of the file system.

Later I found that I will need to do this every time I use drush config-import so I decided to overwrite the value in settings.php as following:

$conf['file_temporary_path'] = '/tmp';


You can try drush archive-dump default,example.com,foo.com command to archive the DB and codebase. If it is not possibel through it, then you can create a shell script, which creates backup of the codebase and database.


How to combine different node in single views

For Applicant Profile use Profile 2 module instead of node. Then when you create the View of Job List, add relation to Flags, Content: Author and User:Profile, in that way you will get all the fields you need.


Display OR between two fileds in a content type

If you simply want to display "(OR)" between  two fields in content type, you can achieve this in form alter

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

    if ($form['#id'] == 'page-node-form'){ //contenttype-node-form

   $form['field_test']['#prefix'] = '
 OR';
       $form['field_test']['#suffix'] = '
';
       //where field_test is your file upload field
    }
 }


How do I open a custom module ajax form in colorbox popup?

If you output your form hidden in the html, you can pop it up with colorbox_inline.

If your form lives in a menu callback and has a path, you can put a rendered link to your page everywhere and it will open modal with colorbox_load - see also ng_lightbox, if you put your path in it's config.


Custom tokens breaking on node save with "node entity cannot have a URI" error

If the token is being generated before the node has been saved, this will cause a WSOD, since no URI can be created for the node. Entity URIs require an entity ID to built the path to the entity.

As such, I'd change your code to:

function MYMODULE_token_set_custom_type($node) {
  if ($alias = $node->toURL()->toString()) {
    preg_match('(/.*/)', $alias, $matches);
    if ($matches[0] == '/apples/') {
      return "Apples";
    }
    else {
      return "Oranges";
    }
  }
}


You have three options:

1) Apply the patch from https://drupal.org/node/1240216. It will give you a rules action that will remove the tax.

2) Always enter product prices without tax, then the VAT rules can just be made conditional based on the customer address.

3) Use commerce_vat (and commerce_eu_vat).

The first one is probably your easiest way out at this point.


'File used may not be referenced' if form field submits same image twice

Using the skumy's approach worked for me, but instead of putting 'managed_file' as the third parameter for $file_usage->add(), I put 'file'.

$fid = $config['image'][0];
$file = File::load($fid);
$file->status = FILE_STATUS_PERMANENT;
$file->save();
$file_usage = \Drupal::service('file.usage');
$file_usage->add($file, 'mymodule', 'file', $fid);

That's because putting 'managed_file' causes an error when I check the file usages, following the links in the "Used in" column in /admin/content/files, since in my installation does not exist any entity called 'managed_file'.

  The "managed_file" entity type does not exist

Using 'file' instead of 'managed_file' solves the problem.


I don't know really why but I have a solution for you
first put you result in a variable, ( try you result something like this Y/n/j )
then exclude variable by / and finally use your character.

$temp=date('Y/n/j');
list($y,$n,$j)=exclude('\/',$temp);
$final="$y\年 $n\月 $j\日";

I hope be useful for you. :)


How to do user relations, and User editing only their content?

You could use the Group module for this. Group allows for creating arbitrary collections of your content and users on your site, and grant access control permissions on those collections. The Group module creates groups as entities, making them fully fieldable, extensible and exportable.

Some basics about he Group module to be aware of:

Make sure you enable gnode, a submodule of the Group module.
For each group type you need to define the appropriate permissions (view, edit, delete, etc) for the various Content Types.
Every group can have users, roles and permissions attached to it (refer to "What are the various roles supported by the Group module?" for more details about that).

With the appropriate permissions configured, it's just a matter of assigning a node to a Group: based on how you configured the roles and permissions, the Group module will allowed/deny access for any user.
Refer to "How to create collections of content that can be accessed by users with various access levels?" for more  info about all this.

Resources

Community documentation for the Group module.
Video tutorial "How to use the Group module in Drupal 8 to manage editorial access control to different areas of a web site".


How do I change the redirect page for unpublished nodes?

The default behaviour is an "Access denied" page, because a visitor hasn't access to unpublished nodes.
It's not possible "nothing appens".
You could use Rules and create a Rule like this:

event: viewing a node
condition: user has role "anonymous"
condtion: node is unpublished
action: redirect to a custom page


How can I add an BCC or CC email with programmatically?

What you want to do is ensure you are defining a message type in your custom module, you can then target the message within a hook_mail_alter() to add the desired CC or BCC.
function MYMODULE_mail_alter(array &$message) {
  $bccEmail = 'test@test.com';

  if ($message['xxx'] == 'xxx') {
    $existingBcc = isset($message['headers']['Bcc']) ? $message['headers']['Bcc'] : '';
    $message['headers']['Bcc'] = implode(' ', array_merge(
      explode(' ', $existingBcc), [$bccEmail])
    );
  }
}

https://git.drupalcode.org/project/bcc/-/blob/8.x-3.x/bcc.module has an example of adding a bcc.


The argument has to be a route name.

Try:

$breadcrumbs->addLink(Link::createFromRoute($term_name, "entity.taxonomy_term.canonical", ["taxonomy_term" => $tid]));

See the docs for this method.


Displaying alternate text for a taxonomy term in node

You can override the display your theme node.tpl.php template. Place something like this in your template.php...

function MYTHEME_preprocess_node(&$variables) {
   $variables['price_display'] = '';
   if(isset($variables['node']->field_terms[LANGUAGE_NONE]) && is_array(($variables['node']->field_terms[LANGUAGE_NONE]))) {
     foreach($variables['node']->field_terms[LANGUAGE_NONE] as $tag) {
        if(isset($tag['taxonomy_term']) && $tag['taxonomy_term']->name == 'price') {
          $variables['price_display'] = 'see website';
          break;
        }
      }
    }
  }
}

At this point you should have the variable $price_display available to print out in node.tpl.php.


What's the difference between combining Rules conditions with AND and just have them follow one after the other?

No difference, except if you want to do something more complex like this:

____ AND _____ OR _____ AND _____

You can only do that with conditional rules. (If I recall correctly)


Javascript aggregation issue with new server

It's likely that your web server isn't sending the correct Content-Type or Content-Encoding header for compressed files.

Adding one of these to your httpd.conf file should solve the problem:

AddType application/x-gzip .gz .tgz

or

AddEncoding x-gzip .gz .tgz

There should be comments in your httpd.conf file that will help you determine which one's most appropriate for your situation (search for <IfModule mime_module> in that file if you're interested).


How to costumize the input fields but only in the page /user?

Check out the classes added to the opening body tag in the HTML. It will help you narrow down styles to just that page.

I know one of my D6 sites, there is a class in the body tag 'page-user' so you can use some CSS such as...

body.page-user .form-text {
  /* Add styling */
}

Inspect the HTML and style as necessary. :o)


Drupal7, draggable menu reordering missing, weight dropdowns instead

Has your client accidentally clicked on "Show/hide row weights" in the top right corner of the menu list?


Twig template print all comments but not the comment form

You must add a file to your template called

field--comment.html.twig

Use the following code.

{#
/**
 * @file
 * Theme override for comment fields.
 *
 * Available variables:
 * - attributes: HTML attributes for the containing element.
 * - label_hidden: Whether to show the field label or not.
 * - title_attributes: HTML attributes for the title.
 * - label: The label for the field.
 * - title_prefix: Additional output populated by modules, intended to be
 *   displayed in front of the main title tag that appears in the template.
 * - title_suffix: Additional title output populated by modules, intended to
 *   be displayed after the main title tag that appears in the template.
 * - comments: List of comments rendered through comment.html.twig.
 * - comment_form: The 'Add new comment' form.
 * - comment_display_mode: Is the comments are threaded.
 * - comment_type: The comment type bundle ID for the comment field.
 * - entity_type: The entity type to which the field belongs.
 * - field_name: The name of the field.
 * - field_type: The type of the field.
 * - label_display: The display settings for the label.
 *
 * @see template_preprocess_field()
 * @see comment_preprocess_field()
 */
#}
{%
  set classes = [
    'field',
    'field--name-' ~ field_name|clean_class,
    'field--type-' ~ field_type|clean_class,
    'field--label-' ~ label_display,
    'comment-wrapper',
  ]
%}
{%
  set title_classes = [
    'title',
    label_display == 'visually_hidden' ? 'visually-hidden',
  ]
%}

  {% if comments and not label_hidden %}
    {{ title_prefix }}

{{ label }}

    {{ title_suffix }}
  {% endif %}

  {{ comments }}

  {% if comment_form %}

{{ 'Add new comment'|t }}

    {{ comment_form }}
  {% endif %}


You can do this with a policy file.  See examples/policy.drush.inc.

In the example policy file, specific named destinations are rejected.  To increase the stability of the system, you could reverse this test to reject any destination except for known good targets, or perhaps some combination -- for example, you could reject sql-sync to any remote destination except @stage.

You probably should not allow sql-sync to @prod, but of course it's up to your policy to decide that.  For moving configuration stored in the database, see ctools_export_bonus.


Seems your preprocess function is the key. To get the value of a field, do the following:

$callout_tab = $node->get('field_active_callout_tab')->first()->getValue();
$variables['callout_options'] = $callout_tab['value'];

Really, please install the Devel submodule Kint and then check first what you get:

ksm($node->get('field_active_callout_tab')->value);

Which will most likely get you NULL or an array. So {% if callout_options == 'Single' %} can never work.

And regarding the subparagraph, all I could get was the entity ID:

{{ kint(content.field_paragraphs.0['#paragraph'].get('field_subparagraph').value) }}

but maybe I'm doing something wrong (and you already solved that yourself). But if the entity ID really is the maximum you can get you are better off loading the subparagraph in the preprocess function as well and pass the render array over to Twig like you did pass the bool. In theory this should work :)


Views Hacks does this with Views Selective Exposed Filters:

  Views Selective Exposed Filters

  On list and checkbox exposed filters, you can specify the filter
  option "Limit list to result set" to only display values that are
  actually returned in the view's results. The filter option "Further
  limit list to active filters" restricts the displayed values to view
  results obtained by applying exposed filter values.


Drupal 7 WYSIWYG Editor Auto Spell Check

The CKEditor is a very popular Drupal editor that already has a built in SCAYT as you can see here, as well as many other plugins and extensions.


Drupal 6 site not sending password reset emails

Are other kinds of mails correctly sent, or are ALL mails from the senong site discarded ?

If other mails are sent from the same server/site, then something's wrong with the Drupal installation.

If they're not and the sending server's logs are indicating a correct sending, then I'd check the destination server logs to see what's happening here. Sometimes mails got discarded for voodoo reasons, like blacklisting (which is not the same as spam detection) etc.


Dynamically changing the href on a link with data-dialog-type = modal does not work

Presumably, the JS used to generate the dynamic href is on the page that the modal opens?  If I'm not mistaken, iframes do not run their attached scripts by default.  So this page may be helpful:

https://stackoverflow.com/questions/251420/invoking-javascript-code-in-an-iframe-from-the-parent-page?utm_medium=organic&utm_source=google_rich_qa&utm_campaign=google_rich_qa

Since your requested iframe is on the same domain as your parent page, there shouldn't be any CORS issue.


8 - How do a get a view then save it with a new value

Replace

// **************
// SAVE VIEW HERE
// **************

with

$view_exec = Views::getView($view->id());
$view_exec->setHandlerOption($display_key, 'sort', 'weight', 'source', $source_value);
$view_exec->save();

When you call Views::getEnabledViews() it gives you an array of View classes.  What you need is the ViewsExecutable class.   Views::getView($id) returns this.

ViewsExecutable

  An object to contain all of the data to generate a view, plus the member functions to build the view query, execute the query and render the output.

Views vs ViewsExecutable

Another good example of using setHandlerOptions is in the TestCase

FieldGroupRowTest


Drupal Commerce Kickstart 2 Mysql problem: "Table XYZ is marked as crashed and should be repaired"

I have run into this problem a few times. It is indeed not directly Drupal related. However, since we are looking at MySQL through a Drupal lens, I guess we might as well answer it here.

The real source of the problem is a performance problem for your MySQL server. Drupal might have contributed to the problem by adding too much load. When I ran into a similar problem, I found out that a module I had written was making a huge amount of inserts into the access_log table, which then caused the table (and sometimes other tables) to crash. I ended up migrating to stronger hardware, which made the problem occur less frequently. Then I cleaned up my code to insert only what I really needed and the problem was gone.

I suspect, you will probably see this problem first on the tables that have the fastest growth rate. If so, take a look at which Drupal module inserts into them and find out, if you can optimize your insert strategy. If you can't, you might have to move your MySQL server to a separate machine or upgrade the hardware you are running on.


Save FileField file to an external server

As far as I know, there is no other way to do this in Drupal 6 than what CDN does.

In Drupal 7, this is a completely different story, however. Drupal 7 uses stream wrappers when dealing with files and it is a) possible to implement custom stream wrappers with PHP code and b) the stream wrapper can be chosen per file/imagefield.

So if it is possible to access X with PHP (FTP, Flickr, Amazon S3, ..) then it should be possible to write a stream wrapper for it and therefore allowing Drupal to write the files to that place.

This probably doesn't help you in your situation, but maybe it will help someone else, when deciding to use Drupal 6 or 7 for a new project for example :)


You can use hook_menu_alter().

Example :

/**
 * Implements hook_menu_alter().
 */
function Module_menu_alter(&$items) {
  $items['node/%node/delete']['page arguments'] = array('_custom_node_delete', 1);
}

/*
 * Custom delete.
 */
function _custom_node_delete($form, &$form_state, $node) {
  node_delete($node->nid);
  cache_clear_all();
  watchdog('content', '@type: deleted %title.', array('@type' => $node->type, '%title' => $node->title));
  drupal_set_message(
    t('@type %title has been deleted.', array('@type' => node_type_get_name($node), '%title' => $node->title))
  );
  $form_state['redirect'] = '<front>';
}


in your module use hook_theme() in drupal 7

function YOURMODULE_theme() {
  return array(
    'YOURMODULE_CUSTOM_THEME_NAME' => array(
      'variables' => array('title' => NULL, 'path' => NULL), // eg: if you want $title, $path in ur tpl. you can use any variable or an entire array/object.
      'template' => 'CUSTOM-TPL',
    ),
  );

and in your module folder ,create CUSTOM-TPL.tpl.php

now you can call it in

$block['content'] = theme('YOURMODULE_CUSTOM_THEME_NAME', array('title' => $title, 'path' => $path));

for drupal 6 , user 'arguments' instead of 'variables' and

theme('YOURMODULE_CUSTOM_THEME_NAME', $title, $path);


Manually removing an orphaned entity type

In case it is of use to anyone else dealing with an old module that doesn't uninstall correctly. The solution to my problem was the following.
WARNING: Do this on a copy of your actual site and database. You could break a live site doing this.
Most of the troublesome database entries are in the config table.
You can use the error list produced above when trying to install the module to track down the rows to purge.
In the database a query such as:
SELECT name FROM config WHERE name LIKE '%support_ticket%';
should show you most of the problematic entries.
In my case that exactly matched the offending active configuration so i could just change the above to:
DELETE FROM config WHERE name LIKE '%support_ticket%';
I would be very careful about doing this with a LIKE query unless you are sure you won't accidentally delete something else.
I assume directly removing entries like this in the database is probably a bad idea but I really couldn't find another way to move forward.
Once the above is done Drush updb worked and the update completed.


How do I add conditional fields to a paragraph?

I've used form states with these pre-requisites:

Form states with paragraphs
The content widget used is: Inline Entity Form - Complex
The widget should be changed, not the field

There is this content type with the paragraph reference with a two-fields paragraph: content reference and content number. The content reference field cardinality is 5, and the number of content is a select list (1, 2, 3, or 5). So, the logic is used to enable the content input according to the number of content selected.
This was the solution I've used, hopefully, it can help someone else:
/**
 * Implements hook_field_widget_WIDGET_TYPE_form_alter().
 */
function HOOK_inline_entity_form_entity_form_alter(&$entity_form, &$form_state) {
  if ($entity_form['#entity_type'] === 'paragraph' && $entity_form['#bundle'] === 'PARAGRAPH_BUNDLE') {
    $parents = $entity_form['#parents'];
    // It needs to get the parent form (content type form field) in order to work fine.
    $identifier = $parents[0] . '[' . implode('][', array_slice($parents, 1)) . ']';
    // I need to use the target_id to aim the wdiget.
    // The first input should be shown if I select 1, 2, 3, or 5 content to be added.
    $entity_form["field_content_reference"]["widget"][0]["target_id"]['#states'] = [
      'enabled' => [
        'select[name="' . $identifier . '[field_content_number]"]' => [
          ['value' => 1],
          'or',
          ['value' => 2],
          'or',
          ['value' => 3],
          'or',
          ['value' => 5],
        ],
      ],
    ];
    // The second input should be shown if I select 2, 3, or 5 content to be added.
    $entity_form["field_content_reference"]["widget"][1]["target_id"]['#states'] = [
      'enabled' => [
        'select[name="' . $identifier . '[field_content_number]"]' => [
          ['value' => 2],
          'or',
          ['value' => 3],
          'or',
          ['value' => 5],
        ],
      ],
    ];
    // The third input should be shown if I select 3, or 5 content to be added.
    $entity_form["field_content_reference"]["widget"][2]["target_id"]['#states'] = [
      'enabled' => [
        'select[name="' . $identifier . '[field_content_number]"]' => [
          ['value' => 3],
          'or',
          ['value' => 5],
        ],
      ],
    ];
    // The rest of the input should be shown if I select 5 content to be added.
    $entity_form["field_content_reference"]["widget"][3]["target_id"]['#states'] = [
      'enabled' => [
        'select[name="' . $identifier . '[field_content_number]"]' => ['value' => 5],
      ],
    ];
    $entity_form["field_content_reference"]["widget"][4]["target_id"]['#states'] = [
      'enabled' => [
        'select[name="' . $identifier . '[field_content_number]"]' => ['value' => 5],
      ],
    ];
  }
}


How to optimize APC when running many sites with common codebase?

I think the key here is to limit the total number and size of your PHP scripts. You've already taken the first step by running them off a shared codebase. The next step is to make sure you're not duplicating modules or themes that are shared. For example, you should have sites/all/modules/views, not sites/site1.com/modules/views and sites/site2.com/modules/views.

Once you've done that, I can't imagine that the total size of your php files would be more than, say, 200MB.

The next step is to configure APC and figure out exactly how large all of your php scripts are. For a production server, I like to permanently cache my php scripts. Place the following in your apc.ini file:

apc.enabled=1
apc.shm_segments=1
apc.shm_size=512
apc.cache_by_default=1
apc.stat=0
apc.ttl=0

Note the apc.shm_size=512 setting. We've purposely set it to something much larger than we think we will need. Once this is set (and you've restarted Apache), you should hit every single php script on your site so APC caches each of them. This includes the module admin page, views, theme pages etcetera for each of your sites. Once you're done with that, load up the apc.php script and see how much memory APC is actually using and adjust the apc.shm_size downward accordingly.

I have detailed instuctions on configuring APC for Drupal on Github.


hook_image_effect_info_alter() doesn't change effect callback

I found the issue.

It turns out there was another custom module "restoring" the original callback.


Send reminder to referenced users day before event date in cck date field

I will show you how to do it when a new event is created. You must in addition provide for when an event is updated (by deleting the scheduled event and rescheduling it) and when an event is deleted (by deleting the scheduled event). If an event does not exist and you delete it it won't throw an error, so it is acceptable to do it.

You need the following additional modules installed: Views and Views Bulk Operations, reason being you will use views to obtain the list of emails and VBO is needed to interface it with Rules.

STEP 1
Start by adding a view (don't select page or block in wizard as we only want a master) of type 'Users'. Remove the sort and pager as it is not necessary.

Add a relationship 'A bridge to the Content entity that is referencing User via field_staff' and make it required.

Add a contextual filter of nid: 'The node ID.', make sure the relationship created earlier is selected, and Hide view when filter value is not available.

Add a field 'Bulk operations: User' and accept the default. This is the important field and technically the only field needed.

Test the view by typing a known node id in the preview field.

STEP 2
Create a Rules component of type 'Action Set' and call it 'Send Notification'. Add a Variable of 'Entity: Node', give it a label and machine name of 'node'.

Add an action to this component: 'Load a list of entity object from a VBO View'. Select the view you created earlier. Set its argument to '[node:nid]' and leave the provide variables at default. Note the variable name of the List of entities: entity_list.

Add a loop to this action, and select 'entity-list' as the Data Selector. Note the default name of the current list item: list_item.

Add an action to the loop (note: add it to the loop and not the component) of 'System: Send Mail'. In the to value select '[list-item:mail]'. Fill the rest out the way you want.

STEP 3
Add a new rule and call it 'On new event', to react on 'Node: After saving new content'. Restrict it to type 'event'.

Add an action to this rule, 'Rules schduler: schedule component evaluation', and select the 'send notification' component you created earlier.

Set the evaluation date to node:field-event-date.

Add an offset: -1 days

Add an identifier of 'node-[node:nid]-event' and note its pattern as you will be using it to delete events.

Select the Node as 'node'

That should be the gist of it.


How to programmatically create a node on user registration with the user as author?

In an insert hook the user is already saved and should have an user id. So creating a node and assigning it to the new user as author should be no problem:

/**
 * Implements hook_ENTITY_TYPE_insert() for user entities.
 *
 * Adds a first node for a new user
 */
function mymodule_user_insert(\Drupal\user\UserInterface $user) {
  \Drupal\node\Entity\Node::create([
    'type' => 'XYZ',
    'title' => 'First node for user #' . $user->id(),
    'uid' => $user->id(),
  ])->save();
}


How do I programatically add address to commerce order

To record the address on the order, you must create a customer profile of the relevant type (billing information or, if you have Commerce Shipping on the site, shipping information), populate its addressfield value, and reference it from the order you've created. My recommendation would be to use the entity_metadata_wrapper() from the Entity API to manipulate those field values.

The addressfield on the customer profile you need to populate is commerce_customer_address, and the reference field on the order is commerce_customer_billing (or _shipping respectively).


How to make global math expresssion in views searchable?

views doesn't allow to filter data based on computational field. In your case you are using global math function which is a calculated field.

I would suggest to use computed_field module and calculate your value in this field then you can easily filter your result based on this field.


Issues with updating modules on Drupal 7

I have encounted this in the past and usually you get a module that causes an issue with AJAX.

What I would suggest is to update modules manually (download from drupal.org, extract and upload then run update.php) or via drush one by one.

If you are doing multiple modules at once this can happen quite often.

Also make sure you have Overlay module disabled as for some odd reason this can cause the same error.

Your best bet is to update modules one by one to isolate which module is causing the issue.


You need to place

 $form['hotels']['rooms'] = array(
    '#collapsed' => '0',
    '#type' => 'fieldset',
    '#collapsible' => '0',
    '#prefix' => '
',
    '#suffix' => '
',
);

in globallink_ui_search_form function. The wrapper tag must be loaded before callback send.


How to enable field_ui "Manage display" for a custom entity?

I'm pretty sure your view display configuration there is invalid, there is no "file" formatter. There are many formatters for file fields but none is called just file, there is file_link, file_uri, file_default and many more, you have to pick the one you want.

Granted, the error handling there could be better. Feel free to open a core issue about that.


View filtered by taxonomy term - is there a better way?

Create a view with an exposed filter for each News category.
Under its settings, in Admin, there is a Filter identifier which can be changed. This goes after ? in the URL.
Build your menu to link to the new view and add the category after the filter identifier.

The benefit of this is you can do it with any view so your tpl will work. And users can change category quickly using the dropdown menu. Or you can hide the exposed filter with CSS and make them use the menu.


form_set_error: How to set for an array Drupal 6

There is a comment on the API page for form_set_error which explains how to set a form error on a subelement of a form item.

From the comment:

form_set_error('field_name][i][value', t('Your message'));


Infinite scroll is firing multiple times

When using Drupal.behaviors you need to use .once('behaviorName')

$(window).scroll(function(){

needs to be:

$(window, context).once('news').scroll(function(){


When the BigPipe module is installed, the animation does not work

Bigpipe's purpose is to load dynamic/uncachable blocks of content (e.g. forms) in via javascript. This is so that the rest of the site can remain cached and just the dynamic parts get loaded in separate.

So the issue here is probably your own javascript is triggering before big pipe has loaded the targeted content in. Have you got your JS in window.load or something like that? You should place it into a Drupal behaviour which will get called each time something dynamic is loaded in by drupal.


How to use multiple reverse relationships from different content types in a single View Drupal 7?

Going of memory here, so things may not be exact.

One possible solution:

For Contextual Filter add Industry

When Filter is not in the URL select fixed value

Type select fixed

In the text box put construction

Another possible solution, if your Industry field is tax term reference field then add Terms of the node as a relationship. Then in Filter Criteria (below Fields), add tax terms and type your term name construction


Try making it absolute:

$options = array(
  'type' => 'external',
  'scope' => 'footer',
  'weight' => 5,
  'absolute' => TRUE
);
drupal_add_js(path_to_theme() . '/js/script.js', $options);


Use hook_hook_info() to implement hook_form_FORM_ID_alter()s in a separate file

It works pretty well, the only thing is that if you want to implement hook_form_FORM_ID_alter(), you need to add:

  $hooks['form_FORM_ID_alter'] = array(
    'group' => 'form'
  );
  return $hooks;


You can add the html in your form_alter, just use '#type' => 'markup'.


Yes, create a utility module, so your consumer modules can declare a dependency to the utility module in their .info.yml file. Optionally to keep the admin UI clean you could use hidden: true in the utility module's .info.yml

(I assumed you are speaking of a very drupal-specific helper lib, not some general purpose library like e.g. Guzzle that would go into composer)


How do I enable CORS on Service endpoint?

If your endpoint is "your.host/api/v1/" this minimal CORS module configuration should work for anonymous GET requests:

api/v1/*|<mirror>


<?php
$node = menu_get_object();

if(node_access('update', $node)) :
    $lang = 'en';
    $translations = translation_node_get_translations($node->tnid);
    $translated_node = (isset($translations[$lang])) ? node_load($translations[$lang]->nid) : $node;
    if(is_object($translated_node)) :
?>

English title: <?php print $translated_node->title; ?>

<?php endif; ?>
<?php endif; ?>

Directly in tpl file.


public:// urls being printed in source code

Drupal 7 uses stream wrappers instead of "file paths" to reference files in the public and private upload directories. If you want to research that more, the rabbit hole starts here - http://drupal.org/node/555118

In a "vanilla" D7 setup "public://" is equivalent to the D6 "sites//files" or "sites/default/files" directory. These directories still exist in D7 but have been moved in D8 - using a stream wrapper means the files can be moved anywhere, even a remote location, and still be referenced in a consistent fashion if you update the default stream wrapper.

Clive's comment referencing file_create_url() is a function that takes a stream uri and converts it to a url that a web browser can use.

The problem is that your server-side code delivering media to jPlayer is not sending URIs in the right format. If it's a contrib module, you should open an issue in the queue and link to it here; Clive or myself might be able to provide a patch.

I'm going to assume that the module you're using was originally released in D6 and then upgraded at some point to D7? (maybe the upgrade didn't go so well :P)

Edit:

Based on the code that was posted after I originally put this answer up I'd suggest looking into two things:

Shouldn't
$file->url = str_replace('public:/', $base_url . '/' . variable_get('file_public_path', 'files'), $file->uri);
be
$file->url = file_create_url($file->uri); ?
The "setMedia" action for jPlayer, I can't remember off the top of my head if it needs to be a url or a file path, but if it's a url shouldn't you be using $file->url? if it's a file path shouldn't it be generated by drupal_realpath()?


How to create template file for specific node?

In Drupal 7, you can use node--[node-id].tpl.php for theming specific nodes. In your case, you can use node--3.tpl.php.


uid shouldn't be 0, just change 'uid' => '0' by 'uid'=> \Drupal::currentUser()->id():

$file_data = file_get_contents('http://www.africau.edu/images/default/sample.pdf');
$file = file_save_data($file_data, 'public://3010.pdf', FILE_EXISTS_REPLACE);
$media = Media::create([
  'bundle'           => 'file',
  'uid'              => \Drupal::currentUser()->id(),
  'field_media_file' => [
    'target_id' => $file->id(),
  ],
]);
$media->setName('Hello')->setPublished(TRUE)->save();


Using ImageStyle with dependency injection

Yes, inject the entity_type.manager service and load it that way:

$url = $this->entityTypeManager
  ->getStorage('image_style')
  ->load('machine_name')
  ->buildUrl($path);


You can simply use Field Permissions module:

  Author-level permissions allow viewing and editing of fields based on who the entity owner
  is.

This seems to be exactly what you need.

To have real field (not display suite element), you can use Computed Field - more complicated than Display Suite, true, but at the same time more versatile and integrates well with everything field-related.

On the other hand, you can forget all these modules, and in your node.tpl.php simply compare current user id with node author's id, and if they are equal, print your data.


I've had success utilizing the Bootstrap Library module.

  This module loads via libraries the Bootstrap files installed on /sites/all/libraries/bootstrap, regardless of the theme you are using. It does nothing else.

  When using Bootstrap themes is particularly helpful to:

  Correct Browser Support issues, installing respond.js.
  Update your Bootstrap version over your current theme options.
  Just to avoid CDN files loading.


You could use hook_form_alter(),
In this hook we could redirect with $form['redirect'] = $url;


How to show only user assigned contents in his dashboard?

In your view simply follow these steps:

Click the Advance Tab under the RELATIONSHIPS add a new relationship  Content:Author

Keep the Identifier as it is, but remember to check the Require this relationship option.

Now, under FILTER CRITERIA add a new filter User: Current and check the Is the logged in user as Yes

The exported code:
$view = new view();
$view->name = 'article';
$view->description = '';
$view->tag = 'default';
$view->base_table = 'node';
$view->human_name = 'Article';
$view->core = 7;
$view->api_version = '3.0';
$view->disabled = FALSE; /* Edit this to true to make a default view disabled initially */

/* Display: Master */
$handler = $view->new_display('default', 'Master', 'default');
$handler->display->display_options['title'] = 'Article';
$handler->display->display_options['use_more_always'] = FALSE;
$handler->display->display_options['access']['type'] = 'perm';
$handler->display->display_options['cache']['type'] = 'none';
$handler->display->display_options['query']['type'] = 'views_query';
$handler->display->display_options['exposed_form']['type'] = 'basic';
$handler->display->display_options['pager']['type'] = 'full';
$handler->display->display_options['pager']['options']['items_per_page'] = '10';
$handler->display->display_options['style_plugin'] = 'default';
$handler->display->display_options['row_plugin'] = 'fields';
/* Relationship: Content: Author */
$handler->display->display_options['relationships']['uid']['id'] = 'uid';
$handler->display->display_options['relationships']['uid']['table'] = 'node';
$handler->display->display_options['relationships']['uid']['field'] = 'uid';
$handler->display->display_options['relationships']['uid']['required'] = TRUE;
/* Field: Content: Title */
$handler->display->display_options['fields']['title']['id'] = 'title';
$handler->display->display_options['fields']['title']['table'] = 'node';
$handler->display->display_options['fields']['title']['field'] = 'title';
$handler->display->display_options['fields']['title']['label'] = '';
$handler->display->display_options['fields']['title']['alter']['word_boundary'] = FALSE;
$handler->display->display_options['fields']['title']['alter']['ellipsis'] = FALSE;
/* Sort criterion: Content: Post date */
$handler->display->display_options['sorts']['created']['id'] = 'created';
$handler->display->display_options['sorts']['created']['table'] = 'node';
$handler->display->display_options['sorts']['created']['field'] = 'created';
$handler->display->display_options['sorts']['created']['order'] = 'DESC';
/* Filter criterion: Content: Published */
$handler->display->display_options['filters']['status']['id'] = 'status';
$handler->display->display_options['filters']['status']['table'] = 'node';
$handler->display->display_options['filters']['status']['field'] = 'status';
$handler->display->display_options['filters']['status']['value'] = 1;
$handler->display->display_options['filters']['status']['group'] = 1;
$handler->display->display_options['filters']['status']['expose']['operator'] = FALSE;
/* Filter criterion: Content: Type */
$handler->display->display_options['filters']['type']['id'] = 'type';
$handler->display->display_options['filters']['type']['table'] = 'node';
$handler->display->display_options['filters']['type']['field'] = 'type';
$handler->display->display_options['filters']['type']['value'] = array(
  'article' => 'article',
);
/* Filter criterion: User: Current */
$handler->display->display_options['filters']['uid_current']['id'] = 'uid_current';
$handler->display->display_options['filters']['uid_current']['table'] = 'users';
$handler->display->display_options['filters']['uid_current']['field'] = 'uid_current';
$handler->display->display_options['filters']['uid_current']['relationship'] = 'uid';
$handler->display->display_options['filters']['uid_current']['value'] = '1';
$handler->display->display_options['filters']['uid_current']['expose']['operator_id'] = '';
$handler->display->display_options['filters']['uid_current']['expose']['label'] = 'Is the logged in user';
$handler->display->display_options['filters']['uid_current']['expose']['operator'] = 'uid_current_op';
$handler->display->display_options['filters']['uid_current']['expose']['identifier'] = 'uid_current';
$handler->display->display_options['filters']['uid_current']['expose']['required'] = TRUE;

/* Display: Page */
$handler = $view->new_display('page', 'Page', 'page');
$handler->display->display_options['path'] = 'article';

Cheers!


Database administration site on Drupal: entities vs. manual programming

While I can't see any significant benefits to doing this with Drupal, I think this should generally work. I've converted old systems that were using db_query and custom code to Drupal 7 Entities with the Entity API module with success, and I've been pretty pleased with the results. As long as the schema is solid, without issues, or you can modify it as needed, this will work fine.

Depending on the data structures and the normalization of related entities/properties you may need to create your own EntityController to override the loading (and saving if using Entity API module) to ensure that the data is queried and updated properly.


How to know when a node is going to be deleted when using Rules Event "Before saving content"?

Have a look at this rule (in Rules export format):

{ "rules_before_saving_content_but_not_when_deleting" : {
    "LABEL" : "Before saving content but not when deleting",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "ON" : { "node_presave" : [] },
    "DO" : [
      { "drupal_message" : { "message" : "The path of the content being saved = [site:current-page:path]" } }
    ]
  }
}

If you request an edit a node (say with nid=71) your path will be node/71/edit. If you then save the node by hitting the Save button, the above rule will show a Drupal message like so:

The path of the content being saved = node/71/edit

If you request an edit a node (say with nid=72), your path will be node/72/edit. But if you then decide to delete (instead of save) the node by hitting the Delete button, then no Drupal message (similar to the previous scenario above) will be shown.

This (rather basic) Rules debugging scenario, leads me to believe that, out-of-the-Rules-box, Rules Event Before saving content does NOT get triggered when a node is deleted. So whatever problem you are experiencing (when a node is deleted), it must be because of something else happening in your site, in your custom rule, or your custom code of your rule. If I was to further investigate your issue, I'd start "Rules debugging", as explained in the answer to "How can I display the value of a variable inside a condition?".

PS: a quick-and-dirty workaround for whatever issue you're experiencing, might be to check the results you get by adding an extra Rules Condition to check if the (saved) node will still have status "published" (assuming a deleted node is no longer marked as "published").


How do I use an array with an 'IN' condition on EntityFieldQuery::entityCondition?

Correct me if I'm wrong, but aren't commerce_product and product_share bundles not entity_type's (both of entity_type node)?

I think you may want:

// The types we're looking for.
$types = array('commerce_product', 'produce_share');

// Build the query.
$query = new EntityFieldQuery()

  // Looking for nodes.
  ->entityCondition('entity_type', 'node')

  // With the specific bundles.
  ->entityConditiion('bundle', $types, 'IN');

// Run the query.
$result = $query->execute();

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


Does my Feature module have to explicitly define the body field in it's components?

... I always do. :)  It should be no problem -- and if for some reason the field doesn't exist on the destination server it will then be created (the Minimal install profile for instance I don't think has the body field by default). If you look in /profiles/standard/standard.install you'll see it creates the fields and basic content types in code, eg:

// Around line 229 of standard.install where $type is
// essentially 'page' or 'article'.
node_add_body_field($type);


Page not found on new server in Drupal 7 custom module

Turns out the module requires curl which the server didn't have.  The module didn't bring down the whole site but just didn't work itself.  No way anybody could have diagnosed that!


How to fix my String Translation error in my selection list value?

This can be fixed via a hook_form_alter, in which you loop through all select list options and run the option text through decode_entities().

Refer to HTML Encoding in Drupal Entity References for more details, which also includes this code sample:

function misc_form_alter(&$form, &$form_state, $form_id) {
 $to_fix = array('field_reference');
 foreach($to_fix as $fix) {
   if (isset($form[$fix]) && isset($form[$fix][$form[$fix]['#language']]['#options'])) {
     foreach($form[$fix][$form[$fix]['#language']]['#options'] as &$text) {
       $text = decode_entities($text);
     }
   }
 }

}


How can I remove the "This translation is published" checkbox?

So it turns out I needed to define a translation handler for my entity.

inside of MyEntityTranslationHandler that extends the ContentTranslationHandler I override the entityFormAlter function and add this:

$form['content_translation']['status']['#access'] = FALSE;


How do I resolve an unnamed requirements problem during an update?

Since the database information was transferred into a new settings.php file instead of keeping the old one, it is possible that the the custom value for the path to the synch configuration directory is not found.

Reference: Upgrading Drupal

Look for the code:

$config_directories['sync'] = 'sites\default\files\your-config-folder

in the settings.php file & update it to match the address on your web server.

"This solution worked for me.
In order to find that config_gobblygook, I looked in docroot/sites/default/files and in there is a folder named config_ and then a whole bunch of letters and numbers. I copied that full name and then inserted it into line 247 of the settings.php file."

The same problem is described here with a similar solution.

Related:

Changing the storage location of the sync directory
How do I fix this Configuration Directory sync error?

Otherwise make sure the most recent nginx.conf file for Drupal is in use, as there have been changes to that to fix the update.php issue. See:

web /update.php sequence does not work with Drupal 8
Drupal 8 Nginx configuration on Homestead (update.php works ok)
Latest Version - NGINX


This is a container parameter now.

Put this in services.yml or another service definition YAML file:

parameters:
  session.storage.options:
    cookie_domain: '.domain.com'

Since it is in a yaml file, it can't easily be dynamic, one option you have is having multiple yml files, and you dynamically add the one for the right environment, or you have a services.local.yml, just like settings.local.php that you have on each environment and not in git.


rendering node $content but not all $content is there

Check your display options for that content type to make sure that those fields are set to display in teaser mode.

Drupal 6: admin/content/node-type/NAME-OF-CONTENT-TYPE/display

Drupal 7: admin/structure/types/manage/NAME-OF-CONTENT-TYPE/display


Permissions are stored in the permission table.

The table stores a comma-separated list of permissions that are enabled for each role, by role ID, which links back to the role table.

The users_roles table makes the final link between users and the roles assigned to them.


How can I write a query to get a list of users who have registered in the last 24 hours?

It seems to me that you aren't doing anything wrong; it's just that the object you will get back from db_query() in your case is not something you can use as is.

Invoke ->fetchField() method after db_query() so that Drupal's DB API returns you one single value.

Use this:

$users_registered = db_query("SELECT COUNT(DISTINCT u.uid) FROM {users} u WHERE u.created >= :timestamp AND u.uid > 0", array(':timestamp' => (REQUEST_TIME - 86400)));

Also, use REQUEST_TIME constant to get current timestamp.

Hope this helps.


Image styles with $settings['file_public_base_url']?

Finally got it working. It seems that currently there is a bug in the image core module that prevents the use of absolute paths in the $settings['file_public_path'].

For those interested, you can follow the issue where you can find the patch attached.

Note, that you must also set some rewrite rules on your static files server to get it working. I provided a docker example on how to configure this on GitHub, but mainly here are the main config:

Vhost configuration of the static file server

Configuration example provided for Nginx:

server {
    listen 80  default_server;
    root /files/domain.fr/public;

    index index.html index.htm;

    location @rewrite {
        rewrite ^/(.*)$ http://DRUPAL.SERVER.IP/files/domain.fr/public/$1;
    }

    location ~ ^/styles {
       try_files $uri @rewrite;
    }

    location ~ ^/core {
        rewrite ^/(.*)$ http://DRUPAL.SERVER.IP/$1;
    }
}

Drupal settings file

Add this to your settings.php file:

$settings['file_public_base_url'] = 'http://STATIC.WEB.SERVER';
$settings['file_public_path'] = '/files/domain.fr/public';