What are effective optimization techniques for Views 3? I have been doing a bit of profiling on a site I am working on which extensively uses views.

Views takes up about 2/3 of the processing time even with the views caching on. Are there best practice ways to speed up views, or things which are known to cause performance hits.

I should add that the views are solr views, so this is a question mostly about the views architecture rather than optimizing queries.

Have tried using APC, but it didn't change the execution time much.

You first should find out where the performance bottleneck is.

Is it the executing of the query
Is it the rendering of the view
Is it a specific function

See http://drupalperformanceblog.com/drupal-xhprof-profiling about the article.

Once you have the problem it's possible to fix it.
You wrote that you had enabled views caching: Which kind of caching output or query cache?


How to add an autocomplete field to a form I've got a page that, in response to a button click, brings up a Bootstrap modal form.  In that form is a textfield with the standard Drupal autocomplete behavior; it's working fine.

I now want to set things up so that, after a value is put into that field, another mostly-identical autocomplete field is added to the form -- the idea is to let the user specify additional values for the property being handled by this part of the form.

I've hung a jQuery blur handler off the textfield that takes the HTML that ends up in the form for the initial autocomplete form, parameterizes it a bit to avoid duplicate ID numbers, and inserts this updated field into the form when the first field gets a value.  This is working fine from an HTML perspective, but the autocomplete behavior is not happening on the added form.

Minor notes:

After I insert the new field into the form, I re-run Drupal.attachBehaviors(), which I thought was going to make this all work.  I've also added a delay to make sure the rewriting of the form is completed before attachBehaviors() is called, but that has no effect.
The autocomplete behavior continues to work on the original field after the new field is added to the form.
The blur handler that does all this stuff to the first autocomplete field is not firing when I blur control from the second, added field.

It looks like some other bit of initialization stuff needs to happen, but I have no clue what it is.  Does anybody else?  Thanks!

Well, that was pretty ugly, and a LOT of guesswork is going on here.  But:

When Drupal sets up an autocomplete field, it adds a hidden variable to the form, which (I'm guessing here) is used to track the status of the whole autocomplete thing.  If you inspect a rendered form, it will look something like:

<input type="hidden" id="edit-field-name-autocomplete"
      value="https://example.com/path/to/autocomplete/handler" disabled="disabled"
      class="autocomplete autocomplete-processed">

That autocomplete-processed field seems to be the key: I had blindly copied it into my code and made it part of the field I was added to the form.  Once I removed it -- autocomplete-processed, that is -- autocompletion ran properly on it and all other similar fields.

Whew.  Your mileage may DEFINITELY vary.


Drush Omega Guard - "command could not be found" or "could not locate Gemfile" I have a multisite installation on Windows 7. I am now trying to execute the drush omega-guard command on an Omega sub-theme.

When I am in the theme folder (sites\all\themes\theme_name) I get the response "The drush command 'omega-guard' could not be found."

When I am in the site folder (sites\site_name.com) omega-guard prompts me with "Which theme do you want to run Guard for?" Once I choose the number for my sub-theme, it responds with "Could not locate Gemfile." I think the Gemfile should be in my theme directory.

What am I doing wrong?

Answer from the comments above, documented here per Molot's request:

In the case where your settings.php file is not in the 'default' folder, Drush needs you to specify --uri=site_name.com, unless it can determine the site to use via your cwd (e.g. if you have set your working directory to sites/site_name.com, as described in the question).  --uri is not necessary if you have a 'default' site, but it is necessary if you use any other name for your site folder, even if you only have one site in the Drupal installation.

Seems that the problem with finding the Gemfile was resolved by always setting the working directory to the theme directory, where the Gemfile was located.  Doing this while using --uri with Drush solved the problem.


Need to add a condition between two fields in a view I am a Drupal 7 novice. I have two fields of two different contents in a view. The first field is a boolean and the second is text (configured to an external link). Now, I want to make a condition like "If the first field is Yes, then the second field should be hidden."

This can be accomplished through the Form API.  However, if you are a PHP novice, you would probably be better off using the Conditional Fields module.  Although this is still in dev (no official release) for Drupal 7, it does work.  (If you have security-related requirements, you should use Form API instead though.)

Basically, the module provides you with a UI for adding conditions to fields.  The example you give is the same given on the module's page, so this is one solution to your problem.


Showing content of subterm under parent term I have following taxonomy structure

parent-A
    subterm-1
        sub-subterm-a
        sub-subterm-b
    subterm-2

how can I show contents of both the sub-subterm (a and b) when i select/click subterm-1 ; and contents from subterm-1 (sub-subterm a+b) and from subterm-2 when I select parent-A      using views - block display

This may not be the most standard way of achieving it but it may help in your case.
Just try the following code by replacing 24 with a $termid that exists in your case. And see if this gets your work done.

    //to get the children of a taxonomy term
    //lets take 24 for example

      $terms = taxonomy_get_children('24');

      //to get the nodes associated with a termid

     foreach ($terms as $term) {
         $termnodes = taxonomy_select_nodes($term->tid);

         foreach ($termnodes as $termnode) {
              $node = node_load($termnode);
              $node_output = node_view($node);
              print render($node_output, $view_mode = 'teaser'));
        }
  }


Add a class to a panels pane Is it possible to add a class to single pane (like the left side) on a panels page? I'm using a grid based theme and it would be nice if i can just add things like 'grid-5 alpha' to a certain pane.

In the Panels UI, every Pane has a little cog. Click it, and menu appears. There is an entry called "CSS Settings". There you can add per pane classes.


How can I increase the number of allowed values on an image field? I need to increase the allowed number of image uploads to 15. Is there anyway to do this in a module or other means without hacking core files as suggested here - http://drupal.org/node/680546#comment-4126378?

This is Drupal 7.

Thanks,
Tim

You could also change the cardinality setting of your field instance without doing a direct query. The key function would be field_update_instance() and here is an example of how to modify your field: http://sivaji.drupalgardens.com/how-programmatically-change-field-instance-properties


Mutliple rewrites/redirects in settings.php on a Pantheon hosted site We are in the process of migrating a Drupal site to Pantheon. The site uses about 55 rewrites and redirects rules in its pre-migration NGINX configuration. Most of them (32) include widlcards (eg. ^/something/(.*) redirects to /something-else/) and an handful even keep the matching substring into the redirect-to URL (eg. ^/another/one/(.*)$ redirects to /something/else/$1).

Pantheon does not support redirects at the web-server levels and suggests doing redirects in the settings.php (to avoid boostraping Drupal). But 55 redirects seems enough to start worry about maintainability of a bunch of if blocks. There is also the performance cost of 32 pattern matching for each request. So a little care has to be taken to avoid maintenance nightmare in the future.

I'm not too worried about performances since the site is mostly cached anonymous traffic. But in addition to requiring a full bootstrap, the Redirect module (already used on the site) is not an option as it does not support wildcards.

I'm toying with the idea of crafting something with nikic/FastRoute to be used from settings.php. But this seems a bit overkill for 55 redirects.

I'm curious what options have been used on other sites with similar requirements.

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

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

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


What is the hook to alter workflow access permissions? In the Workflow module, How can I programmatically change permissions? In addition to roles I want to check against a proflie value to allow or not allow users see or edit a node in a specific workflow state.

There is no single hook that allows you to control who can see or edit a node in a specific workflow state. You might want to implement hook_node_access_records() to give out grants for a specific node and hook_node_grants() to check whether a specific user has that grant.

The result of your hook_node_access_records() implementation is stored in the database and checked via your hook_node_grants() implementation. Have a look at node_access() to see how the latter is done.

I cannot tell you off-hand what to use as realm and what to use as grant ID. The most important restrictions are:

the grant ID is an integer,
hook_node_access_records() does not know which user tries to access the node,
hook_node_grants() does not know about the node that is being accessed.

In your case, it seems reasonable to put the expected profile value into the "realm" (along with the module name for disambiguation) of your hook_node_access_records() implementation. Your implementation of hook_node_grants() would then check whether the user has that profile value and return the appropriate realms. Still you need to accommodate for the workflow state somewhere.


Need CKEditor to encode special characters I would like CKEditor to encode all special characters. Currently it only html escapes >, <, and & I believe.

I need the current html markup of this

Let's take a "ride!"

to become something like this

Let&rsquo;s take a &ldquo;ride!&rdquo;

In this situation, the Let's take a "ride!" is still what would display to the user, but the html should reflect the encoding so my styling is properly applied.

I am seeing that Drupal 7 had a config.js file that could be modified to accommodate this; however, Drupal 8 does not have this by default and does not seem to recognize it when one is created.

Does anyone know how I can make this happen?

EDIT: our content authors are using the Basic HTML editor permissions.

A clean solution would be to alter your twig template to include escape. There are plenty of examples in that guide.


How to get Node Url in RSS view? We are using the default RSS feed view found at /admin/structure/views/view/frontpage. We want to change the Show to be Fields so we can setup up which field should be used for the title, link, description, creator, and publication date.

When we attempt to add the node url field we cannot find it. How to add the absolute URL of the node?

We have tried searching for, but cannot find it:

Content: Path
Node URL

It's called Link to Content.

Path field could also be used in older 8 versions (you could construct the full URL with replacement patterns while overwriting the field output).

But the Path field is deprecated in 8.5 and you can use Link to Content instead, with Output the URL as text option.

Read more here, you can also see screenshots: Path field deprecation and backwards compatibility for existing views.

There is still work being done related to this, and if you get the wrong link in 8.5.1 there is a patch that seems to help: RSS view with fields give wrong URL from path field.


How to remove non breaking space from body/value in migration process? I am successfully migrating the content from Drupal 7 to Drupal 9. However, I am getting some extra non-breaking spaces I'd like to remove.

I tried using a basic str_replace plugin, but that doesn't work.

What am I doing wrong? What else should I look into?

By taking a look into the StrReplace class I see that you are missing the source key, which should be the name of the field/column/whatever you are importing from.
If it does not work, try to also remove the "regex" key and if it still does not, try to use a simpler search, to ensure that the problem does not lie with your data.


run javascript every 24 hours I want to run a piece of javascript every 24 hours for each specific user? This is to clear HTML5 local storage, how would I run this script every 24 hours for each user when they are logged in?

The best way would be to to store an additional value in local storage that is the last time you cleared it.

Each page view, you simply check that value and if the last time was > 24 hours ago, you clear the local storage and set the last clear time to now.

(function () {

  var lastclear = localStorage.getItem('lastclear'),
      time_now  = (new Date()).getTime();

  // .getTime() returns milliseconds so 1000 * 60 * 60 * 24 = 24 days
  if ((time_now - lastclear) > 1000 * 60 * 60 * 24) {

    localStorage.clear();

    localStorage.setItem('lastclear', time_now);
  }

})();

Put this in a JS file that is added only when the current user is logged in.

Here is an example using a module named 'sample':

/**
 * Implements hook_init().
 */
function sample_init() {
  global $user;

  // User with uid 0 is anonymous/logged out, any uid greater is logged in.
  if ($user->uid > 0) {
    drupal_add_js(drupal_get_path('module', 'sample') . '/js/sample.js');
  }
}


What is the proper way to drop database references for an uninstalled drupal module? I've uninstalled the Commerce Coupon 7.x-2.0-beta3 through the admin ui and removed the corresponding folder from the sites/all/modules directory. Now when I install the previous version of Commerce Coupon 7.x-1.0-beta7 I get hit with the error.

DatabaseSchemaObjectExistsException:
 Table commerce_coupon already exists.

When I look at the Database in phpMyAdmin I see the the following references.

commerce_coupon
commerce_coupon_type
field_data_commerce_coupon_order_reference
field_data_commerce_coupon_reference
field_revision_commerce_coupon_order_reference
field_revision_commerce_coupon_reference

I am not very familiar working with tables through SQL. Is there a basic procedure or query that is commonly used for deleting all references to a particular Drupal module?

There's no single procedure for manually removing a module, it kind of depends on what has been installed, where it's been installed and how it's been used.

For commerce coupon the basics are pretty simple:

Remove commerce_coupon and commerce_coupon_type
Remove the 4 field tables.
DELETE FROM field_config_instance WHERE field_name IN ('field_data_commerce_coupon_order_reference', 'field_data_commerce_coupon_reference')
DELETE FROM field_config WHERE field_name IN ('field_data_commerce_coupon_order_reference', 'field_data_commerce_coupon_reference')
Flush the caches

From there it gets a bit trickier. Depending on how the module's been used you may have references to coupons in the commerce_line_item table, with relationships back to their order in field_data_commerce_line_items (and the corresponding revision table). Those should also be removed to prevent errors when line items are loaded.

As you mentioned in the comments there may also be related rules (and potentially views as well), hunting down and deleting those manually might be the easiest thing to do.


How to check the value for specified field across all nodes? I have minimal Drupal and PHP experience ...

Problem:

I have an autocreate function for a Content Type ('hannibal'), which has one defined field type ('faceman'). When Content Type 'hannibal' is created, it is done automatically through rules by passing the value for field 'murdock' from another content type. 'murdock' and 'faceman' are sometimes identical values (they are also identical formats: text, same formatting, direct copies).

I need to check across all other nodes of type 'hannibal', to see if the value for 'faceman' already exists in that field. I have Unique Field module active, but because the nodes are being created through Rules, it is not functioning in this case (perhaps it only works when in a user entered form).

Issue: A method to check field 'faceman' for the value being entered, in all nodes of type 'hannibal'.

I've already tried a LOT of options for this:

Rules - I have tried setting conditions, but can't find a way to load all nodes of type 'hannibal' to check that field value. I've tried to do it in PHP using snippets taken from elsewhere, but no luck. Also tried setting a rules component, but couldn't make sense of it.

Database query - I'm using SQLite. I've identified the table to check, and tried an EntityFieldQuery but the code I've tried as a condition is just crashing the page:

$value = token_replace('[node:field_murdock]', array('node' => $node));

$query = new EntityFieldQuery();
$query->entityCondition('entity_type', 'node')
  ->entityCondition('bundle', 'source')
  ->propertyCondition('status', NODE_PUBLISHED)
  ->fieldCondition('faceman', 'faceman_value', '$value',)

$result = $query->execute();
if (isset($result['node'])) {
  return TRUE;
}

So long as I can create the nodes automatically, and prevent new nodes being created if they have an identical value to a pre-existing value for field_faceman, I'm not that bothered about how it is done (within reason!).

This seems like such a basic function (checking all the values of a given field in the database), I must be missing an easier way to do this. Right?

Any help?

UPDATE & SOLUTION

Managed to solve it with EntityFieldQuery in the end. I'm convinced I can't be the only person with this issue, so for anyone of around my skill level in the same position in future:

Solution is via Rules using the PHP conditional.

Rules trigger is save content event. Conditional 1 is "content has 'faceman' field". Conditional 2 is Execute Custom PHP as below. No link between the two conditionals - trying an AND function broke them.

Custom PHP code:

// display murdock field taken from saved content as plaintext

$value = token_replace('[node:field_murdock]');

// search database for identical values of field faceman

$query = new EntityFieldQuery();
$query->entityCondition('entity_type', 'node')
->entityCondition('bundle', 'hannibal')
->propertyCondition('status', 1)
->fieldCondition('field_faceman', 'value', $value, '=')
;

// if identical value of field faceman is found, return FALSE to Rules condition

$result = $query->execute();
if (isset($result['node'])) {
return FALSE;
}
else {
return TRUE;
}

Therefore the action part of the Rule will only be executed if the value is not already present in the Faceman field somewhere in another node. So long as your existing node types Hannibal have fields Faceman with equivalent values / formats, then a duplicate node will not be created.

My actions rules then create the Faceman field in the new content by directly copying field Murdock from the saved content which triggered the Rule. This ensures that the above logic works, and the node should only be created once, because Faceman will always be a child & copy of a Murdock field.

You can make this work by using Rules in combination with the Views Bulk Operations module, as further detailed below.

In what follows, I'm assuming that the machine name of your field is field_optionlist (change to whatever fits).

Step 1 - Create a VBO view

Use the Views Bulk Operations (VBO) module to create a view of all relevant nodes, in which you should:

Add a VBO field to it.
Add a contextual filter for the field_optionlist field for which you want to check that its value is unique. Make sure to correctly configure this contextual filter, similar to what is mentioned in this answer to "How to have a field that counts the nodes submitted by the current user?" (credits to Niall Murphy, merci!).

Include a field like nid for each node (no need for any other fields). Just make sure you get exactly 1 row for each node you want to take into consideration.

Here is an export of such VBO view:

$view = new view();
$view->name = 'relevant_nodes';
$view->description = 'Produce a list of node ids that satisfy a specific filter';
$view->tag = 'default';
$view->base_table = 'node';
$view->human_name = 'Relevant nodes';
$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'] = 'Relevant nodes';
$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'] = 'table';
$handler->display->display_options['style_options']['columns'] = array(
  'title' => 'title',
);
$handler->display->display_options['style_options']['default'] = '-1';
$handler->display->display_options['style_options']['info'] = array(
  'title' => array(
    'sortable' => 0,
    'default_sort_order' => 'asc',
    'align' => '',
    'separator' => '',
    'empty_column' => 0,
  ),
);
/* Field: Content: Nid */
$handler->display->display_options['fields']['nid']['id'] = 'nid';
$handler->display->display_options['fields']['nid']['table'] = 'node';
$handler->display->display_options['fields']['nid']['field'] = 'nid';
/* 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;
/* Field: Content: OptionList */
$handler->display->display_options['fields']['field_optionlist']['id'] = 'field_optionlist';
$handler->display->display_options['fields']['field_optionlist']['table'] = 'field_data_field_optionlist';
$handler->display->display_options['fields']['field_optionlist']['field'] = 'field_optionlist';
/* Field: Bulk operations: Content */
$handler->display->display_options['fields']['views_bulk_operations']['id'] = 'views_bulk_operations';
$handler->display->display_options['fields']['views_bulk_operations']['table'] = 'node';
$handler->display->display_options['fields']['views_bulk_operations']['field'] = 'views_bulk_operations';
$handler->display->display_options['fields']['views_bulk_operations']['vbo_settings']['display_type'] = '0';
$handler->display->display_options['fields']['views_bulk_operations']['vbo_settings']['enable_select_all_pages'] = 1;
$handler->display->display_options['fields']['views_bulk_operations']['vbo_settings']['row_clickable'] = 1;
$handler->display->display_options['fields']['views_bulk_operations']['vbo_settings']['force_single'] = 0;
$handler->display->display_options['fields']['views_bulk_operations']['vbo_settings']['entity_load_capacity'] = '10';
/* Contextual filter: Content: OptionList (field_optionlist) */
$handler->display->display_options['arguments']['field_optionlist_value']['id'] = 'field_optionlist_value';
$handler->display->display_options['arguments']['field_optionlist_value']['table'] = 'field_data_field_optionlist';
$handler->display->display_options['arguments']['field_optionlist_value']['field'] = 'field_optionlist_value';
$handler->display->display_options['arguments']['field_optionlist_value']['default_action'] = 'default';
$handler->display->display_options['arguments']['field_optionlist_value']['default_argument_type'] = 'raw';
$handler->display->display_options['arguments']['field_optionlist_value']['default_argument_options']['index'] = '0';
$handler->display->display_options['arguments']['field_optionlist_value']['summary']['number_of_records'] = '0';
$handler->display->display_options['arguments']['field_optionlist_value']['summary']['format'] = 'default_summary';
$handler->display->display_options['arguments']['field_optionlist_value']['summary_options']['items_per_page'] = '25';
$handler->display->display_options['arguments']['field_optionlist_value']['limit'] = '0';
/* 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',
);

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

Step 2 - Create a Rule

Create a rule like so:

Rules Event: something like "Before saving content of type Article" seems most appropriate, though you can use any variation that fits.
Rules Condition: "Check number of results returned by a VBO view". And select the VBO view created in the previous step. In doing so, you will be asked to "specify arguments to pass to the view, one per line. You may use token replacement patterns.". The token to be entered there is node:field-optionlist. If the number of results is 1 or more, then you know the value already exists. So within Minimum number of results you should enter the value 1.
Rules Action: this is pretty much up to your own imagination. For example if the Rules Condition is TRUE, you could use "Set a data value", to restore the value of that field to what it was before, i.e. node-unchanged:field-optionlist. Maybe also display an appropriate message, such as (when trying to change the value from Advanced to Basic):

  The value "Basic" has already been used in at least 1 other node ... (field value remains "Advanced").

Here is an export of a Rule that does exactly what is described above (if you have the Rules UI enabled, and a field with the machine name field_optionlist, you should be able to just import this rule):

{ "rules_prevent_multiple_nodes_with_same_field_value" : {
    "LABEL" : "Prevent multiple nodes with same field value",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "views_bulk_operations", "rules" ],
    "ON" : { "node_presave--article" : { "bundle" : "article" } },
    "IF" : [
      { "views_bulk_operations_condition_result_count" : {
          "view" : "relevant_nodes|page",
          "args" : [ "node:field-optionlist" ],
          "minimum" : "1"
        }
      }
    ],
    "DO" : [
      { "drupal_message" : {
          "message" : "The value \u0022[node:field-optionlist]\u0022 has already been used in at least 1 other node ... (field value remains \u0022[node-unchanged:field-optionlist]\u0022).",
          "type" : "error"
        }
      },
      { "data_set" : {
          "data" : [ "node:field-optionlist" ],
          "value" : [ "node-unchanged:field-optionlist" ]
        }
      }
    ]
  }
}

Note that my Rules Event is limited to "Article" (change to whatever fits), and replace (prior to trying to import this rule) the machine name of field_optionlist to whatever other machine name your field.

Done!


Add a drop-down list to a pager I want to add drop-down list that allows users to select which page they want to visit.

How can I accomplish this?
What code should I use?

If you want to replace the whole site pager with a drop-down list, you should write a custom module (see 1 and 2). If you want to show it only for some pages, you just invoke the module (see 2):
1. Declare this in the template.php of your theme (replace YOURTHEMENAME and YOURMODULENAME with the appropriate theme/module name):

function YOURTHEMENAME_pager($tags = array(), $limit = 10, $element = 0, $parameters = array(), $quantity = 9) {
  global $pager_page_array, $pager_total;
  // Calculate various markers within this pager piece:
  // current is the page we are currently paged to
  $pager_current = $pager_page_array[$element] + 1;
  // max is the maximum page number
  $pager_max = $pager_total[$element];
  // End of marker calculations.

  return drupal_get_form('YOURMODULENAME_pagerform', $_GET['q'], $pager_max, $pager_current);
}

2. Create a custom module, adding the following code to the YOURMODULENAME.module file:

function YOURMODULENAME_pagerform(&$form_state, $path, $pager_max, $pager_current = 0) {
  $form = array();
  $pagers = array();

  for ($i=0;$i<$pager_max;$i++) {
    $pagers[$i] = $i+1;
  }

  $form['pager'] = array(
    '#type' => 'select',
    '#title' => t('Current page'),
    '#options' => $pagers,
    '#default_value' => $pager_current,
    '#attributes' => array('onchange' => 'this.form.submit();'),
  );
  $form['path'] = array(
    '#type' => 'value',
    '#value' => $path,
  );
  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Submit'),
    '#attributes' => array('style' => 'display: none;')
  );

  return $form;
}

function YOURMODULENAME_pagerform_submit($form, &$form_state) {
  drupal_goto($form_state['values']['path'], 'page='.$form_state['values']['pager']);
}

p.s. The code was quickly written in browser without any debugging, so may be some errors happen, but it's should give "idea".


Getting error message on fresh install I am trying to install drupal using drush site-install and keep getting the following error at the top of the page.

Warning: Illegal string offset 'field' in DatabaseCondition->__clone() (line 1817 of /var/www/mydrupalsite/includes/database/query.inc).

Even when I logout of administrator, the error still pops up at the top of the page. Can anyone explain what is going wrong and how to get rid of these messages? Everything else seems to have installed properly.

Make sure you're installing a current version of Drupal 7, that error appears to have been fixed in an earlier version.

https://drupal.org/node/1622886


Views custom output into specific divs I am a kind of noobie so excuse me for that.

I am trying to implement this into my website.

It is a fancy looking bookshelf gallery. I am using drupal 6.x. I have already set up a view to list out the items I would like to appear in the gallery. In other posts, I saw that if I set up the view output as "fields" I can wrap individual fields into custom divs. That is kind of what I want to achieve. The code I need to alter is the following:

What I need to know is how to make the view output my field data (node url, img, nodetitle) in specific parts of the HTML (data-url ,img ,title); plus, based on taxonomy terms, form different categories. So my books will be under books, and my DVDs will be under dvd.

When editing the view, under Basic Settings -> Style -> Settings (the "gear" icon) you can choose to group the results by a certain field. Hope this helps.


How to change the language of strings like "read more" and "submitted by"? I've managed to create a website with Drupal 8.3.7.

How do I get Drupal to print things like "Read more" in views and "Submitted by", "Wednesday, August 23" in an article or t("something supposedly translated") in another language?

I'd like the administration interface to remain in English. I'd like to avoid a language prefix in URLs (yes: /mycurrenturlalias, no: /XX/mycurrenturlalias) but at this point I really don't even care anymore.

I've tried installing the Language module, adding a new language, setting it as the default and only language, installing some translation modules and fiddling with their settings. I've broken the site in some interesting ways but what I haven't gotten is a single translation of those strings anywhere. I must be doing something horribly wrong, but please ignore that and just tell me what should work.

Install the core modules Language and Interface Translation
Add other language (admin/config/regional/language)
Configure the Selected language setting (admin/config/regional/language/detection)
To have a different language in admin enable the detection method Account administration pages
Go to user/1/edit and in Language settings section select your Administration pages language
Translate your strings (admin/config/regional/translate)


How to delete all Persistent variables when a page is loaded? I have many variables set through variable_set. Is there any other way to delete them all at once apart from variable_del?

or How can find all the persistent variables set in the module?

It is considered bad practice to delete all the persistent variables whose name starts with the short name of the module. There could be a module whose short name starts with that short name; in that case you would be removing the persistent variables of that module.
For example, given the Views module, there could be a Views Enhancer module. Deleting all the persistent variable matching the SQL pattern '%views_%' would mean deleting the persistent variables of both modules.

Instead, you should have a list of all the persistent variables your module uses. (That is not hard, since you are writing the code of your module.) Using that list (for example, contained in $variables), a code like the following would delete all the variables.

  global $conf;

  db_delete('variable')
    ->condition('name', $variables, 'IN')
    ->execute();
  cache_clear_all('variables', 'cache_bootstrap');

  foreach ($variables as $name) {
    unset($conf[$name]);
  }

This is, essentially, the code of variable_del() adapted to delete a list of variable names contained in $variables.

You could also use that code to implement a function your module uses.

function variable_delete_multiple(array $variables) {
  global $conf;

  db_delete('variable')
    ->condition('name', $variables, 'IN')
    ->execute();
  cache_clear_all('variables', 'cache_bootstrap');

  foreach ($variables as $name) {
    unset($conf[$name]);
  }
}


How do I group and add space between checkboxes? I need to group the checkboxes and put some spacing between each group.
They need to look like this:

item1
item2

item3
item4

I can easily add an additional field to the options array specifying which group each item belongs to but I how do I render them this way?
I imagine I would have to do this by adding classes. But how do I do that?

You can normally do this already without any extra effort.

Each option should have a class assigned to it that you can target in your CSS.

You can then apply any spacing you like there.


Different node / entity templates based on display type Is it possible to have different template files for different display modes of the same entity without using template_preprocess_page()? If not, how can I get all the available display modes for a certain entity type so I can create some sort of automatic template suggestion?

Eg: For a node I have by default the 'Full' and 'Teaser' display types. I can add more display types using Display suite module or by creating a custom module. I need to create multiple template files like node--content-type--teaser.tpl.php to keep everything clean and not use lots of IF statements.

Thanks :)

I'll go with this solution after all:

function MYMODULE_preprocess_node(&$vars) {
  $vars['theme_hook_suggestions'][] = 'node__' . $vars['type'] . '__' . $vars['view_mode'];
}


How can I substitute field in hook_query_alter? I have a query, with a date field, let's say it is aliased as enabled. And joined table with field enabled_for_website. In my query alter, I want to substitute global enabled with date specific to website user is viewing (domain access, but it doesn't really matter here).

I tried simplistic approach:

function MYMODULE_query_MYTAG_alter($products_query) {
  $products_query->join('website_has_product', 'wp', 'p.idProduct = wp.idProduct');
  $products_query->join('website', 'w', 'wp.idWebsite = w.idWebsite');
  global $user;
  if ($user->uid == 1) {
    $products_query->addField('wp', 'website_enabled', 'enabled');
  }
  $products_query->condition('w.WebsiteName', /*where are we */, '=');
}

I'm getting expected error:

  PDOException: SQLSTATE[23000]: Integrity constraint violation: 1052 Column 'enabled' in order clause is ambiguous

Is there a way to remove other column? SelectQuery::$fields is protected, and I see no method to remove / substitute fields in it. I would prefer to avoid extending any classes.

SelectQuery::getFields() returns by reference, so something like this should do it:

$fields =& $query->getFields();
$found_index = FALSE;
foreach ($fields as $key => $val) {
  // Check what's in the field, note the index if it matches the one to remove
}

if ($found_index !== FALSE) {
  unset($fields[$found_index];
}


File save upload doesn't replace existing file despite FILE_EXISTS_REPLACE I'm trying to force replacement of existing file with same name, if a new version is uploaded by user. I've seen a lot of posts about this topic but none that I could find addresses how to force the replacement.

I'm using a custom form, and here's the code I've been trying to make work during the form validation:

  $file = file_save_upload(
      'file',
      array(
        'file_validate_is_document' => array(), // Validates file is really a document.
        'file_validate_extensions' => array('pdf doc ppt pps avi mpg mov wmv'), // Validate extensions.
      ),
      'public://',
      FILE_EXISTS_REPLACE
  );

The revised file (let's say "file.jpg") is uploaded, but inevitably Drupal creates a new copy and renames it file_0.jpg, file_1.jpg, etc for each new version.

I even tried to programmatically delete the original file using "file_delete" prior to committing the upload but I still get the copy!

Any help would be appreciated.

This is drupal's default behaviour and a known issue. It has been addressed a couple of ways.

The Upload File Replace module addresses this issue by swapping the filenames so the new file retains the original name.

The Media Update module allows in situ replacement of media files (part of the Media project).

You could either make use of one of these modules, or use them as a model for your own function.


Double slash in path of downloaded module I get a strange behaviour on 2 websites under Drupal 8.
When I download a module via Drush, the path contain two consecutive slashes like this.

  Project key_value (8.x-1.1) downloaded to /home/www/example/sited8//modules/contrib/key_value.

In admin/config/media/file-system, no extra slash is shown in the path settings.

  URL de base des fichiers publics       http://example.com/sites/default/files
  Chemin du système public de fichier sites/default/files

Perhaps it could be set in another part of the website.

Could it be a bug?

It's an artifact of how Drush builds the path. It looks at your Drupal project dir, and where it's placing the the project download, then appends it together without concern for a trailing slash in the Drupal project dir. It has nothing to do with your Drupal project file settings

Is it bug? Perhaps if you consider it a UX problem. As far as POSIX is concerned, the double slash is treated as one so it shouldn't matter in terms of referencing the directory. Whatever the case, drush pm-download is deprecated in later versions.


Drupal 8 - User Login I am using Drupal 8 and want to know how I make my wesbite only usable when a user login. At the moment my websites features also used when a user has not logged in.

Go to Admin -> People -> Permissions, and uncheck any permissions for anonymous users.

Go to Admin -> Configure -> People -> Account settings, and under 'Who can register accounts?', choose 'Administrators only'.


Migrate source id's and map them to already existing Drupal entity id's I've tried a bunch of different setups, but I can't get it to work. Here are the two setups I was the most confident in that it would work. I simply want to map existing id's in the source to new id's that are already created in taxonomy.

Attempt 1:

  field_season:
    # Map the seasons to our already existing taxonomy terms
    -
      plugin: static_map
      source: season
      map:
        '1': 26 # Lente
        '2': 29 # Zomer
        '3': 24 # Herfst
        '4': 28 # Winter
    -
      plugin: entity_lookup
      value_key: tid
      entity_type: taxonomy_term
      bundle_key: tid
      bundle: seasons

Attempt 2:

  field_season:
    plugin: iterator
    source: field_season
    process:
      target_id:
        # Map the seasons to our already existing taxonomy terms
        plugin: static_map
        source: season
        map:
          '1': 26 # Lente
          '2': 29 # Zomer
          '3': 24 # Herfst
          '4': 28 # Winter

Edit: FWIW, all the other processes work just fine!

This happens to me all the time, I post a question after fiddling around for hours and shortly after, I manage to find the answer myself. It appears that the first attempt was almost right. Though bundle_key should be vid, I'm not sure why though.

The config, for completeness sake.

  field_season:
    # Map the seasons to our already existing taxonomy terms
    -
      plugin: static_map
      source: season
      map:
        '1': 26 # Lente
        '2': 29 # Zomer
        '3': 24 # Herfst
        '4': 28 # Winter
    -
      plugin: entity_lookup
      value_key: tid
      entity_type: taxonomy_term
      bundle_key: vid
      bundle: seasons


How to find the cause of 'The following module has moved within the system'? I can't get rid of this message whenever I install a module, it shows:

  User warning: The following module has moved within the file system: [modulename]. In order to fix this, clear caches or put the module back in its original location. For more information, see the documentation page. in _drupal_trigger_error_with_delayed_logging() (line 1138 of /data/all/000/core/drupal-7.54.2/includes/bootstrap.inc).

I read the documentation mentioned, but cannot find a module that could cause this.

What would be the right way to find the cause?

It might be tough to find the module that causes your error message.

However, you may want to have a look at 'How to fix "The following module is missing from the file system..." warning messages' which describes a few possible causes and corresponding solutions, such as:

You removed a module from the file system without disabling and uninstalling it.
You moved the module inside your Drupal installation.
Leftover fields or other configuration entries.
Obsolete modules existed from a previous Drupal version.
There is a bug in a module installed on your site.

The one I ever used in the past (to get rid of that message) is to use the module 'Module Missing Message Fixer' (also mentioned on that same page).


How to render a @FormElement in Views area plugin I am doing a custom plugin area for displaying some data in a views footer (Drupal 8).

I do something about just like this : Create a custom area plugin

The only point is, instead of #markup in the return array of render() method, I would like to return some more complex stuff.
If I try to return a textfield if works:

return  [
  '#type' => 'textfield',
];

If I try another form API element (defined via a @FormElement): it does not render.

return  [
  '#type' => 'datetime',
];

Two questions:

Should it render ?
If not, I can render a block there using this (ViewsBlockArea) how to do the equivalent but with a FormElement instead ? (actually rendering a form API render array.)

EDIT: Here a the finality of what I want to render:

$element['form'] = [
  '#type' => 'commerce_coupon_redemption_form',
  '#order_id' => $order->id(),
  '#cardinality' => 1,
  '#element_ajax' => [
    [get_class($this), 'ajaxRefreshSummary'],
  ],
];

But you may see that more trivial render array like the datetime one given above does not work either.

Also notice that any element defined by a @FormElement annotation from within the namespace Drupal\Core\Render\Element is okay.
But @FormElement "from elsewhere" like datetime does not render.

You can create block Form first. And from View UI, add a view object to your header or footer. And from View object configuration choose the form block you created.


Using sender name and removing HTML entity encoding in Swiftmailer I have swiftmailer installed on a Drupal 8 installation. I am using a hook_mail() function to edit the message params as follows:

function mymodule_mail($key, &$message, $params) {
    $options = array(
        'langcode' => $message['langcode'],
    );
    switch ($key) {
        case 'support_form':
            $message['files'] = $params['files'];
        case 'submit_to_admin':
        case 'submit_to_user':
            $message['from'] = array(\Drupal::config('system.site')->get('mail') => 'site admin name');
            $message['subject'] = t('@title', array('@title' => $params['title']), $options);
            $message['body'][] = Html::escape($params['message']);
            break;
    }
}

I am sending the e-mail like this:

$mailManager = \Drupal::service('plugin.manager.mail');
$module = 'mymodule';
$key = 'support_form';
$params['message'] = $message; //defined elsewhere
$params['files'] = $attachments; //defined elsewhere
$params['title'] = $title; //defined elsewhere
$langcode = \Drupal::currentUser()->getPreferredLangcode();
$send = true;
$result = $mailManager->mail($module, $key, $to, $langcode, $params, NULL, $send);

The e-mail is sending fine, including attachments (so I know Swiftmailer must be working), but when I receive the e-mail the sender is listed as just the e-mail address and not as "site admin name".

Additionally, any & symbol in the body is showing up as &amp;amp;

My swiftmailer install is configured according to this guide.

Is there a setting or code piece I am missing that is making this happen?

I had the same issue and did the following to solve the issue with the entities.

$text = $message['body'];
$message['body'] = array_map(function ($text) {
  return Markup::create($text);
}, $text);

This will convert the body and will not display any entites anymore.


How to execute a VBO using Drush So I want to execute a VBO using drush, taking advantage of vbo-execute command to change my workflow state in my views, based on few resources I found this is the command I'm using:

drush vbo-execute list_of_node_for_expire  action::workflow_vbo_given_state_action argument:1

and I end up with this error:

  in field_sql_storage_field_storage_write() (line 514 of
  /modules/field/modules/field_sql_storage/field_sql_storage.module).
  PDOException:

  SQLSTATE[23000]: Integrity constraint violation: 1048
  Column 'field_workflow_states_value' cannot be null: INSERT
  INTO {field_data_field_workflow_states} (entity_type, entity_id,
  revision_id, bundle, delta, language, field_workflow_states_value)

  VALUES (:db_insert_placeholder_0, :db_insert_placeholder_1,
  :db_insert_placeholder_2, :db_insert_placeholder_3,
  :db_insert_placeholder_4, :db_insert_placeholder_5,
  :db_insert_placeholder_6); Array (
      [:db_insert_placeholder_0] => node
      [:db_insert_placeholder_1] => 34924
      [:db_insert_placeholder_2] => 34924
      [:db_insert_placeholder_3] => listing
      [:db_insert_placeholder_4] => 0
      [:db_insert_placeholder_5] => und
      [:db_insert_placeholder_6] => )

I have no idea why it's giving me such an error, I'm not even sure if it has something to do with VBO or not, but using Views UI, I can execute my VBO with no errors.

From the looks of the error, it looks like vbo operation or the action is trying to insert a blank value into the field_data_field_workflow_states table.

Without actually seeing any code it's a little harder to determine what's going on in the vbo or the action, but check either list_of_node_for_expire or action::workflow_vbo_given_state_action and make sure you're working with the correct data before it makes the database request.


Should I include arguments in views_embed_view or in a hook_views_pre_view function? I have a tonne of views across my site and pretty much all of them need to have their arguments passed programmatically.

I'm wondering which method is best assuming I'm using views_embed_view to print all of them.

Thanks.

views_embed_view takes arguments as the third parameter. Since you have to use that to print a view on-demand, might as well pass them along there.


How to find "next day date" (xx/xx/xx 00:00:00) from a given date & time value in Rules? I'm trying to figure out how to find the next day date (xx/xx/xx 00:00:00) from the given date&time value in rules without the use of PHP filter module. Played with offset already - couldn't get the needed result.

The idea is to set up scheduled task in Rules that will take the date & time value from a node field#1 and change the field#2 on that node at midnight of the next day.

EDITED: To simplify: if my date field = 07/30/15 05:00:00 how do I schedule task at 07/31/15 00:00:00 without the use of PHP filter.

Any ideas are greatly appreciated.

Let's see my example.

First: I created content type with two date fields: date1 and date2

Second: I created rule

Create Action 'Add variable' to store first date field value in your
variable
Create Action 'Set data value' and choose your second date field as
Data and your variable name as Value
Create Action 'Set data value' and choose your second date field as
Data and don't "Switch to data selector", simply set "+1 day
midnight" as Value

What's the point: when you r creating 'Set data value' action and choosing Date type you can see next description under Value field in form:

  The date in GMT. You may enter a fixed time (like 2015-08-16 14:05:10)
  or any other values in GMT known by the PHP strtotime() function (like
  "+1 day"). Relative dates like "+1 day" or "now" relate to the
  evaluation time.

If you google strtotime() php function you can simply understand what goes on.

"+1 day midinight":

"+" means add
"day" means what to add
"midnight" means "The time is set to 00:00:00"


How can I upload a .eps file? I added an image field to my user on this page admin/config/people and marked the allowed file extensions to be eps, png, jpg.  However, it doesn't allow me to upload .eps file, but only .png and .jpg.

I get this message:

  The specified file gold coins elements vector5.eps could not be uploaded. Only files with the following extensions are allowed: jpg jpeg gif png txt doc xls pdf ppt pps odt ods odp.

How can I upload an .eps file?

I'm pretty sure EPS files can't be displayed in browsers, which may be why you're having a problem. There's a module which will allow for EPS files to be converted on upload, which may solve your particular issue:

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


How to allow users change theme for specific pages A page has been created with panels which list all the contents of each user.
I want to allow each user to be able to change the theme used for his own panel page.  Whenever anyone visits the user panel page,  they should see the theme of that user.

I have tried themekey but it only allows for sitewide theme.

What else can i do?

You hook_custom_theme()

function MYMODULE_custom_theme() {
  // Set path specific theme.
  if (current_path() == 'Your Path') {
    return 'Your theme name here';
  }
}

Note: Clear cache and have a check

Or You can use Drupal module: ThemeKey

  ThemeKey allows you to define simple or sophisticated theme-switching
  rules which allow automatic selection of a theme depending on current
  path, taxonomy terms, language, node-type, and many, many other
  properties.


What is the best way to tell anonymous users apart? My company wishes to split their website so that anonymous users are given slightly different sites based on a question when they first visit.

I intend to use a cookie to store the answer to the question between sessions, but I'm wondering what the best way is to use that answer once the user is browsing the site?  I intend to use page manager to handle the context but I'm still trying to determine where it should be stored:

Cookies can be turned off by the user, or the IT department, much of our target audience have policies restricting or outright banning cookies
Session variables seem to be the way to go, unless:
Does the Global $user variable store different information for each anonymous visitor?

Are there downfalls in either of the latter two options?  Have I missed any options?

Session variables seem to be the way to go

Don't forget that session variables rely on cookies

  Have I missed any options?

The traditional solution would be to use the ip address as a fallback if cookies are disabled.
PHP does support an alternative to cookie-based sessions -- it can rewrite the URLs to include "?PHPSESSID=xyz". However, securing this can be difficult.
Another approach would be to use html5 local storage and do all the cusomizations on the client-side. This will work in all modern browsers regardless of cookie or firewall settings.


drupal/core vs. drupal/core-recommended I've got a question regarding drupal/core and drupal/core-recommended. So drupal/core-recommended uses fixed versions of the packages, which the corresponding core version was tested with. And yes it does make sense that this prevents bugs introduced by version differences of let's say different versions of symfony packages for example.
But on the other hand, let's say you install a dev version of a modul or any other third party library with composer, which explicitly needs a different version of a symfony component than drupal/core-recommended, these locked versions of the core dependencies will cause trouble, as the third party library/the module could not get installed due to version conflicts.
So how would one deal with this kind of situation when using drupal/core-recommended?

It's "core-recommended" as in "recommended to avoid having dependency-related trouble with core."
Drupal core (and some of the contributed modules, but not all) has a variety of automated tests that are run to make sure that everything is working as expected.  However, Drupal also needs dependencies to run. If you use different versions of the dependencies that were not tested, there might be a bug and the tests might not pass. core-recommended contains the specific dependencies that were used to test a given version of Drupal core.
By using core-recommended, you are guaranteed to get the same dependencies that were used to release that version of Drupal core, and Drupal core is only released when those tests pass.  So, you can be more confident when you are deploying your site because you know that your combination of core + dependencies is verified to work according to the tests.

let's say you install a dev version of a modul or any other third
party library with composer, which explicitly needs a different
version of a symfony component than drupal/core-recommended,

It's relatively rare for a contributed module to need a specific version of a Symfony component.  When you do need to use such a module and you switch from core/recommended to core, you might experience some Symfony-related or other dependency-related bugs because some of the dependencies may require changes in core that have not been made yet.  So when you do this, you are now responsible for running the tests, and if you encounter bugs you may have to search the core issue queue and apply patches, etc.
As for dev modules, it's never recommended to install dev modules on production, so whenever you install a dev module, you are taking responsibility for testing into your own hands.
TLDR: Recommended means "recommended because it passed the tests."  These are the recommended dependencies because they are known to work, but of course you can try to use others if you like. But, if you don't use the recommended dependencies and then you find a bug and think, "hey, core is broken, let's file an issue!", you should first check with core-recommended to make sure the issue isn't specific to the contrib module/dependency that required you to remove core-recommended.


Schema for group module I have installed this module and I assume that this works not only in the regular content type but also in the group module. I was expecting that after enabling the module there is an option to map my group type fields in the manage fields section but none even in the edit setting of the group type.

See RDF Mappings in the Basic Page content type:

Notice this from the module:

  Features

  RDF UI Map Content Types to Schema.org Types. Map Fields to Schema.org
  properties.

Does the group module supports schema integration? If yes, is there any documentation provided?

The RDF UI module only provides the 'RDF Mapping' local task for nodes at the moment (so not Group entities). See the if statement in this snippet from Drupal\rdfui\Plugin\Derivative\RdfUiLocalTask::getDerivativeDefinitions():

foreach ($this->entityManager->getDefinitions() as $entity_type_id => $entity_type) {
  if ($entity_type->get('field_ui_base_route') && $entity_type_id === "node") {

    $this->derivatives["overview_$entity_type_id"] = array(
      'route_name' => "entity.$entity_type_id.field_ui_fields",
      'title' => $this->t('Fields'),
      'parent_id' => "field_ui.fields:overview_$entity_type_id",
    );

    $this->derivatives["rdf_$entity_type_id"] = array(
      'route_name' => "entity.$entity_type_id.rdf_ui_fields",
      'weight' => 2,
      'title' => $this->t('RDF Mappings'),
      'parent_id' => "field_ui.fields:overview_$entity_type_id",
    );

  }
}


How to output just a page's contents in page.tpl.php in Drupal 7? I am creating a page.tpl.php template in Drupal 7 in which I want to rearrange how certain elements of the page are laid out. Specifically I want the title of the page to appear before the tabs and messages section (which I have done) and have the content of the page appear after the tabs and messages section (this is where I run into issues). I can't find a way to just render the $page['contents'] without the title. Is there a way to achieve this in Drupal 7?

I know that the node.tpl.php template handles the node specific layout, but it doesn't allow me to layout the page like as described above.

Thanks.

Somethings can be done in page.tpl.php & some in node.tpl.php

Like you said, you need to make title of the node appear before tabs. You can do this in your page.tpl.php. Find $title variable as well as $tabs & arrange accordingly in your page.tpl.php. Like --

<?php if ($title) : ?>

    <?php print $title; ?>

<?php endif; ?>
<?php if ($tabs): ?>

    <?php print render($tabs); ?>

<?php endif; ?>

After this you will have print render($page['content']);, where node.tpl.php comes into the scene, so arranging other things like node content, comment, links you will have to go to your node.tpl.php & arrange accordingly. More modification such as in comment & other TPLs will come into the scene like comment.tpl.php etc..


What is the difference between "Path redirect" and "Global Redirect" I read the description of Global Redirect and Path redirect, but I still don't understand what the difference between the modules is, and why Path redirect recommends Global Redirect.

What is the difference between the modules?

Global Redirect searches for an alias of the current URL and does a 301 redirects to it if found. This prevents content from being displayed on multiple urls when the path module is enabled. Displaying duplicate content at multiple url's can cause a loss of search engine site ranking.

Path Redirect allows you to specify a redirect from one path to another path or an external URL, using any HTTP redirect status. This is important if you want to change your url scheme for some reason and you don't want to break all exisiting links (search engines, user's bookmarks etc.)


(dis)advantages of staging dev->production using 'drush rsync' vs 'git'? I set up a Drupal site under git control for development work.

It's parented in a master, bare GIT repo, and as changes are made in my various project-work git clones, and pushed back to the master, a post-update hook immediately pushes the changes to a single live Staging website (http://staging.loc.). Nothing special, works as expected.

I've also drush-aliased the site "@STAGING". On occassion, I want to promote my changes from the Staging site to a production server.

Two relatively straightforward methods come to mind:

(1) At a point in time when the Staging site appears stable, create the Production site as a git checkout from the master repo,

(2) use drush rsync + drush sql-sync from the staging site to the production site.

Both can be made to work.  Other than the fact that (2) seems more Drupal-centric/aware by nature -- drush is, after all, a Drupal-specific set of tools -- what are the relative merits of the two approaches?

Is there any particular reason I should consider (1) over (2)?

In either case "Everything" is under at least one instance of revision control ...

I have used both techniques.  Both can be used to guarantee that the same files that you test on @stage end up on @live.  The advantage of rsync is that you do not end up with extra files (e.g. ".git" and associated) on your production server.  I tend to rsync to a vps, and use git on a box I own (e.g. intranet sites).


Using Views to List a Member's Organic Groups (7.x-2.3) I am migrating a site from using OG 7.x-1.4 to OG 7.x-2.3. The migration seemed to go fine, but it broke the view that shows the current users group (i.e. groups the user is a member of). In the original view for 1.4, it had a contextual filter:

(OG membership from OG group) We pass to the "Entity ID" the User ID.

And the following relationships:

OG group: OG group from Node
(node being the OG group) OG group: OG membership from OG group

However, the new Organic Groups 7.x-2.3 now uses the OGMembership data model and I cannot figure out how to recreate this view using OGMembership, as I am not clear exactly how it works and I cannot seem to find any in-depth documentation for this kind of thing.

This is how to get the OG membership ID:s to start with.

Add new view.
Show -> OG membership (important!)
Then in some display add a contextual filter -> OG membership: Entity id.
Provide default value -> Type -> User ID from logged in user.
Override title: %1's groups.
Specify validation criteria -> User.

Now you have the list of ID:s.

Next to get the actual titles of the groups (as the base table is OG membership, not node), Add a relationship -> Group Node from OG membership.
Add a field -> Content: Title.
Relationship -> Group node from OG membership.

Now you have the titles too. Add some filters and sort criterias to taste.


Multililingual views displaying wrong content I have created a view which lists a bunch of nodes. This works fine when the site is in the default language of English. I have cloned that view and made sure it only displays the French version of those nodes and changed the path where it should be displayed. This all works as it should in the view's preview area. However when I go the French url for that page, I only see the English version of the listed nodes and not the French ones as defined in the view.

I am confused as to why this would be. Different urls should display different content but it is not. What could be causing this issue? I am completely stumped and this is an urgent issue for a client.

To make the view results correspond to the language switcher, add a filter for Content  Translation: User's Current Language, which is the language that an authenticated user has set in the user settings (it is NOT the same as the current browser language or the site language).

If no option for the 'User's Current Language' is available in the filter criteria form, then verify your configuration at Configuration -> Languages -> detection and selection: the order should be 'URL, Default, User', and not something like 'Default, URL, User' (as mentioned also in https://www.drupal.org/node/1701854#comment-6279474).

Note: filtering Views results in a multi language site can sometimes be challenging, as illustrated also in discussions such as in https://groups.drupal.org/node/47478 ...


Views Filters: find nodes that have more than one term in taxonomy vocabulary How can I set a filter to find nodes that have more than one term in a particular taxonomy vocabulary?

Note: The vocabulary allow unlimited values and is required field. So, nodes can have 1-∞ terms.

In order to list down only those nodes of a specific content type that has more than one taxonomy term, I did the following and could only see nodes with more than one taxonomy term:

Create content type with taxonomy term field
Create views with following filter criterias

A. Published=Yes

B. Content Type={Your Content type}

C. taxonomy term field:delta (= 1)

For "C" I have clicked on Add filter criteria, then searched for the (content type's) field that contains taxonomy term and selected the one that has :delta (i.e. my field name is field_taxonomy_term and I choose field_taxonomy_term:delta), Once you selected the delta of your taxonomy term field then choose the operator as is equal to and provide the value as 1 and save.

If a content type has exactly one taxonomy term then the delta field will never have index 1 but, will always have index 0. If a node has more than one taxonomy term (i.e. 2) then there is index 1 (Index 1 is always present for content types with more than one taxonomy term), that is why the filtering works.

See the screenshots for more info:

The page is configured to show only nodes with more than one taxonomy temr

The following attachment is configured to show all nodes (it is then attached to the page)

The result of the above page and attachment is as follow

In case you are interested in the view, here is the export code:

$view = new view();
$view->name = 'viewfornodewithtaxonomy';
$view->description = '';
$view->tag = 'default';
$view->base_table = 'node';
$view->human_name = 'ViewForNodeWithTaxonomy';
$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'] = 'Attachment display all nodes with any taxonomy terms';
$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'] = '20';
$handler->display->display_options['pager']['options']['offset'] = '0';
$handler->display->display_options['pager']['options']['id'] = '0';
$handler->display->display_options['pager']['options']['quantity'] = '9';
$handler->display->display_options['style_plugin'] = 'default';
$handler->display->display_options['row_plugin'] = 'fields';
/* 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;
/* Field: Content: taxonomy terms */
$handler->display->display_options['fields']['field_taxonomy_terms']['id'] = 'field_taxonomy_terms';
$handler->display->display_options['fields']['field_taxonomy_terms']['table'] = 'field_data_field_taxonomy_terms';
$handler->display->display_options['fields']['field_taxonomy_terms']['field'] = 'field_taxonomy_terms';
$handler->display->display_options['fields']['field_taxonomy_terms']['delta_offset'] = '0';
/* 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(
  'nodewithtaxonomy' => 'nodewithtaxonomy',
);
$handler->display->display_options['filters']['type']['group'] = 1;
/* Filter criterion: Content: taxonomy terms (field_taxonomy_terms:delta) */
$handler->display->display_options['filters']['delta']['id'] = 'delta';
$handler->display->display_options['filters']['delta']['table'] = 'field_data_field_taxonomy_terms';
$handler->display->display_options['filters']['delta']['field'] = 'delta';
$handler->display->display_options['filters']['delta']['value']['value'] = '1';

/* Display: Page */
$handler = $view->new_display('page', 'Page', 'page');
$handler->display->display_options['defaults']['title'] = FALSE;
$handler->display->display_options['title'] = 'page display node with at least one taxonomy term';
$handler->display->display_options['path'] = 'viewfornodewithtaxonomy';

/* Display: Attachment */
$handler = $view->new_display('attachment', 'Attachment', 'attachment_1');
$handler->display->display_options['pager']['type'] = 'some';
$handler->display->display_options['defaults']['filter_groups'] = FALSE;
$handler->display->display_options['defaults']['filters'] = FALSE;
/* 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(
  'nodewithtaxonomy' => 'nodewithtaxonomy',
);
$handler->display->display_options['filters']['type']['group'] = 1;
$handler->display->display_options['displays'] = array(
  'page' => 'page',
  'default' => 0,
);
$handler->display->display_options['attachment_position'] = 'after';

Don't forget to mark your question as resolved if the answer helped you.


Drupal Commerce add to cart is no longer working for anonymous users I just updated to Commerce Kickstart 7.x-2.52 and add to cart is no longer working for anonymous users. It shows the success add to cart message but nothing is added to the cart. If I log in it works fine. I’ve tried:

I checked out and UID 0 is still in the DB
Disabled honeypot module
emptied the cache_from table
enabled “disable SQL rewrite” on the cart view
check permissions for the anonymous user
cleared the cache

UPDATED
The order entity is being created but nothing shows in the cart.

Commerce Kickstart added these lines to the /profiles/commerce-kickstart/.gitignore which prevented new files from being added to git and thus not getting pushed to production.

libraries
modules/contrib
themes/contrib

https://www.drupal.org/project/commerce_kickstart/issues/2937535


How to include menu item in breadcrumb I've this breadcrumb I've created, where I would like to show it as

Home > Main menu > Sub menu

Where sub menu is connected to a node. So when a user click on node, it must show the breadcrumb of the above format.

I've done this, but it is only giving

Home > Sub menu

Menu is missing.

function basis_preprocess_breadcrumb(&$variables) {
  if (($node = \Drupal::routeMatch()->getParameter('node')) && $variables['breadcrumb']) {
    $variables['breadcrumb'][] = array(
      'text' => $node->getTitle(),
      'url' => $node->URL()
    );

  }
}

Menu Breadcrumb might be what you're looking for.


Join multiple tables in D7 Views I'm trying to create a View Block to display related information on a node.

I'm creating an image gallery where each image node is tagged with one/more taxonomy terms, and a block on each of those nodes then displays a list of users who have expressed an interest in the same taxonomy term(s).

So the node is tagged with e.g "landscape" and a user has a Profile2 profile in which they have have also selected "landscape" with a taxonomy ref field.

I'm having trouble building the view to achieve this. If I create a new view with a block and select that i'm displaying "Profiles" from the initial dropdown, views seems to remove some of the kinds of objects I can choose in the Contextual Filters or Relationships menus: Node isn't available for linking in a relationship.

If I go about in the "other direction" and make a view of Nodes, then try and create relationships backwards to the Profiles I want, I'm unable to select fields present in the Profile for output - the only fields available are those on the Node.

It seems that by choosing a specific kind of object to list, Views immediately excludes certain possibilities for joining.

Is this not possible? I know what the exact SQL would be, but I'd rather not write a module if a View would do.

Should the relationship not go via the taxonomy reference rather than direct profile to node? Or have I misunderstood what you've tried/want to achieve?


How can i set different language for 2 different domain? How can i set different language for 2 different domain?
I have 2 different domain for single drupal installation
www.example.en
www.example.fr
i want to display 2 different language based on the user coming from any domain?

Go to http://example.com/admin/config/regional/language/configure
Enable URL
Save
Go to Configure
Select Domain

Keep configuring it all.


Is it possible to embed a content creation form in views header? Suppose I am building a twitter-like site, and allow members to form groups with OG. So I have set up a view to list all the posts in a given group. However, I would like to embed a content creation form in the header (similar to how twitter is at the moment) with group audience set automatically to the group (therefore is not shown as an option in the form). Is there a way to do it without writing code (I haven't been doing drupal module development after D6...)?

It doesn't have to be in the view header. Just place it block above the view and adjust the css so they sit together.

If you use entity forms and entity form blocks, you can just place a block above the view block (or panel pane).

Rules will allow you to create a new node, set the current OG_context as the new new node's group and then redirect back to the same page or to the new node.


I try to customize my block id and it doesn't work I create a block which I want to theme.

My block ID is 1.

In my mind it was simple as create a file block--block--1.tpl.php and make some theming on it, but I didn't see any of my change.

One important point here, is that I'm using Panel.
I wanted to drop this block into a panel region.

this is what I see in firebug

contextual-links-region panel-pane pane-block pane-block-1

Thanks a lot.

You can set your block to a 'system block' from within the Panels pane management interface. It should then pick up on the system level block template files.

This also may be a duplicate of How to use a custom block template when the block is embedded in a panel pane?, but there wasn't a definite 'good' answer there either it seems.


Module to make View Tokens available I'm looking for a module which adds Views into tokens. E.g within some content, I want to be able to use [view-vid], or something similar.

Is there anyway for me to do this without needing to write custom code?

In D7 you can use a phpsnippet calling views_embed_view. Modules to do the job like Views embed filter seem to have died at the D6 stage.


Struggling with Feeds Importer to custom content type I am struggling to get to grips with the Feeds Importer, getting it to create nodes of my custom content type.

I have created the Feed Importer :

$feeds_importer = new stdClass();
$feeds_importer->disabled = FALSE; /* Edit this to true to make a default feeds_importer disabled initially */
$feeds_importer->api_version = 1;
$feeds_importer->id = 'feed_new_horizons';
$feeds_importer->config = array(
  'name' => 'New Horizons',
  'description' => 'NASA New Horizons News Feed',
  'fetcher' => array(
    'plugin_key' => 'FeedsHTTPFetcher',
    'config' => array(
      'auto_detect_feeds' => FALSE,
      'use_pubsubhubbub' => FALSE,
      'designated_hub' => '',
      'request_timeout' => NULL,
      'auto_scheme' => 'http',
      'accept_invalid_cert' => FALSE,
    ),
  ),
  'parser' => array(
    'plugin_key' => 'FeedsSyndicationParser',
    'config' => array(),
  ),
  'processor' => array(
    'plugin_key' => 'FeedsNodeProcessor',
    'config' => array(
      'expire' => '2592000',
      'author' => '63',
      'authorize' => 1,
      'mappings' => array(
        0 => array(
          'source' => 'title',
          'target' => 'title',
          'unique' => 1,
        ),
        1 => array(
          'source' => 'description',
          'target' => 'body',
          'unique' => FALSE,
        ),
        2 => array(
          'source' => 'url',
          'target' => 'field_feed_source',
          'unique' => FALSE,
        ),
        3 => array(
          'source' => 'author_name',
          'target' => 'field_feed_author',
          'unique' => FALSE,
        ),
      ),
      'update_existing' => '1',
      'update_non_existent' => 'delete',
      'input_format' => 'full_html',
      'skip_hash_check' => 0,
      'bundle' => 'feed_news_item',
    ),
  ),
  'content_type' => 'feed',
  'update' => 0,
  'import_period' => '1800',
  'expire_period' => 3600,
  'import_on_create' => 1,
  'process_in_background' => 0,
);

And although it runs and imports the articles, it does not create the nodes as my custom content 'Feed News Item' - it always creates them as the default 'Feed Item'

I don't see (or understand) how the Feed links to the Importer - I can't see an obvious link between the two, so it's possible I have missed something!

So I gave up with Feeds Importer.
Despite a clean install, I could not get the feed description to go into any other target field other than description.

Despite setting the text format as Full HTML, it defaulted back to Filtered HTML and would not show the image in the feed. I had to edit each node, change the text format and then it would display.

So, I reverted back to the core aggregator and after some head scratching with CSS, got it to do what I wanted..

You can see the initial result at http://bedsastro.org.uk - this will be revised and updated shortly, but at least I got it working!


How to Allow User to Choose to Pay by Invoice OR Credit Card with Drupal Commerce does anyone know if its possible to have a Drupal Commerce checkout form that allows a user to choose whether they want to pay by credit card OR have us send them an invoice so they can pay by check? The form should allow the user to submit the form regardless of which option they choose.

Note: if they choose credit card they would of course have to fill out their credit card information. IF they chose invoice they wouldn't have to pay at this time.

If you have multiple payment options available, the customer will be prompted to choose the payment option they want.

If you're not picky, you can use Commerce Custom Offline Payments and just create a payment type for an invoice.


php.ini opcache path for multiple websites with shared code base I have a D9 website set up already and I want to add another that shares the same code base.  (This is on a shared hosting environment)
Below is an example my current php.ini settings for the opcache with 'MyWebSite1.com' as the initial website cache directory path.  I want to have the two sites cached in different directories.
How do I specify the path in this php.ini set up for the second 'MyWebSite2.com' website?  Or, does this cache directory contain generic php info that can be shared between multiple sites so that only one directory can be specified?
Thank you.
date.timezone = 'America/City'

zend_extension=opcache.so;
opcache.enable=1;
opcache.memory_consumption=32;
opcache.interned_strings_buffer=8;
opcache.max_accelerated_files=3000;
opcache.revalidate_freq=180;
opcache.fast_shutdown=0;
opcache.enable_cli=0;
opcache.revalidate_path=0;
opcache.validate_timestamps=2;
opcache.max_file_size=0;
opcache.file_cache=/AbsoluteDirectoryPath/sites/MyWebSite1.com/.opcache;
opcache.file_cache_only=1;

If I understand your question correctly, I believe you can use ini_set() in your settings.php files if your multisite required different PHP ini configurations.
Example 1a:
// @file docroot/sites/default/settings.php
ini_set('opcache.file_cache', '/path/to/opcache/default');

Example 1b:
// @file docroot/sites/my-other-site/settings.php
ini_set('opcache.file_cache', '/path/to/opcache/my-other-site');


How to force rules configuration to load There is a rule that comes with Commerce Paypal, commerce_payment_paypal_wpp, it implements an Action: "PayPal WPP - Credit Card", which provides an admin interface to configuring the PayPal WPP, with API Username, password, etc.   We've implemented our settings for this, as with other rules, as commerce_paypal_wpp.rules_defaults.inc.

The problem is that, in this case, commerce_paypal_wpp.rules_defaults.inc is not loaded for some reason when the rule is installed.  After installation, we have to log in, navigate to that admin form, open it and press save, no changes, just press save.

We tried without success:

function MODULE_default_rules_configuration_alter(&$configs) {
  $configs['commerce_payment_paypal_wpp']->active = TRUE;
  $rule = rules_config_load('commerce_payment_paypal_wpp');
  $rule->save;
}

What do we need to do in code that would do the work of clicking that save button?  This is the last obstacle to a zero-touch installation, would really like to get that in.  Any ideas?

Your question is a bit confusing, because the default Rule in question is defined by the Payment module in commerce_payment.rules_defaults.inc, not by the PayPal module. It sounds to me like a general case of cache trouble, though in my testing and development of the PayPal module I've never seen any issues with it. If what you mean is simply that the payment method rule is disabled by default, that's just how we've built the modules - enabling it like you show with your custom code will just be a necessary step.


How to show/hide fields based on visitor's country? I have two fields (consider field_A, field_B). Anyone should see only one of these 2 fields based on their IP address:

If users from US access the page, only field_A should be visible.
For other countries, field_B should be visible.

How can I achieve this?

You can make use of Geo Ip to do this. Install Geo Ip by following the instruction mentioned in the link http://www.beginninglinux.com/home/php/ubuntu-php-5-geo-ip

Make use drupal ip_address() function to get user ip address.

function test() {
  $code = geoip_country_code_by_name($ip);
  if ($code == 'US') {
    //hide  field B
  }
  else {
    //hide field A
  }

}

geoip_country_code_by_name returns country code. I think this approach gives you solution.


Unpublished content is displaying in entity referenced fields I am using entity reference to refer another content type. But in the list I am getting unpublished content also. Because I have given permission to view Unpublished content, but I don't want to show them here. So how can I restrict those content from displaying in Entity referred field value.

While adding entity reference field to the content type,

In Field Setting--> Entity selection-->Mode -->Select Views and create a view by filtering only Published content, and assign the same to "View used to select the entities *"

Hope this will help you in building views link


Reducing number of DB queries when using views, search_api and relationships I have a view which uses search_api (and solr) to get a list of nodes, and then displays selected fields, including some from a relationship to commerce_product
This is resulting in about a thousand database queries to display about 20 nodes, which I think is inefficient.
Digging in further, it looks like search_api returns a list of nids, which are then loaded with a single invocation of entity_load (which causes several DB queries as field_attach_load loads each of the bundle's fields in turn, loading values for all nodes at once)
But when it comes to the commerce_products in the relationship, these are loaded one-by-one somewhere during the field render process, rather than all in one go. So the total number of queries is close to (number of results) x (number of fields) instead of just (number of fields) like it would be without the relationship.
(Yes, I have quite a few fields)
Is there any way I can get Views to load all of the referenced entities in one go, rather than in this inefficient one-by-one manner?

Is there any way get Views to load all of the referenced entities in one go? No, there's not much you can easily change to fix that.

There's a lot of behaviour built in so that Drupal can handle multilingual data or different data storage back ends like MongoDB.

If you're not already doing so, you can use entitycache module to lighten the load. For cached entities, you will eliminate a lot of queries.

FYI, Entitycache will not work on its own. You will need to integrate with a cache back end like Redis or Memcache. See the module documentation and READMEs for configuration details.


How to add a css file to the admin theme from a front subtheme? Is it possible to add a css file to the back office from a front sub-theme?

I would like to avoid having to create an admin sub-theme or a module just for the sake of adding one line of css to modify the existing back office styling.

There are a few options to accomplish this.

If your admin theme has a html.tpl.php you could manually add it in the head using <link type="text/css" rel="stylesheet" href="linktoyourcssfile">

Although, know that, when you update your admin theme, the html.tpl.php file probably will be overwritten so you will need to add it every time again.

Another solution is to install the Add To Head module and add the above line to the head without having the trouble it will be overwritten the next time you update the theme.

It's up to you to see which solution fits you best.


How can I send HTML mail when a new content is created with attachments using these modules? In my project, I need to send HTML mail when a new content is created with attachments using the Mimemail, Mail System, SMTP, and Rules modules.
Plain text mail is working fine with rules module but problem is with HTML mail.
Can you please tell me the procedure to configure Mail System and Mime mail with SMTP?

First you need to create a Rule to send a HTML email via Mimemail:

Once you've configured the rule correctly and have entered your HTML email content, you need to ensure the correct mail system class is being used by Drupal to send your emails:

If you don't select the MimeMail class within these settings, the default Drupal mail system will be uses and your HTML emails will be sent in plain text.


How to get attachments out of a twig file How do I get the attachments out a twig file and add them to a build array?

If there is a twig file with

{{ attach_library('mytheme/pullquote') }}

And because it's in an ajax response, I need to get the attachments out without rendering the page, how do I get a new build array with that library attached?

In my controller:

   $build['pullquote'] = [
      '#theme' => 'pullquote',
      '#quote_text' => $quote_text,
      '#attribution_name' => $attribution_name,
      '#attribution_title' => $attribution_title,
      '#size' => $size,
    ];

    $response = new AjaxResponse();
    $response->addCommand(new EmbedInsertCommand($build));
    return $response;

Because the library is added in twig and not in the build array, it's not coming through in the response.

The EmbedInsertCommand is from the embed module, which entity_embed inherits from, at embed/src/Ajax/EmbedInsertCommand.php

which uses the CommandWithAttachedAssetsTrait, with this function:

 /**
   * Processes the content for output.
   *
   * If content is a render array, it may contain attached assets to be
   * processed.
   *
   * @return string|\Drupal\Component\Render\MarkupInterface
   *   HTML rendered content.
   */
  protected function getRenderedContent() {
    $this->attachedAssets = new AttachedAssets();
    if (is_array($this->content)) {
      $html = \Drupal::service('renderer')->renderRoot($this->content);
      $this->attachedAssets = AttachedAssets::createFromRenderArray($this->content);
      return $html;
    }
    else {
      return $this->content;
    }
  }

Unfortunately, AttachedAssets::createFromRenderArray misses libraries added within twig.

Usually ajax commands which add html are able to catch attachments bubbling up when they render the content. Don't know EmbedInsertCommand(). The name clearly says it is an command inserting html, so it should be able to do it.

For commands not able to handle attachments you can render the content already in the controller and add the attachments to the response here:

  $response = new AjaxResponse();
  $html = \Drupal::service('renderer')->renderRoot($build);
  $response->addCommand(new EmbedInsertCommand($html));
  $response->setAttachments($build['#attached']);
  return $response;

This is only a workaround, not the recommend way, because Ajax does some more processing of the attachments before adding them to the response, but for a single command this should be OK.


Views - how to display a column showing who made the last update I'm updating the main content2 view, and I'd like to add another column to show which user made the last update. I'm using workbench moderation, in case that makes any difference.

Edit your content type's Publishing options & enable 'Create new revision'.
In Views' Advanced pane, add a Relationship of type 'Content revision: User'.
Under Fields, add the field 'User: Name' AND use the relationship you just created.

Voilà!


Sharing the same code base and one database I would like to have multi-sites that share the some code base and one SQL database in Drupal 8.

Is this possible and recommended? I am interested also in security concerns. Is this safe?

This is very much possible using the domain module:

  "The Domain Access project is a suite of modules that provide tools
  for running a group of affiliated sites from one Drupal installation
  and a single shared database."

Which is currently under development for Drupal 8 here:

https://github.com/agentrickard/domain

This of course assumes you are not talking about actual Drupal multi-sites which are intended to share the same codebase but always have separate databases.


How to load jquery in twig file I need to run a jQuery file in a twig file in order to bind aqua lift segments.  but jQuery is not loaded yet .  How can I load jQuery at this point without loading it twice?
thanks

I think your question is that you want to put inline javascript in twig templates, but it does not work, because jquery is not loaded yet?

You can override the default that the libraries are loaded in the footer and put jquery and any of your own js in the header:

mytheme.libraries.yml:

mylibrary:
  version: 1.x
  header: true
  js:
    js/myjavascript.js: {}
  dependencies:
    - core/jquery

mytheme.info.yml:

libraries:
  - mytheme/mylibrary

The important part is header: true.

If you make a dependency on core/jquery for the header, jquery is not loaded a second time in the footer, even if there are multiple dependencies for core/jquery by other libraries.

Now you can put your jquery dependend js code in the header (in this example in myjavascript.js) or put inline js in twig templates.


Set site URI for drush uli without 'default' Versions discussed: Drupal 8.6.13, Drush 9.6.1.

This is somewhat similar to How to have an environment specific drush.yml? except that the other thread is now four or five months out-of-date and Drush 9.6.1 doesn't seem to respect the drush.yml anymore.

I'm just trying to set my Site URI.

As detailed in that thread, I've tried web/sites/default/drush.yml as well as many other locations for the drush.yml, done a drush cc drush, and yet drush status still reveals an incorrect Site URI of http://default, showing that it is not respecting the uri: line in any of my drush.yml files.

To complicate matters, I'm using DDEV, so following up on some suggestions that I've gotten from the Drupal Slack that we should really be using an environment variable (namely DRUSH_OPTIONS_URI) have proven tricky, as I'm not exactly sure where that goes inside of the DDEV environment.

Inside the DDEV container, if I do export DRUSH_OPTIONS_URI=http://my.ddev.local/ then everything works great, but once I quit the container or try to do things from outside it, such as ddev exec drush uli, things are back to the incorrect Site URI.

How can I persist this environment variable across restarts of DDEV/Docker?

I'm writing this up for posterity, since the Slack is relatively ephemeral. Here's the current method, following Providing custom environment variables to a container:

In e.g. .ddev/docker-compose.environment.yml put the following:

version: '3.6'

services:
  web:
    environment:
      - DRUSH_OPTIONS_URI=http://my.ddev.local

Then ddev rm and ddev start to prove to see it working. (This works for drush uli inside the container, after ddev ssh.)


How can I set form values with Ajax? I want to set the value of a textfield based upon the selection of a field above. You can choose a template and the textfield would have it as a value.

This is the select field used to select the template with the ajax call

// Template Select field
$form['template'] = [
'#type' => 'select',
'#title' => $this->t('Template'),
'#options' => $event_templates_select,
'#required' => TRUE,
'#ajax' => [
    'callback' => '::changeOutputValue',
    'disable-refocus' => FALSE,
    element.
        'event' => 'change',
        'wrapper' => 'edit-output',
        'progress' =>[
            'type' => 'throbber',
            'message' => $this->t('Updating e-mail template'),
        ],
    ]
];

This is the textfield that I want to display the value. It's in a ckeditor.

// Textarea field
$form['output'] = [
'#type' => 'text_format',
'#format' => 'full_html',
'#required' => TRUE,
'#disabled' => FALSE,
'#value' => 'hallo',
'#prefix' => '
',
'#suffix' => '
',
];

And finally, the ajax function

  public function changeOutputValue(array &$form, FormStateInterface $form_state) {

    $selected_option =  $form_state->getValue('template');
    if ($selected_option == 0){
        $output_text = '';
    } else {
        $template = \Drupal::entityTypeManager()->getStorage('taxonomy_term')->load($selected_option);
        $tempate_content = $template->get('field_template')->getValue();
        $tempate_content = $tempate_content[0]['value'];
        $output_text = $tempate_content;
    }

    $form['output']['#value'] = $output_text;

    $response = new AjaxResponse();
    return $response;

  }
}

Can someone explain what I'm doing wrong. I was trying to follow the drupal 8 form api docs but I can't get it to work with a ckeditor field.

The select field contains a number of e-mail templates. Upon selecting one, I want to display the template in the output field with a ckeditor so the user can still make changes if necessary.

I'm using Drupal 8 with a custom module.

Thanks in advance.

From the ajax callback, you only need to return the render array containing the data to be inserted into the div you have specified as the callback to your #ajax.

So in the ajax callback you can return this, rather than an AjaxResponse:

return $form['output'];