Best way to set up attributes/variations This is probably an embarrassingly basic question, but I haven't been able to find a definitive answer after a fair bit of searching.
If you're setting up a store with Drupal Commerce (2.x, in Drupal 8), and each of your products come in a variety of colours, but the range of colours is different for each product - should Colour be a single attribute, added to a single product variation type, and then assigned to a single product type (assuming no other significant variations in product structure)?
Or should each specific set of colours be a different attribute and/or a different product variation type, which I suppose would mean each individual product would need a unique product type?
To clarify, we're talking several dozen products, each of which might come in anywhere from 10-30 unique colours that are only used for that one product, so the total possible number of colours would be well into the hundreds, if that makes a difference.
I'd like to set this up in the most efficient and user-friendly way possible, since the staff who will be maintaining the site and adding items in the future may not be very technical... So the less configuration they have to do for new products, the better. But on the other hand, having hundreds or thousands of colours showing up in a single dropdown when they're trying to create product variations might be overwhelming.

I'll preface this by saying that every situation is different so it's hard to say what the "best" option is. This tutorial seems to go the route of having different product variation types, with a specific color attribute created per variation type. Having a separate variation type for every item feels a bit awkward, but it might make sense in your scenario.
Two other solutions that I can think of are:
1. Multiple Attributes (only):
You could do this without creating unique product types for every product, or even multiple product variation types. You could have 5, 10, 2000, however many different color attributes, all of which are made available to your single product variation type.
The main drawback that I foresee with having separate attributes for each color set is that, after the fact, any grouping/reporting that needs to be done on colors may need to accommodate all of these disparate attributes in a single place. One way to help mitigate this might be to create an "attribute categories" (or similar) taxonomy vocabulary to group related attributes together, and tag that on a taxonomy ref field on each attribute. If you anticipate this only ever being an issue for "colors" then you could probably also get away with adding a boolean field to do something similar.
That said, having the color sets as separate attributes might be preferred for reporting as well. Hard to say.
2. One Attribute
Another option is to have a single Color attribute containing every single color, but add a Product Entity Reference field onto it. In this case, every color would inherently be treated the same, but you could relate them directly to their associated Products. This avoids the issue of needing to relate the different attributes after the fact. This would give you the option to do a form_alter on the product_variation creation form to limit the options on the color attribute field to those which reference the Product that you're creating a variation of.
This option could end up with a pretty big list of options when editing the attribute, though, so it might be worth populating it with a bunch of dummy data to see how it fares. Devel_generate (included with Devel module) might be helpful, here.
EDIT: I should note that I initially failed to say that option 2 was my preferred option, for the same reason that Ryan notes in his answer. That is to say, all colors are colors and should be present on the same attribute. If Select2 is viable for attributes fields then that's probably the simplest way to make the list more manageable when authoring new product variations.
Alternatively, as mentioned in 2, using a reference field on each color to its related products (or alternatively a reference field on the product to its given colors) would maintain the "correct" single attribute while also allowing you to limit the options to those appropriate for the current product. IMO this probably leads to a less overwhelming interface in the event that the list of available colors is sufficiently large, and could also be paired with something like Select2 to further improve the authoring UI/UX.


How to display form module in two coloms? I again looking for your help.
I have a form module that should be displayed in two coloms, like this one:
http://www.quickbase.com/help/images/form_example.gif
I did a lot of researches for how to solve this and couldn't find so much.

do I need both functions hook_form_alter and hook_theme?

should they look like this?
function my_module_form_alter(&$form, &$form_data, $form_id){ if(stripos($form, 'my_module_form') === 0 && $form['#parameters'][2]->type =='product') {
        $form_data['#theme']  = 'mytemplate';
         }
}

function my_module_theme()
    {
          return array(
            'my_module_form' => array(
              'arguments' => array('form' => NULL),
              'template' => 'mytemplate',
            ),
          );
        }

What should contain file mytemplate.tpl.php ?

Here is part of my form:
function my_module_form($form_data) {
    $form['contact_information'] = array(
        '#value' => variable_get('contact_form_information', t('Please fill in all fields.'))
    );
    $form['first'] = array(
        '#type' => 'textfield',
        '#title' => t('First name'),
        '#maxlength' => 20,
        '#required' => TRUE,
    );
    $form['last'] = array(
        '#type' => 'textfield',
        '#title' => t('Last name'),
        '#maxlength' => 20,
        '#required' => TRUE,
    );
    $form['street'] = array(
        '#type' => 'textfield',
        '#title' => t('Street Address'),
        '#required' => TRUE,
    );
ect

Finally I solved it:
function my_module_theme($existing, $type, $theme, $path) {
  $hooks['my_module_form'] = array(
    'template' => 'mytemplate',
    'arguments' => array('form' => NULL),
  );
  return $hooks;
}

and here is mytemplate.tpl.php

        <?php print_r(drupal_render($form['contact_information'])); ?>

        <?php print_r(drupal_render($form['first'])); ?>

        <?php print_r(drupal_render($form['last'])); ?>

        <?php print_r(drupal_render($form['street'])); ?>

        <?php print_r(drupal_render($form['city'])); ?>

        <?php print_r(drupal_render($form['postal'])); ?>

        <?php print_r(drupal_render($form['state'])); ?>

        <?php print_r(drupal_render($form['mobile'])); ?>

        <?php print_r(drupal_render($form['ext'])); ?>

        <?php print_r(drupal_render($form['phone'])); ?>

        <?php print_r(drupal_render($form['home_phone'])); ?>

        <?php print_r(drupal_render($form['email'])); ?>

                <?php echo drupal_render($form['submit']),
                            drupal_render($form['clear']); ?>

You can use the markup-type in your form array to group form items and then style the groups.
The code below will wrap the three items with a div which has the class column-left. Do the same for the right column.

To clear things up: The column_left-item is of the type markup, which is the default type.

$form['column_left'] = array(
    '#prefix' => '
',
    '#suffix' => '
',
);
$form['column_left']['first'] = array(
    '#type' => 'textfield',
    '#title' => t('First name'),
    '#maxlength' => 20,
    '#required' => TRUE,
);
$form['column_left']['last'] = array(
    '#type' => 'textfield',
    '#title' => t('Last name'),
    '#maxlength' => 20,
    '#required' => TRUE,
);
$form['column_left']['street'] = array(
    '#type' => 'textfield',
    '#title' => t('Street Address'),
    '#required' => TRUE,
);

For Drupal 7, you can use the container-type and use the attributes array to add the class. A div is generated automatically.

$form['column_left'] = array(
  '#type' => 'container',
  '#attributes' => array(
    'class' => array('column-left'),
  ),
);


I can't turn off/pause automatic slideshow when there is only 1 picture (using lightbox2) I am using lightbox2 and it is a wonderful module. The only issue that I have is that I cannot seem to find a way to turn off the automatic diashow when there is only 1 picture.

When 5 pictures are added to a blogmessage there is a slideshow, 1 by 1 the pictures are shown. This can be paused in case someone wants to have a longer look at a picture.
When there is only 1 picture it is not possible to pause. It is possible but I have to configure a button, standard is Space button. But my users do not know this. How can achieve this without a keyboard key?

What I want:
I want to make sure that when there is only 1 picture it can also be paused. So you don't have to click on the thumbnail of the picture again to see it in deatil.

I hope that is somewhat clear.
Thanks in advance!

when there is only one picture then it won't go off untill click somewhere else on the screen ... for better understanding go to lightbox configurations...


What is wrong when Open atrium is installed with no colors and images? I have successfully installed Open Atrium. Upon opening the site first time in the browser, i literally see no images, layouts of colors. Here is the screenshot:

I also have a series of warning messages being displayed as shown below:

Anyone has a clue, what's wrong really?

This is certainly a permissions issue on your temp and possibly also files directory. Go to admin/config/media/file-system and make sure that the directory set as your temporary directory exists, is writeable to the webserver, and is specified from your server's root directory. Also make sure sites/default/files and/or sites/[yoursite]/files (if using a multisite) exists and is writeable to the webserver.


Custom fileds are not visible on user profile page I am fetching those value of this fields from database. But somehow, I couldn't be able to see it on user profile view page.

Can anyone help me to solve it out.

There are many things that may be causing this. If you are not using a custom template try going to the display options of the user's profile page
(admin/config/people/accounts/display) and set the fields to visible there.


Fixed time per questions in quiz modules I'm new to Drupal, and I'm developing a site in Drupal 6. It's an online exam related site. I want to add quiz questions that have their own time; each question will have its individual time, and the total time of the quiz will be the total sum of the single question's times.

Is this possible in Drupal 6 with one of the quiz modules?

Made a similar functionality for their tasks.

https://www.drupal.org/project/quiz/issues/2940636


Drupal file upload field via popup So I'm using a "file" type input inside a form which is called within a popup...but then whenever I submit that form inside the popup after having selected a file, the popup always return an error....

Is there a way to prevent this from happening and to successfully submit the form accordingly even with a file upload?

I made it by creating 'VIEWS' by selecting the facebook style micro publisher images as 'field' and filtered according to my requirement.


How to programmatically clear/refresh module file cache? I'm maintaining a module, and have reworked the file structure of the module to make it more... modular.

In the update functions, some of the new files are referenced, but Drupal isn't aware of the new files until the cache has been cleared. The files are included in the .info file.

Please can someone tell me how to get Drupal to refresh its list of the files in this module?

Thanks,

[Side note - quite surprised that hooks and cache aren't available as tags!]

Add a MYMODULE.install file to your module. In there implement hook_update_N to flush all caches. When others update your module, and then do database updates, Drupal will pick up this hook and flushes the cache and your new files will be recognized.

/**
 * Pick up new files.
 */
function MYMODULE_update_7100(&$sandbox) {
  drupal_flush_all_caches();
}


How to get paragraph field values? I'd like to create a product list in drupal and send it in a webservice.
For this I created an entity type with paragraphs for each product.
How can I load the paragraph and access its fields? Until now I see only the target_id and target_revision_id of the product. Thanks!

$nodestorage = \Drupal::entityManager()->getStorage('node');
$productslist = $nodestorage->loadUnchanged(9)->toArray();
foreach($productslist['field_products'] as $prod) {
  debug($prod);
}

Result:

Array
(
  [target_id] => 1
  [target_revision_id] => 3
)

You should be able to include the Paragraph entity class, and use Paragraph::load($entity_id) to load it.

Example:

use Drupal\paragraphs\Entity\Paragraph;

$paragraph = Paragraph::load($target_id);
$foo = $paragraph->field_name->value;


What is the need to have the Unicode class? Why is it necessary to have the Unicode class?

What does Unicode::strtoupper() or Unicode::strtolower() do that cannot be done just using native the PHP functions strtoupper() or strtolower()?

The reasons to have its own replacement of strtoupper and strtolower() is to support multi-bytes string in those sites where the Multibyte String extension is installed, and in those sites where that extension is not installed.

strtoupper() and strtolower() don't support multi-byte strings. Even in the case Drupal would not try to use the Multibyte String extension when installed, Unicode::strtoupper() and Unicode::strtolower() would not be reduced to simply calls to strtoupper() and strtolower(). Their code would probably be the following one.

public static function strtoupper($text) {
  // Use C-locale for ASCII-only uppercase.
  $text = strtoupper($text);
  // Case flip Latin-1 accented letters.
  $text = preg_replace_callback('/\xC3[\xA0-\xB6\xB8-\xBE]/', '\Drupal\Component\Utility\Unicode::caseFlip', $text);
  return $text;
}

public static function strtolower($text) {
  // Use C-locale for ASCII-only lowercase.
  $text = strtolower($text);
  // Case flip Latin-1 accented letters.
  $text = preg_replace_callback('/\xC3[\x80-\x96\x98-\x9E]/', '\Drupal\Component\Utility\Unicode::caseFlip', $text);
  return $text;
}

If Drupal required the Multibyte String extension to be present, then Unicode::strtoupper() and Unicode::strtolower() would not be necessary, since Drupal would use directly mb_strtoupper() and mb_strtolower().

That is not different from what happened in previous versions, except they implemented drupal_strtouppper() and drupal_strtolower(). If you look at the code, it is not much different.

function drupal_strtoupper($text) {
  global $multibyte;
  if ($multibyte == UNICODE_MULTIBYTE) {
    return mb_strtoupper($text);
  }
  else {
    // Use C-locale for ASCII-only uppercase
    $text = strtoupper($text);
    // Case flip Latin-1 accented letters
    $text = preg_replace_callback('/\xC3[\xA0-\xB6\xB8-\xBE]/', '_unicode_caseflip', $text);
    return $text;
  }
}

public static function strtoupper($text) {
  if (static::getStatus() == static::STATUS_MULTIBYTE) {
    return mb_strtoupper($text);
  }
  else {
    // Use C-locale for ASCII-only uppercase.
    $text = strtoupper($text);
    // Case flip Latin-1 accented letters.
    $text = preg_replace_callback('/\xC3[\xA0-\xB6\xB8-\xBE]/', '\Drupal\Component\Utility\Unicode::caseFlip', $text);
    return $text;
  }
}


Moving Host - concern about PHP memory limit I'm moving my projects from Bluehost to GreenGeeks, and I'm concerned about the Drupal (v7) PHP memory limits.  Maybe I'm overly concerned, but has anyone experienced any issues with GG or BH about running Drupal for clients' commercial projects requiring more than average PHP memory levels above 64meg to a max 128meg memory requirement. Any comments welcome.

A 128M memory limit is often not "more than average" for a Drupal project.
Also, just because you've specified 128M as the memory limit, that doesn't mean your webhost is giving you that much (or even half as much).

Let me explain.
I'll use Commerce Kickstart v2 with the demo store installed as an example (matching a medium-sized Commerce store).
It has 10 content types, 6 product types.
146 modules installed, out of that 23 provided by Drupal core, and 123 contrib.

Installing Commerce Kickstart requires 77M of RAM (xhprof peak memory usage).
A Kickstart page (frontpage, the view that lists products in a category, faceted search page) takes about 17M (as reported by devel).
This number can spike easily on admin pages that show many items, or thanks to a misbehaving module.

Our minimum memory limit requirement for Kickstart is 128M, based on our personal experience developing Drupal sites (it's easy to get "memory limit exceeded" with less than that).
Also, if the server doesn't have enough memory when generating the request, it won't give you how much you asked for. I saw it with my own eyes (MacBook Pro, Chrome with a million tabs, only a bit of RAM left. PHP fails to allocate 77M of ram despite the memory limit being 128M).
I also saw this complaint from people with shared hosting (I strongly believe that running anything more than a blog on shared hosting is pure masochism without excuse in the age of cheap VPS).

Why does Drupal need so much memory? Among other things, because it has a cache problem (which of course saves your database)
Drupal currently likes to cache ALL views in one place, ALL fields in one place, etc. So once you get a site with many content types, fields, views, the caches become huge, and they are all loaded into your memory with each request.
Thankfully, this is being fixed as we speak, thanks to people like catch (See this article for details).

The fix to Views got committed a few days ago and is now available in 7.x-3.x-dev. Quoting #29 from that thread, where the memory usage for Views dropped from 34M to 17M:

  So, for normal use, there's a 15% improvement in execution time, and 49% improvement in memory usage.

There is also a RTBC fix for fields in Drupal core that should make it into the next Drupal 7 release. Benchmarks showed savings between 1M and 50M (depending on your number of fields).

There's an in-progress fix for the system (module & theme) list in Drupal core that should shave a megabyte or two as well.

So, install Devel, go to admin/config/development/devel, enable "Display memory usage", and find out how much your pages need.
Also follow the fixes I mentioned, test them and see how much they help you (they give me a few megabytes of savings on the Kickstart install, which still counts).

And of course, find a decent hosting (I don't know if GreenGeeks is decent, don't have much experience in that field), set a decent memory limit, and don't worry too much :)


Attach behavior only to the file upload button I have a form with a managed_file field where I need to know when the upload button is clicked, and then perform an action. I decide to make it by attaching a behavior to my button but it also trigger when I click on the remove button. Here is my code:

Drupal.behaviors.mattButtons = {
    attach: function (context) {
    jQuery('input.form-submit', context).bind('mousedown', Drupal.matt.checkFile );
    }
};

Drupal.matt = Drupal.matt || {
    checkFile : function(){
        console.log("Hello");
        var url = jQuery('.file a').attr('href');
        console.log(url);
    }
};

Is there any way to only attch my behvior on the file upload button?

You can simply be more specific with your jQuery selector. For example, you could theme_file_managed_file to give your upload button it's own class and then change your jQuery('input.form-submit', context) line to include that class in the selector.

jQuery('input.my-upload-class', context)


How do I set the cookie lifetime? I'm having trouble setting the cookie lifetime in my D8 instance.  I'd like to set it to zero so that closing the browser logs-off the user.

I've added ini_set('session.cookie_lifetime', 0); to the site/default/settings.php file.  There was no previous cookie_lifetime reference in the file.  I added the line.  I've also cleared the Drupal cache and cleared my Chrome cache.  Sadly, it's not being respected.  Sessions still persist after browser close.

I've searched the entire codebase for ini_set('session.cookie_lifetime', 200000); but it doesn't appear to exist in my site. I don't see where Drupal is setting the cookie lifetime.  I've also tried adding the setting via a php.ini file in the root but that's being over-ruled by Drupal.

I feel like this is a simple thing, so I'd like to avoid plugins. Looking forward to hearing from everyone.  Thanks in advance.

For the session cookie options D8 uses container parameters instead of settings. Create a services.yml file in the same folder as settings.php. The default values are in default.services.yml. You can copy this file to services.yml and modify it:

/sites/default/services.yml:

parameters:
  session.storage.options:
    # Default ini options for sessions.
    #
    # Some distributions of Linux (most notably Debian) ship their PHP
    # installations with garbage collection (gc) disabled. Since Drupal depends
    # on PHP's garbage collection for clearing sessions, ensure that garbage
    # collection occurs by using the most common settings.
    # @default 1
    gc_probability: 1
    # @default 100
    gc_divisor: 100
    #
    # Set session lifetime (in seconds), i.e. the time from the user's last
    # visit to the active session may be deleted by the session garbage
    # collector. When a session is deleted, authenticated users are logged out,
    # and the contents of the user's $_SESSION variable is discarded.
    # @default 200000
    gc_maxlifetime: 200000
    #
    # Set session cookie lifetime (in seconds), i.e. the time from the session
    # is created to the cookie expires, i.e. when the browser is expected to
    # discard the cookie. The value 0 means "until the browser is closed".
    # @default 2000000
    cookie_lifetime: 2000000


Send content in mail + Rules When a user registers an account I would like to create an invoice (this is a content type) and send it as a pdf to the user. But I have no clue how I can send the invoice to the user... .

I know you can send a mail, but how to include the invoice I have no idea.

I've searched on the internet but no luck ... .

I just had to implement this on a site in a similar fashion. You can use MIME Mail and it's submodule MIME Mail Attachments along with the Print and the Rules Download module. It will allow you to create a rule and email (with attachment.


Modify token used in path URL alias generation We would like to have the URL pattern for Article content type to use article/[node:field_short_description]. In the scenario where field_short_description is not populated, we would like for the URL pattern to be article/[node:title] as a fallback.

Questions

Is it possible to use the field_short_description field if populated, else use the title field without custom code?
How would we do this without custom code?

We tried to use article/[node:field_short_description]|[node:title] but when both fields are populated, then both are added to the URL.

We found the solution using the sample found on How To Create A Custom Token In Drupal 8?

Code

/**
 * Implements hook_token_info().
 */
function my_module_token_token_info() {
  $info = [];
  $info['types']['my_token_group'] = ['name' => t('Custom Group'), 'description' => t('Custom Group')];
  $info['tokens']['my_token_group’][‘my_token’][] = 'A token to extract desired characters from Node body to be used in meta descriptions';
  return $info;
}

/**
 * Implements hook_tokens().
 */
function  my_module_token_tokens($type, $tokens, array $data, array $options, \Drupal\Core\Render\BubbleableMetadata $bubbleable_metadata) {
  $replacements = [];
  if ($type == 'my_token_group') {

    foreach ($tokens as $name => $original) {
      // Find the desired token by name.
      switch ($name) {
        case ‘my_token’:
          $node = $data['node'];
          if(is_object($node) && !$node->myFieldName->isEmpty()) {
            $token_value = $node->myFieldName->value; // or something similar.
          }
          else {
            $token_value = $node->label();
          }
          $replacements[$original] = $token_value;
          break;
      }
    }
  }
  return $replacements;
}


How can I sort taxonomy term using attachment in drupal view I would like to sort taxonomy term using attachment in view like this (A B C ...). When I created sort for Taxonomy term using contextual filter, the Alphabetical(radio button) was disabled under "When the filter value is NOT available" section for taxonomy term. This radio button already enabled for content: title but it was disabled for taxonomy term.

If u are creating view of taxonomy term, then it gives you option for sorting taxonomy term using name, However if u are using content type view and u want to show attachment, then add Global:View in attachment fields, and choose a view of taxonomy, with passing contextual filters in it.


Anonymous User gets cookie I recently saw that when I open of my sites as a anonymous user, a session cookie is set. I checked the database sessions table, and there is a line for uid 0 as well.
How can I prevent drupal from setting this cookie?

Greetings SG

This is what the cookie looks like in the session table:

Sry that the image is so tiny ...

Drupal7 unlike drupal6 does not use sessions for anon users. This is an improvement for performance reasons. If you see that there are sessions created it means that there is a contrib module that creates them, so it may be a bad idea disabling them. You can inspect the contents of the session to get an idea which module is using it.

If this is d6 site, you may check the pressflow distribution.


Search indexing slow query Drupal 7.x

The search module's indexing maintenance sql query takes a couple of minutes to complete each time cron gets triggered.

SELECT t.word AS realword, i.word FROM search_total t LEFT JOIN search_index i ON t.word = i.word WHERE i.word IS NULL`

Database search info data info:

127k nodes

37m  search_index

1.3m search_total

Search settings:
100 Number of item to index per cron ron

Indexing settings:
2 Minimum word length to index

Search is only enabled for nodes and once indexed, searches are fairly fast. However the actual process of re-indexing takes it's toll in our database server. Do you guys have any suggestions on how to mitigate this problem caused by extremely large websites? How do large websites scale Drupal's built-in search functionality without using additional tools like solr, elatisticsearch, etc.? All indications I'm seeing is to probably throw more hardware at this problem.

Maybe you should use a Search API and Search API database module? It's more flexible in terms of working with index. For example, you can configure index settings(which fields to index)and rebuild index after it.
Try to use Google Custom Search module.


visibility of a view based on current node field I am displaying a block of related articles in node page using views. I want to hide a view on node page if certain entity field on this node is empty. My view has contextual filter with default value node nid (relationship to entity ref. field) and relationship to entity reference field. How is it possible to do?
My aim is to show block in sidebar or mail content based on what is in the field (n/a or sidebar for example). Or is there any better way to show that block on various positions of page?
I use context module so I would create views - one for sidebar and second for main page. One would be set to show only if field is empty and the second one opposite.
Thank you.

Just add another filter on the parent node relationship for that current field.  Not sure on what field is what for you but it seems you have all the relationships added into the view based on the parent node page?

Just add another filter, select the field you want to check, add the parent node relationship and make sure its NOT EMPTY.

If you just have the contextual filter as a nid, add a relationship to that nid so you can get access to the parents fields.


Module installation in D8.3.6 was possible, using D8.3.7 the same module couldn't be installed I have installed the "Serial field" module with the file serial-7.x-1.8.zip in D8.3.6
I have tried to install with the same zip file in  D8.3.7 and it is coming wih the error message "serial-7.x-1.8.zip does not contain any .info.yml files. "

I've found general info that  ..yml file is required in D8, but is this requirement raised in D8.3.7 first and in D8.3.6 still was possible w/o ..yml?

is this requirement raised in D8.3.7 first and in D8.3.6 still was possible w/o ..yml?

No, YAML has been the format for Drupal 8 info files right from early dev versions, way before even the 8.0 release.

  I have installed the "Serial field" module with the file serial-7.x-1.8.zip in D8.3.6

Unless the naming of the archive is an error, and despite being labelled as containing 7.x code, it actually contained 8.x code, I’m afraid you’re mistaken.


Multi-site for user groups I have to carry out a procedure for the management of information by a group of users. Later I could have the same need but for a group of different users. Since I haven't understood how the multisite works, I can't make up my mind.

The software will be the same, but for database copy, user management and security issues, I would prefer to have the database different for the group of users.

Can the multisite manage multiple databases with a single software?
Do I have to foresee it and create it from the beginning or can I create the software and subsequently, if there is a request, transforming it into a multisite?

Can the multisite manage multiple databases with a single software?

Yes.

  Do I have to foresee it and create it from the beginning or can I create the software and subsequently, if there is a request, transforming it into a multisite?

You can perfectly start with a single site, and late on transform it into a multisite.

As an alternative to using a multisite, you may also want to consider using the Group module. From the specs in your question, it appears to me that only using this module (without a multisite setup), it could well be sufficient ...


Drupal Media Library - File Upload Library shows “No files available.” I am actualy running in some sort of strange problem. I installed Media 7.x-2.x-alpha2. I can upload files without any problems. When I go to "admin/content/file" I see the uploaded files.

Now comes the problem, when I want to add a image via the library dialog, while creating a new node, the box shows me "No files available.".

I checked the media browser view and the very strange is, that the files shows up in there

I tried updating to newest dev release and checked the permissions, but anything looks just fine. I am working as user 1.

Any idea about that?

Answer from basti:

  The problem could be solved by removing the Query Tag under "Query settings" inside the view options. I have no idea why, but after removing it, anything works just fine.


How to load node object in node preview page? In drupal 8, how do you load the node object in hook_preprocess_page() when on the node preview page?

I had a bug come up where this standard way of loading the current node object was failing on the preview page:

$node = \Drupal::routeMatch()->getParameter('node');

If you need to use the node object in hook_preprocess_page() on the preview page, you need to use the "node_preview" parameter, instead of the "node" parameter:

function mymodule_preprocess_page(&$vars) {

  $route_name = \Drupal::routeMatch()->getRouteName();

  if ($route_name == 'entity.node.canonical') {
    $node = \Drupal::routeMatch()->getParameter('node');
  }
  elseif ($route_name == 'entity.node.preview') {
    $node = \Drupal::routeMatch()->getParameter('node_preview');
  }


Values from $node object in Views Contexual Filter I'd like to create a PHP contexual filter for a view.

This code isn't right, but I want something like this:

global $node;
if ($node->type=="ABC") {
return 5880;
}

if ($node->type=="XYZ") {
return 6200;
}

How do I access the $node object in a PHP contexual filter?

Also, is there a better way to debug/troubleshoot this? I feel like I'm operating in complete darkness.

You can access the $node object by doing this in the filter:

$node = menu_get_object()


How do I divide taxonomy term pages by content type? Drupal out of the box lists all of the content tagged with a term in a single list on a terms page. I would like to split up that list into sub pages based on content types tagged with that term. See mockup below. Seattle is the term page and the "Attractions, Museums, Restaurants and Shopping" are content types tagged with "Seattle". To achieve this, i cannot use quicktabs as it requires an admin to create a new quicktab collection everytime a new city is created. Also, panels is not an option on this project either. I am thinking it they are just views pages, with a term id from URL contextual filter, but I am lost on how to add them as secondary tabs on the term page. Unless I am heading in the worng direction. I would love some advice.

A couple approaches come to mind, I will outline the one that does not use panels.

Start by overriding the default taxonomy page by enabling the one that comes with views.  At this point you will have the same behavior as the default taxonomy pages.

Clone the default taxonomy view and disable the clone (this is case you want to restore the view).

Now back to the taxonomy view

Remove the existing two contextual filters  (not this means the depth feature will no longer be available)

Add a contextual filter on "Content: Has taxonomy term ID"
Add another on "Content: Type".

Change the path to "taxonomy/term/%/page" (for page use the content type machine name you want for this tab)

Change "menu" setting to "default menu tab"

(A) Clone the "Page" display, I gave by clone the name of the content type for the tab

(B) Change the path so "page" is replaced with the next content type you want.

(C) Change "menu" setting to "menu tab"

Repeat (A) (B) and (C) for each content type/tab


How to tell travis that test is failed? I am trying to integrate travis test bots to my module. Travis can run the test correctly, in console log, I can see drush run-test discover pass and fail assertions, but the final result is still passed. Is there any trick to tell Travis know that the test is fail?

My test code is: https://travis-ci.org/andytruong/at_demo_travis/builds/12999422

Thank you

The test-run is outputting XML and reporting success on the generation, which is useful for Jenkins, but not Travis CI.

drush test-run --xml 'Andy Truong'

Change that to

drush test-run 'Andy Truong'

And you should be set.

For reference, see https://drupal.org/project/travis_ci_drupal_module_example and https://travis-ci.org/sonnym/travis-ci-drupal-module-example


duplicate search field appearing with just one block There's suddenly two search fields appearing on my dev site. I'm afraid I'm not sure what the last change was before this.

There's just one standard Drupal search block configured

here's the html from chrome's inspector

Configure block

  <form action="/" method="post" id="search-block-form" accept-charset="UTF-8">

Search form

  Search
 <input title="Enter the terms you wish to search for." type="text" id="edit-search-block-form--2" name="search_block_form" value="" size="15" maxlength="128" class="form-text">

<input type="submit" id="edit-submit--6" name="op" value="Search" class="form-submit">
<input type="hidden" name="form_build_id" value="form-siNBZmrvpwkL6N9gfwu4Li2LBMPzp0TVxw81H7C4H2U">
<input type="hidden" name="form_token" value="nxWBZ6gSMs4INvrbfpGyfd4DTr2QhLdfSrjuYA5PSC0">
<input type="hidden" name="form_id" value="search_block_form">

</form>

It's probably a css problem.

My guess is the search bar is using a background image. The image contains both the inactive search background and the active search background. It's a good thing to avoid to load 2 different images.
If you want this to work, you need to ensure that the search box has a fixed height.

So in the css, you should have something like :

#edit-search-block-form--2 {
  height: 10px;   /* 10px => replace this with the real height */
}


How to reproduce drupal.org search? I would like to reproduce drupal.org search.
I know that is used the Apache Solr module.What I don't know is how to make appear the available selections like Module,Themes,All,Groups etc so as to filter only these.
How can I do this?
Thanks

This is not so much an issue of suing Apache Solr as it is one of working with the database query system.  To do what you want you will have to become very familiar with the Views module.  I recommend watching the nodeone.se series 'Taming the Beast'

Views is a UI for making sql queries.  You create a view definition with a path you assign to your look-up page.  It will include filters to sort content by types.  The various categories of information at Drupal.org are basically different content types. The various displays lists etc. used to provide the information can be provided by a variety of modules.  I would recommend exploring Panels and Page Manager to provide and display the information.  Nodeone.se also has an excellent series called 'Learn Page Manager' that can help you master those issues.

If you want custom functionality and know your way around PHP you may want to look at the Drupal Forms API, the Search module, and Search API module for additional functionality in creating customized searches and forms.


How to favor exact matches in entity reference autocomplete? Right now if you use entity reference autocomplete for short titles of a node type or entity type, and you have many items, due to the fact that by default they are ordered by entity id (nid), less relevant entries show up before exact matches.

For example, if you create a content type for stock symbols, and you have tens of thousands of them, and you want to search for "EA" or "DIS", longer strings that contain these substrings show up before exact matches.

How can you change the behavior so exact matches show up before other matches with lower entity ids?

Here's a way to alter the query for entity reference autocomplete. You can add an expression that returns the string length and then sorts by this.  This way, if a string contains "DIS", and it sorts by the string length, it will start with 3, and the only item that contains the string and is of the shortest length that contains the string (3) is the exact match, so it will show your exact match first, and then other relevant items that contain the string.  For example "ADIS" or "DISV".

/**
 * Implements hook_query_TAG_alter().
 *
 * Favor exact matches and shorter matches in node reference
 * autocomplete.
 */
function mymodule_query_entity_query_node_alter(AlterableInterface $query) {
  $routeMatch = \Drupal::routeMatch();

  if ($routeMatch->getRouteName() != 'system.entity_autocomplete' ||
    $routeMatch->getParameter('selection_handler') != 'default:node' ||
    $query->getMetaData('entity_type') != 'node') {
    return;
  }

  if (is_object($query->getMetaData('entity_reference_selection_handler')) && $query->getMetaData('entity_type') == 'node') {
    $tables = $query->getTables();
    if (!empty($tables['node_field_data'])) {
      $query->addExpression('CHAR_LENGTH(node_field_data.title)', 'shortest');
      if ($groups = $query->getGroupBy()) {
        $query->groupBy('shortest');
      }
      $query->orderBy('shortest');
    }
  }
}

//You can use the same basic template for other entity types:

/**
 * Implements hook_query_TAG_alter().
 *
 * Favor exact matches and shorter matches in mycustomentity entity reference
 * autocomplete.
 */
function mymyodule_query_entity_query_mycustomentity_alter(AlterableInterface $query) {
  $routeMatch = \Drupal::routeMatch();

  if ($routeMatch->getRouteName() != 'system.entity_autocomplete' ||
    $routeMatch->getParameter('selection_handler') != 'default:mycustomentity' ||
    $query->getMetaData('entity_type') != 'mycustomentity') {
    return;
  }

  if (is_object($query->getMetaData('entity_reference_selection_handler')) && $query->getMetaData('entity_type') == 'mycustomentity') {
    $tables = $query->getTables();
    if (!empty($tables['mycustomentity_field_data'])) {
      $query->addExpression('CHAR_LENGTH(mycustomentity_field_data.title)', 'shortest');
      if ($groups = $query->getGroupBy()) {
        $query->groupBy('shortest');
      }
      $query->orderBy('shortest');
    }
  }
}


Drupal 7 img src path issue I created a block, in which an img with src="sites/mysite/files/imagename". It works every node, but failed loading in search page.

Is this an issue of Search module?
Drupal 7, I hope, has a uniform url management, for example:

exapmle.com/files, exapmle.com/modules/Module_name, or
exapmle.com/modules/core(Symbolic Link points to sites/all/modules) /Module_name
exapmle.com/themes/Theme_name, or
exapmle.com/themes/core(Symbolic Link points to sites/all/themes) /Theme_name ...
...

For any source or path of any thing in drupal site use src like this. It will work everywhere.$src = base_path() .'sites/files/logo.png';


enable dd() for drush - temporary://debug_drupal.txt call fails If I included calls to dd() from code I run with drush, I see messages like this:

WD php: Warning: file_put_contents(temporary://drupal_debug.txt):      [warning]
failed to open stream: "DrupalTemporaryStreamWrapper::stream_open"
call failed in drupal_debug() (line 1624 of
/home/planetary/April/sites/all/modules/devel/devel.module).

How to make it so that dd('...') actually prints stuff to the drupal_debug.txt file?

As of a recent change to Drush (March 30, 2013), Drush is aware the  environment variables TMP and TEMP.  So the solution (on Ubuntu) is:

export TMP="/tmp/"

and

sudo chmod g+w /tmp/drupal_debug.txt
sudo usermod -a -G www-data DrushUser


Field Collection, with Entity Reference, can get value I've got a field collection, which contains

A copy field
A user field, via entity reference

Now when I try to access the copy field by storing the collection in $collection, via

$collection->field_my_collection_copy->value();

I get what im looking for, but trying similar on the entity referenced field

$collection->field_my_collection_user->value();

It breaks. By looking into the variables for $collection->field_my_collection_user I should have 'uid' available on it, but $collection->field_my_collection_user->uid gives me nothing and $collection->field_my_collection_user->uid->value(); gives me Unable to get the data property uid as the parent data structure is not set

Hah, I should've given the anonymous user the privilege to view the data.


Able to use custom variables in page.html.twig but not in menu.html.twig I have a module setting config variables which I'm trying to display in a twig template. When I use

function mytheme_preprocess_page(&$variables){
    $variables['facebook'] = \Drupal::config('social.settings')->get('facebook', 'No username');
    $variables['twitter'] = \Drupal::config('social.settings')->get('twitter', 'No username');
    $variables['instagram'] = \Drupal::config('social.settings')->get('instagram', 'No username');
    $variables['youtube'] = \Drupal::config('social.settings')->get('youtube', 'No username');
}

I'm able to display the variables in my page.html.twig template by invoking

{{ facebook }}{{ twitter }}{{ instagram }}{{ youtube }}

However I'd like menu.html.twig to invoke it. Even when adding a preprocess hook for menu like so

function mytheme_preprocess_menu(&$variables){
    $variables['facebook'] = \Drupal::config('social.settings')->get('facebook', 'No username');
    $variables['twitter'] = \Drupal::config('social.settings')->get('twitter', 'No username');
    $variables['instagram'] = \Drupal::config('social.settings')->get('instagram', 'No username');
    $variables['youtube'] = \Drupal::config('social.settings')->get('youtube', 'No username');
}

menu.html.twig produces nothing when invoking

{{ facebook }}{{ twitter }}{{ instagram }}{{ youtube }}

I know menu.html.twig is being used because I can make changes to it and the changes will appear. I also know that mytheme_preprocess_menu is being called because drupal_set_message works from it.
However {{ dump() }} from menu.html.twig is not displaying anything on the page.

The menu theme is declared using the variables key (see doc).

That means that only the keys present in the variables array can be passed to the template.

Any custom variable needs to be first added using hook_theme_registery_alter


user login screen is gone after using panels I've been trying to login with /user, /?q=user, and /?q=user/login but when I load the pages I can only see my header and nothing else.

This is likely because in the process of trying to learn how to use panels I somehow turned it off.  The default node variant was the first I created, where I put basic header information (site name, slogan, navigation) in the header, body content in the middle, and regular footer content in the footer with the new node-template variant.  As I recall I disabled this page/variant after I realized it applied it to every page and messed up a different system page.  Even though I disabled it and it was fine last time i was on the site, it seems to be back.

Is there any easy way to fix this?  Is there any thing I cut paste into a php file to load my user login block so i can at least get back into my site?

Used drush to disable panels ( drush dis panels).

Thanks to 4life for the suggestion.  (i don't know why it won't let me credit him with the answer on here)


How do I save a new field value for node without saving the node? I am developing a Drupal 8 website and I added a new field to a custom content type called Download. This field is updated each time a file is downloaded from this content type. I use hook_file_access to find a node from which a file was downloaded. I then get current download count value by getting a field from a node. The value is incremented by 1 and the new value is stored in the field. I then save the node to store the value. Below is the code used for node (field change) saving:

$field_download_count = $entity->get('field_download_count')->get(0);
if ($field_download_count == null) {
    $download_count = 1;
} else {
    $download_count = $field_download_count->getValue()['value'];
    $download_count += 1;
}
$entity->set('field_download_count', $download_count);
$entity->setNewRevision(false);
$entity->save();

The problem is that with this code, updated date of the content changes and this is a problem for me as I use updated date in many view and data is not valid as per this code, updated date is changed with each file download from the node.

Is there a way to store the field value only on Drupal 8?

In Drupal 7, one could use field_attach_update but this function was removed in Drupal 8.

I tried to update the field value using Drupal update SQL function, but this is not a proper way and also didn't play well with a cache system.

You could directly update the field table in the database ?

$database = \Drupal::database();
  $result = $database->query("UPDATE node__field_download_count SET field_download_count = field_download_count + 1  WHERE entity_id = " . $entity_id);


EntityMalformedException: Missing bundle property on entity of type taxonomy_term I have strange behavior that when i visit www.mysite.com/taxonomy/term/516/sdfsdf

i get

  EntityMalformedException: Missing bundle property on entity of type taxonomy_term. in entity_extract_ids() (line 7788 of /../includes/common.inc).
      The website encountered an unexpected error. Please try again later.

while it should load content of

www.mysite.com/taxonomy/term/516

Can anyone help?

there seems to be an error in

  entity_extract_ids()

in some circumstances the entity info for taxonomy term is wrong ..
(probably with entity translation in my case)

function entity_extract_ids($entity_type, $entity) {
  $info = entity_get_info($entity_type);

  // Objects being created might not have id/vid yet.
  $id = isset($entity->{$info['entity keys']['id']}) ? $entity->{$info['entity keys']['id']} : NULL;
  $vid = ($info['entity keys']['revision'] && isset($entity->{$info['entity keys']['revision']})) ? $entity->{$info['entity keys']['revision']} : NULL;

  if (!empty($info['entity keys']['bundle'])) {
    // Explicitly fail for malformed entities missing the bundle property.
    if (!isset($entity->{$info['entity keys']['bundle']}) || $entity->{$info['entity keys']['bundle']} === '') {
      throw new EntityMalformedException(t('Missing bundle property on entity of type @entity_type.', array('@entity_type' => $entity_type)));
    }
    $bundle = $entity->{$info['entity keys']['bundle']};
  }
  else {
    // The entity type provides no bundle key: assume a single bundle, named
    // after the entity type.
    $bundle = $entity_type;
  }

  return array($id, $vid, $bundle);
}

this is 1:1 the code (not patched ..), that needs changes. from common.inc

see here for patches: https://www.drupal.org/node/1270340#comment-9890989

when using EntityFieldQuery and fe. node_load_multiple make sure to pass fully loaded entites !
use node_load_multiple and pass that result.


Is there a way to disable username for logging in? I'm using realname with this small moduel to generate username from some profile field.

Now users can login with both username and email by using LoginToboggan.

Only the problem is that I don't want to let users login with their username. It looks like LoingToboggan has the function to let users login with email but not disable username login.

Is their anyway I can just disable username login?

I don't know of an existing module that does this, but it would only take a few lines of code in a custom module to get the effect you're looking for:

function MYMODULE_form_user_login_alter(&$form, &$form_state) {
  // Add an extra validation step to the form.
  // The user is actually authenticated during the validation stage
  // so we have to make sure this validate function runs before any others
  array_unshift($form['#validate'], 'MYMODULE_user_login_validate');
}

function MYMODULE_user_login_validate($form, &$form_state) {
  // Make sure the provided username field is in the form of an email address.
  // If not we can safely say the user shouldn't be allowed to log in,
  // regardless of whether or not a user exists with that username.
  if (!valid_email_address($form_state['values']['name'])) {
    form_set_error('name', 'The email address you have entered was not found in the system.');

    // Empty the name variable so further validation definitely fails.
    // There are probably better ways to do this so be creative :)
    $form_state['values']['name'] = '';
  }
}


Drupal fetching object I am trying to fetch an object:

$field_name= 'field_test';
$json_code = $node->$field_name['und'][0]['value'];

NOT WORKING

$json_code = $node->field_test['und'][0]['value'];

WORKING

I must have variable because it's every time different field name

any solution?

Your PHP is incorrect for what you're trying to accomplish.

Drupal has field_get_items() for this purpose, though:

$items = field_get_items('node', $node, $field_name);
...


Add external JavaScript files containing a parameter in the URL I need to add some external JS files to my website. This is an extract of the module.libraries.yml file.

my_live_chat:
  js:
    https://mylivechat.com/chatinline.aspx?hccid=12345678 : { type: external, attributes: { defer: true, async: true, data-cfasync: 'false' } }
    https://www.mylivechat.com/chatapi.aspx?hccid=12345678 : { type: external }

As you can see, they have this final variable hccid in them that is different for each website.

I'd like to create a custom module where I only need the client ID (the hccid value) and the module adds all the needed JavaScript files.

I know how to create a custom module with a settings form to ask for the variable value and I know how to add external JavaScript files to my module.libraries.yml file.

How can I deal with that variable so it can be different on each website without modifying the module?

Use the hook_library_info_build hook to add dynamic library definitions.

The key(s) could be stored as configuration. e.g. use Simple Configuration API

You would then in the hook, check if the configuration has a value and if so add the library and if not, well depending on how you want to deal with it.


Providing a default value for an Entity Reference Field using Views Bulk Operations I have a content type called 'Schools' and a CSV spreadsheet that has columns for information such as School Name, Location, Telephone etc...

Using Feeds I can import the information on the 111 Schools to individual pages.

Furthermore I have a field on the 'Schools' Content type that is an entity reference field to an entity  (an entity form - that lets the user contact the school - of widget type 'Select list')

However when I import the school data with my feed the 'entity reference' 'select-list' field defaults to 'none' and the 'Contact form' does not display. Furthermore the entity reference field does not let me set a default value for the 'select list'.

I don't want to go through 111 schools to do this manually. While the previous question on this subject calls for some code...that I do not yet understand...

Therefore is there a way to essentially set a default value for my entity reference ... Perhaps 'Views Bulk Operations' is the answer?

I figured this out.

Views > Create New View > Content type 'Schools'

Format > Table

Add Fields > Title

Add Fields > Bulk Operations (Content) > Bulk Operations > Modify Entity Values > 'Your Entity Reference Field' > Skip Confirmation Step > Show Token Values

done - navigate the views bulk operations URL, select all of your nodes and apply the changes ... You might need to adjust the pager options in the view to see all of your nodes, and also disable the feeds importer while you adjust the nodes associated with it...


Theming with Views generates error undefined variable I have a basic installation of Drupal 7, with the Views module. I am using the Garland Template.

When I try to create a new template for my views the following error is thrown:

  Notice: Undefined variable: build in include() (line 2 of /XXX/public_html/themes/garland/views-view—block.tpl.php).

There is only one line in that template:

<?php dpm($fields); ?>

Most likely this is something simple to resolve, but I cannot find the answer.

Not sure what the variable $fields are but try and do a dpm($rows) this should return an array of the fields from the views.


EntityDrupalWrapper->value() causes infinite recursion on user login? I have a few instances on my site where I perform actions on User Login.

I create an EntityMetadataWrapper like so:

global $user;
$uw = entity_metadata_wrapper('user', $user);

And then I go to retrieve values like this:

$special_value = $uw->field_special_value->value()

For some reason, this particular line will cause an infinite recursion and crash my site.

Does anyone know what I'm doing wrong here? I am calling one of these from a Rules event and another one from hook_user_login, but it seems like no matter what, I get this recursive error.

This ONLY seems to happen in hook_user_login, all of my other value() calls to Entity Metadata Wrappers seem to work fine.

Note; these are both Entity References -- one references a Taxonomy Term and the other references a custom Entity.

are you sure the user is logged in and you have a full $user object available in your rule?

Maybe you have to call $user = user_load($uid, TRUE); explicity for this 1 case?


How to use entity_metadata_wrapper in hook_boot I am trying to create an entity with entity_metadata_wrapper from within hook_boot.  I know everyone will say "use hook_init" but for performance reasons, I'm going w/ hook_boot :) .

I have a couple modules loaded like so:

require_once DRUPAL_ROOT . '/includes/common.inc';
drupal_load('module', 'entity');
drupal_load('module', 'field');

This is what I have:

$entity = entity_create('myentity', array('type' => 'click'));
$ew = entity_metadata_wrapper('myentity',$entity);
$ew->field_myentity_url_reference->set($row->rid);
$ew->save();

The above works fine if run normally (like from form_alter or something), but not from hook_boot.

I am getting the following errors:

Warning: class_implements(): object or string expected in entity_create() (line 367 of /data/disk/host/distro/005/drupal-7.18.1-dev/sites/mysite.com/modules/entity/entity.module).
Warning: in_array() expects parameter 2 to be array, boolean given in entity_create() (line 367 of /data/disk/host/distro/005/drupal-7.18.1-dev/sites/mysite.com/modules/entity/entity.module).
EntityMetadataWrapperException: Invalid data value given. Be sure it matches the required data type and format. in EntityMetadataWrapper->set() (line 122 of /data/disk/host/distro/005/drupal-7.18.1-dev/sites/mysite.com/modules/entity/includes/entity.wrapper.inc).

Anyone know what else I need to drupal_load to get this to work?

EDIT - Figure out how to do this:

I used the background process module: http://drupal.org/project/background_process.  I added the code below to hook_boot:

//load the required modules needed to do background_process
require_once DRUPAL_ROOT . '/includes/common.inc';
require_once DRUPAL_ROOT . '/includes/path.inc';
drupal_load('module', 'background_process');
drupal_load('module', 'progress');

background_process_start('shurly_create_click_log', $row);//  drupal_load('module', 'entity');

Then I put the entity code in a new function:

function shurly_create_click_log ($row){
    $entity = entity_create('linkpin', array('type' => 'click'));
    $ew = entity_metadata_wrapper('linkpin',$entity);
    $ew->field_linkpin_url_reference->set($row->rid);
    $ew->save();
}

Basically, the shurly_create_click_log function gets ran at full bootstrap in the background, so it doesn't slow down my pageload/redirect from hook_boot.

Here's a solution.

Add this to the top of your hook_boot() function:

function hook_boot() {
  global $user, $base_path;
  drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);
...
}

drupal_bootstrap keeps track of what level it has been called so this trick effectively pushes hook_boot to being later in the boot process.


drush updb fails with "the 'media_delete_action' plugin does not exist" after 8.4.6 > 8.5.1 update We have recently updated a Drupal 8.4.6 installation via composer to Drupal 8.5.1. After the composer update I ran

drush updb

as usual. However, the command fails at one point with the following error message:

Failed: Drupal\Component\Plugin\Exception\PluginNotFoundException: The "media_delete_action" plugin does not     [error]
exist. in Drupal\Core\Plugin\DefaultPluginManager->doGetDefinition() (line 52 of
…\htdocs\casali\web\core\lib\Drupal\Component\Plugin\Discovery\DiscoveryTrait.php).

After that, every drush updb wants to do the following updates, since they are never completed:

system module :
  Change plugin IDs of actions.
  Clear caches due to schema changes in core.entity.schema.yml.

views module :
  Update dependencies for moved bulk field plugin.
  Add additional settings to the entity link field and convert node_path usage  to entity_link.
  Add placeholder settings to string or numeric filters.
  Fix cache max age for table displays.
  Include views data table provider in views dependencies.

I am not quite sure what to do here. As far as I have researched, media_delete_action is part of the media_entity module. However, that module is already part of the core in Drupal 8.4.x (https://www.drupal.org/project/media_entity).

If I run

drush en media_entity

it tells me

media_entity was not found.                                                                                [warning]
The following projects provide some or all of the extensions not found:                                                    [ok]
media_entity
Would you like to download them? (y/n):

But I don't think I should have to do that, since it's already part of the core?

This is how we were able to solve this problem:

Temporarily install drupal/media_entity_actions:

composer require drupal/media_entity_actions:^1.0
drush en media_entity_actions

Run the database update:

drush updb

This time it will work:

system module :
  Change plugin IDs of actions.
  Clear caches due to schema changes in core.entity.schema.yml.

views module :
  Update dependencies for moved bulk field plugin.
  Add additional settings to the entity link field and convert node_path usage  to entity_link.
  Add placeholder settings to string or numeric filters.
  Fix cache max age for table displays.
  Include views data table provider in views dependencies.

Do you wish to run all pending updates? (y/n): y
Post updating system                                                                                [ok]
Post updating system                                                                                [ok]
Post updating views                                                                                [ok]
Post updating views                                                                                [ok]
Post updating views                                                                                [ok]
Post updating views                                                                                [ok]
Post updating views                                                                                [ok]
Post updating views                                                                                [ok]
Post updating views                                                                                [ok]
Cache rebuild complete.                                                                                [ok]
Finished performing updates.                                                                                [ok]

Then the module can be uninstalled safely:

drush pm-uninstall media_entity_actions
composer remove drupal/media_entity_actions


Problems while migrating drupal website from localhost to server I am trying to migrate my Drupal website from localhost to server, but I am having some problems. I tried many guides from Google, but with no luck.

What I did:

First I did a fresh drupal installation on server

Once installation was complete I edited the .htaccess file as

RewriteBase /site-name

Then I used mysqldump to dump my database from localhost to server I found that I had total 126 tables in localhost while in server I had 128 tables

Then I copied my complete "sites" directory from localhost to server

My problem:

Now when I enter www.mysite.com/site-name I get proper home page of my website but if I go to any other link such as www.mysite.com/site-name/user it is not able to open the page but if I enter www.mysite.com/?q=user then it works perfectly and this happens for all pages such as /content, /config etc.

What should I do to solve this issue? I think it is a problem of clean-urls So I went to configuration but it said clean URL enabled but test failed!

I need to make website live by tomorrow so need your help!

Note: I am using ubuntu on localhost as well as server

Thanks!

To avoid requiring ?q=user or ?q=some/page/path you should assure ModRewrite is enabled on your Apache webserver. If you're on shared hosting you made need to ask your host provider to enable this module of Apache.
Moving a Drupal site is essentially moving all the PHP + MySQL data from 1 computer to another. Pick you're tools: mysqldump + zip, rsync, scp, ftp ... Drush whatever ... but the procedure is essentially the same -- move everything in it's entirety.

Why you have 2 less tables between your Drupal installs is unfortunately simply bad project management on your behalf -- good luck tracking down the differences.

Comparing drush pm-list between the 2 Drupal installs should help to find any modules on 1 system and not on the other. I like using drush archive-dump and drush archive-restore to move Drupal sites around -- but under your time constraint I recommend using SQL migration tools and code migration tools your comfortable and most familiar with.


Drupal URL encoding breaks redirects/links I added a link to my Toolbar Shortcuts list and the path is:

admin/content?title=&type=slides&author=&status=All&vid=All

But when you click it, Drupal redirects to:

admin/content%3Ftitle%3D%26type%3Dslides%26author%3D%26status%3DAll%26vid%3DAll

Which breaks the link and redirects to a wrong page.

How do I prevent Drupal from converting symbols and leave it as it is.

This is drupal core functionality that converts special correctors to string when using in toolbar shortcut menu.


queries with db_select don't respect integers When I check "SHOW PROCESSLIST" in phpMyAdmin I can see lots of queries where argument-integers are being inserted as strings (with single quotation marks).

I'm wondering if this is due to the way phpmyadmin reports the queries (if it puts every argument between quotation marks) of if it is db_select that puts every argument between quotation marks.

An example of my code where integers are being used as arguments:

$select->join('taxonomy_index', 't_'.$key, 't_'.$key.'.nid = n.nid AND t_'.$key.'.tid = :tid_' . $key, array(':tid_'.$key => (int)$tid));
$select->condition('t_'.$key.'.tid', (int)$tid);

As you can see I explicitly write (int)$tid but in my query log I can see the following:

... WHERE (t_0.tid = '10') ...

The big question is: How can I be sure that integers are being treated as integers in my queries? I don't want MySQL having to transform strings to integers.

Drupal doesn't alter the arguments you give it (apart from expanding arrays), but because they're passed directly to PDOStatement::execute, in which

  All values are treated as PDO::PARAM_STR.

the quotes are inevitably added.

Assuming a recent-ish version of MySQL you can try disabling prepared statement emulation to let MySQL sort them out instead. In settings.php:

$databases['default']['default'] = array(
  'driver' => 'mysql',
  'database' => 'drupaldb',
  'username' => 'username',
  'password' => 'secret',
  'host' => 'dbserver1',
  'pdo' => array(PDO::ATTR_EMULATE_PREPARES => FALSE),
);


Use JQuery Cycle with custom Javascript I have build a view with a HTML-list were all my images are listed. Goal is to create a JQuery Cycle with those images, but for some reason, my custom Javascript isn't working...

Here is the HTML generated by Drupal:

And here is my custom Javascript I wrote:

(function ($) {
    Drupal.behaviors.initFrontPageSlider = {
        attach: function(context, settings) {
            $('body').once('initFrontPageSlider', function() {
                $('.homepage-slider').cycle({
                    fx: 'fade'
                });
            });
        }
    }
}(jQuery));

But for some reason, my image-list isn't picking up my javascript. What's missing on this?

If you want to cycle the <li>'s then you need to call .cycle() on the <ul> element. At the moment looks like you're trying to cycle the <ul> elements inside the <div class="homepage-slider">. If there's only 1 child element cycle doesn't progress further since there's nothing to cycle.


tableselect checkboxes i want to change values of only checked elements on tableselect.
How can i do that please ?

this is my tableselect :

$form['tab'] = array(
    '#type' => 'tableselect',
    '#header' => $header,
    '#options' => $rows,
    '#empty' => t('empty !'),

);
return $form;

i've also a submit button that makes changes (update database) on one column of the tableselect :

 $form['published'] = array(
        '#type' => 'submit',
        '#value' => t('Publish'),
        '#states' => array(
            'invisible' => array(
            ':input[name="select_list"]' => array('value' => 'Published'),
            )
            ),
        '#submit'=> array('publish_submit'),
    );

My function to make changes (to publish elements that aren't now) :

function publish_submit($form, &$form_state){
$check = $form_state['values']['tab'];
//$check = array_filter($form_state['values']['tab']);

$sql = db_update('field_data_field_books');
$sql->fields(array('field_books_value'=> 'Published'));
$sql->condition('entity_id',$check); //update only books i checked on the tableselect
$query = $sql->execute();
   }

this is what dsm($check) returns (when i check one or more elements on the tableselect )

this is dsm($rows) (6 elements are ok):

This is how i created the $rows :

$rows = array();

foreach ($result as $res){

    $rows [] = array(

            'book_title' => l($res-> field_title_value, 'node/'.$res->entity_id),
            'book_state' => $res-> field_state_value,
            'book_editor' => $res-> field_editor_value,
            'book_categories' => $res-> name,
            'edit_books'=>l(t('Details'), 'node/'.$res->entity_id.'/edit'),
          );

}

$form['table'] = array(
    '#type' => 'tableselect',
    '#header' => $header,
    '#options' => $rows,
    '#multiple' => TRUE,
    '#empty' => t('nothing!'),

);

As beebee said on comments :

$rows should be indexed like this :

foreach ($result as $res){

    $rows [$res -> entity_id] = array(

and the condition of the publishing function :

function publishing_submit($form, &$form_state){

    $check = array_filter($form_state['values']['table']);
    $sql = db_update('field_data_field_state');
    $sql->fields(array('field_state_value'=> 'Published'));
    $sql->condition('entity_id', $check, 'IN');
    $sql->execute();
}

Thanx beebee


fatal error on a drupal site I have a site based on drupal. Few weeks back an error appeared on our site

  Fatal error: Cannot redeclare file_entity_file_presave() (previously
  declared in
  /home/newprofi/public_html/new/sites/default/modules/file_entity/file_entity.module:177)
  in
  /home/newprofi/public_html/new/sites/default/modules/file_entity/file_entity.file.inc
  on line 37

it happened after an upgrade that distorted our theme, and only restoring could have saved that.

i tried to find duplicates of that module, but there is nothing on our servers.
Is there anything else i could do to fix that?

Thanks,
Noam

I had seen similar error in the past and I followed these steps which worked for me:

Manually disable the module in db
Clear the cache
Re-enable the module


Webform css stylesheet overriding my css file I am using drupal 6.25 with webforms 6.17 and conditional stylesheets 6.12 and am noticing that the webform style.css file is overriding my IE7style.css file even though the IE7style.css file appears after the webform stylesheet when I view the source in IE7.

It makes no difference if I have css caching turned on or off - the result is the same.

Here is the relevant line in IE7style.css

.webform-container-inline .form-item {
    display: block;
}

Here is the line in webform's sytel.css it should be overriding

.webform-container-inline DIV.form-item {
    display: block;
 }

How is this possible and more importantly how do I fix it???

The 'div' in the webform's CSS makes it more specific than your CSS in IE7styles.css, thus overriding your styles. You should copy the CSS selector from the webform module's CSS exactly if you want to override it with a style in a file later in the cascade.

Here is a good article on general traits of CSS specificity and inheritance.


How to add the proper javascript to a page for using the Chartbeat module? Has anyone successfully used the Chartbeat module with Drupal to get the analytics statistics?

It doesn't seem to work for me. I don't get the proper javascript added to the page.

the module doesn't work for me, I ended up putting the required javascript code into the template files.


Using rules how to redirect to a url + element id After saving a node, I am redirecting to another form using rules.

I want to be able to append this value "field_article[und][0][nid]" to the url that I am sending to.  This corresponds to a select list id. Basically, I want this id appended to the url when I redirect.

Any ideas?

You can use token from Replacement Patterns list. Token will be something like [node:field_node_ref].


Notice: Undefined index: highlighted in include() (line 124 of page.tpl.php I keep getting this error in a fresh drupal install with fusion and a custom fusion subtheme:

Notice: Undefined index: highlighted in include() (line 124 of /home/username/public_html/modules/system/page.tpl.php).

Would anyone happen to have any clue as to what is causing this?

If I am correct highlighted is a region name and you might have not defined it in you theme info file which is why it is throwing this error.

Give me more details of your info file and your page tpl file so that I can guide you in a better way.


Should I disallow drupal path or alias by robots.txt? I have 2 languages enabled on my site English and Japanese.

Japanese is the default and English has prefix "en".

I want search engines to crawl one View page only in Japanese.

So I decided to use Disallow: /en/my-view/* in robots.txt but my-view has alias.

Should I use Disallow: /en/my-view/* or Disallow: /en/alias-my-view/* ?

You should add both paths, as both of them are accessible.

However, I recommend installing Global Redirect plugin. It will permanently redirect your internal path to the alias (if any). This way you only have to add one path to your robots.txt.


how to include .inc files in drupal8 in custom form I have my custom module in drupal8.I have created a custom form.My form has many fields so i was wanted to move it to .inc files.Please can someone suggest me how and where to include my .inc file.

The procedural function for include files seems still to exists module_load_include(), but you shouldn't use it in a form class. Normally you would refactor the code inside of the form class in multiple class methods. If you want an extra file, then create a new class and include it in your form class with an use statement. Each class has it's own file, which is autoloaded with PSR-4, see https://www.drupal.org/docs/develop/coding-standards/psr-4-namespaces-and-autoloading-in-drupal-8

A Trait is an alternative option. You would put the refactored methods in an extra Trait file, but logical the methods remain class methods and at the same time are reusable by other classes. The Traits are also autoloaded. See https://drupalize.me/blog/201503/dependency-injection-traits-drupal-8


Permissions not working with Tabs menus? I have Menus with Tab structure Working from my custom module. But When I built permissions for each Tab It does not work according to assigned user roles in permissions, also it just made those url's not accessible. Please suggest what I am doing wrong, Thanks!

function my_module_permission() {
  $arr = array();
  $arr['access one_type_titles'] = array(
    'title' => t('Access First Type Titles'),
    'description' => t('Allow users to First Type Titles page.')
  );

  $arr['access second_type_titles'] = array(
    'title' => t('Access Second type Title page'),
    'description' => t('Allow users to access Second type Title page.')
  );

  return $arr;
}

function my_module_menu() {

  $items['type'] = array(

    'description' => t('Page for translation'),
    'page callback' => 'drupal_get_form',
    'page arguments' => array('custom_list'),
    'access arguments' => array('access one_type_titles content'),

  );

  $items['type/fr'] = array(
    'title' => t('French Links'),
    'type' => MENU_LOCAL_TASK,
    'weight' => 1,
    'page arguments' => array('custom_list'),
    'page callback' => 'drupal_get_form',
    'access arguments' => array('access one_type_titles content'),
  );

  $items['type/en'] = array(
    'title' => t('English Links'),
    'type' => MENU_LOCAL_TASK,
    'weight' => 2,
    'page arguments' => array('custom_list'),
    'page callback' => 'drupal_get_form',
    'access arguments' => array('access second_type_titles content'),

  );

  return $items;
}

Using 'access callback' => can_the_user_see_this_item, and then coding access according to user role make it works but not with above method.

function can_the_user_see_this_item(){
 if (condition....) ) {
    return TRUE;
  }else{
    return FALSE;
  }
}

Try to remove 'content' word from 'access arguments' in hook_menu, because you custom permissions don't contain it. Clear cache.

'access arguments' => array('access one_type_titles'),


How to remove the create prefix text when adding new content? Tried a couple of attempts and no luck with function framework_preprocess

function framework_preprocess_ask_a_question(&$vars, $hook) {
  if (arg(0) == 'node' && arg(1) == 'add' && arg(2) == 'ask_a_question') {
      $variables['title'] = 'Ask a new question';
   }
}

Content type is called "Ask a Question" want to change the title from "Create Ask a Question" to "Ask a new question" (removing the create text set by default)

You can use hook_form_FORM_ID_alter().

You could also use hook_form_BASE_FORM_ID_alter() or hook_form_alter() if you preferred or it fit better with your other custom code and requirements.

You would do something like this in a custom module:

/**
 * Implements hook_node_FORM_ID_alter().
 */
function MODULENAME_form_ask_a_qustion_node_form_alter(&$form, &$form_state) {
  // Only change the title on the add form, not the edit form.
  if (empty($form['nid']['#value'])) {
    drupal_set_title('Ask a new question');
  }
}

Or if you want to do multiple content types:

/**
 * Implements hook_node_BASE_FORM_ID_alter().
 *
 * Alter all node forms.
 */
function MODULENAME_form_node_form_alter(&$form, &$form_state, $form_id) {
  // Only change the title on the add form, not the edit form.
  if (empty($form['nid']['#value'])) {
    $title = '';
    switch ($form_id) {
      case 'ask_a_qustion_node_form':
        $title = 'Ask a new question';
        break;
      case 'other node type_node_form':
        $title = 'Other title';
        break;
    }
    if ($title) {
      drupal_set_title($title);
    }
  }
}

There is also the node add title module that allows you to set the title of the add form per content type.
At a quick glance over the code of that module though I see a few issues so I personally wouldn't use it at this stage, although I will open some issues to try to get them fixed.


Which hook to use to reorder multi-value field values before saving content I have a multi-value field added to my content type. It is actually a field collection.

The users can add unlimited items to this field, and rearrange the items using Drupal's drag-and-drop utility.

However, I want to add some custom logic to the arrangement of field values according to the content.

Which hook should I use, to modify the arrangement of field values before the node saved into the database.

For example, I have the following structure:

My Content Type
|
|-- Field Collection Field // unlimited values
    |
    |-- Name // Text field
    |-- Surname // Text field
    |-- Company // Select list

Let's say a user created a content with the following values:

John - Doe - ACME
Jane - Doe - Ace
Bob - X - ACME
Fred - Something - Ace

I want to sort them with a custom logic in a hook, so that they are arranged like that:

Bob - X - ACME
John - Doe - ACME
Fred - Something - Ace
Jane - Doe - Ace

My question is NOT how to write the logic, BUT which hook to use to modify the arrangements so that I can put my function into it.

I would suggest you hook_node_presave to modify node edit form submitted values before saving it into DB.


New User Registration Sequence for Services 3.4? This comment outlines a working way to login with the new CSRF token:

POST to /rest/user/login (nothing in headers). Construct the $cookie from session name + id
GET to /services/session/token (include $cookie in the headers). Save the $token returned.
Include $cookie and $token in the headers of subsequent requests of a logged in user.

That sequence works even though the first POST happens without sending the token. (The documentation suggests that the token should be used for any POST requests, which does not work in this case.)

What is a working sequence of HTTP requests to register a new user account? I'm looking for what requests to make in what order - not implementation code.

UPDATE: To be clear, I'm not looking for the login sequence. I need a sequence of requests (similar to login example above) that allow a new user to *register* their account.

Failed Attempt with system/connect:

1. GET:services/session/token

2. POST:system/connect
      Content-Type: application/json
      Accepts: application/json

3. POST:user/register
      Content-Type: application/json
      Accepts: application/json
      X-CSRF-Token: [token]
      Cookie: [session_name]=[sessid]
      Body: {
               "name":"drupalspec0rVzsWAU",
               "pass":"PYKSItFK",
               "mail":"drupalspec0rVzsWAU@drupalspec.com"
      }

The Drupal user is created correctly, but the request in step 3. times out.

Edit: to address the change in the question

  I'm looking for what requests to make in what order - not implementation code

You can safely ignore the actual code implementation below - the order of the requests remains the same. In fact, exactly the same as in your original question.

If you're already making requests in the order that you've outlined, you needn't do anything more except provide an actual implementation. I'll leave the code in as an example, and so you can see exactly what order the requests need to be made in. I've stuck some numbering in to make it more obvious; the requests are denoted by 1, 2 & 3.

This is a basic PHP (i.e. non-Drupal) example...

First off make a generic function for sending your requests:

function send_request($url, array $post_array = array(), $cookie = NULL, $token = NULL) {
  $ch = curl_init();

  curl_setopt($ch, CURLOPT_URL, $url);
  curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
  curl_setopt($ch, CURLOPT_USERAGENT, 'googlebot');
  //curl_setopt($ch, CURLOPT_VERBOSE, $post_array);

  if (!empty($post_array)) {
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $post_array);
  }

  if ($cookie) {
    curl_setopt($ch, CURLOPT_COOKIE, $cookie);
  }

  if ($token) {
    curl_setopt($ch, CURLOPT_HTTPHEADER, array('X-CSRF-Token: ' . $token));
  }

  $result = curl_exec($ch);
  curl_close($ch);

  return $result;
}

1. Then make your first call to log the user in:

// Login.
$data = array(
  'username' => 'user',
  'password' => 'password',
);

$result = send_request("http://server/endpoint/user/login.json", $data);

try {
  $result = json_decode($result);
}
catch (Exception $e) {
  die('Login failed: ' . $e->getMessage());
}

Next get the session name and ID, creating your cookie string to send with subsequent requests:

$session_id = $result->sessid;
$session_name = $result->session_name;
$cookie = $session_name . '=' . $session_id;

2. Then get a CSRF token, making sure to pass the cookie along:

$token = send_request("http://server/services/session/token", array(), $cookie);

3. Finally you can perform your request to the endpoint you're actually interested in. The cookie and token are injected by the send_request() function.

$user = array(
  'mail' => 'test@test.com',
  'name' => 'name',
  // Other relevant properties/fields.
);

$result = send_request('http://server/endpoint/user', $user, $cookie, $token);

I haven't tested the user creation endpoint so that might not be the exact structure it needs, but checking the responses for errors should let you know exactly what it's after quite quickly. I get the impression from your question that you're mainly interested in the steps leading up to that last request anyway.

The above is adapted from a basic test script I use, for a production environment you'll want to add more error/sanity checking in there. And the functionality is crying out to be wrapped in a class, and be extended to support PUT/DELETE, but I'll leave that to you :)


"Login to your account" form block not showing on frontpage when "View published content" is disabled for anonymous I am new to Drupal 8 but not to Drupal ;

In Drupal 8, I enabled the "Login to your account" block in one of my regions :

But on the homepage, the block is not showing in the correct region, instead the login form appears in the "Main content" block (but on 404 pages, for instance, it works fine).

Please note that as it is a private website, I disabled the "View published content" for anonymous users, may it be related ? Maybe it triggers the login form in the main content block, thus deactivating the one in the other region ?

How to set up the login form block in the correct region, on my homepage ? Do I have to render the form in a template hook and then pass it to html.twig ou region.twig ?

Thanks in advance for your answers

For the comment reply :

There is nothing fancy with the theme, this is the generic page template, and the theme is quite empty, derivated from the Stable theme, in which I didn't find any noisy tampering. My gues is that the Core is rendering the form, thus hiding the block.

Drupal core does not support a good way to have a site that requires the user to log in.

The Require Login contrib module adds this functionality.  It also allows for public sections of the site (e.g. a login landing page, links to how to get help, and the like.


Can't change default settings in foundation theme I am thinking about changing my Drupal site theme to a Foundation based one. I use Windows 7, with the Foundation module installed and activated, along with Ruby, Compass and Sass.

To experiment I have changed this in the scss files:

_variables.scss:

 $row-width: em-calc(1280);
 $column-gutter: em-calc(30);
 $total-columns: 12;

_init.scss:

$topbar-height: rem-calc(90);

I get no error messages when I navigate to my sub theme's folder and run compass compile from the command line. Instead I get this:

 write css/custom.css
directory css/foundation
 write css/foundation/foundation.css
 write css/foundation/normalize.css

... which looks promising enough. After this I added this to my sub theme's info file:

stylesheets[all][] = css/foundation/foundation.css
stylesheets[all][] = css/foundation/normalize.css

I also commented out the app.css line in the info file:

; For CSS users, load the app.css file:
; stylesheets[all][] = css/app.css
; Comment the app.css file (above) if you're using sass to preprocess css:
 stylesheets[all][] = css/custom.css

I have looked in the page source and can confirm that those files are actually loaded.

The width is still is the default 1000px value and the top bar still have the same height (45). And yes, I have cleared all cache.

What have I forgotten?

Sorry about the noise... after a couple of hours of struggling I removed these lines in the info file:

stylesheets[all][] = css/foundation/foundation.css
stylesheets[all][] = css/foundation/normalize.css

... and everything began to work. So never mind this question.


What is the easiest way to export Field settings into a .install file? I have a bunch of custom fields on a custom content type. I'm trying to make my module create these fields and remove them on install and uninstall respectively.

There was a previous question and answer on this: https://drupal.stackexchange.com/a/629/2384 However, it is not adequate. The code was not completely presented. The author used node_type_delete() without deleting the content first, and that allegedly leads to trouble later down the line. So I checked the node_example.module as per recommendations on Drupal.org, node_example.install etc. These files provide insight into the structure of the module, but do not discuss all the varieties of fields (like file, taxonomy, etc.,) and how they are to be structured in the .install array.

I have tried to export my content type using Features, and it does produce an array. But the syntax is radically different from what was presented in the example, and I was lost in the arrays and sub-sub arrays.

Is there a simple guide somewhere, that can help me convert my content type into an array specification I can smoothly fit into my hook_install declarations?

There are some useful resources on how to do this. And you dont have to use Features.

Exporting and creating field definitions in Drupal 7 blogpost by Joel Stein
Drupal 7 export content type and fields blogpost by Kristian Nissen

Features is great if you understand what it's doing (calling Field API in an automated fashion and exporting definitions). You can use the Field API to define, create instances, attach fields to entities -- and then remove them all module uninistall as you need.

The easiest way for me to do this is look at the functions in the link above and use var_dump() on $field or its $settings after you make it using the Field UI. Then just use the appropriate Field API call like field_create_instance() to wire these var_dump'd arrays into your modules hook_install(). So i'm saying dont create the arrays by hand, create them in Drupal and just copy an export to your code ...


Using the Rules module, is it possible to access the fields of a referenced entity of an entity? I've got this scheme:
entity person, bundle person, entity health, bundle health. Bundle health has field energy.

Bundle person has an entity reference of type health.

In Rules data selector, I want to access to person:health:energy. Is that possible?

Only, you have to add a Condition (in 'Elements') to the rule of the class "Entity has field", and then a whole bunch of the referenced fields of the entity will appear and will be available.


Can a large amount of CSS using  tags in a template file slow page load time? Front page of a site has a HUGE amount of CSS in the front.tpl.php file using  tags. Does this significantly reduce page load time? If so, why?

Thank you Drupalists! Or Drupaleers. Drupaleeros. Drupal-Heros!

Significantly? depends on how much is your definition huge.

It's best practice to have your style's in CSS file because the browser can cache it. Therefore, on subsequent page loads it doesn't have to download your CSS file again.

The browser doesn't cache your HTML, so it would have to download your huge HTML each and every time.

Caching off

Caching On


Can we add the destination query parameter to a link from yml configuration? When creating a link from yaml

ie: mymodule.links.action.yml

my_module.my_entity.add:
  route_name: node.add
  title: 'Add My Entity'
  route_parameters:
        node_type: 'my_entity'
  appears_on:
    - my_module.my_entity.admin_content

Is there a way that this links would be generated with the ?destination=path/to/redirect ?

Yes, you can add the destination query directly in the yml file.
@see : \Drupal\Core\Menu\LocalActionDefault::getOptions

ie: mymodule.links.action.yml

my_module.my_entity.add:
  route_name: node.add
  title: 'Add My Entity'
  route_parameters:
        node_type: 'my_entity'
  options:
    query:
      destination: '/path/to/redirect'
  appears_on:
    - my_module.my_entity.admin_content


How to integrate JS / CSS only on specified Pages / custom content types I would like embed my module JS / CSS files only in specified cases.
Like on a /url/ or if a custom content type is rendered?

The concept given by Molot is good. Because url can be changed any time.

Still you can add the css and js file using hook_preprocess_page or yourtheme_preprocess_node in your template.php of active theme.

function yourtheme_preprocess_node(&$vars) {
// Add JS & CSS by node type
if( $vars['type'] == "your-node-type") {
drupal_add_js( /* parameters */ );
drupal_add_css( /* parameters */ );
}

where yourtheme need to be replaced by the name of the your active theme.
Please clear cache for changes to reflect.

Hope it will work for you.


Adding elements to a field widget What I need to accomplish is adding a link to a node to field widgets (the node contains the formatted instructions to properly compile the field).
The goal is something like this:

"What is this?" is the link to a node, to be opened in a new tab or in a popup. In this example the field is a select, but it could be any type of field.

So far I've been able to add the node reference field in the field config form, using Third Party Settings:

function mymodule_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {
  if ($form_id === 'field_config_edit_form' && $form_state->getFormObject()->getEntity()->get('entity_type') == 'myentity') {

    $field = $form_state->getFormObject()->getEntity();
    $help_page_id = $field->getThirdPartySetting('mymodule', 'help_page_id');

    $form['help_page_id'] = array(
      '#type' => 'entity_autocomplete',
      '#title' => t('Help page'),
      '#target_type' => 'node',
      '#selection_handler' => 'default',
      '#selection_settings' => array(
        'target_bundles' => array('help_page'),
      ),
      '#default_value' => $help_page_id ? Node::load($help_page_id) : NULL,
      '#weight' => 100,
    );

    $form['#entity_builders'][] = 'mymodule_form_field_config_edit_form_builder';
  }
}

Now I'm having troubles retrieving this information when showing the form, and altering the field widget in order to display the link.
Using hook_field_widget_form_alter, I cannot get the custom configuration value from the arguments I have:

function mymodule_field_widget_form_alter(&$element, \Drupal\Core\Form\FormStateInterface $form_state, $context) {

}

I guess I have to load the field configuration entity, but I don't know how.

Make sure you include the following:

use Drupal\Core\Form\FormStateInterface;
use Drupal\field\Entity\FieldConfig;

I'm assuming your function mymodule_form_field_config_edit_form_builder() looks something like this:

/**
 * My module form builder to map values to third party settings.
 */
function mymodule_form_field_config_edit_form_builder($entity_type, FieldConfig $field, &$form, FormStateInterface $form_state) {
  $field->setThirdPartySetting('mymodule', 'help_page_id', $form_state->getValue('help_page_id'));
}

In your widget form alter you'd access the settings with with FieldConfig. This would add it to all field types, you can check $field_name if you want to filter it a bit.

function mymodule_field_widget_form_alter(&$element, \Drupal\Core\Form\FormStateInterface $form_state, $context) {
  $field_name = $context['items']->getName();
  $field = FieldConfig::loadByName('node', 'myentity', $field_name);
  $help_page_id = $field->getThirdPartySetting('mymodule', 'help_page_id');
}


How to apply the page-hiding snippet for Google Optimize? I'm trying to use Google Optimize on a Drupal 8 site through Google Tag Manager.  I have set up the tags in Google Tag Manager through Google's UI and used the Google Tag Manager module to add the snippets to my site on path /test/*.

However, according to the Google Optimize documentation, I should also add a "page-hiding snippet":

<HEAD>
<!-- Page hiding snippet (recommended)  -->
<style>.async-hide { opacity: 0 !important} </style>
<script>(function(a,s,y,n,c,h,i,d,e){s.className+=' '+y;h.start=1*new Date;
h.end=i=function(){s.className=s.className.replace(RegExp(' ?'+y),'')};
(a[n]=a[n]||[]).hide=h;setTimeout(function(){i();h.end=null},c);h.timeout=c;
})(window,document.documentElement,'async-hide','dataLayer',4000,
{'GTM-XXXXXX':true});</script>

There are three requirements here.

The snippet needs to come before the Google Tag Manager tag in the HEAD of the page.
The snippet should only be shown on pages with path /test/*
Inside the snippet, the GTM-XXXXXX needs to be different for dev/staging/live environments.

Is there a way to standard way to set this up?  I assumed that Google Optimize/Analytics is popular enough there would be some information for integrating it with Drupal, but all I found was this DrupalCon 2019 seminar that hasn't happened yet.

Setting up Google Tag Manager was fine, but I'm lost at how to get this final bit in the right place.

Well, since posting my question, there is now a Google Optimize Hide Page module, which provides a code example of how to do this.

There is also a patch to add this functionality to the Google Tag Manager module.


field_group: the save button is now in the wrong place I am using the Field Group module to group my content input fields in my add and edit node pages.  After adding a few groups, I noticed that the Save / Preview buttons moved from the bottom of the page, to a position between my un-grouped content and the groups that I have just created.  How do I move the buttons back to the bottom of the page?

You can change the weight of the Save / preview buttons, and place them at the bottom with form alter.

Weight is used to sort the list of form elements before being output; lower numbers appear before higher numbers.

function YOUR_MODULE_form_alter(&$form, &$form_state, $form_id) {
  // Only change actions container (submit, preview, cancel buttons) weight
  // on node edit forms.
  if (!empty($form['#node_edit_form']) && $form['#node_edit_form'] == TRUE) {
    $form['actions']['#weight'] = 100;
  }
}


Create user permission with specific role? How do I give the "create user profile" permission to a role? I have the manager role and I want to give permission to to it to create an editor or manager user. I don't want to show all the roles on the user create or edit page.

Is there any module for achieving this?

Use the role delegation module

  This module allows site administrators to grant some roles the
  authority to assign selected roles to users, without them needing the
  administer permissions permission.

  For each role, Role Delegation provides a new assign ROLE role
  permission to allow the assignment of that role.

UPDATE:

Simply create two roles Manager and Editor role. When you create this roles, two permissions will appear on the permissions page. Assign Manager role and Editor role. Give the manager the two roles to assign. And also give the user permission to create new users.

And if you login as that user, that user will only be able to create the roles you have assigned to them.

UPDATE 2:

Use the module administer user by role. To stop the manager role from canceling or editing the adminstrator role or any other role you don't want them touching

  This module allows site builders to set up fine-grained permissions
  for allowing users to edit and delete other users — more specific than
  Drupal Core's all-or-nothing 'administer users' permission. It also
  provides and enforces a 'create users' permission.