How do I programmatically generate an entity form? I need to programmatically generate the entity form for my custom entity - basically get the same output that happens when you call

\Drupal::formBuilder()->getForm('form namespace')

When I try to do that with my entity form I get the error:

Call to a member function getEntityTypeId() on null in Drupal\Core\Entity\EntityForm->getBaseFormId() (line 77 of core/lib/Drupal/Core/Entity/EntityForm.php).

Really stumped on how to proceed.

Here's an obfuscated version of code I'm using

Entity Definition:

/**
 * Defines the My Entity entity.
 *
 * @ingroup my_module
 *
 * @ContentEntityType(
 *   id = "my_entity",
 *   label = @Translation("My Entity"),
 *   handlers = {
 *     "view_builder" = "Drupal\Core\Entity\EntityViewBuilder",
 *     "list_builder" = "Drupal\my_module\MyEntityListBuilder",
 *     "views_data" = "Drupal\my_module\Entity\MyEntityViewsData",
 *     "translation" = "Drupal\my_module\MyEntityTranslationHandler",
 *
 *     "form" = {
 *       "default" = "Drupal\my_module\Form\MyEntityForm",
 *       "add" = "Drupal\my_module\Form\MyEntityForm",
 *       "edit" = "Drupal\my_module\Form\MyEntityForm",
 *       "delete" = "Drupal\my_module\Form\MyEntityDeleteForm",
 *     },
 *     "access" = "Drupal\my_module\MyEntityAccessControlHandler",
 *     "route_provider" = {
 *       "html" = "Drupal\my_module\MyEntityHtmlRouteProvider",
 *     },
 *   },
 *   base_table = "my_entity",
 *   data_table = "my_entity_field_data",
 *   translatable = TRUE,
 *   admin_permission = "administer as my_entity entities",
 *   entity_keys = {
 *     "id" = "id",
 *     "label" = "name",
 *     "uuid" = "uuid",
 *     "uid" = "user_id",
 *     "langcode" = "langcode",
 *     "status" = "status",
 *   },
 *   links = {
 *     "canonical" = "/admin/structure/my_entity/{my_entity}",
 *     "add-form" = "/admin/structure/my_entity/add",
 *     "edit-form" = "/admin/structure/my_entity/{my_entity}/edit",
 *     "delete-form" = "/admin/structure/my_entity/{my_entity}/delete",
 *     "collection" = "/admin/structure/my_entity",
 *   },
 *   field_ui_base_route = "my_entity.settings",
 *   constraints = {
 *     "CustomContraint" = {}
 *   }
 * )
 */
class MyEntity extends ContentEntityBase implements MyEntityInterface {

Form namespace

namespace Drupal\my_module\Form;

use Drupal\Core\Entity\ContentEntityForm;
use Drupal\Core\Form\FormStateInterface;

/**
 * Form controller for My Entity edit forms.
 *
 * @ingroup my_module
 */
class MyEntityForm extends ContentEntityForm {

Okay, so this is what I've found so far. User oknate's answer partially works; I also had to add a dummy function to my container form class to get around a callback error, which looked like this:

 public function processForm($element, FormStateInterface $form_state, $form)
  {
    return $element;
  }

This is probably not the right way to do this, but it does result in a form object that will render in another form.

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

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

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

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


Getting JQuery Masonry to work with Drupal 7 Views I want to do this without porting the fluid grid module to 7 from 6. I can't for the life of me get a view page of images to work with Masonry.

Does anyone has experience with this and know how to get it working with just masonry.js and not a module?

Thanks

There's actually a Masonry module now

  Makes the jQuery Masonry plugin available to Drupal as a library.


How to create a family tree structure of nodes? I have to create a family tree in Drupal. I am trying to use tree views module to do the same.

I have 3 nodes (A, B and C) of the contact type (I have created custom node), whereas C is son of A (Father ) & B (Mother).

I need to show the same in a tree like structure.

I have used relationship module and made these relations:

A isFatherof C
B isMotherof C

How do I show them as a tree like structure? Something like so:

A - B
  |
  C

I have tried using the trees views module.

I'm assuming you've tried to use the Views tree module (there doesn't seem to be a "trees views" module ...). To my knowledge, that module cannot create a graphical visualisation of a tree structure.

I'd recommend to create such tree structure using Graphviz diagrams, and use the Graphviz Filter module. Some more details about this module (from its project page):

  ... a little filter that treats input text as DOT syntax for Graphviz, converts it using Graphviz tools to the requested format(s) and renders it in HTML. It's useful to quickly create graphs dynamically from within Drupal nodes.

For more information, refer to the Community Documentation about Graphing Modules, which has a list of modules for creating either Static or Dynamic Graph Diagrams.


Views UI doesn't provide links to expand fieldsets anymore I have moved an entire drupal site to another server. While everything else seems to work fine, I can't quite access collapsed fieldsets in Views UI anymore. It looks like this

All fieldsets (STYLE SETTINGS and so forth) are collapsed. The fieldset label however is not a link. The content of the fieldset exists when I view the HTML of the site. If I remove the CSS

html.js fieldset.collapsed .fieldset-wrapper {
  display: none;
}

I can again see the fieldsets' contents, but the error must be somewhere else. But I don't have any clue where to look for. Anyone has an idea?

I tried to google the error, but it seems all known errors are related to some "Expand all" or "Collapse all" buttons.

This probably means that there is something wrong with JS making collapsible not work.

Is there anything in the JS error log? Check if all JS files are moved and that they are complete. Also check for error 404 for JS files.


How to make Drupal Commerce tokens available in the Commerce Message module? In addition to the Drupal Commerce module, I installed the Commerce Message module for Drupal 7. Everything works fine so far.

I created a new Rule to send a billing e-mail in addition to the order completed e-mail to the customer.

But now I have the problem that I can not apply any tokens that give me the address or full name of the customer. It seems, that the standard Drupal Commerce tokens do not work in the Commerce Message module.

I looked through the files of Commerce Message and I can only find a few tokens that do not help at all.

According to law I need to send billing information to the customer. Including the customer's full name and address.

How can I use the Drupal Commerce standard tokens with Commerce Message?

Also despite saying that it would be able to use multiple html tags it does not. Whenever I use  (for example: italic) it does not include such  in the e-mail (for example: it only includes  /italic/).

Any help?

Even though your question is about the "Commerce Message" module, at its core your question relates to the Message module. And since you are using the Rules module, you can make the missing tokens (= the commerce standard tokens, as in your question ...) available by using the Replacement patterns for each message type.

So the answer to your question is "Whatever token you're missing, just make it available via Rules, by creating a replacement token for them". Refer to the answer to What's the purpose of "Replacement tokens" of a Message type? for way more details on that.

These Replacement tokens are really a hidden gem about how Rules integrates with Message. For an example to see them at work, refer to my answer to "Which user related token(s) can be used to create a Rule for setting up a message type?".


Dynamic content with a view and a block I'm new to Drupal (using Drupal 8) and have been struggling to get content from a block I've create to display when accessing the view.

I've created a "service" view (page) which lives at the path "/service". I've configured the view to display the desired fields from the "service" content type. The view uses a contextual filter on the title of the "service" content type which allows clean URLs to work "/service/name-of-service"

The above works well. I'm running into problems with an "info" view (block) that I've created. The "info" block pulls in different fields from the same "service" content type. I decided to use a block for the remaining fields as it allowed me to place them in a specific block region that works for our desired page layout.

I've tried setting up a contextual filter in the block to filter by "ID" and provided a default value of "Content ID from URL", but I can't get this to work, no fields display at all. If I flip the setting to "Display all results for the specified field", fields do display, however, the content of the fields displaying in the "info" block is not pulling from the same node (because there is no contextual filter).

Is there a way I can setup a contextual filter to accomplish this? I've been able to use the contextual filter by ID successfully when working with the node itself, but can't get the same behavior when using views.

I was able to get this to work with the following contextual filter in my "info" block.

Filter by "Title"


CTools - How to limit the result of ctools_export_load_object()? How can I limit the result of ctools_export_load_object? Imagine I have something like this:

$result = ctools_export_load_object('mytable', 'conditions', array('date' => '1337020900'));

Also, What is the difference between ctools_export_load_object() and db_query()?

You are right; that is how you should call ctools_export_load_object() to filter the returned objects. Keep in mind that:

For each condition you can just enter a value a database field must have
If you enter more than one condition, the function will return the objects for which all the conditions are verified

The code used from the function for handling the conditions is the following one.

  else if ($type == 'conditions') {
    foreach ($args as $key => $value) {
      if (isset($schema['fields'][$key])) {
        $query->condition($key, $value);
      }
    }
  }

Because that code, you cannot get (for example) the objects for which the date is 1337020900, or 1337020910, or 1337020940, or 1337020906. You cannot choose the operator to apply for the conditions, which means (for example) that you cannot get all the objects for which the date is greater than 1337020900, or lower than 1337020900.

The difference between ctools_export_load_object(), and db_query() is that:

ctools_export_load_object() doesn't just return the objects obtained from a database table; it returns also object returned from a specific hook. This is done from the following code, contained in _ctools_export_get_defaults().

if ($export['default hook']) {
  if (!empty($export['api'])) {
    ctools_include('plugins');
    $info = ctools_plugin_api_include($export['api']['owner'], $export['api']['api'], $export['api']['minimum_version'], $export['api']['current_version']);
    $modules = array_keys($info);
  }
  else {
    $modules = module_implements($export['default hook']);
  }

  foreach ($modules as $module) {
    $function = $module . '_' . $export['default hook'];
    if (function_exists($function)) {
      foreach ((array) $function($export) as $name => $object) {
        // Record the module that provides this exportable.
        $object->export_module = $module;

        if (empty($export['api'])) {
          $cache[$table][$name] = $object;
        }
        else {
          // If version checking is enabled, ensure that the object can be used.
          if (isset($object->api_version) && version_compare($object->api_version, $export['api']['minimum_version']) >= 0 && version_compare($object->api_version, $export['api']['current_version']) <= 0) {
            $cache[$table][$name] = $object;
          }
        }
      }
    }
  }

  drupal_alter($export['default hook'], $cache[$table]);

ctools_export_load_object() can automatically join tables, if it finds the right information in the database schema defined in hook_schema().

// Build the query
$query = db_select($table, 't__0')->fields('t__0');
$alias_count = 1;
if (!empty($schema['join'])) {
  foreach ($schema['join'] as $join_key => $join) {
    if ($join_schema = drupal_get_schema($join['table'])) {
      $query->join($join['table'], 't__' . $alias_count, 't__0.' . $join['left_key'] . ' = ' . 't__' . $alias_count . '.' . $join['right_key']);
      $query->fields('t__' . $alias_count);
      $alias_count++;

      // Allow joining tables to alter the query through a callback.
      if (isset($join['callback']) && function_exists($join['callback'])) {
        $join['callback']($query, $schema, $join_schema);
      }
    }
  }
}

ctools_export_load_object() caches the result obtained, which means it could not execute any query at all.
ctools_export_load_object() uses many functions that are defined in the database schema. You can look at the comments contained in the code for ctools_export_get_schema() to see which functions are used.

As side note, a comment contained in ctools_export_get_schema() says (emphasis is mine):

  Please do not call these directly, always use the ctools_export_crud_* wrappers to ensure that default implementations are honored.


How to set up URL alias patterns? I would like to set the URL patterns in such a way that the page name of the parent page gets inserted into the URL. For example, in the Main Menu I've got an "About Us" link (about-us) and I would like to create a child page Contact Us (contact-us) underneath it.

How do I set up the URL alias patterns so that the child page URL is automatically set to about-us/contact-us?

URL aliases is supported in Drupal by help of pathauto module; if you enable the Token module, you can use it efficiently by using tokens. Once these modules are enabled, you can visit admin/config/search/path/patterns to set the patterns for URLs.

But as I see in your question, you are looking to set this for menu; you can't do that here.

There is logic behind it for not supporting it. Suppose you have a node/18 for about-us and you have two menu 'About-Us" & "About-Company". Now you can add this same node/18 to both places as child.

How can you have two URL aliases for single node/18? So this is the reason why menu are not supported I think.

You can go for creating content type & use pattern for that. You can set pattern for taxonomy, users, etc.


Check to see if two nodes are translations of each other What is the easiest way to check to see if two nodes are indeed part of the same translation set? Is there a function or some property that can be used? I am using the i18n suite of modules to perform node translation.

You can use translation_node_get_translations($tnid) function :

// $node is the node which translation set is needed
// this function returns an array of two node objects
translation_node_get_translations($node->tnid);

If you want to test it you need to put it somewhere (a wise place) in the code, clear your cache, and then show it with devel module.

Wish helps,

cheers,

jramby.


trying to add a template file to my module using hook_theme_registry_alter Here's my .module code:

/**
 * Implements hook_theme_registery_alter()
 */
function popover_theme_registery_alter(&$theme_registery) {
    $theme_registery['popover'] = array(
        'template' => drupal_get_path('module','popover'). '/popover.tpl.php',
        'type' => 'module',
    );
}

I'm having some plain html elements in the tpl.php file so that might be not good? or do I have to call this hook somewhere? what's wrong?

I'd imagine you should be using hook_theme() instead of hook_registry_alter() to define your theme function:

function MYMODULE_theme() {
  return array(
    'popover' => array(
      'template' => 'popover',
      'variables' => array('var1' => array(), 'var2' => '')
    )
  );
}

Then you can call it from anywhere (including a page callback, which I think is where you're trying to return this from given your comment above):

$output = theme('popover', array('var1' => $var1, 'var2' => $var2));

In the popover.tpl.php file in your module's root folder you'll have access to the variables $var1 and $var2, which will be the vars you defined/passed into the theme function.

Then you can build up your HTML as you need.


In Drupal Commerce - Rules configuration. What is the default operator in the conditions section? I'm setting up Drupal Commerce in the checkout Rules section. But this question also applies to any Rules.

Currently I have 3 conditions in my rule set. By default what is the default operator in this section? Is it an OR or AND? I see you can add these in manually, but it would be good to know what they are by default.

  Data comparison

  Entity exists by property

  Data comparison

AND

And here's some filler text to get me over the 30 character minimum.


How to send emails to the subscriber? I have two content types movie types(say comedy, horror, action are node titles) and movies. where I am using movie types node titles as a node reference in the movies content type. here user can subscribe to the movie types and can watch all the movies under the type. Now where i am stuck is to send a mail to the subscriber when new movie is uploaded under the type he/she subscribed. Please help me to sort out this issue.

Check out Subscriptions.

  This module enables users to subscribe to be notified of changes to nodes or taxonomies, such as new comments in specific forums, or additions to some category of blog. Once enabled, all nodes will have an additional link that allows the user to change their subscriptions. Users have tab on their user screen to manage their own subscriptions. Users can also set an auto-subscribe function which notifies the user if anyone comments on posts they have made. Admins can turn this on by default.

It provides a very powerful and flexible subscription framework, and there are many ways to configure subscriptions with this module.

One that probably will match your use case is to use taxonomy terms for the type of movie (comedy, horror, action, etc.) and let the users subscribe to the type of movie they're interested in by taxonomy term.


Insecure content warning with D7 and SSL I'm running Drupal 7 with Drupal Commerce module. I have SSL enabled on my server. I've confirmed that the SSL is properly enabled (If I replace Drupal's index.php with a simple index.html, Chrome allows me to browse to my domain via https).

I'm getting a bunch of error messages like this:

  The page at https://example.com/ ran insecure content from http://www.example.com/sites/default/files/css/css_TsVRTbLFUpEZAfw-_bWPJu840QT523CPjUVJ5MRWfyk.css

There are about 20-30 of these errors - mostly .js and .css files, some .png etc.
Questions:

How can I configure d7 so that it accesses these files via relative paths
Are there any other workarounds here, to enable https on my drupal install?

Much thanks in advance.

Simply remove $base_url from your settings.php file; Drupal will detect $base_url automatically.

If you must set this value explicitly, you can add a little conditional logic to your settings file, such as:

if (isset($_SERVER['HTTPS']) && strtolower($_SERVER['HTTPS']) == 'on') {
  $base_url = 'https://example.com';
}
else {
  $base_url = 'http://example.com';
}


Views as definition list? Is there a way to output the content of a view as a definition list?
Example:

Nodes title

Nodes content

Another nodes title

Another nodes content

Any ideas?

You can also create a new template for how the Views row style works for your View: Views 2 theming.


How to print a page in drupal 7? I have a module for drupal 7 that generate reports. I want to print one of the reports with out drupal menus and footer. I want the report to be displayed on second page alone with view descriptive data? Please Help.

You might want to check out the Print Module.  I've used it successfully for print media in the past.


How do I create overridable templates? I have a module and a theme with different names. The module implements hook_theme() to specify a group of templates with 'template' and 'variables' for each. Template files in the module are working as intended.

In my theme, I implement templates/html.tpl.php and templates/page.tpl.php - which both work. But, theme/templates/mytemplate.tpl.php is not overriding the module's template. I have cleared the cache.

What do I have to do so that templates in my theme's templates/ folder will override my own module's templates?

I found the answer in this comment. For Drupal to find the theme's template overrides, I had to change my theme keys to underscore versions of my dashed template names.

function mymodule_theme($existing, $type, $theme, $path)
{
  return array(

    'my_theme_key' => array(
      'template' => 'my-theme-key',
      'variables' => array(
        ...
      ),
    )
  );
}


How to user listen the songs after purchasing their songs or products using Drupal commerce? I am using Drupal commercekickstart.. I have installed Commerce file module  and Commerce license module also.If user purchasing their product after that their can download the files at the same time user can listen the songs through player inside this project.Is it possible? Anyone guide to me?

You could probably place a view on the confirmation / download page to link to the mp3 inside html5 audio tags.

<audio controls>
  <source src="mymusic.mp3" type="audio/mpeg">
Your browser does not support the audio element.
</audio>

You could make the default view in a block, place it on the confirmation page where the link to download the mp3 is, and get the mp3 file with a contextual filter with a default value of get ID from URL.


Creating posts linked to map I want to create a map where on clicking on a certain location ,a user can find all the content/nodes/posts related to that location. ( Something like http://42floors.com/ )

Is it possible to build it using drupal? Can you suggest some modules that will be useful for this purpose?
Thanks. :)

location

gmap

views

With these three drupal modules you can easily create a map which will display all nodes with location details.


How to filter content on a view page using cookies? I'm developing a website where users access the content without registration but it still needs to have a favorites system for the elements on the web.
Right now I have implemented a system where i can add items to a "favorites" and the node id for every item is saved on a cookie.
Is there a way to filter the items that are shown by a view page using this node ids saved on the cookies?

I thought that it can be done by altering the query sent by the view or by aplying a filter in some point of the process where i check whether the element returned by the view corresponds with the node id saved in the cookie.

Is any of this options feasible? Is there a simpler way to focus this problem?

A better way to tackle your problem might be the Flag module.

It also has a good views integration and is quite easy to set up.

Just add a "favorites" flag and set it as private flag, so every user can have its own favorites.

On your favorites-view set your filter criteria to match the flag and you are good to go.


Check if Workbench Content Has Published Revision We are using Rules for advanced Workbench notifications. However, we have a notification that needs to change depending on whether content actually has a previously published version or is entirely new content.

Does anyone know of a way, using  Rules, to check for whether Workbench content has a published revision? (Note: Not whether the current revision is published.)

I'm assuming this question is about D7 ...

Step 1 - Flag published revisions

Use the Flag module to flag Workbench content whenever a published revision gets created. The flag you'd want to use is a global flag. To actually flag such content, use the Rules module.

Step 2 - Check if flagged

Adapt your existing Rule(s) (for advanced Workbench notifications) to take into account if your content has yes or no been flagged. To do so, you have a choice:

Split your current Rules Action (for those notifications) in 2 Rules Components (in which you can use Rules Condition to check the flag).
Use the Conditional Rules module so that you can include the required Rules Condition(s), to check the status of the flag, within the Rules Actions of your existing rule.


How do I show the user full name? I am building a Drupal 7 site, and using the Hybridauth module. On my site, users can register with Facebook and Twitter (through the Hybridauth module), or regularly through the registration form.

When I am using a view, and add the field "User: Name", if the user registered through Hybridauth, it will show the full name; if the user registered on the site, and entered the full name in two dedicated fields, the view will show only the first name.

How can I present always the full name in both the cases?

It seems the hybridauth module passes the username trough a hook before output an if the user is registered through hybridauth,
You should be able to get your desired outcome by also using the Real name module which Hybridauth seems to integrate with.


How to print an image in a paragraph that references a node with an image field I have the following scenario:

I have a paragraph called Timeslot that contains an entity reference field to a content type called Class.

That content type has an image field called Class Badge.

I would like to print the Class Badge image inside this paragraph using a twig template.

I went in circles for hours before I found the solution. There are many posts with partial or theoretical solutions, but none of them worked for me.

My solution consists of a twig file, paragraph--timeslot.html.twig, which prints all of the fields from the Timeslot paragraph. The line which prints the Class Badge image looks like this:

Working from right to left:

entity.uri.value is the uri value for the image field in the referenced node, which is the url prefaced by public:// or private://

entity.field_class_badge is the field in the referenced node that contains the image.

paragraph.field_class is the field in the paragraph that references the node.

file_url strips public:// or private:// from the uri that is retrieved so it can be used as the src in the image tag.

It is worth noting that uri is one of the database fields in the file_managed table. An alternative approach above could have been to use the filename field instead, and construct the URL manually within my code. Other fields that may prove useful would be filesize, created, and status.

Hopefully this helps someone. I doubt it's the definitive solution, but it worked for me.

UPDATE: I have since extended the solution above to display a specific image style, rather than the original image. Simply change the  tag in the code to look like this, where class_badge is the machine name of the image style.

Essential - you'll need to install the Twig Tweaks module to get this version of the solution to work.


Custom cache context confusion I made my own custom cache context by creating the service which links to a class which implements CacheContextInterface, and it seems to work, but the problem is, on page load, it doesn't seem to check if the context itself has changed.  Neither the getContext() function nor the getCacheableMetadata() function runs on page load.  If, for example, I go to a page that is a different route, it will run those functions for my cache context, as well as others.  Also, if any cache tag on any page is invalidated, it will go to my custom cache context and update, but otherwise it will remain cached.  How do I get that same invalidation goodness that different routes seem to have?

I notice, in core's core.services.yml, the cache_context.route service depends on the current_route_match service, which links to CurrentRouteMatch.php and depends on the request_stack service.  Which of these things is what causes Drupal to end up checking if the route has changed?  I want to do this same thing for my custom cache context.

Will I have to depend on some core service, or is there something I can put in either a service definition (in the module's services.yml) or the service class itself that says it wants to be updated?

EDIT: What was happening was that I put this new context on a block which loads on the main page, and it was indeed checking the context only for logged in users (just as 4k4 said) but for anonymous users, on page load, it wasn't checking the context so it wasn't updating the block.  I guess when it comes to requiring a cache context for anonymous users, it would be better to have the page invalidate more frequently, or get the content with ajax instead.

How do I get that same invalidation goodness that different routes
  seem to have?

Cache contexts are not invalidated. If you set a cache context, you increase the number of variants cached. For example if you would make a custom cache context for the weekday and set this cache context on a block, you would get 7 variants of the block in the cache. If you don't set any other cache metadata they will remain in the cache and will never be invalidated or updated.

  I notice, in core's core.services.yml, the cache_context.route service
  depends on the current_route_match service, which links to
  CurrentRouteMatch.php and depends on the request_stack service. Which
  of these things is what causes Drupal to end up checking if the route
  has changed? I want to do this same thing for my custom cache context.

Injecting other services in your own service is not enough. You have to use the injected service.

As example this code from the cache_context.route service you've mentioned:

public function getContext() {
    return $this->routeMatch->getRouteName() . hash('sha256', serialize($this->routeMatch->getRawParameters()->all()));
  }

$this->routeMatch is the injected service current_route_match. You can see how the service is used to build the context from the route name and the hashed route parameters.

  Will I have to depend on some core service, or is there something I
  can put in either a service definition (in the module's services.yml)
  or the service class itself that says it wants to be updated?

You only have to inject other services, if you need them in your code. But this depends, on what you try to do with your custom cache context.


Print Taxonomy Term in block.tpl.php I am using a specific content type as blocks (via Nodeblock Module). The nodes have certain taxonomy terms referenced via a term reference field, which I would like to print out in the corresponding block.tpl.php to use them as block classes. Same procedure as one would print terms as body classes, but only in block classes array. I find solutions for printing the term field in node.tpl and page.tpl but not in block.tpl.php
Glad for any help on this
thanks
Matthias

Here is code tested to work on a minimal install with nodeblock. It's well commented but to recap: get the node displayed in the block, get the term, use one the term's field as css class.

// change mytheme to your theme's name
function mytheme_preprocess_block(&$vars) {
  // don't do anything if it's not a nodeblock block
  if (empty($vars["elements"]["#node"]) || !is_object($vars["elements"]["#node"])) {
    return;
  }

  // get the node object, already loaded
  $node = $vars["elements"]["#node"];

  // get the linked term's id (change field_term to yours)
  $tid = $node->field_term[LANGUAGE_NONE][0]['tid'];

  // load the term fully to get access to its fields
  $term = taxonomy_term_load($tid);

  // turn one of the term's field into a css class (change name to any field)
  $css_class = drupal_clean_css_identifier($term->name);

  // add the css class to the list of classes for this block
  $vars["classes_array"][] = $css_class;
}


How to keep in sync git repository and related htdocs directory? I use the following set up for my @dev site:

(a) ../git/repository/dev

where I keep version control using git,

and a separate

(b) ../htdocs/dev

that I have an almost exact copy of  git repositor (a) used by the http server

How to make sure git repository (a) is always in sync with http (b) ?

I don't want to version control (b) directly from various reasons.

use the "post-update" hook in the /hooks directory provided in your .git directory to push a copy (sans -gitignore- the files not needed) each time you make git commits to your dev files


Set custom cache expiration time for a block When returning info for a custom block we can specify what kind of caching that will be used for the block according to the values in: hook_block_info().
Notice that if the block is cached the hook_block_view() will not be called at all.
In a module I'm developing I would like the user to be able to set the expiration time for the block cache, so I have tried something like this:

/**
 * Implements hook_block_info().
 **/
function CUSTOM_MODULE_block_info() {
  return array(
    'custom_block' => array(
      'info' => t('Custom Block'),
      'cache' => DRUPAL_NO_CACHE,
    ),
  );
}

/**
 * Implements hook_block_configure().
 **/
function CUSTOM_MODULE_block_configure($delta = '') {
  $form = array();
  $form['custom_module_cache_expire'] = array(
    '#type' => 'textfield',
    '#title' => t('Cache expire'),
    '#default_value' => variable_get('custom_module_cache_expire', 0),
  );
  return $form;
}

/**
 * Implements hook_block_view().
 **/
function CUSTOM_MODULE_block_view($delta = '') {
  $block = array();
  if ($delta == 'custom_block') {
    $cache = &drupal_static(__FUNCTION__);
    if (empty($cache)) {
      // Try to get data from cache.
      $cache = cache_get('custom_module');
      if (!empty($cache->data)) {
        // Check the expiration time.
        if (time() > $cache->expire) {
          // Remove the cache.
          cache_clear_all('custom_module');
        }
        $block = $cache->data;
      }
      else {
        // Build the renderable array and cache the result for 5 minutes.
        // The 'custom_module_get_items()' is a long running task and
        // the reason why we want to cache this block at a certain interval.
        $block['content'] = array(
          '#items' => custom_module_get_items(),
        );
        cache_set('custom_block', $block, 'cache', time() + (60 * 5));
      }
    }
    else {
      $block = $cache->data;
    }
  }
  return $block;
}

The above almost works as expected, but I was wondering if there some better way of doing this.

In Drupal 8 we can use the cache max-age to achieve this behavior.

I also tried to set the cache in the renderable array for the block, but I'm not sure what this does actually:

$block['content'] = array(
  '#items' => custom_module_get_items(),
  '#cache' => array(
    'expire' => time() + (5 * 60),
  ),
);

Perhaps the best way would be to simply set the caching to DRUPAL_NO_CACHE for the block and then in custom_module_get_items() use cache_set() and cache_get()?

I was also thinking that another way of doing this might be to just remove the default block cache from the database at a specific interval?

There is a real live example of custom cache for drupal 7 in forums:

Asis in Core forum module:

    /**
     * Implements hook_block_view().
     *
     * Generates a block containing the currently active forum topics and the most
     * recently added forum topics.
     */

function forum_block_view($delta = '') {
  $query = db_select('forum_index', 'f')
    ->fields('f')
    ->addTag('node_access');
  switch ($delta) {
    case 'active':
      $title = t('Active forum topics');
      $query
        ->orderBy('f.last_comment_timestamp', 'DESC')
        ->range(0, variable_get('forum_block_num_active', '5'));
      break;

    case 'new':
      $title = t('New forum topics');
      $query
        ->orderBy('f.created', 'DESC')
        ->range(0, variable_get('forum_block_num_new', '5'));
      break;
  }

  $block['subject'] = $title;
  // Cache based on the altered query. Enables us to cache with node access enabled.
  $block['content'] = drupal_render_cache_by_query($query, 'forum_block_view');
  $block['content']['#access'] = user_access('access content');
  return $block;
}

Here drupal_render_cache_by_query does caching based on query result.

  Prepares an element for caching based on a query.

  This smart caching strategy saves Drupal from querying and rendering to HTML >when the underlying query is unchanged.

  Expensive queries should use the query builder to create the query and then >call this function. Executing the query and formatting results should happen in >a #pre_render callback.

As in quote query executing and rendering happens in hook_block_pre_render() as in forum.

Another Example:

$block['content'] = array(
  '#items' => custom_module_get_items(),
  '#cache' => array(
   'cid' => 'custom_module',
   'bin' => 'cache',
    'expire' => time() + (5 * 60),
  ),
);

The above code is similar to what you did with cache_get, cache_set methods in much similar terms with less code, as drupal_render() function handles this for you setting up cache using drupal_render_cache_set().

You can read more from here: ADVANCED CACHING WITH RENDERABLE CONTENT

As for cache policy when you are caching stuff with custom code in hook_block_info DRUPAL_CACHE_CUSTOM and DRUPAL_NO_CACHE has no difference. However, using DRUPAL_CACHE_CUSTOM for custom caching is better standard.

Check out Block Caching for drupal 7.


Some #states not working for custom field but do work on identical webform field I'm working on a project where I'm programmatically cherry picking elements from a webform and then creating a custom form with all sorts of alterations and additions to the "cloned" webform fields.
$my_custom_field = $webform->getElement($webform_field_id, TRUE);

I'm then rendering a number of custom fields like the above in a custom form that extends from FormBase. The custom webform consists of fields, custom containers, attributes etc.
Everything works fine, #states included, apart from the "pattern" state and a few other states that are based on relative values e.g. "greater" / "greater_equal" / "lower" / "lower_equal". I'm adding these #states programmatically to the custom fields.
Example:
$custom_field['#states'] = [
  'visible' => [
    ':input[name="controlling_field_name"]' => [
      'value' =>
        // I've tested this pattern, it works in the webform field fine.
        'pattern' => $some_regex_pattern,
      ],
    ],
  ],
];

Apart from 'pattern', I've tried 'between' and 'greater', 'greater_equal', 'lower' and 'lower_equal' with no success.
The same exact #states (same field being dependant on same controlling field under the same exact conditions) work fine on the original webform field (when I view the webform on the admin theme for example) which makes me think that something is missing from / messing up with these #states on my custom theme.
No JS errors in the console whatsoever.
The structure of "data-drupal-states" when I render this custom field (webform field "clone") in my custom theme is exactly the same as the webform field that's rendered on the admin theme ie in its "native" webform.
Other #states work fine for the custom field ("value", "checked" etc.).
Any ideas on what's possibly messing up these specific states?

Webform form elements have additional goodies, not available in Drupal Core. But you can add those additional features with just a few lines of code:
<?php
public function buildForm(array $form, FormStateInterface $form_state) {
 $config = $this->config('custom_module');
 // Define the element(s).
 $form['nodes'] = [
   '#type' => 'entity_autocomplete',
   '#title' => $this->t('Select favorite articles.'),
   '#multiple' => 15,
   '#target_type' => 'node',
   '#selection_handler' => 'default:node',
   '#selection_settings' => [
     'target_bundles' => ['article' => 'article'],
     'sort' => ['field' => 'title', 'direction' => 'ASC'],
   ],
   '#default_value' => $config->get('nodes'),
 ];
 // Process the element(s).
 $this->elementManager->processElement($form['nodes']);
 // Attach behaviors. Unsaved: Warn users about unsaved changes.
 $form['#attributes']['class'][] = 'js-webform-unsaved';
 $form['#attached']['library'][] = 'webform/webform.form.unsaved';
 return parent::buildForm($form, $form_state);
}

Notice the elementManager->process() and the additional libraries. Watch the video in the linked blog post to get an idea where to get the elementManager and the libraries.
https://www.jrockowitz.com/blog/webform-apis


Show all terms that are children of term with argument tid I need a view that shows all terms that are children of the argument tid.

term 1
-term 2
-term 3
term 4
-term 5

view/4 should return term 5

I must be missing something fundamental because no matter how I mess with contextual filters and relationships I never come close to actually filtering my results by the context.

If you add a contextual filter for taxonomy term with depth modifier, it should work, e.g terms/1/1


How to add comment to a node with ajax (ctools modal)? I' trying to create custom module that should add comment to a content type in a modal window, with ajax. I wrote following code, but when I click on the 'Add review' link, browser loads new page when I can add 'reviews about shop' content type. I want to do this in a modal window, without reloading

function current_posts_menu() {
 $items['add/%ctools_js/review'] = array(
   'page callback'    => 'current_posts_ctools_modal_review',
   'page arguments'   => array(1),
   'access arguments' => array('create review content'),
 );
 return $items;
}

function current_posts_popup_style() {

  static $added = FALSE;
  if ($added == FALSE) {
    $added = TRUE;

    // Include the CTools tools that we need.
    ctools_include('modal');
    ctools_include('ajax');
    ctools_modal_add_js();

    $popup_style = array(
      'first-popup-style' => array(
        'modalSize' => array(
          'type' => 'fixed',
          'width' => 420,
          'height' => 'auto',
        ),
        'modalOptions' => array(
          'opacity' => (float) 0.3, .
          'background-color' => '#000000',
        ),
        'closeText' => '',
        'loadingText' => '', .
        'animation' => 'fadeIn',
        'animationSpeed' => 'fast',
      ),
    );

    drupal_add_js($popup_style, 'setting');

  }
}
function current_posts_block_info(){
 $blocks['add_review'] = array(
   'info' => t('Add review'),
 );
 return $blocks;
}

/**
* Implements hook_block_view().
*/
function current_posts_block_view($delta = '') {
    $block = array();
 switch ($delta) {
   case 'add_review':
     ctools_include('ajax');
     ctools_include('modal');
     ctools_modal_add_js();
     current_posts_popup_style();
     $comment_site_id = arg(1);
      $block['content'] = l(t('Add a review'), "add/nojs/review/{$comment_site_id }", array('html' => TRUE, 'attributes' => array('class' => "ctools-use-modal ctools-modal-first-popup-style")));
/*ctools-modal-first-popup-style */
     break;
 }
 return $block;
}

function current_posts_form_alter(&$form, &$form_state, $form_id) {
 switch ($form_id) {
   case 'comment_site':
     $comment_site_id = arg(3);
     if (is_numeric(arg(3))) {
       $lang = field_language('node', $form['#node'], 'field_news');
       // Declaration the default value for field on the comment creating form.
       $form['field_news'][$lang][0]['nid']['#default_value'] = $comment_site_id;

     }

 }
}

function current_posts_ctools_modal_review($js = FALSE) {
 // loading libraries ctools'a
 ctools_include('node.pages', 'node', '');
 ctools_include('modal');
 ctools_include('ajax');

 $type = 'reviews_about_shop';
 $node = (object) array(
   'uid' => $user->uid,
   'name' => (isset($user->name) ? $user->name : ''),
   'type' => $type,
   'language' => LANGUAGE_NONE
   );
  // Loading node form with disabled scripts.
 if (!$js) {
   return drupal_get_form($type . '_node_form', $node);
}
 // Create array $form_state.
 $form_state = array(
   'title' => t('Add Review'),
   'ajax'  => TRUE,
 );

    $form_state['build_info']['args'] = array($node);
    $output = ctools_modal_form_wrapper($type . '_node_form', $form_state);
    // Actions after form submit.
    if (!empty($form_state['executed'])) {
    $output = array();
    // Close pop up.
    $output[] = ctools_modal_command_dismiss();
    $comment_site_id = arg(3);
    // Insert  updated  view into a  page.
    if (is_numeric(arg(3))) {
     $output[] = ajax_command_html('.latest-reviews-full-style', views_embed_view('reviews_on_main_page', 'block', arg(3)));
    }
 }
    print ajax_render($output);
}

Note: I need like adding content type in a modal window. In my module reviews_about_shop is a content type that linked to a content type comment_site.

You need to add ajax library to that

drupal_add_library('system', 'drupal.ajax');

Or you can use the below function to render the ajax link

$block['content'] = l(t('Add a review'), "add/nojs/review/{$comment_site_id }", array('html' => TRUE, 'attributes' => array('class' => "ctools-use-modal ctools-modal-first-popup-style")));

Replace the above line to below.

$block['content'] = ctools_modal_text_button(t('Newsletter datacapture modal'), "add/nojs/review/{$comment_site_id }", t('Add a review'), "ctools-modal-first-popup-style");

Modify the argument

function current_posts_menu() {
 $items['add/%ctools_js/review/%'] = array(
   'page callback'    => 'current_posts_ctools_modal_review',
   'page arguments'   => array(1,3),
   'access arguments' => array('create review content'),
 );
 return $items;
}

and not to mention "Clear Cache"


How do you build an auto-generating menu for forums? I am using Drupal 7 with advanced forum and taxonomy menu and cannot figure out how to create a menu that will automatically add topics as menu items to forum containers with the right URL path structure. Taxonomy menu gets close but will not allow URLs other than taxonomy/term/[tid] (See: http://drupal.org/node/1161114). They need to generate in the pattern: forums/[container name]/[topic title]. I cannot seem to do this using the URL alias.

Has anyone built a drupal forum that generates a menu when topics are added and deleted that follow the standard forum URL path structure?

Looking back at this, I realize I was asking two questions:

1) How do you configure a URL alias pattern for a forum topic in the format: [forums]/[container_name]/[forum_topic_name]?

Install and enable Pathauto. Then configure a URL alias pattern at admin/config/search/path/patterns in this format [node:taxonomy-forums:parents]/[node:taxonomy-forums:name]/[node:title].

2) How do you then add this Forum topic to a menu underneath a specific parent automatically?

Install and enable Menu Position. Add a Menu Position rule at: admin/structure/menu-position/add for Content Type: Forum topic and select the menu parent item for Forum topics.


Export Broken Links records as CSV/XLS In Drupal 8 I can see the list of broken links at Administration->Configuration->System->Broken Link.
It is showing thousands of records with pagination.

I'm using Broken Link Module.

Is there any way we can export the entire record as a CSV or XLS file?

The Broken Link module seems to have views support, so you can use the Views Data Export module and a View of the data to export it.

If you'd prefer to go directly to the database, the module stores information in a table called broken_link so you can query that and use tools to move database results into a csv/excel if you'd like.


How to install a distribution on Docker using ddev composer command? I am new to docker. I have to install Openy distribution on docker using ddev CLI. ddev use this command to setup a normal Drupal 8 installation.

ddev composer create drupal-composer/drupal-project:8.x-dev --stability dev --no-interaction --prefer-dist

it's working fine. Now I have to install openy on docker, composer command for openy is:

composer create-project ymcatwincities/openy-project MY_PROJECT --no-interaction --no-dev

I tried writing ddev before openy command and many other changes are made but not successful. Now my main question is that, that how to install any other Drupal distribution using composer command on docker.

Note difference. First the official command.

ddev composer create ...

And now the command you executed.

ddev composer create-project ...

See? DDEV provides its own command to create a project. So just adding ddev in front of any composer command doesn't always work. Instead it's ddev composer create ....


Commerce, how to show 'view' of 100 products without speed/loading issues I am attempting to work out my own delivery/collection slot setup.

Each delivery 'slot' is its own 'commerce product,' 10 x 1 hour slots per day for 10 days - 100 slots to span 10 days. Pick a slot and add it to the cart.

For the year I think there is around 4000 variants in one spreadsheet which i can import with feeds - so I have all the raw 'product data.'

Only thing is when I create a view of the 100 products it seems to get bogged down and takes ages to load - sorry for being non-technical.

Below is a screenshot of what I have and would like to achieve, how can I display my products as below but rapido!

As the commenters above indicate, there's nothing in particular that should be causing this slowdown. You'll want to look into what might be happening during the render phase of your View and see if some Views query caching and / or render caching might help. The challenge, of course, would be preventing double bookings of fully utilized time slots - but maybe you could easily invalidate the cache in those cases.

If anything is causing the slowdown, it could be price calculation across 100 products happening multiple times per pageload. Commerce by default runs price calculation to determine if an Add to Cart button should be enabled or disabled and also to display the calculated price to render on the product page. That shouldn't be coming into play if you're just rendering product entities directly - typically you'd only see that on the product display node, and you could easily prevent it by editing the Views field to simple display the price as loaded.

To check out what's happening w/ price calculation, you can simply enable the Rules log and see if it's firing off a bunch of rules and then figure out how to disable it. I think Views caching with some smart invalidation as products are purchased is the right thing.


How to add a value to the object group in group module? I have been using the Group module with D7 for a while, but I always regretted that there was no 'creation date' value for each group. I added a column in my database which fills in that value automatically, but I would like it to be part of the object group so that I can retrieve the value more easily. Ideally I want to be able to do this:

$group = group_load($gid);
$thedate = $group->creation_date;

How should I go about it? Thanks.

Groups are fieldable entities, so you could add a field with a fieldname of, say, creation_date.

And if you'd then use the Rules module, you could create a custom rule like so:

Rules Event: After saving a new group.
Rules Action: Set a data value, i.e. to set the value of your creation_date field.

Note: If the field (like such creation_date field) does not show up within the Rules Action to be added, you may have to first add a Rules Condition like "Entity has field".


D7: copy data from node to node I got a content type 'activities' with a text field called 'transport'.
When a users submit a new activity, I want them to be able to copy data from earlier activities: just recycling data in other words.

Example:
Activity1 has a field ('transport') that contains text.
Activity2 has an empty field 'transport'.
Is there an easy way for a user to copy the data from Activity1 to Activity2?
The less clicks the better. What's the best practice?

Thanks!

I don't know if it's the best way to do it, but if I was in this situation I will do that way:
hook_form_alter => use a sql query to get the last node id of his last post, then node_load() and in form_alter copy the data you got from node_load() into the new node.

This solution should work if you already have a value in at least one of the previous one.

function YOURMODULENAME_form_alter(&$form, &$form_state, $form_id) {
    //get your form id of the admin activity page
    drupal_set_message($form_id); //or echo $form_id; it should be activity_node_form
    if($form_id == 'activity_node_form'){
        $form['#submit'][] = 'YOURMODULENAME_submit';
    }

}

function YOURMODULENAME_submit(&$form, &$form_state){
    if(isset($form_state['values']['field_activitiy'][LANGUAGE_NONE][0]['value'])){
        if(empty($form_state['values']['field_activitiy'][LANGUAGE_NONE][0]['value'])){
           $lastNode =  YOURMODULENAME_query();

           $node = node_load($lastNode['entity_id']);
           if(isset($node->field_activitiy[LANGUAGE_NONE][0]['value'])){
                $form_state['values']['field_activitiy'][LANGUAGE_NONE][0]['value'] = $node->field_activitiy[LANGUAGE_NONE][0]['value'];
           }
        }
    }
}

function YOURMODULENAME_query(){
    global $user;

    $query = db_select('node', 'n');
    $query->join('field_data_field_activity', 'a', 'n.nid = a.entity_id');
    $query->condition('n.uid',$user->uid,'=');
    $query->fields('a', array('entity_id'));
    $query->orderBy('a.entity_id', 'DESC');
    $query->range(0,1);
    $result = $query->execute()->fetchAssoc();
    return $result;
}

Tell me if you got an error.
PS:once you got the form_is remove the line

drupal_set_message($form_id);


Get current language of Drupal 8 in javascript? How can I get the language code or name from the Drupal javascript object in a js script ??

I know I can get language using this in php:

  $language = \Drupal::languageManager()->getCurrentLanguage()->getId();

But I need to have the language in my scripts.

All i got so far is the Drupal Jquery variable

  Var d = Drupal;

Which when printed looks like this.

{behaviors: {…}, locale: {…}, throwError: ƒ, attachBehaviors: ƒ, detachBehaviors: ƒ, …}
Ajax:ƒ (base, element, element_settings)
AjaxCommands:ƒ ()
AjaxError:ƒ (xmlhttp, uri, customMessage)
ProgressBar:ƒ (id, updateCallback, method, errorCallback)
Views:{parseQueryString: ƒ, parseViewArgs: ƒ, pathPortion: ƒ, getPath: ƒ}
ajax:ƒ (settings)
attachBehaviors:ƒ (context, settings)
behaviors:{autologout: {…}, drupalDisplace: {…}, responsiveImageAJAX: {…}, AJAX: {…}, activeLinks: {…}, …}
checkPlain:ƒ (str)
debounce:ƒ (func, wait, immediate)
detachBehaviors:ƒ (context, settings, trigger)
dialog:ƒ (element, options)
displace:ƒ displace(broadcast)
encodePath:ƒ (item)
formatPlural:ƒ (count, singular, plural, args, options)
formatString:ƒ (str, args)
history:{fetchTimestamps: ƒ, getLastRead: ƒ, markAsRead: ƒ, needsServerCheck: ƒ}
locale:{}
stringReplace:ƒ (str, args, keys)
t:ƒ (str, args, options)
theme:ƒ (func)
throwError:ƒ (error)
url:ƒ (path)
views:{instances: {…}, ajaxView: ƒ}
__proto__:Object

In pages with the core/drupalSettings library included, it seems to be pretty reliably available through the path:

var langCode = drupalSettings.path.currentLanguage;


The best way to deal with relations I am trying to learn views/panels and therefore am working on cinema listings: there are 2 cities, each has 2 cinemas, each cinema has 2 show halls and there is a list of 10 movies, that are shown in some of these halls during the period of 5 days.

The question is - what would be the easiest way to enter and display such listings - should I use panels pages, panel nodes and is it possible to create such things using node references and relations?

please correct me if I'm wrong - i'm a newbie here:

I was thinking to create 10 nodes for each movie, where there is description of the movie, picture, etc, but then I am lost - shoud I create a node for each cinema and so on, or is it better to use taxonomy terms and to add  these to each movie: city, cinema, hall and show time - I'm lost here... :(

the result that i want to achieve is that I'm clicking on a movie and I'm getting description and all it's showtimes. And if I'm clicking on particular cinema - I'm getting a timetable with movie names and times.

You need to get the data structure right, then everything will fall in place using Views.

Apart from city, cinema and movie content types, I'd suggest creating a session content type, too, which would link a movie with cinema, adding the time and hall number information. To maintain relationships between individual chunks of data, you want to use the CCK's node reference module (it is part of D7).

Roughly, you'd go with content types like so:

city (name)
cinema (name, city_ref, hall_count)
movie (name, description, picture, rating)
session (movie_ref, cinema_ref, hall_number, date_time)

It always depends on your requirements, but in this particular case I'd recommend using a separate content type for cinemas instead of taxonomy. Each cinema's node would serve information about the cinema, number of halls, and it would also reference the city it's located in and would be referenced by the screening nodes.

On the other hand if you have no other information about a city other than it's name, it should be safe to set it up as taxonomy.

To make it all work together, i.e. display listing pages, or allow users to search for movies and session times, you'll have to pick up the Views module.

Implementation of a "movie description and all it's showtimes" page would be the movie node page with a view attached (via Views Attach for D6 or EVA for D7) that would list show times for the movie passed as node ID from URL.

For the "cinema timetable with movie names and times", you'd do the same thing, but since you're displaying information about multiple movies, you would also use Views relationship (session -> movie_ref) to fetch in the movie nodes to be able to use their names as a views field.


Add content type machine name to an attribute in the body tag? I figured this would be easily done in the template_preprocess_html function, but I haven't found a way to do it... yet.

I need to add the content type machine name to a "data-init" attribute in the body tag.  How can this be done exactly?

End result: <body ... data-init="content_type">

template_preprocess_html should be the right function to start with.

So your code should look like the following:

function mytheme_preprocess_html(&$variables) {
  if ($node = menu_get_object()) {
    $variables['attributes_array']['data-init'][] = drupal_html_class('node-type-' . $node->type);
  }
}

Make sure to replace mytheme with your custom theme and clear Drupal cache.


More information about content in Link field autocomplete dropdown? In a project we have a Link field where editors can link to internal content or external content.

There are several cases where nodes of different content types have the same title.

Is there a way to display more information than just the node title in Link fields autocomplete widget - so that we can make it easier for Editors to pick the right node?

We are using LinkIt but that does not support the link module at the moment.

The autocompletion matches are provided by EntityAutocompleteMatcher::getMatches. The format is hardcoded as $key = "$label ($entity_id)". Label and entity id come from selection manager, which packages entity id and label pairs in an array keyed by entity bundle, so that could be used as a source for adding content type into the results. You'll need to override system.entity_autocomplete route's controller to get to your own matcher.

The same controller is used for rendering the selection dropdown though it does not display the entity ids, only labels (in web/core/misc/autocomplete.js). Overriding that is another thing you'll need to do.


From single site to multi site of an existing site broke all pages images I had a single site that is running in prod. We wanted to use the multi site feature of Drupal 7 because a few site will be using the same core code. So I moved the default/files/ to mysite.com/files like it was suggested. I created a settings.php that point to my existing DB. Everything worked fine until I reach a page that was created from the CMS and pointed to images in the default/files/ folder.

I understand that somewhere I need to change the image source paths from default/files to mysite.com/files but I can't find where. I find a lot of examples like this one stating that I need to run a sql script in the files table. The thing is, there is no files table... I figure it must be for Drupal 6 or older. I am on Drupal 7 and can't find where to change the images path. I found a table called file_managed which looks like the right place but all uri are ex: public://folderUnderFiles/image.png. There must be a way to change the public:// to point to my new folder!

I reckon that the paths which are stored in the database refer to the old url. In such case, you need to run a SQL command inside MySQL that corrects the paths.

To fix entries inside field_data_body table, you can run this command:

UPDATE field_data_body SET body_value = REPLACE(body_value, 'sites/all/files', 'sites/mysite.com/files');

You have to do the same for the corresponding revision table.


How can you sort taxonomy terms based on number of times used, in a view? I'm creating a view that lists the top 10 most popular taxonomy terms (tags). Currently I have the view returning all the terms and I can limit the view to 10 but I can't work out how to order the terms by popularity (i.e. number of times used across all nodes).

Anyone have experience of this?

Create a new view
limit to taxonomies "show taxonomies of term all"
Add a relationship "Taxonomy term: Content with term"
Use aggregation
Add field "Content: Title"
Aggregation type "Count"
Change label to something like "number of times used"
Add Sort criteria "Content: Title"
Aggregation type "Count"
Sort to whatever you like

it should look like this:


Get node form inside preprocess_views_view_fields() how can I get the node id  through the  : preprocess_views_view_fields()

You can get nid (node id) from $vars as like following:

$vars['row']->nid

You can also check the $vars to view the structure of the object as like following:

dpm($vars);

To use dpm(); you have to install devel module.


Get the NID from url Possible Duplicate:
  Get a node ID from the URL

I have two content types which one referenced to another by url widget, when i click on the link the node id passing with the url.
How can i get this nid from the url?
Is there some function for that?
Thanks

If you are wanting to use the nid of the node reference field inside a node template, you could grab it as $node->FIELDNAME[0]['nid'] (D6 anyway, add an ['und'] or something similar in the mix for D7 :)  Otherwise, a lot of other examples are given in the article @refineo references above.


Auto Post to Google + from RSS Feed Content I am using Drupal 7. I used Feeds module for content from the RSS. So i can get the content from RSS Feeds. Now Feed Content types automatically saved with RSS Feeds content. So now I want to auto Post the Feeds content to the twitter,linkedin and facebook.I am using Twitter module.

So i can Auto post the content using rules module to Facebook.
Same Time I Can Auto Post the content using rules module to twitter..

Now I want to auto post the content to Google + also.I am using Google plus for Google+ connect to my drupal site. After saving my new node display the google+ icon and sharing option also. Same time I want to Auto post the the new node to Google+ Page.

Edit: google+ does have an api, but this module is old, and doesn't implement it.

You can't post using this module.

This link night give you some more information: https://stackoverflow.com/questions/7570327/how-to-post-in-google-plus-wall


reference a field in CCK Drupal 6 I have two content types: students and chemistry labs.
Students content type has a cck field that lists student type (field_student_type) with Chemistry.Biology, Math, and etc. And Chemistry labs content type has a cck field (field_chemsitry_students) that node references to "students" content type as a list widget. Since it's a chemistry content type, the list needs to pull only chemistry students. With the current setup, it's pulling every student. I can't set the filter in views as it's a drop down list (widget). Views won't let me put operators to be ield_student_type = "Chemistry Student". How would I filter this out? Any suggestions? php filter? The question is more about field to field reference using node reference.

I have no idea why the maintainers haven't fixed this glaring oversight, but after hours searching and testing I figured his out and want to share.

Total results for views with multiple displays and pager

Inline with the view, drop this in view header:

<?php
print $view->query->pager->total_items;
?>

Outside the view:

<?php
$view = views_get_view('MY_VIEW_NAME');
$view->set_display('MY_DISPLAY'); // like 'block_1'
$view->execute();
print $view->query->pager->total_items;
?>

That freakin' easy...


What is the safe way to update to latest version? I am taking over a Drupal project that's running on Drupal 8.8.5.
Can I upgrade to Drupal 9.1.5, or do I need to upgrade for each version that's been missed?

In theory you should update to the latest recommended version of your current site's minor release. So in this case you should update to version 8.9.13 then you should be good upgrade. Remember to also make sure you do the same for all contributed modules and themes.
You might find using the Upgrade Status module helpful before upgrading.
As with everything you do, make sure you create a full backup of the sites files and database/s before attempting any updates.


Get the select list current value not key For example, There is a field with 3 options in allowed values, like option1, option2, option3.Is there any function which receive the field name and returns selected values not a keys ?

With this just return key of selected opinion

  print ($node->field_opinion['und'][0]['value'])

Update :

I have create select list field and with this field user can answer and select own value like this

1|Stars
2|Nights
3|Awesome
4|Days

With above code just return the keys field and i want to return values like "Stars"

Try this code:

$key = $node->field_opinion['und'][0]['value'];
$label = list_allowed_values(field_info_field('field_opinion'))[$key];


Commerce Kikstart rules how to I'm trying to make a subscription product with "Commerce subscription products" module, so I've stuck here, on how to edit rule for subscription to last for 30 days, that is the first, part, second is, is there some good tutorial on rules, in drupal 7 ?

It's hard to say, what your problem with Commerce subscription products is, without more detail.

Randy Fay have made a lot of screen casts about Commerce which also include configuration about Rules. You might be able to find a more better tutorial on Rules, but Randy does a really good job on stepping through different tasks in Commerce. There isn't a screen cast about subscriptions, but you should be able to get a lot of help from some of these anyways.


Altering the text after a checkbox using the Drupal Form Api I got the following issue. A clients wants that the text after checkboxes are links to other pages and thus between ...

I have the following code:

$form['boxes_brands'] = array(
    '#type' => 'checkboxes',
    '#title' => '
Merken
',
    '#options' => $brandArr,
    '#default_value' => $_SESSION['filter_brands_cat'],
);

$brandArr is an array of brands.

I looked in the Form API of Drupal but I did not find an option to do this. I could alter the values in $brandArr but of course that changes the value of the value attribute of the input object too.

Using the prefix and suffix options won't work either because I don't want the checkboxes in the  tags too.

Is there a clean way to do this?

You can give the $options as an array of value and label. And the label can then be given as a link using l().

'#options'       => array(
  'facebook'     => l(t('Facebook'), 'http://www.facebook.com'),
  'twitter'      => l(t('Twitter'), 'http://www.twitter.com'),
),


Combination of textfields and checkboxes in a custom form I need to create a custom form that contains a list of checkboxes and textfields next to each other, as in:

There are many meal items in the list. Right now I'm using something like:

$form[$meal_type->sku] = array (
    '#type' => 'fieldset',
    '#attributes' => array('class' => array('container-inline')),
  );
  $form[$meal_type->sku]['meal'] = array (
    '#type' => 'checkbox',
    '#title' => $meal_type->title,
    '#return_value' => $meal_type->sku,
  );
  $form[$meal_type->sku]['quantity'] = array (
    '#type' => 'textfield',
    '#default_value' => 1,
    '#size' => 5,

  );

This creates an individual fieldset for each meal item and quantity.  I just wanted to see if there are any suggestions for a better approach. Thanks!

I ended up using a '#type' => 'container' instead of fieldset. And I used #prefix and #suffix in the children to add specific classes for spans and horizontal alignment etc.

One other thing that seemed useful but I ended up not using: template files for form theming. This is a very useful tutorial:

http://themery.com/dgd7/advanced-theming/forms/with-templates


How to theme help text of field groups in node form I put some HTML tags in the help text of field groups in node form but HTML tags are automatically removed after saved the change. It seems that also there is no selection list of input format for help text. Is there any way to theme it?

Help text is run through content_filter_xss():

/**
 * Like filter_xss_admin(), but with a shorter list of allowed tags.
 *
 * Used for items entered by administrators, like field descriptions,
 * allowed values, where some (mainly inline) mark-up may be desired
 * (so check_plain() is not acceptable).
 */
function content_filter_xss($string) {
  return filter_xss($string, _content_filter_xss_allowed_tags());
}

/**
 * List of tags allowed by content_filter_xss().
 */
function _content_filter_xss_allowed_tags() {
  return array('a', 'b', 'big',  'code', 'del', 'em', 'i', 'ins',  'pre', 'q', 'small', 'span', 'strong', 'sub', 'sup', 'tt', 'ol', 'ul', 'li', 'p', 'br', 'img');
}


How do I disable a core installation profile? There is the Allow install profiles to be uninstalled issue that doesn't allow installation profiles to be uninstalled. Is there any way to do this in D7?
(With a little more effort if necessary.)

When you install D7, you typically have to choose an install profile; this could be the "standard" profile shipped with Drupal core. Once installed, the install profile will sit in the "system" table forever, with no obvious way to disable it.

Is there some more hackish way to disable the install profile.

To harmonize the question with the accepted answer even more, I extend the question to: If the install profile cannot or should not be disabled, then can it be replaced at least?

In Drupal 7, a install profile is like a module, but a special one, with two major exceptions:

Any module required by a install profile can be disabled --as you have found-- except the ones required by drupal core (field, filter, node, system, user). See module_disable() function for details, where the dependency on the install profile is explicitly discarded.
The profile used to install a site is also a required module. This is hardcoded in drupal_required_modules().

So a profile can't be uninstalled, because it is a required module.

You can set status to 0 in system table, but you shouldn't, since:

Drupal expects the install profile to be enabled, and rely on that for some operations, none if them critical afaik.
it is a module, it may implement any hook (in its .profile file), or declare any function required by a profile's submodule. Disabling it the hard way may produce misfunction or a php fatal error in those scenarios.

Btw, the install profile used to install the site is stored in the install_profile variable

# drush vget install_profile
install_profile: 'minimal'

You can, if you find it useful for some reason, change the install profile by setting install_profile to any other profile name and enabling it in the system table.


Render node from Controller I have a controller that passes a list of nodes to a template for rendering. I think I'm missing something simple.

I've tried this with no success:

public function content() {
  $students = $this->getStudents();

  return [
    '#theme' => 'dashboard',
    '#students' => $students,
  ];
}

private function getStudents() {
  $user = $this->currentUser();

  $nids = \Drupal::entityQuery('node')
    ->condition('type','student')
    ->condition('uid', $user->id())
    ->execute();
  $nodes = Node::loadMultiple($nids);
  return $nodes;
}

I have a dashboard theme function:

function dashboard_theme() {
  return [
    'dashboard' => [
    'variables' => ['students' => NULL],
    ],
  ];
}

And a twig template being called:

  {% for student in students %}

{{ student }}

  {% endfor %}

This blows up the page with the error Object of type Drupal\node\Entity\Node cannot be printed, which is no surprise, I'm just not sure what/how to send a proper object to twig.

Of course as soon as I posted this I figured an answer. This looks a little ugly, but I guess this is the way to go:

public function content() {
  $nodes = $this->getStudents();

  foreach ($nodes as $node) {
    $student = \Drupal::entityTypeManager()
      ->getViewBuilder('node')
      ->view($node);
    $students[] = render($student);
  }

  return [
    '#theme' => 'dashboard',
    '#students' => $students,
  ];
}

Basically, I'm looping through the list of nodes, getting the view builder on each, then calling the render function and adding it to a new array. I had stumbled on this earlier because I was using viewMultiple, which output another array...

If you have a cleaner implementation with viewMultiple let me know.


Multiple contextual filters using or statements I have a taxonomy which defines the sections of a site. One of the terms is "Global". What I am doing is creating pages with the site section term and also creating promo boxes which use the same taxonomy. By default the "Global" term is selected wherever the term relation is used.

I would like to have a block view using contextual filters. I have set it up to use one filter which is the term id from the url. This works great but when I have a page that has a specific section but does not have any related promo boxes I would like to load the "Global" set of promo boxes.

Is there a way to create multiple contextual filters using or statements? The default sets them up as and statements which will not allow me to load the "Global" plus the related to the page. I am sorting the view by taxonomy weight and have "Global" at the bottom so if I can get an or contextual filter I'll be in business.

Does anyone know of a module to do this or will I have to hook the view using hook_views_query_alter

In case anyone wants to know, I was able to accomplish this with some views hooks and will share my solution.

First you need to register view api information

/**
 * Implements hook_views_api().
 */
function mymodule_views_api() {
  return array(
    'api' => 3,
  );
}

Then you need to alter the view at pre build to include the "Global" term. I am using entity query to determine if there is any content with the Global term. If so I am adding that term as an argument.

/**
 * Implements hook_views_pre_build().
 */
function mymodule_views_pre_build(&$view) {
  // we were getting no results if the tid of the Global term was not 1
  // in some build instances it is not so we need to ensure that the default
  // value being passed is the actual tid of the Global term.
  if (($view->name == 'badge' || $view->name == 'promo_box' || $view->name == 'article'|| $view->name == 'tips') && $view->current_display == 'block') {
    $vocabulary = taxonomy_vocabulary_machine_name_load('site_section');

    $entityQuery = new EntityFieldQuery;
    $entityQuery->entityCondition('entity_type', 'taxonomy_term')
      ->propertyCondition('name', 'Global')
      ->propertyCondition('vid', $vocabulary->vid)
      ->range(0 ,1);

    $result = $entityQuery->execute();

    if ($result) {
      $term = array_slice($result['taxonomy_term'], 0);
      $view->argument['tid_1']->options['default_argument_options']['argument'] = $term[0]->tid;
    }
  }
}

And finally you need to switch the where statement to and or

/**
 * Implements hook_views_query_alter().
 */
function mymodule_views_query_alter(&$view, &$query) {
  //  Let's find out if we are attempting to load either the badge or promo box
  //  view. If so we need to alter the where clause to include an or statement
  //  in the conditional filter to also look for the global term in the site secttion
  //  taxonomy. I was not able to find a way to create an OR condition filter via a
  //  module so for now this is the best to do it.
  if (($view->name == 'badge' || $view->name == 'promo_box' || $view->name == 'article'|| $view->name == 'tips') && $view->current_display == 'block') {
    if (isset($query->where[0]) && isset($query->where[1])) {
      $query->where[0]['type'] = 'OR';
    }
  }
}


Why doesn't composer install drush on $HOME/bin directory? I'm trying to learn to to use drush.

I installed composer to my $HOME/bin/directory:

$ ls ~/bin
composer  composer.phar  subl  sublime  sublime_config.sh  sublime_text

Then I tried to install drush globally:

$ composer global require drush/drush:dev-master
Changed current directory to /home/nnieto/.composer
./composer.json has been updated
Loading composer repositories with package information
Updating dependencies (including require-dev)
  - Installing pear/console_table (1.1.5)
    Downloading: 100%

  - Installing symfony/yaml (v2.2.1)
    Downloading: 100%

  - Installing d11wtq/boris (v1.0.8)
    Downloading: 100%

  - Installing drush/drush (dev-master 31fa220)
    Cloning 31fa220c9ee33a250d135ad0d65b5b6c92c6c188

pear/console_table suggests installing pear/Console_Color (>=0.0.4)
drush/drush suggests installing youngj/httpserver (dev-master#41dd2b7 as 1.0.1)
Writing lock file
Generating autoload files

I expected to find a drush file on ~/bin, but instead I got a nope from Linux:

[nnieto@localhost ~]$ ls ~/bin
composer  composer.phar

What am I doing wrong?

Composer downloads things and puts them where you (read: your composer/project settings) tells them to go; or in the default location if you haven't specified. It won't assume you want to link anything from the downloaded library into /usr/bin, though this could theoretically be done through a post-install-cmd in your composer.json file.

If you install something globally you'll find it in ~/.composer/vendor/ (the Drush executable will probably be in ~/.composer/vendor/bin/drush).

You've probably missed this important step from the instructions to install Drush via Composer:

  Make sure Composer's global bin directory is on the system PATH

Once Composer's global bin path is in your system path, the drush command will start working immediately.


Is it safe to change INT to BIGINT or DECIMAL in database? I need to change a field from INT to BIGINT or DECIMAL. I tested changing it directly in the database on field_data and field_revision tables and apparently all is working fine, but I have my doubts and I don't want to do that on production until I'm entirely sure it's safe. It's enough to change the data type on database or I have to do something else like the solutions listed in the links below? If it's not safe to just change it in database, I'd like to know why.

change field from int to big int in drupal
How to change a field type from Integer to Decimal?
field is Integer and I am getting PDOException error thrown

Usually, when you make a change of this type it is recommended to make it in a development environment, so you can make some test to check your site is working correctly.

In the case you decide to make it in a production environment, be sure you make a backup of your database, in order to restore your system in case of problems.


PostgreSQL unbuffered query I am producing large query results that can exceed a sizable PHP memory limit (128 Mb). I've been trying to address this and came across unbuffered queries. Unfortunately, these only seem to be supported by MYSQL while I'm using PostgreSQL. There does seem to be a similar process for PostgreSQL involving cursors, but I'm unsure how to implement them within the Drupal framework using db_query(). Demo implementation with plain PHP can be found here.

My alternative solution would be to call a query multiple times with restrictions to LIMIT and OFFSET. Query performance is reasonably good, so this may be a viable solution as well. With this method I have yet to figure out how to divide queries into chunks by memory size. Instead, I would have to use a fixed row range. This could be a problematic approach given rows can significantly differ in size.

There are certain cases where db_query may not be able to do certain things, and this very well could be one of those cases.

That said, nothing is stopping you from leveraging PDO just like that blog post you linked to.

Here is an example from a project of mine in 2015 in Drupal 7 that performs a function using PDO:

/**
 * This takes the provided uploaded file and imports it directly into a temporary table in the database.
 * Drupal has some issues executing the statement, so the PDO class is leveraged with some different options to allow it without error.
 *
 * @param $table_name
 * @param $uri
 */
function populate_mysql_table_with_infile($table_name, $uri) {
  $database = Database::getConnectionInfo()['default'];

  $data_source = 'mysql:host=' . $database['host'] . ';dbname=' . $database['database'];
  $db_user = $database['username'];
  $db_password = $database['password'];

  $connection = new PDO($data_source, $db_user, $db_password,
    array(
      PDO::ATTR_EMULATE_PREPARES => TRUE,
      PDO::MYSQL_ATTR_USE_BUFFERED_QUERY => TRUE,
      PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
      PDO::ATTR_PERSISTENT
    )
  );

  $statement = $connection->prepare("LOAD DATA LOCAL INFILE '" . drupal_realpath($uri) . "' INTO TABLE " . $table_name . "
    FIELDS TERMINATED BY ','
    LINES TERMINATED BY '\r\n'
    IGNORE 1 LINES");
  $statement->execute();
  $statement->closeCursor();
}


How to replace I18nVariableLanguageRealm controller? I have done custom module with .class.inc and .module file. Class file is added in module info file.

Inside class file:

/**
 * Controller for Language realms.
 */
class MyModuleI18nVariableLanguageRealm extends I18nVariableLanguageRealm {
  public function getKey() {
    return isset($this->current_key) ? $this->current_key : FALSE;
  }
}

Inside module file:

/**
 * Implements hook_variable_realm_info
 */
function mymodule_i18n_variable_variable_realm_info() {
  $realm['language'] = array(
    'title' => t('Language'),
    'weight' => 1,
    'controller class' => 'MyModuleI18nVariableLanguageRealm',
    'store class' => 'VariableStoreRealmStore',
    // Variables for this realm can be selected from a list.
    'select' => TRUE,
    'select path' => 'admin/config/regional/i18n/variable',
    // Name for variables that belong to this realm: 'multilingual' variable/s
    'variable name' => t('multilingual'),
    'variable class' => 'i18n-variable',
    // Automatically handle these variables in system settings forms.
    'form settings' => TRUE,
    'form switcher' => TRUE,
  );
  return $realm;
}

but debugging shows that custom controller isn't in use. What am I doing wrong here?

In the Drupal world 'replace' in your context is usually synonymous with 'alter'.

Try this:

function mymodule_i18n_variable_variable_realm_info_alter(&$realm) {
  $realm['language']['controller class'] = 'MyModuleI18nVariableLanguageRealm';
}


How to use $language array in region--header.tpl.php I am using Language Switcher Dropdown module for language selection.

Successfully implemented this module and also get $language array properly in page.tpl.php file based on language selection.

But I am not able to get $language array in region--header.tpl.php file.

So how can I use this array in region files ?

$language; is a global variable in drupal 7. You can get this variable in region--header.tpl.php as shown below:

global $language;


Exclude certain taxonomies from url reachbility I have the following structure example.com/taxonomy/term/334 and there are several terms that I don't want to be reachable by domain.

I use the autopath module, so for example it could be I want example.com/status/green and example.com/status/red so to say every example.com/status/* to be reachable, but example.com/media/blu-ray and example.com/media/dvd or example.com/media/* not.

Any ideas how this can get realized?

Use hook_menu_alter to change the access control for taxonomy/term/%


Is it bad to add js and css in template_preprocess for a custom block? If I load my page where my block is displayed as user 2 (any user besides user 1) my block displays correctly.  If I reload the page my block doesn't display correctly and my js and css that was added via template_preprocess() doesn't show up.

I verified that if I turn off Block caching the problem goes away so it tells me that I shouldn't be adding js and css in the template_preprocess functions and add it via '#attach' but I have a function (video_widget_add_js) that I am adding javascript because I am adding it in multiple places and want to reuse the code.  Anyone have a good suggestion on this?

  <?php

  /**
   * Implements hook_block_view().
   */
  function leadership_block_view($delta = '') {
    $block = array();

    switch($delta) {
      case 'leadership_all_companies':
        $node = menu_get_object();

        $data_card_content = leadership_get_data_card_content($node);

        if (!$data_card_content) {
          $block = array(
            'subject' => '<img class="ld-block-logo" src="' . variable_get('leadership_block_logo') . '" alt="Leadership Logo" />',
            'content' => theme('leadership_allcompanies', array(
                'taxonomies' => leadership_get_taxonomies(FALSE),
                'delta' => $delta,
              )
            ),
          );
        }
        break;

    }

  }

  /**
   * Implements hook_theme().
   */
  function leadership_theme() {
    return array(
      'leadership_allcompanies' =>  array(
        'variables' => array('taxonomies' => NULL, 'delta' => NULL, 'has_data_card' => NULL),
        'template' => 'leadership-allcompanies',
      ),
    );
  }

  /**
   * Preprocess for the all companies block.
   *
   * @param array $vars
   *   An associative array containing:
   *   - taxonomies array
   *     An array that contains taxonomy objects @see taxonomy_get_tree().
   *   - delta string
   *     The block string key.
   *   - has_data_card
   *     This will only be used in the all_companies_and_data_card block. If set
   *     to FALSE then only all data that would appear in the all companies block
   *     will appear. If set to TRUE both will appear.
   */
  function template_preprocess_leadership_allcompanies(&$vars) {
    // Add js and css files.

    $js_extension = (variable_get('smg_global_is_production', false)) ? '.min.js' : '.js';

    $path = drupal_get_path('module', 'leadership');
    $video_widget_path = drupal_get_path('module', 'video_widget');
    drupal_add_css($path . '/css/all_companies_block.css');
    drupal_add_css($path . '/css/datacard.css');
    drupal_add_css($path . '/css/datacard_' . variable_get('smg_global_site') . '.css');
    drupal_add_css($video_widget_path . '/video_widget_includes/css/video_widget.css');
    drupal_add_js($video_widget_path . "/video_widget_includes/angular/app{$js_extension}");
    //drupal_add_js('sites/all/libraries/angularjs/bower_components/angular-animate/angular-animate.min.js');
    drupal_add_js($path . "/angular/js/all_companies_block{$js_extension}", array('every_page' => TRUE, 'preprocess' => TRUE));
    drupal_add_js($path . "/angular/js/datacard{$js_extension}");

    $vars['site_id'] = variable_get('smg_global_site');

    $taxonomies = $vars['taxonomies'];
    if ($taxonomies) {
      if (variable_get('smg_global_site') == 'pw') {
        // Add the parent tids,titles (Ex: Machinery, Materials, Service)
        foreach ($taxonomies as $taxonomy) {
          $categories[$taxonomy->parents[0]]['tids'][] = $taxonomy;
        }
        foreach ($categories as $tid => $category) {
          $categories[$tid]['tid'] = $tid;
          $categories[$tid]['title'] = taxonomy_term_load($tid)->name;
        }
        $vars['taxonomies'] = $categories;
      }

      // Add taxonomy list to Drupal object to be used by Angular.
      drupal_add_js(array('leadership_all_companies_block' => $taxonomies), 'setting');

      // Call the video widget registering function
      video_widget_add_js();
    }
  }

Generally, yes, you should use ['#attached'] in renderable arrays to add assets in a cache-compatible way. $block['content'] can be a renderable array if you make it an array instead of a string, so you're not too far off here. I'm not sure exactly what you're doing inside video_widget_add_js(), but if it's just adding a bunch of assets, then consider implementing hook_library() instead. Library implementations are attachable in ['#attached'].

In your case, however, the attached assets aren't your only problem. With block caching enabled, a cache hit bypasses hook_block_view() completely, instead retrieving the previously compiled $block array from cache. Since you use $node = menu_get_object() in hook_block_view(), you probably need the block to vary by page. However, the default block cache setting is DRUPAL_CACHE_PER_ROLE, which only varies by a user's role combinations.

You could set your block to cache with DRUPAL_CACHE_PER_PAGE instead, but the easiest thing to do without refactoring a bunch of your code is to set your block to DRUPAL_NO_CACHE.  DRUPAL_CACHE_PER_PAGE isn't hugely efficient anyway unless you have a lot of authenticated user traffic.

To set a particular cache setting on a block, edit the hook_block_info() implementation:

/**
 * Implements hook_block_info().
 */
function leadership_block_info() {
  return array(
    'leadership_all_companies' => array(
      'info' => t('Leadership block'),
      'cache' => DRUPAL_NO_CACHE,
    );
  );
}


Views: Multiple Contextual Filters (Taxonomy) My view should be filtered by multiple taxonomy terms, e.q. : show me all "events" that are tagged by the terms "show", "age over 40" and "outside".

While I can filter by one taxonomy term just fine, it is not working with multiple terms.
View Settings:

Relationship: Taxonomy terms on node

Contextual Filters: (term) Taxonomie-Term: Name
Allow multiple values is checked!

What am I doing wrong?

I need to filter by the name, not the ID.

I spent lot of time to figure this out, but finally found a solution:

Instead of Content: The name of Taxonomy (taxonomy_vocabulary_#) you need to select Content: Has taxonomy term ID Contextual filter and enable Allow multiple values to able to use multiple values in the form of 1+2+3 (for OR) or 1,2,3 (for AND).


How to change page title for admin users to easly find which admin page they are During development I need to work with modules, views, site configurations, nodes etc.. I open all of them in new tabs (browser). It would be much convenient to switch between tabs to choose desired page if page title (html title that displays in the browser) has name of the admin navigation link/name. I have set 'Seven' as admin theme. Is there any configuration available to enable this or I need to tweek code?

You can use shortcut bar,

  The Shortcut module provides a toolbar on the top of the page to which
  you can add links. This toolbar is site-wide, so any links added will
  be visible to all users who have permissions to see the Shortcut
  toolbar. This is useful for creating links to commonly-used pages
  within your site. You can organize these links in multiple sets of
  shortcuts.

Click on the + sign as shown below in any page you want to bookmark

You will see links next to Add Content , Find Content like below

Explained in link given above...


What is a "fluid" column in Display Suite? What is "fluid" in Display Suite?  I want to create a two-column layout, with a 25% left and 75% right.  Is the fluid 2-column layout what I want?

In Display Suite, the "fluid" refers to the templates ability to expand the column width if one (or more) columns are empty.

For a 2 column layout, the CSS is:

.ds-2col > .group-left {
  float: left; /* LTR */
  width: 50%;
}

.ds-2col > .group-right {
  float: left; /* LTR */
  width: 50%;
}

So even if there is no content in .group-right, the .group-left element will still take up only 50% of the available width.

For the fluid 2col layout, the CSS is:

.ds-2col-fluid > .group-left {
  float: left; /* LTR */
  width: 50%;
}

.ds-2col-fluid > .group-right {
  float: right; /* LTR */
  width: 50%;
}

.ds-2col-fluid.group-one-column > .group-left,
.ds-2col-fluid.group-one-column > .group-right {
  width: 100%;
  float: none;
}

The last ruleset (the one with '.group-one-column') means that if either of the columns contains no content then the other column will expand to 100% of the available width. You can see the little piece of PHP logic that adds the extra CSS class to the template here: http://drupalcode.org/project/ds.git/blob/refs/heads/7.x-2.x:/layouts/ds_2col_fluid/ds-2col-fluid.tpl.php

For your case, either is fine, but to get the 25% / 75% split, you'll need to override the DS CSS code in your own theme's stylesheet.

You could use something like

body .ds-2col .group-left {
    width: 25%;
}
body .ds-2col .group-right {
    width: 75%;
}


How to get the block by string ID I have a block, and want to print it in the template. I use the following code:

 $block =  module_invoke('block', 'block_view', '6');
 print render($block["content"]);

It works, but in module_invoke() I use the ID of the block in the database, which is very bad. Is it possible to assign the string ID to the block and use it instead?

If it's impossible, how can I use strings instead of numbers?

There's no built-in function for loading a block by string, but you can use a simple SQL query to get the ID of the block using a string.

$block_name = "Your block name";

$block_id = db_query("SELECT bid FROM {block_custom} WHERE info=:info", array(":info"=>$block_name))->fetchField();

$block =  module_invoke('block', 'block_view', $block_id);
print render($block["content"]);


Upgrade Commerce Kickstart 1 site with drush From http://www.drupalcommerce.org/blog/9072/updating-commerce-kickstart-2 I learned that it's possible to upgrade a CK2 site using drush.

Is it possible to do a minor upgrade od CK1 using drush dl --select commerce_kickstart and selecting the proper version? I tried and failed.

According to this page http://www.drupalcommerce.org/commerce-kickstart-2/install you should use Drush 8.x-6.x for an upgrade.


Custom checkout pane for order comments not saving I've created a custom checkout pane for commerce 2.x, Drupal version 8.7.x. I've added a textfield called field_order_notes on the order entity. The pane works, and I can run
$this->order->set('field_order_notes', $values) in my pane's submit handler, and I can debug the order object and see the value's set. But when i finish the order,  field_order_notes is empty on the order. Not sure what I'm missing here.

 /**
 * Adds a section for order notes.
 *
 * @CommerceCheckoutPane(
 *   id = "order_notes",
 *   label = @Translation("Order notes"),
 *   default_step = "order_information",
 * )
 */
class OrderNotes extends CheckoutPaneBase implements CheckoutPaneInterface {
  /**
   * The inline form manager.
   *
   * @var \Drupal\commerce\InlineFormManager
   */
  protected $inlineFormManager;
  /**
   * {@inheritdoc}
   */
  public function __construct(array $configuration, $plugin_id, $plugin_definition, CheckoutFlowInterface $checkout_flow, EntityTypeManagerInterface $entity_type_manager) {
    parent::__construct($configuration, $plugin_id, $plugin_definition, $checkout_flow, $entity_type_manager);
  }
  /**
   * {@inheritdoc}
   */
  public function buildPaneForm(array $pane_form, FormStateInterface $form_state, array &$complete_form) {
    $pane_form['order_notes'] = [
      '#type' => 'textarea',
      '#title' => $this->t('Order notes'),
      '#default_value' => $this->order->get('field_order_notes')->getString(),
      '#required' => FALSE,
    ];
    return $pane_form;
  }
  /**
   * {@inheritdoc}
   */
  public function submitPaneForm(array &$pane_form, FormStateInterface $form_state, array &$complete_form) {
    $values = $form_state->getValue($pane_form['#parents']);
    $this->order->set('field_order_notes', $values);
  }
}

This was fixed by passing ['order_notes'] into $values.

 /**
   * {@inheritdoc}
   */
  public function submitPaneForm(array &$pane_form, FormStateInterface $form_state, array &$complete_form) {
    $values = $form_state->getValue($pane_form['#parents']);
    $this->order->set('field_order_notes', $values['order_notes']);
  }