How to set non Drupal 404 and 403 pages for Drupal? Under Site Information we can provide custom 404 and 403 pages to Drupal, but these need to be created inside Drupal, and non Drupal pages are rejected. (such as myerror/404.html).

Contrib modules like custom error and static 404 also work inside Drupal. Any ideas on how to set an external page as 404 or 403?

If you want to catch errors not handled by Drupal, you can do this using .htaccess:

ErrorDocument 403 /error403.html
ErrorDocument 404 /error404.html
ErrorDocument 500 /error500.html

However, if you want to intercept the errors handled by Drupal, and redirect that to an standalone error page, you should be able to do this with Redirect 404.


Adding Social counter i need to show in my site the social media counter like Facebook fans count ...

its some thing like :-

Share count statistics

Allows your Drupal site to gather statistics on how many times your
content (and other entity types) have been "shared" with
social/sharing services like Twitter, Google+, Facebook, etc. Also
provides an API for other modules to hook into and provide their own
share counts.

Social Stats

This is a statistics module. It provides data from various social media sites. The data which is saved per node. It includes data from:

Facebook : likes count, shares count, comments count & total count.
Twitter : tweets count.
LinkedIn : share count.
Google Plus : plus one count, share count & total count
Total Share Count : total across all available social networks


Exporting nodes using Views Bonus Pack strips all formatting I've exported all of my nodes using Views Bonus Pack Export CSV; it works rather nicely. The only trouble is that it strips all of the formatting on my nodes: no paragraphs, no bold text, nothing. The resulting node is a single block of text.

Is there any way I can work around this?

Yes and no - this restriction is by design in the Views Bonus Pack module because of the difficulties in exporting HTML tags in a CSV format but there is a patch available in this d.o thread.


Theming and overriding taxonomy term/vocabulary page I have a taxonomy vocabulary (Authors) which is used only for the Books content type. What I would like to achieve is to create a file (taxonomy-term--authors.tpl.php) in which I can customize the HTML markup.

Currently when I create the file I can only more static markup instead of modifying the output of the books which contain the specified term.
I also tried to use the mytheme_preprocess_page() and give a template suggestion but when I add content to the file it's not rendering how I would expect. It does not include header/footer styles and other stuff.

I also tried using Views module but the behavior is similar to first point 1.

You can have full control over the taxonomy/term/ID page by intercepting the menu call with hook_menu_alter() and let the content be generated by a custom function.

This allows you to completely customize the taxonomy term page. You can check for a certain vocabulary ("Authors") and have a custom generated page for that vocab and leave the others untouched.

You can have fine grained control over how results are displayed using view modes and templates.

No contributed modules are needed.

Here is an example to be used in a custom module. The custom content is generated using Drupals EntityFieldQuery because it is a lazy and robust way of generating a list of content, but anything goes here.
.

/**
 * * Implements hook_menu_alter().
 */
function YOURMODULE_menu_alter(&$menu) {
  if (isset($menu['taxonomy/term/%taxonomy_term'])) {
    $menu['taxonomy/term/%taxonomy_term']['page callback'] = 'YOURMODULE_taxonomy_term_page';
    $menu['taxonomy/term/%taxonomy_term']['access arguments'] = array(2);
  }
}

/**
 * Callback function for taxonomy/term/%taxonomy_term.
 *
 * @param $taxonomy_term object
 * @return * Themed page for a taxonomy term, specific to the term's vocabulary.
 */
function YOURMODULE_taxonomy_term_page($term) {
  $voc = taxonomy_vocabulary_load($term->vid);
  switch ($voc->machine_name) {

    case 'SOMEVOCUBALARY':

      // here you generate the actual content of the page
      // could be done e.g. with an entityfieldquery as follows

      $query = new EntityFieldQuery();
      $query->entityCondition('entity_type', 'node')
              ->fieldCondition('field_gallery', 'tid', $term->tid)
              ->propertyOrderBy('sticky', 'DESC')
              ->propertyCondition('status', 1);
      $result = $query->execute();
      if (!empty($result['node'])) {
        $build['content']['nodes'] = node_view_multiple(node_load_multiple(array_keys($result['node'])), 'teaser'); // output the node teasers. you can control the markup of the 'teaser' view mode with a template in the theme folder
      } else {
        $build['content']['status']['#markup'] = t('No results found for term ID !tid.', array('!tid' => $term->tid));
      }
      return $build;

    // If the term page is for an other vocabulary then use Drupal's default taxonomy page
    default:
      module_load_include('inc', 'taxonomy', 'taxonomy.pages');
      return taxonomy_term_page($term);
  }
}


Create migration stubs of entities for a multiple value reference field? I need to import a set of authors as part of a content entity. It is an array in a JSON object of id/name. I have a field in Drupal on the content type to be a user reference that accepts unlimited cardinality.

First of all, I don't know these users ahead of time, no way to query it, so I cannot just create a migration dependency and do that first. This seems to be a popular answer, but doesn't fit any of my use cases.

Second, I think you should be able to take the source data and loop each one, and create a user stub if they do not exist already. How do you do that? If the user does not exist yet they should be created, if they do exist, just look up the uid and put it into the target id per row.

This won't be the only spot I run into this, I will have content related to content that I will need to stub too. I won't know the latter content until I run their migrations later.

Is this even possible in D8?

Yes. This use scenario is covered by migration_lookup plugin with its stub_id property and making sure it's referenced migration (in your case, a user migration sourced from the JSON array) has defined all the required fields via the default_value plugin such that migration_lookup can rely on it to stub out a user before the stub_id migration can be run on its own to fill in fields for each referenced entity.


Translating the homepage I am quite new to translation of Drupal and cant figure to translate a the page content on the homepage.

The entire site is translate with the normal translation methods offered by Drupal.

I have translated the blocks on the homepage but the home page content always shows in English. I have already changed the homepage alias to 'home' and both translations aswel.

This should get you on the road:
https://www.drupal.org/node/1216132


Generate fields in content from other content values? I want to generate fields in a content from the values of other content.

Specifically,  I have a list of "players" stored as a content type, and a separate content type called "Events". Events list the rank of each player that participated. On the "player" content, I'd like to be able to display the players wins by searching all the "events" content. Is this possible?

Also, in Views, is it possible to generate a list of all the events a player has won, as well as how many?

Yes, this is possible.  On approach is to use the Entity Reference module.  This allows one field to reference another content type.  With this approach, on your Event content type, you could have a field Winner that is an entity reference to the player(s) who won.

In Views, you could then easily a list of events a player has won by using a contextual filter to limit the wins displayed to those of the player URL.  You could create a second view and attach it to the first to show how many.

These all require a fair bit of configuration and may be hard to set up at first, but it's definitely possible.


Allow Role to change only Moderation State of Content Type without possibility to edit content fields The system we are building has a role Publisher.
It's task is to change  Moderation State of a content (news content_type) without having a possibility to edit an actual content.

In short, the user in role Publisher sees all News created by other users and only has permission to change its state.

In short, how do I allow a user in a role to edit only 1 field and block the rest?

how do I allow a user in a role to edit only 1 field and block the rest?

The standard solution is the Field Permissions module:

  The Field Permissions module allows site administrators to set field-level permissions to edit, view and create fields on any entity.

It provides you with a role-based UI like so:


How to use drush with a specific PHP Instance What drush command can I use to tell drush to use php 5.6 instead of 7.1 which my  site is currently running on.

A million thanks in anticipation.

Drush is just a PHP script at heart so all you need is this:

/path/to/my/php /path/to/my/drush  ...


Drupal 7 - Profiles 2 Module - Share profile data or migration I'm making a platform for 2 types of users:free and paid.

The issue I encounter is the data of the users when updating from one profile to another.

If the user has "free" profile he gets some fields, but when updating the "paid" profile has the same fields+extra.

I first thought of showing the "paid" fields as an extra to the "free" (so the users with "paid" profile have both "free" and "paid" profiles assigned to them), but the issue appears when the user wants to create the profile directly paid as he has no option completing the "free" ones only after he has registered.

Is there any way to make the fields autopopulate (when completing the "field_1" in "free" the data to apear in "field_1" in paid)?
Or to make the data viewable cross multiple profile types?

Conclusion:I need a way for the data to ve visible cross profiles

I think you can use a hook_form_alter() to add visibility conditions on your user_profile_form elements :

Add these kind of attributes on field you want to hide for free users :

'#states' => array(
   'visible' => array(
      ':input[name="field_1"]' => array(
         array('value' => 'paid'),
     ),
   ),
),


How to send an eMail notification when a specific field of a node or user has been changed? When a node (or user profile) is modified, is it possible to send an email notification only when a specified field is modified?

With the node I have no problem, but I cannot get it to work for a specific field.

You can use the Rules module for this. Here are some details about how to do so:

Rules Event: Before saving content.
Rules Condition: Compare the value of the specific field, for both the original value (before editing the field) and the (new) updated value, to verify if they are different.
Rules Condition: Send an eMail (which is typically implemented as a separate "Rules Component" (that is invoked as the Rules Action), whereas you pass the values like node id, current user, maybe author, etc. Within the Rules Component, you then compose the actual eMail (template) that you want to be eMailed. For an example of such a Rules component, have a look at my answer to "How can I set a reminder for a specific user to be triggered on a specific date?" (which includes such component in Rules export format also).

Should be straight forward to "develop" such rule, no (PHP) coding at all involved (only site building using admin UI).


Is Menu-minipanels reliable to make a mega menu I'm going to implement a mega menu in my site and am considering the Menu Minipanels module...

Has anyone tried it? Did you find it easy to use/customize?

What about performance? Panels is often quite a heavy module.

Menu Minipanels looks like a good choice.

An alternative you might want to try for a simple 'mega menu' is the Mega Menus module. Worked well for me, once I had my settings and CSS sorted out. See also this answer for lots more mega menu options...

Finally, regarding performance, since Menu Minipanels uses Panels you will have full control over caching of individual panes within it. The performance burden can therefore be significantly reduced.


Views filter that alternates content types? Does anyone know if it's possible to have a view that alternates between content types? Aka show 1 of content type news and then 1 of content type article repeating?

Not automatically. You could custom code such a solution, maybe an advanced Pager for showing different number of results for each CT.
The usual way to solve this problem is to create different Attachment or Block Displays, each for a different Content Type, show them in the same Region and adjust the CSS styles to make them look like they are part of the same "box".


How can I modify the values in variable table using phpmyadmin? I modify the site name in variable table using phpmyadmin as below.

s:21:"example@example.com";  to  s:21:"example@example.info";

But then when I run cron I get the follwoing message.

  Warning: Cannot modify header information - headers already sent by (output started at /public_html/includes/bootstrap.inc:566) in /public_html/includes/bootstrap.inc on line 739

This is just a examle, but if I change something in variable table using phpmyadmin I always get the same error.

When I modify variable table do I need to modify also other tables at the same time ?

As stated in comments serialized string variable lenght must match the integer prefixed, eg

s:20:"example@example.info";

drush vset is alot better for this kind of adjustements.

That beeing said, for users with drush 4.5 where modifying more complex variables is not available (use variable-set with arrays and objects. Accept JSON via STDIN like cache-set), direct access to database can be handy way to tweak the system. Remember to clear caches after.


SQLSTATE[23000]: Integrity constraint violation I am using Commerce Kickstart 2 to build a store. I have several Feeds importers working well. I duplicated a working importer and updated the mapping for the "product variation" and "product display".

When trying to import, I now receive the following error:

  SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry
  'commerce_product-236' for key 'PRIMARY' SQLSTATE[23000]: Integrity
  constraint violation: 1062 Duplicate entry 'commerce_product-237' for
  key 'PRIMARY' SQLSTATE[23000]: Integrity constraint violation: 1062
  Duplicate entry 'commerce_product-238' for key 'PRIMARY'

I have re-run the working importers and do not have this problem. Reading other posts, it sounds like the importer is trying to import the same item twice, but I don't see why.

I checked the log and see that it isn't grabbing "SKU" from my csv and is assigning it something else. How do I deal with this?

  SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry
  'commerce_product-236' for key 'PRIMARY'
  Original item

array(
  'title' => 'model',
  'brand' => 'brand',
  'product category' => 'prod',
  'primary use' => 'MTB',
  'intended use -alt' => '29+',
  'frame material' => 'Steel',
  'brake type' => 'Disc',
  'rohloff' => 'Yes',
  'rohloff axle plate' => 'OEM',
  'belt compatible' => 'Yes',
  'tensioning method' => 'Pivoting Dropouts',
  'build kit img' => '',
  'body' => 'Customized for Cycle Monkey: Rohloff-optimized designed for trail riding and versatile enough for...',
  'sku' => 'VN001',
  'price' => '738000',
  'dealer price' => '627300',
  'color' => 'Orange',
  'frame size' => 'XS',
  'wheel size' => '29+',
  'build kit' => 'Signature',
  'images' => '',
)

  Entity

(object) array(
  'type' => 'bikes',
  'product_id' => '236',
  'sku' => 'Bikes-236',
  'revision_id' => '233',
  'title' => 'model',
  'uid' => '1',
  'status' => 1,
  'created' => 1463278774,
  'changed' => 1463278774,
  'log' => 'Created by FeedsCommerceProductProcessor',
  'revision_timestamp' => 1463278774,
  'revision_uid' => '1',
  'language' => '',
  'is_new' => TRUE,
)

When setting up this product variation, I selected for the SKU to be automatically generated. In doing so, it was tripping up the feeds importer. Not sure if this was a timing issue, but I reviewed the importer set up and product variation fields for the importers that were working vs. not.

This SKU setting was the only difference. Since this field is unique ID, this seemed like the most likely culprit.

I would appreciate an explanation of why this was triggering an issue, but am happy to be able to move on.


Link to documents from several nodes What would be the best way to set up several nodes so that some of the content is linked to a single document stored on the server?
For example, I want a document that has some official rules on it and display it on several pages by only editing the source document.

If you want to display a common piece of content on all the pages, you can  create a block with the common content, and display that block in the content region of the required pages.

Just go to /admin/structure/block and position the block before or after the Main page content block, and set it to only display on the required pages.


How do I print the node title from the object? How do I print the title of a node entity? Printing the node object, I get this output.

stdClass Object
(
    [__CLASS__] => Drupal\node\Entity\Node
    [in_preview] =>
    [values] => Array
        (
            [vid] => Array
                (
                    [x-default] => 2
                )

            [nid] => Array
                (
                    [x-default] => 2
                )

            [type] => Array
                (
                    [x-default] => common
                )

            [title] => Array
                (
                    [x-default] => Terms of Use
                )
}

Are you in a twig template rendering a node? If so:

{{ label }} or {{ node.label }}

Via code in PHP:

$node->label(); via label() and/or also $node->getTitle(); via getTitle()


What permission gives users access to the "additional settings" options (author, etc.)? Which permission should I give to users to allow them to change the author of node content?

Administer nodes is the permission for changing the author.


Why can't I find the parent term of a tag when a node is being inserted? I'm following another question I asked, How can I get the parent term in a taxonomy with a hierarchy? and I can get the parent term when I am on the view operation, but not when I'm on the insert operation. var_dump() shows the $terms variable, but NULL for $pterms. Here is my code being called in hook_nodeapi('insert').

  foreach ($node->taxonomy as $term) {
    $terms[] = $term;
  }
  $tid = $terms[0]->tid;
  $parents = taxonomy_get_parents($tid);
  foreach ($parents as $term) {
    $pterms[] = $term;
  }

Did you try taxonomy_get_parents_all()?

$parents = taxonomy_get_parents_all($tid);
  foreach ($parents as $term) {
    $pterms[] = $term->name;
  }


Drush 6 on Windows not doing anything I've installed Drush 6 on Windows using this installation package and have ensured that the following is in my PATH variable:

  C:\ProgramData\Drush\;C:\Program Files (x86)\Drush\GnuWin32\bin;C:\Program Files (x86)\Drush\Php

When I open the Drush Command Prompt and type "drush status", nothing happens. The cursor moves a line down and blinks as if it's working on executing the command, but nothing is shown, and the process never ends. I have to Cntl+C to get out of it.

The same thing happens in Git Bash. No error messages, nothing. Just the ever blinking cursor. Any idea what's happening or how to fix it? Thanks in advance!

Figured it out. It was a problem with the reverse-proxy we're using. I installed a different version of drush in cygwin and tried to run it. Here it paused like I described above, but after a minute showed me this error:

  Drush needs a copy of the PEAR Console_Table library in order to function, and the attempt to download this file automatically failed.
  To continue you will need to download the 1.1.3 package from http://pear.php.net/package/Console_Table, extract it into C:\cygwin64\usr\local\src\drush/lib directory, such that Table.php exists at C:\cygwin64\usr\local\src\drush/lib/Console_Table-1.1.3/Table.php.

I installed this package manually and now things are working. I just didn't realize Drush was trying to download extra content.


Views, add field value as class to list element I have a content field called Featured which is an list integer checkbox.

When using Views to display a list of this content, I would like to add a css class to the item wrapper when that value is 1 like so:

<li class="views-row views-row-1 views-row-odd views-row-first featured">

I suspect editing the views row template would be one option, although I do not know how to achieve this, and since this is the only change I need to make, is there an easier way?

The question is a bit old, but i was looking for the same.
The answer is for drupal 7 / views 3.5, and works fine on Drupal Views 8 || 9 as well..
You can use some field replacement patterns when specifying the classname for the row (in the view edit : Format / Settings / Row Class )
To do so, on the same settings page you may have to check the box 'force using fields'
You then have to make sure the field you want to use is added to the fields section of the view edit
To know what pattern you can use, click on the field in the fields section and go to 'rewrite results' / 'rewrite the output of this field', there is a 'replacement patterns' block that will show you the available patterns.
hope that help, I'm still stuck though by the fact that the string you will get is not class friendly and may contain spaces.


content_extra_field_weight() function in Drupal 7 I am porting a module to Drupal 6. I came across this function content_extra_field_weight(), what is the similar function in Drupal 7 for content_extra_field_weight()?

Invoke hook_field_extra_fields(), pass the result to  hook_field_extra_fields_alter() and look for weight keys in the result.


How to remove markup from file field I have added a file field in views and when displaying it has some markup like this

 6783c11f-0b05-49e3-a494-ca68d2e6c23b-2060x1366.jpeg

Configure

  Edit

 Delete

While all I need is

How can I remove this markup. Can I use views-view-field-field_name.tpl.php. Only line this file contains is print $output. How can i use this file to remove markup. Or does any preprocess hook helps

You can use theme layer to override the views output , if you want only theme a certain field you can use this template file :views-view-field.tpl.php

for more information check this tutorial : Theming a single field in a Views


Converted CSS/HTML theme to D7, .js files ignores integrated jQuery and works only with jQuery imported via .info I got a basic static CSS/HTML theme which is using some .js like jcarousellite.js and it has a jquery file together which is jquery-1.4.2.min.js

So I import that jcarousellite.js via theme's .info:

scripts[] = js/jcarousellite.js

Then there is some inline script which goes with that template, so I pasted that to my html.tpl.php

    $(function() {
         $(".carousel").jCarouselLite({
                    btnNext: ".next",
                    btnPrev: ".prev"
         });
});

Now, to make it all work, it needs jQuery. So since D7 loads jQuery by default from its core (and it does load it and current version is 1.4.4 that comes with Drupal 7.21) I understand that the jquery-1.4.2.min.js which comes together with static template is not needed right? So I do not add it to my .info and after flushing caches and everything, it loads my jcarousellite.js and it loads inline .js, but it doesn't work.

If I load that jquery-1.4.2.min.js via .info then all .js is working on the website. So what I am missing? How to make it work without importing that older jquery library via .info and using the jQuery from Drupal's core? Now both and core jQuery and that custom jQuery libraries are loaded at same time.

add a anther js file via theme's .info;

scripts[] = js/mycustomscript.js

dont add your inline script in html.tpl.php , add it in mycustomscript.js file like

(function ($) {

  Drupal.behaviors.exampletheme = {
    attach: function (context, settings) {
      $(".carousel").jCarouselLite({
                btnNext: ".next",
                btnPrev: ".prev"
     });
    }
  };

})(jQuery);


Manual Ubercart Views Taxonomy Order (D6) Client wants the parent taxonomy view page to be ordered in a manual arrangement just based on his belief of which products are most popular (this isn't a field in the database; nor do we have this information in the database).

Is there anyway to order the view page based on a weight?

Ended up using taxonomy manager: http://drupal.org/project/taxonomy_manager

Allows you to setup weights for Taxonomy Terms easily and quickly.

I then had to adjust the view to sort terms by Taxonomy weights in order to order the terms accordingly in my views.


Count of users who are logged in per day I searched to find a way to display the number of users who are logged in per day.

I want to display a chart using views for last month to show the login statistics of the website.

Any suggestion?

Well in other to achieve this, you will be using a combination of modules.

Use the counter module for gathering that kind of statistics. Another option is to enable the statistics module in Drupal core

  Counter module counts how many visitors on your website. This module
  provides real time counting. All data saved to database.

And with google chart tools and the views module create a chart

  Display live data on your site using Google Chart Tools Google Chart
  Tools module provides a simple API to Build custom interactive SVG
  charts. The module contain an example module which demonstrate how
  this module can be use.


How to set block visibility by role in Drupal 8 In Drupal 7 it was easy to set block visibility by role in "block configuration" page.

How it can be done in Drupal 8?

I found a discussion about this here:
https://www.drupal.org/project/drupal/issues/2952962

And solution in 28 worked for me:
https://www.drupal.org/project/drupal/issues/2952962#comment-12549257


Why does drupal_set_message function encode all html tags? Since I updated to Drupal 7.53 the function drupal_set_message does not work anymore as expected, as it encodes or strips all HTML tags.
For example the code:

drupal_set_message("<b>This is important,</b> this not.");

used to print:

  This is important, this not

But since the update it prints:

  This is important, this not.

I could not find any change to that functions mentioned in the release messages. Can anybody explain to me what has happened?

By the way, I am using the Bootstrap theme, what was updates as well. Maybe the Theme is to blame?

The messages added with drupal_set_message() are rendered in the page.tpl.php template file of the theme, if the file it is using one; otherwise, they are rendered through the template file defined from the System module.

By default, the System module and the core themes use the following code to print them.

<?php print $messages; ?>

There could be some HTML markup to wrap them, as in the Bartik theme, but that should not have the effect you are seeing.

  <?php if ($messages): ?>

      <?php print $messages; ?>

  <?php endif; ?>

The way those messages are printed has not been changed from recent updates to Drupal core, so I would check the used theme and any installed (and enabled) modules to find out what is happening.

Apart from looking the page.tpl.php template file used from your theme, you should check the implementation of theme_status_messages() (which is normally called from template_preprocess_page()) done from the theme you are using, any preprocess function for theme_status_messages() (hook_preprocess_status_messages()), and any preprocess function used for the page.tpl.php template file (hook_preprocess_page()). Keep in mind that preprocess functions can be implemented by any module, or the theme used for the rendered page.

As side note, it is usually better to use t() and its placeholders, with drupal_set_message().

drupal_set_message(t("!important. This not.", array('!important' => 'This is important')));

If you don't need to translate the message (e.g. because it is a debugging message), you could use [format_string()][5].

drupal_set_message(format_string("!important. This not.", array('!important' => 'This is important')));


How to change node add form I'm wondering how I can change the layout of the node add form in Drupal 8. in Drupal 7 I worked with Panopoly and could overwrite the url in Page Manager and add a Panels Variant. I thought it would work the same way in Drupal 8 but in the Panels variant I cannot add the form items. Thus I get a blank page on activating the variant.

Any ideas?

In drupal 8 there are new display modes. They are not only to view the node (view mode). They are also for the node add form (form mode).

For example to change the node add form of the content type article you go to:

/admin/structure/types/manage/article/form-display

Here you can select which fields you want to show and how they are formatted (field widgets). You can make more adjustments with php in form alter hooks or with twig in templates.

By default you have one form mode for each content type. You can create more if you go to the admin interface of display modes:

/admin/structure/display-modes

If you want to use different form modes for different users you can use this module:

Form mode control

Readme:

  WHAT FOR ?

  Form Mode Control allows you to use the form modes for any bundle /
  entity, per role and for edition / modification. Which means using
  different forms (fields, order, widgets, etc.) for different roles.

  HOW TO USE IT ?

  A - DEFAULT FORM MODES

  1 - You must at first add form mode for content entities. Ex. : go to
  "www.your-site.com/admin/structure/display-modes/form/add" to add a
  new form mode.

  2 - Activate the form mode for the related bundle of the right entity.
  Ex.if we want to activate a form mode named Super 2 (machine name =
  super_2) for an article (entity type : Node, Bundle : Article). Go to
  www.your-site.com/admin/structure/types/manage/article/form-display
  and activate it.

  3 - Go to www.your-site.com/admin/people/permissions, a section named
  Form modes control was added for all form modes activated (and only
  activated), So , configure all permissions and give roles permissions
  to access form modes. NB, the permission Access all form modes allow
  you to access to all form modes linked to bundle and entity type.

  4 -  Then configure on the Form mode control administration page
  (www.your-site.com/admin/structure/display-modes/form/config-form-modes)
  and give for each role a default form modes for creation / edition (of
  course, each role must have access to the form mode).    B - ACCESS
  DIRECTLY FORM MODES    You can also use it with a simple extra query in
  the URL (?display=machine_name_of_the_form_mode) if the role is
  allowed to see it. Of course, the user must have the right permission
  for it.        Ex. : if you want to access to super_2, go
  www.your-site.com/node/add/article?display=super_2.


Help with a custom field widget I am trying to create a custom field widget to be used by the taxonomy term reference field.
Basically I would like to select which taxonomy terms can be shown in the select list.

So far I am able to register the widget along with a custom settings page but when I use the widget on a node edit form. The values are not saved.

Here is the code below I have implemented a hook_widget_info hook_widget_settings_form and hook_field_widget_form from my understanding those three hooks should be enough

function my_module_field_widget_info() {
  return array(
    'my_module_term_reference_limit' => array(
      'label' => t('my module Term reference select'),
      'field types' => array('taxonomy_term_reference'),
      'description' => t('Allows you to limit the number of terms allowed in a select list'),
    ),
    'settings' => array(
        'terms' => array(),
      ),
  );
}

function my_module_utils_field_widget_settings_form($field, $instance) {
  $widget = $instance['widget'];
  $settings = $widget['settings'];
  $vocabulary = taxonomy_vocabulary_machine_name_load($field['settings']['allowed_values'][0]['vocabulary']);
  $type = $instance['widget']['type'];
  $terms = taxonomy_get_tree($vocabulary->vid);
  $options = array();
  $default_value = array();

  foreach($terms as $key => $term){
    $options[$term->name] = t($term->name);
  }

  $form = array();
  if($instance['widget']['type'] == 'my_module_term_reference_limit') {
    $form['terms'] = array(
      '#type' => 'checkboxes',
      '#title' => t('My module terms'),
      '#options' => $options,

      '#description' => t('Select compatible templates'),
  );
}
  return $form;
}

function my_module_field_widget_form(&$form, &$form_state, $field, $instance, $langcode, $items, $delta, $element) {
  $settings = $instance['widget']['settings'];

 $type = $instance['widget']['type'];

  $options = array();
  foreach($settings['terms'] as $key => $value){
    if($value !== 0){
     $options[$value] = t($value);
   }
 }

$widget = $element;

  switch ($instance['widget']['type']) {
    case 'ii_term_reference_limit':
      $field['cardinality'] = 1;
      $widget += array(
       '#title' => t('my term select box'),
       '#type' => 'select' ,
       '#options' => $options,

  );
      break;
  }

  $element +=  $widget;
  return $element;

}

Thank you for your help

Looks like you're just missing the column name for the field (tid).

Just before the return of the widget form function, try changing

$element +=  $widget;

to

$element['tid'] = $widget;


Dependent date_popup maxDate In a profile2 profile, I want to change the maxDate of a date field depending on the selected value of gender field.

I am using a custom module implementing the hook_form_profile2_edit_PROFILE_TYPE_form_alter() and loading JavaScript. The date field uses the datepicker widget and the gender field is set as radios.

When the gender is selected as female, the maxDate should be set to "-18y". When selected as male, the maxDate should be set to "-21y".

Using the JavaScript, when a gender is selected the first time, the maxDate is set correctly. But, when the gender is changed, the maxDate does not change. It remains set at the first value. When the gender is changed, the maxDate should change too.

Here is my JavaScript:

(function($){
Drupal.behaviors.meh_profile = {
    attach: function (context, settings) {
        $('input:radio[name="profile_main[field_profile_gender][und]"]', context).change(function(){
            var genderVal = $('input:radio[name="profile_main[field_profile_gender][und]"]:checked').val();

            if (genderVal == Drupal.settings.gender_options.gender_female) {
                for (var id in Drupal.settings.datePopup) {
                    Drupal.settings.datePopup[id].settings.maxDate = '-18y';
                }
            } // if female

            if (genderVal == Drupal.settings.gender_options.gender_male) {
                for (var id in Drupal.settings.datePopup) {
                    Drupal.settings.datePopup[id].settings.maxDate = '-21y';
                }
            } // if male

        }); // gender change handler
    }
};
})(jQuery);

What am I missing?

Solved!

Instead of trying to change the maxDate using Drupal.settings.datePopup[id].settings, pass it as options to datepicker using the jQuery Datepicker syntax $( ".selector" ).datepicker( "option", { name: value } );

Here is the solved JavaScript code:

(function($){
Drupal.behaviors.meh_profile = {
attach: function (context, settings) {
    $('#edit-profile-main-field-profile-date-of-birth-und-0-value-datepicker-popup-0').attr('disabled', 'disabled');
    $('input:radio[name="profile_main[field_profile_gender][und]"]', context).change(function(){
        var genderVal = $('input:radio[name="profile_main[field_profile_gender][und]"]:checked').val();
        if (genderVal == Drupal.settings.gender_options.gender_female) {
            $("#edit-profile-main-field-profile-date-of-birth-und-0-value-datepicker-popup-0").val('').removeAttr('disabled').removeClass('hasDatepicker').datepicker({
                changeMonth: true,
                changeYear: true,
                yearRange: '-75:-18',
                maxDate: '-18y'
            });
        } // if female
        if (genderVal == Drupal.settings.gender_options.gender_male) {
            $("#edit-profile-main-field-profile-date-of-birth-und-0-value-datepicker-popup-0").val('').removeAttr('disabled').removeClass('hasDatepicker').datepicker({
                changeMonth: true,
                changeYear: true,
                yearRange: '-75:-21',
                maxDate: '-21y'
            });
        } // if male
    }); // gender change handler
}
};
})(jQuery);


How can I print something only when cck field has certain value on node.tpl.php? I need to print something conditionally in my node.tpl.php depending on the cck value of a field on my content type.

For example, if field_color has "red" or "blue", then print "It has color" and if it has other values print empty text.

The following should work:

if (isset($node->field_color[0]['value'])) {
  //If you want the field value to be displayed
  print $node->field_color[0]['value'];
  //If you want some custom text to be displayed
  print 'It has colour';
}
else {
  print 'Empty Text';
}

Or with ternary operators:

print (!empty($node->field_color[0]['value']) ? $node->field_color[0]['value'] : 'Empty text';

You'll probably either want to put in some logic to make sure the field exists though, or create a node-TYPE.tpl.php for your specific content type.

EDIT

This should sort out your red or blue issue:

if (isset($node->field_color[0]['value'])) {

  $colour_value = $node->field_color[0]['value'];

  if ($colour_value == 'red' || $colour_value == 'blue') {
    $colour = $colour_value;
  }
}

print (isset($colour)) ? $colour : t('Empty Text');

I've only put the field value into a variable to save space - you don't have to do this if you don't want to :-)


Wildcards for matching path I am using the Parsely module and I want Parsely to ignore certain paths. I achieve this by setting the paths to be ignored field in parsely's settings page. I am able to use the * wildcard, and I need to know if there are other wildcards I can use to match paths.
Where I can find a list with wildcards used to match paths?

I ended up looking at the function drupal_match_path which is described here: https://api.drupal.org/api/drupal/includes!path.inc/function/drupal_match_path/7 ; it seems that it only replaces newlines,  and asterisks. Am I wrong? Are these the only "wildcards" available?

Unfortunately, the short answer is: No, you cannot use other wildcards.

The reason is the use of preg_quote inside drupal_match_path, any regex wildcards you add to your pattern will be escaped.

P.S.: Very cool question, had to take a good look at this.


Create block content programmatically I've created a custom block type.

I want to create a block with 19 translations programmatically.
I've seen that you can use Block::create() method...for which I can neither find proper documentation nor examples.
Could anyone provide an example?

Fyi my code is:

Block::create([
  'id' => 'my_header_dk',
  'settings' => [
    'id' => 'my_header',
    'label' => 'My header',
    'label_display' => FALSE,
    'provider' => 'my_block',
    'status' => TRUE,
    'langcode' = 'da',
    'icon' => [
      33,
     ],
    'header' => 'This is the header text',
    'link_text' => 'Click here',
    'visibility' => [],
    'region' => 'header',
    'plugin' => 'my_header',
    'theme' => 'my_theme',
    'status' => TRUE,
 ])->save();

If you want to create content for the custom block type basic:

use Drupal\block_content\Entity\BlockContent;

$block = BlockContent::create([
  'info' => 'block 1',
  'type' => 'basic',
  'langcode' => 'en',
]);
$block->save();

And add a french translation:

$french_block = $block->addTranslation('fr', ['info' => 'bloc 1']);
$french_block->save();

Custom block types are content, not configuration. See this answer https://drupal.stackexchange.com/a/218244/47547


hook_simplenews_scheduler_edition_node_alter does not work as expected Using simplenews scheduler 7.x-1.0-beta2.  I created a template newsletter and scheduled it to be sent daily.

I created a simple function to insert a dynamic value into the body of the newsletter edition that is created from the source template:

function hook_simplenews_scheduler_edition_node_alter($edition_node, $scheduler_node) {
  $edition_node->body['und'][0]['value'] = 'my new value';
}

My expectation was that when a newsletter edition is created from my newsletter template ($scheduler_node), the body of the new edition would say 'my new value'.

What actually happens is that the email sent to the newsletter subscribers says 'my new value', but the body of the newsletter edition node that is physically created still contains the body from the template.

Any suggestions?

function hook_simplenews_scheduler_edition_node_alter(&$edition_node, $scheduler_node) {

    $my_arg = '-1day';
    $edition_node->body['und'][0]['value'] = views_embed_view('tracker03', 'page', $my_arg);
    return $edition_node;

}

This does the trick.


Changing color of form html with Javascript I have some custom HTML and CSS added to a form module I've created. It looks fine; the css is styling it correctly with a drupal_add_css() stylesheet. But I also want to add some Javascript using drupal_add_js() so that when a user is on the first page of the form it changes the text color in the HTML I set up. But I can't get it to work!

Here's the Javascript in step-one.js:

document.getElementById("step-one").style.color = "#769EDD";

Here's the code it will be changing:

    $form['progress bar'] = array(
        '#title' => t('Module Tool'),
        '#prefix' => '

Experience Level  >
Primary Role  >
Topics of Interest  >
Recommendations
',
    );

And I'm trying to add the javascript call ABOVE the previous code, right after I do the drupal_add_css() call (which works). Note that this is all within my module_form() function. Here's the relevant code:

function modulename_form($form, &$form_state) {
      drupal_add_css(drupal_get_path('module', 'modulename') .'/modulename.css');
      drupal_add_js(drupal_get_path('module', 'modulename') .'/step-one.js');
      // more code around building the form itself...until eventually
      I get to my $form['progress bar'] = array( // see code above.

Any ideas why this might not be working?

You can try like this (thats's step-one.js file):

(function ($) {
  Drupal.behaviors.yourModule = {
    attach: function (context, settings) {
      $('#step-one').css('color', '#769edd');
    }
  };
})(jQuery);


Custom view format, parse a text value I think this is a pretty easy thing to do once you figure it out once, but I'm struggling to do the following:

I have a content type called YouTube video. It accepts a text field "URL" that is the full video URL (or alternatively just the ending video ID)

I want the displayed content to be an embedded video. How can I set the default embed code and then have a variable to swap for the ID?

Edit: Been poking all day, still can't figure this one out. I'm from a Wordpress background and this would be a simple ~3 minute addition to functions.php. Can someone point me in the right direction?

If you want the fields approach, try looking at the module http://drupal.org/project/emfield
If you want to do it yourself in code, there are different approaches, the most basic one being adding a node template for your content type and adding your embed code there. Look at drupal.org for basic information about addding templates.


Set the allowed options of a selectlist CCK field? I have some CCK select list fields which I do not define allowed values for.

I need to set the options available using information available to me when the form is being loaded.

I tried setting the values in the node-form.tpl file but I get:

"An illegal choice has been detected. Please contact the site administrator."

for each field I set the allowed values for in this way.

What's the proper way to do this?

check this resource http://drupal.org/node/726282 you will find a very useful description about CCK fields when form is loaded, and his relation with the function to alter forms, called hook_form_alter(). In few words, you must also use an after_build() function.


How to create a workflow state field programmatically? I have my custom entity created, workflow module installed and now I would like to create a workflow state field on my entity. I know I have to do it in the src/Entity/MyEntity.php class in my module, but where do I get all those field settings for this particular field type for the BaseFieldDefinition::create method?

I have somehow managed to put this field definition in my entity class:

$field['workflow'] = BaseFieldDefinition::create('workflow')
  ->setLabel(t('Workflow'))
  ->setDescription('Workflow entity')
  ->setSetting('workflow_type', 'test_workflow');

But it does not add a field to my entity. Thanks.

EDIT: test_workflow is existing workflow.

You should do it with entity_reference and target_type to be workflow, it should work like that. And with handler_settings you can set your type of workflow.


Make quiz link look like a button or apply css style I have rendered the quiz entity teaser display into a content type and would like to know how to apply a css class to the "download certificate" and "take quiz" links.

Usually this would be done by editing the content type display, and in this case, the teaser for the quiz. The only options I am given is to show or hide the link.

Furthermore, I can't find the settings for the "download certificate" link, which doesn't show up in the display settings at all. They are called buttons but do not look like buttons.

What I've tried:

looking for the settings where I can apply CSS to these buttons.
used Chrome browser inspection tool to see that there is a style class already being applied to a href, called quiz-start-link; I tried creating some custom css for both a.quiz-start-link and just .quiz-start-link to no avail.

Would I just need to figure out how to harness quiz-start-link or can I edit this to apply my own?

I just needed to apply custom CSS to a.quiz-start-link and .certificate-link respectively and then it worked.

I also learned about templates and this SE Post was helpful for creating a custom template for quizzes, so I could change the class that was being used like I originally wanted to: How to theme a quiz in D7?


How can I get the content of a mini panel that is limited to admin-only access using a scheduled rules component? I'm using Rules to e-mail myself the content of a Mini Panel, which contains several views that are restricted to admin-only access.

I am using a component (Action set) that consists of two actions:

Send e-mail
Schedule component evaluation (re-schedule the same component to be evaluated the following day)

For Send e-mail, the body of my message looks like this (based on this code):

<?php $block = module_invoke('panels_mini', 'block_view', 'admin_user_role_statistics'); print $block['content']; ?>

When I first triggered this component (using a rule that I created to trigger the component for the first time by viewing a user profile), I was logged in as an administrator, so the e-mail I received shows all of the content of the mini panel as I expected.  However, the following day, when the scheduled component was evaluated, the body of the e-mail message was blank, presumably because it was not sent by an admin user.

I re-enabled the rule to trigger the component and tried it as a non-admin user: the message body was empty.  I then tried it as an administrator: the message had the full content.

So, what can I do to make sure the component is evaluated as if triggered by an admin user?

The problem seems to be an anonymous user triggering the component and since you want an admin user to run the component, you will have to impersonate the admin user.

Try this code inside your components to impersonate the admin user :

global $user;
// Save the current user
$current_user = $user;
// Save user session
$current_session = drupal_save_session();
// From now on we don't want to save the session, since it would be unsafe
drupal_save_session(FALSE);
// We impersonate admin user
$user = user_load(1);
// Do wathever needs to be done.
// ...
// Now let's restore the triggering user and session.
$user = $current_user;
drupal_save_session($current_session);


How to disable a troublesome module that causes admin/modules to not list all modules? I ran into an unexpected situation after installing the 7.x-2.1 of the Multilang - Embed multiple translations inside a unique node or block module. I was actually experimenting with that module to better understand the question about Why is the recommended release of my module not proposed in Drupal updates?

After I finished experimenting with that (version of that) module, I wanted to disable it again, via the typical admin/modules link. The link still worked (so no WSOD situation like you may get if you run into memory problems), but not even 1 module (enabled or disabled) was shown in my module list. So no way to "disable" that Multilang module from there.

How can I disable this module without using the admin/modules link (since there it doesn't show up)?

I was lucky enough to have Drush available. So by simply using drush dis multilang, the module got disabled. And Eureca ... the link at admin/modules started to work again.
Even though I have not had to use another approach, this would have been my plan-b: disable the Multilang module manually in the database, via an SQL command like so:

UPDATE system SET status='0' WHERE name='multilang';

or as a variation, using PhpMyAdmin (if that's available).
If for whatever reason plan-b would not have worked either, you could consider deleting the entire module folder (for module Multilang) in the modules directory where that module got installed. That would, pretty sure, have "killed" the trouble module also. Though it would have left the module's row in the system table in some bad shape (to be repaired afterwards, probably with something like the "Registry Rebuild" module.

However, as pointed out by Molot also (merci! aka thanks!), deleting files is problematic. Because it prevents you from ever running uninstall on a module. And Registry Rebuild will probably not fix that. So think twice before using this plan-c ...


Trying to figure out which view to edit! I have a main page of my site that has views and blocks. There is a photo view which I'm trying to figure out which one it is (drupal 6). I need to edit that view to change the sort order.

However (in admin mode) when I hover the cursor over the block of photos, the "Edit View" comes up and then when I move the cursor a bit upwards to edit it, the link disappears! So it's driving me mad which view to edit.

I have then gone to "site building"/ views / list and then I've changed the sort order of every view that has been named by that title but still the sort order on the main page doesn't change (i want to add sticky sort order).

So can anyone help by letting me know how to catch the edit view link that disappears when I hover the cursor around it? Thanks!

You can perhaps figure out what View it is from the id and class names on the containing markup which should tell you the view and the view display to edit. You can also change the theme to a core theme like Garland to get around whatever CSS issue you're having to get into the edit mode so you can identify the view.


How do I set field mapping in the Feeds module for Drupal 8? I'm trying to use Feeds 8.x-3.x-dev on Drupal 8.4. I've created a feed type (eg. News Feed) and I'm trying to set the field mappings, but I get an empty list with no way to add anything to it:

The target content type is a custom one, that's similar to Articles, but it also contains some extra fields (such as the source of the feed).
If I add a feed URL to this type and try to import it, it obviously fails:

Test Source has been created.
Warning message
An entity of type "content" failed to validate with the following errors:
Title (title): This value should not be null.
News GUID (field_news_guid): This value should not be null.
News Link (field_news_link): This value should not be null.
News Source (field_news_source): This value should not be null.
Please check your mappings.
Error message
Failed importing 20 News.

Most tutorials and references online talk about the module for Drupal 7, which looks significantly different from what I see.
Is there something I'm missing or is this mapping feature currently broken?
Edit: I am aware of the pre-release status of this module, but I'm trying to evaluate it to see what works and what doesn't. Downgrading to Drupal 7 isn't an option, so I have to make do with what I have for 8. If not Feeds, is there any alternative for a simple RSS/Atom feed import? Aggregator would work just fine for my needs, but how do I get it to import the contents as nodes?
Edit: I decided to downgrade to Drupal 7.

First, select a target to map to.

This will result into a list of sources to appear. Select one of these sources.

Notes:

The UI for CSV parser is still incomplete. See https://www.drupal.org/node/2669974
If the sources list does not appear after selecting a target, you may be facing javascript issues. In this case, check with a debugger which scripts fails. In D7, the jQuery Update module (or how that modules was configured) sometimes was the culprit.
If there are no targets appearing, try to rebuild caches.
Currently there is a bug with updating items if the target 'Feeds item' is not in the list. Be sure to map to that target if you not only want to insert new items, but also update existing ones. See https://www.drupal.org/node/2857692.


How to disable "publish" content for a particular role? I created a role called writer who should have the ability to create content, but not be allowed to publish it.  A person with the admin role can review the content then publish it.

Also, if a writer edits existing content, it can not be immediately published to the website.  Only an admin can publish it after review.  Until then, the old version is displayed.

How do i disable the ability to publish for a person with the writer role?

Just unchecked publish checkbox on content type setting page and hide this field with CSS if user has writer role or remove it programmatically on the same condition with hook_form_alter


What is correct destination for fid in destination image field? I am attempting to do a simple migration of an image from a D6 CCK file field to a D8 file field, and for some reason it's not working. Following best practices, I've run a separate file migration - named 'file' - and so now I want to just migrate the fid reference during the node migration. In my blog node migration, I have this in the process section:

field_image:
  plugin: d6_cck_file
  source: field_thumbnail
  migration: file

where field_image is the name of the D8 file field, and field_thumbnail is the source D6 field.

The problem is that the image reference is not being migrated to the D8 field (field_image). In going through the code with my debugger, I'm noticing that the CckFile::transform() method is not being called at all (although __construct() and create() methods are being called), and that's where the finding of the fid in the file migration happens.

Is there something I'm missing in my config? It seems pretty straightforward, so I'm not sure what I'm missing.

Thanks.

UPDATE: After doing some debugging, I found that when the process gets to this line in MigratExecutable:processRow() where the $destination is field_image:

$value = $plugin->transform($value, $this, $row, $destination);

the value of $plugin->id is get, not d6_cck_file. I can't understand why, since the plugin name is clearly defined as d6_cck_file in the migration config.

UPDATE 2: After doing some reading, I'm thinking I might need to use the iterator plugin, since both my source and destination fields are multi-value fields (i.e. they are allowed to have multiple values, even if they actually don't).  So I'm trying this:

  field_image:
    plugin: iterator
    source: field_thumbnail
    process:
      field_image_target_id:
        plugin: migration
        migration: file
        source: fid

but that's not getting it either. Still debugging...

UPDATE 3: So with this most recent setup, my destination id is being found correctly, but the issue seems to be the destination. field_image_target_id is the name of the db field where the value is stored, but apparently not the destination value to use. I also tried 'field_image/target_id, but that didn't work, either. What would be the correct destination?

So the final solution that worked for this is as follows:

field_image:
  plugin: iterator
  source: field_thumbnail
  process:
    target_id:
      plugin: migration
      migration: file
      source: fid
    alt: alt
    title: title
    height: height
    width: width

As explained to me by @mikeryan, the iterator plugin allows you to iterate over multiple values which have subfields, and map the subfields in the internal process pipeline the way fields are at the top level. In this case, I just used the migration plugin to get the target fid from the file migration, and this puts it in the field_image_target_id column in node__field_image table.


Where can we store 3rd party application passwords? I've written a Drupal 8 custom module that communicates with 3rd party APIs which need authentication. I have an application username and password for those APIs which I need to store somewhere. I can think of the following two ways to achieve that.

I can store the credentials in the Drupal database as configuration. But the password then becomes visible in plain text to all the site admins, and we don't want all the site admins to see the password (I also am aware that we can set up roles and permissions, so we can disable access to a particular configuration for all the site admins, but still the password is saved in plain text in the database).
I can also store the credentials in the settings.php file.

Is there any other way we can store these credentials? What is the best, secure and preferred way to store 3rd party account credentials in Drupal 8?

Yes, if you're looking for a Drupal-centric solution, the Key module might provide what you're looking for. It supports pulling your stored secrets from a few different locations:

Config
File
Environment Variable
3rd party services

As far a best, there's really no one-size-fits-all answer. It depends on your data storage requirements and what you're protecting (e.g. an API key for a medical records REST API should have heavy restrictions whereas a Slack webhook is pretty low risk).

If you're wanting a scalable solution, you might want to consider one of the many 3rd party services that provide secret management.


Set disabled cache but it's not working I'm a newbie in Drupal site development and I'm using Drupal 9.x. In directory web/sites/default I have 2 files:
settings.php
if (file_exists($app_root . '/' . $site_path . '/settings.local.php')) {
  include $app_root . '/' . $site_path . '/settings.local.php';
}

settings.local.php
<?php

assert_options(ASSERT_ACTIVE, TRUE);
\Drupal\Component\Assertion\Handle::register();

$settings['container_yamls'][] = DRUPAL_ROOT . '/sites/development.services.yml';
$config['system.logging']['error_level'] = 'verbose';
$config['system.performance']['css']['preprocess'] = FALSE;
$config['system.performance']['js']['preprocess'] = FALSE;
$settings['cache']['bins']['render'] = 'cache.backend.null';
$settings['cache']['bins']['discovery_migration'] = 'cache.backend.memory';
$settings['cache']['bins']['page'] = 'cache.backend.null';
$settings['cache']['bins']['dynamic_page_cache'] = 'cache.backend.null';
$settings['rebuild_access'] = TRUE;
$settings['skip_permissions_hardening'] = TRUE;
?>

I think this settings are okay but everytime I modify template and reload page it doesnt change, I must go to admin and then clear cache. Please tell me how do I fix it?

In /sites/default/settings.local.php make sure you have
$settings['container_yamls'][] = DRUPAL_ROOT . '/sites/development.services.yml';

You need to go to /sites/development.services.yml and turn off Twig's cache by adding
Parameters:
    twig.config: { debug: true, auto_reload: true, cache: false }

This is what mine looks like:
# Local development services.
#
# To activate this feature, follow the instructions at the top of the
# 'example.settings.local.php' file, which sits next to this file.
parameters:
    twig.config: { debug: true, auto_reload: true, cache: false }
    http.response.debug_cacheability_headers: true
services:
  cache.backend.null:
    class: Drupal\Core\Cache\NullBackendFactory

For more info, see Disable Drupal 8 caching during development


Why am I failing to programmatically create a webform in hook_entity_insert? I need to create a webform programmatically when a node is created.
I refer and follow https://www.drupal.org/project/webform/issues/3038697
Here are the steps to reproduce:

Create new module via console, and install module.

In module.module add:
use Drupal\Core\Entity\EntityInterface;
use Drupal\Core\Serialization\Yaml;
use Drupal\webform\Entity\Webform;

Add hook with webform create function:
function module_entity_insert(EntityInterface $entity){
  // Build a render array of elements.
  $elements = [
    'name' => [
      '#type' => 'textfield',
      '#title' => t('Name'),
    ],
  ];

  $settings = [
    // Define settings.
  ];

  // Append default settings.
  $settings += Webform::getDefaultSettings();

  // Create a webform.
  $webform = Webform::create([
    'id' => 'custom_id',
    'title' => 'Title',
    'elements' => Yaml::encode($elements),
    'settings' => $settings,
  ]);

  $webform->save();
}

Now, after save and cache clear, go to add new content (any type will do).
Suppose I have new sample webform created along the new node creation, but here is the error message:

The website encountered an unexpected error. Please try again later.Drupal\Core\Entity\EntityStorageException: Object support when dumping a YAML file has been disabled. in Drupal\Core\Entity\Sql\SqlContentEntityStorage->save() (line 847 of core/lib/Drupal/Core/Entity/Sql/SqlContentEntityStorage.php).

Drupal version is latest, fresh install. What am I doing wrong? Or what's missing?

The problem was at line:
'elements' => Yaml::encode($elements)

The solution is to replace the Yaml in the use statement:
from:
use Drupal\Component\Serialization\Yaml;

to:
use Symfony\Component\Yaml\Yaml;

I don't know the exact explanation, it just works on my code.


Views Field Show "NEW" if less than 1 day old I am displaying webform submissions in a view, and need to add a "NEW" notification if the submission is less than a day old.

I have created views-view-field--myfield.tpl.php and have managed to change the value of my field using the template.

I am grabbing the submitted date, which I have printed already to make sure it works, and it comes up as 13/05/2014 - 23:13

I am then trying to figure out how to return a value for a date that is less than 1 day old. I'm pretty sure the following should do it, but it always renders "not new".

<?php
$submitted = $view->style_plugin->rendered_fields[$view->row_index]['submitted'];

if( $submitted > strtotime('-1 day') ) {
  echo '
NEW!
';
}
  else
{
  echo 'not new';
}
 ?>

Can anyone see where I'm going wrong?

UPDATE:

So, this works...

if( strtotime('14 May 2014') > strtotime('-1 day')) {
  echo '
NEW!
';
}
else
{
echo 'nothing
';
}

If i set it to 14th may (today) Its shows up as NEW! , any earlier, it prints nothing.

So, this leads me to believe there is a problem with my submitted date.

But, If I put echo $submitted; i get 13/05/2014 - 23:13

If I put $newDate = date("d M Y", strtotime($submitted)); echo $newDate; i get 01 Jan 1970 for every result.

And If I put $newDate = date("d M Y", $submitted); echo $newDate; I also get 01 Jan 1970 for every result.

So now I don't know what's going on. If its not in timestamp format, strtotime should sort it shouldnt it?

Probably need to strip the html from $submitted and convert to timestamp first,
e.g something like:

$submitted = $view->style_plugin->rendered_fields[$view->row_index]['submitted'];

if (strtotime(strip_tags($submitted)) > strtotime('-1 day')) {
  echo '
NEW!
';
}


Modifying argument of programmatically called render service. (e.g.: theme to use) = Get object from service container with modified argument I use the D8 core render service for generating markup that is indexed in an external search service. The indexing is happening on hook_entity_update, where I call my indexing service. My custom indexing service is then using the core render service for creating the markup.

Example with static service call:

// Get the render array for the teaser.
$viewBuilder = \Drupal::entityTypeManager()
  ->getViewBuilder($entity->getEntityTypeId());
$render_array_teaser = $viewBuilder->view($entity, 'teaser');

// Generate the markup from the render_array.
$renderer = \Drupal::service('renderer');
$rendered_teaser = $renderer->renderPlain($render_array_teaser);
// When called in hook_entity_update $rendered teaser has a crappy
// default markup in it as a 'teaser' view mode and the correct twig
// templates don't exist in the backend theme.

This works fine when called from drush. But when called from hook_entity_update() the renderer has the wrong theme context. As the node edit form that triggers the update uses the backend theme, the renderer gets also the backend theme as context instead of the default theme.

The renderer gets the current theme injected with the ThemeManager object.
See core services:

renderer:
  class: Drupal\Core\Render\Renderer
  arguments: ['@controller_resolver', '@theme.manager','@plugin.manager.element_info', '@render_placeholder_generator', '@render_cache', '@request_stack', '%renderer.config%']

How can I initialize the service but provide my own version of the ThemeManager object?

There is a setter method on the ThemeManager object where I could easily set the right theme. But I need to hand this over to the renderer.

e.g.:

$my_theme_manager = \Drupal::service('theme.manager');
$my_theme_manager->setActiveTheme('my_frontend_theme');

// How to get the service with this alternative context?
// e.g. something like that.
$service = \Drupal::Service();
$service->setService('renderer');
$service->setArgument(['@theme_manager' => $my_theme_manager]);
$default_theme_renderer = $service->getService();

Or is there some way to alter the ThemeManager Object when it is initialized? Before it is injected into the render service? So I can set the correct theme in an event or alter hook?

I know that I can alter the service in general by implementing the ServiceModifierInterfacebut this will modify the container when it gets created as far as I know, and is not a way for manipulation during runtime.

The mailsystem module is doing exactly what you are looking for I think. It has a configuration option to select which theme should be used to render mail templates.

See MailsystemManager::mail()

// Switch the theme to the configured mail theme.
$mail_theme = $this->getMailTheme();
$current_active_theme = $this->themeManager->getActiveTheme();
if ($mail_theme && $mail_theme != $current_active_theme->getName()) {
  $this->themeManager->setActiveTheme($this->themeInitialization->initTheme($mail_theme));
}

try {
  $message = parent::mail($module, $key, $to, $langcode, $params, $reply, $send);
}
finally {
  // Revert the active theme, this is done inside a finally block so it is
  // executed even if an exception is thrown during sending a mail.
  if ($mail_theme != $current_active_theme->getName()) {
    $this->themeManager->setActiveTheme($current_active_theme);
  }
}
return $message;

}

You can't tell the renderer directly which theme to use. But, you can switch out the active theme before you call it an then switch it back (the try/finally is important, so that you don't end up with the wrong active theme in case of an exception).

The service names for the two used services is theme.manager and theme.initialization.


How to get triggering_element I want to get triggering_element element on form_alter after form rebuild, Also I know that this could be used on submit handler on Ajax controller to findout which element cause form submit or Ajax triggered.

So how can I get triggering_element after Ajax call or form submissions?

Eyal is correct. FormState has a method getTriggeringElement. See the original change record for details.

$form_state->getTriggeringElement();

and if you want to get id try

$triggerdElement = $form_state->getTriggeringElement();
$htmlIdofTriggeredElement = $triggerdElement['#id'];


How to display a js popup saying "Loading..." after user saves a node? Been looking for solutions that would show a javascript popup or the like after a user submits or saves a node. How could I achieve this? Any modules out there?

You want it to display the instant they click the "Submit" button? The issue here is that, even if the "Loading..." popped up, the user would immediately see the page go white as the new page begins to load. It seems you're wanting to combat how page refreshes work, not Drupal.

That being said, to achieve the functionality that I think you're looking for you'd want to be opening the node create/edit form in a modal or something like that so it submits via an Ajax call and not a standard HTTP refresh. You can maybe use the Popups API module to do something like this: http://drupal.org/project/popups


Display edit and delete button using content view i am using blog entry content type  and i am displaying blog entry using content view .But their is no any edit and delete button how to add it while using content.Edit and delete button is working only when we use field view.Any idea how to make edit and delete button working when using content view

Node Full Content is displayed using node.tpl.php. If you would like to override tpl you can copy node.tpl.php and rename it to node--blog.tpl.php in your theme templates folder. For more information refer Drupal 7 Template Suggestions.

You can add Edit and Delete buttons using below code to the overrided template..

<?php
   if (drupal_valid_path('node/' . $node->nid . '/edit')) {
     print l('Edit', 'node/' . $node->nid . '/edit');
   }
?>
<?php
   if (drupal_valid_path('node/' . $node->nid . '/delete')) {
     print l('Delete', 'node/' . $node->nid . '/delete');
   }
?>


How do I control user generated contents published state? I want to allow users to submit the content to my site, but the content must be first approved, and then it can be published.

Someone told me to write a module, but I don't know which steps to follow.

Let the current user see the content that it is published by him, which is still not approved.
In addition, create a form to allow the current user to edit the node.

Does anyone know how to write such module?

There is a module for that™: Workflow module!

  The workflow module allows the creation and assignment of arbitrary workflows to Drupal node types. Workflows are made up of workflow states. For example, a workflow with the states Draft, Review, and Published could be assigned to the Story node type.

In your case you only need to workflow states: review and approved/public.


Move Comment form/render out of node.tpl.php (into separate region) I would like to render the $content['comments'] part of my nodes outside the node.tpl.php file, and have the comments (form and all) rendered in a separate region of my theme.

I've noticed Commentsblock does something along these lines, but requires a view, and doesn't seem too complete.

Could I do some preprocessing to get the entire comments renderable array into the page.tpl.php template if I'm on a certain node type page, rather than rendering the array inside node.tpl.php? (Something along the lines of this comment).

Also, wouldn't simply not rendering the $content['comments'], and then getting the comments via some other method (like a View, how Commentsblock works) cause Drupal to load all the comments twice (worse performance, etc.)?

You should be able to just hide() the comments in the node template and then create a block that calls menu_get_object() and then prints them there...


how to resolve ubercart checkout IE Issue? I am using Drupal 6. While checking out with IE 7 or 8, users get stuck in a loop; when they click on

they are redirect to

When users click on the submit button, they are again redirected to the review order page, as in the first image.
When I searched on drupal.org, I found a "fix in Ubercart Webform Checkout Pane" module, but I am not using it.

It is working fine on Firefox and Google Chrome.

Do you have any suggestion?

I fixed this issue by blocking java-script (some java-script file) on page.tpl for this page and found this is working.
the issue was i am using fancy box for my site which was loaded on all pages, and ubercart already have this so there was conflict in java-script.


How to fix "Undefined index" I'm working on displaying information about users on their profile pages.

I want to display a field; if this field is not completed then I display a text message, else, I display its value.

I've written this code:

<?php
     $username = $user_profile['field_username'];

     if($username == "") {
       echo 'Please enter a user';
     } else {
       print render ($user_profile['field_username']);
     }
?>

I get this error:

  Undefined index : field_username

But the code is working properly.

With the following line of your code:

$username = $user_profile['field_username'];

It always gets executed and check index field_username. So in case if the index doesn't exist it throws error.

If you replace your code with the following

if(empty($user_profile['field_username'])) {
  echo 'Please enter an user';
} else {
  print render ($user_profile['field_username']);
}

It will not always check field_username index but only if it is not empty.


Upload an image to a node and term I need to upload an image to a term as well as to a node using BEHAT with Drupal API. How this can be possible?

You need to define a Behat step for it. A possible way would be to define a method to be executed before creating a node (labelled with @beforeNodeCreate), to upload the file first and then to attach its fid to the appropriate file field of the node or term.

A possible way of doing it (for Drupal 8) is explained in detail here: https://webscope.co.nz/testing-image-and-file-fields-with-behat


Which module can create a sitemap based on entity reference rather than menus? Does a module exist that creates a sitemap based on entity reference rather than menus?

The site I am currently working on has it content linked using entity reference rather than using Drupal menus. The reason it has been done like this is because content can fall into multiple categories. But now I am facing the issue of generating a sitemap. Is there anyway to do this? Can it be done using Views maybe?

With the XML Sitemap module, the main alternate to menu-based sitemaps, is the XML Sitemap Node submodule.

Enable the sub-module, then edit each content type.  There should be an XML Sitemap tab at the bottom of the form.  Set the inclusion and priority as needed.  An advantage of this, over using menu-based sitemaps, is that modified times will end up in sitemap.xml


Can you disable drush pm-update for a site? Can you disable drush pm-update for a particular site in drushrc.php?

I have a server which houses the DEV and LIVE versions of the site.  Work is done directly on the DEV site.  Changes to the LIVE site are deployed via git pull from a shared remote on the same filesystem.

In an effort to prevent Doing Something Stupid™, and running a pm-update and pm-updatecode on the LIVE site, I would like to disable these commands for that site.

The $command_specific[] syntax allows you to specify persistent options for commands (like --no-core), but I would like to fully disable pm-update and pm-updatecode for this particular site.

Is this possible?

You can disable the core Update module on the live site,  and then should prevent being able run pm-update on live:

  $ drush pm-disable update The following extensions will be
  disabled: update Do you really want to continue? (y/n): y
  update was disabled successfully. [ok] $ drush pm-update
  Command pm-update needs the following modules installed/enabled to
  run: update. [error] The drush command 'pm-update' could not be
  executed. [error]


Language switcher using get language variable instead of prefix in Drupal 8 In Drupal 8 setting  url with path prefix for language detection, works fine. But when I include the language switcher block included with Drupal, the links instead of using the language prefix, show links using the variable language in the url.

How can I make the language switcher make use of the language prefix instead?

The plugins you enable in the language detection configuration also contain the methods to build outbound paths and the language switcher links. The plugin for Url adds prefixes, not query strings. Others do, for example Session for anonymous users, so you probably have enabled a second detection method.


How to load field value to custom form? I'm using Drupal 7 for my website.
I created custom settings page with custom form in it, but the problem is I don't know proper way to load inserted value from database to my form after saving it, and every time I write something in it, information is written to database, but form is empty.
My code looks like this for this:

function registration_pdf_form($form, $form_state) {
    $form['registration_body_twoside'] = array(
        '#type' => 'text_format',
        '#title' => t('Two-sided PDF'),
    );
    $form['registration_body_threeside'] = array(
        '#type' => 'text_format',
        '#title' => t('Three-sided PDF'),
    );
    $form['actions'] = array(
        '#type' => 'actions'
    );
    $form['actions']['submit'] = array(
        '#type' => 'submit',
        '#value' => t('Save settings')
    );
    return $form;
}
function registration_pdf_form_submit($form, $form_state){
    $values = array(
        'reg_twoside' => $form_state['values']['registration_body_twoside']['value'],
        'reg_threeside' => $form_state['values']['registration_body_threeside']['value'],
    );
    $insert = db_update('pdf_settings')
        -> fields(array(
            'reg_twoside' => $form_state['values']['registration_body_twoside']['value'],
            'reg_threeside' => $form_state['values']['registration_body_threeside']['value'],
        ))
        ->execute();
    drupal_set_message(t('Settings have been saved'));
}

How do I get values to my fields from database?

You can try using system_settings_form which is simple way of storing settings in Drupal..

function registration_pdf_form($form, &$form_state) {
   $form['registration_body_twoside'] = array(
        '#type' => 'text_format',
        '#title' => t('Two-sided PDF'),
        '#default_value' => variable_get('registration_body_twoside', ''),
    );
    $form['registration_body_threeside'] = array(
        '#type' => 'text_format',
        '#title' => t('Three-sided PDF'),
        '#default_value' => variable_get('registration_body_threeside', ''),
    );
  return system_settings_form($form);
}

you can read values using

$twoside = variable_get('registration_body_twoside', '');
$threeside = variable_get('registration_body_threeside', '');


how to set a variable in module and get it in theme i want set a variable in module and use it in my theme,
(except variable_set and variable_get way.)

for instance . in module file

      if(in_array(arg(1),$ex))
      {
//      set a variable
      }

in theme file

if(//variable)
{
echo '

';
}

thank you so much for help me

HOWEVER:

You should really look into the various _preprocess() hooks.  From further commentary below, I am thinking that's where you should be doing all this.

ORIGINAL ANSWER:

If you don't want to use the system wide variable_set() or variable_get() you can always set a variable in the global $_SESSION array that would be seen by the current logged in user only, eg,

if ( // whatever ) {
  $_SESSION['MYMODULE_variable_name']= // whatever
}

SUPER DUPER OVER SIMPLIFIED ADDITION:

function MYMODULE_foo($value=NULL) {
  static $bar;

  if ($value) {
     $bar=$value;
  }

  return $bar;
}

accomplishes it inside your module, eg, you can do:

MYMODULE_foo('this is cool');

and then in your theme do:

$baz=MYMODULE_foo();


How to inspect outgoing email content during a SimpleTest? I see that SimpleTest has a few built in mail functions to check for send success etc, but how can I send a message, assert its content and then click a link within that content during a test?

What is the standard or most common way to test unsubscribe, or account verification links in emails with SimpleTest?

Simpletest automatically captures sent mails during a test and allows you to fetch them using $this->drupalGetMails() in the test class.

I did something like this recently in tests I wrote for the Simplenews project, to test subscription confirmation here.


Change the updated timestamp for users I have a custom module that do some processes after a user entity is updated. I need to just trigger a timestamp update so my module can act on them accordingly. I wrote a script that is going through all my ~350000 users and doing this :

$loaded_user = user_load($uid);
user_save($loaded_user);

While this is working, the process is taking too long to finish. Is there a faster way to do this?

Here is an idea about running this in a more efficient way:

<?php
  $loaded_user = user_load($uid);
  $user->changed' = time();

  field_attach_update('user', $user);
?>

I am not 100% sure if this is gonna work for your setup the way you want to, i.e. if the hook you implement in your module is going to be called (not enough information there).

Let me know and I can give you an updated answer.

Cheers


Is it possible to protect content types with captcha? I would like to protect some pages of my Drupal 7 website with a riddler captcha, to protect those pages from all who can not solve the riddle, but don't make it necessary to login to see the content. As I am using Organic Groups it would be the best, to protect all content that is part of a group by such a riddle.
To make my goals more clear and avoid misunderstandings:

I want to protect pages in a soft way against unauthorized access.
I don't want the audience to login to my side, because for my use case that would be too complicated.
I don't need high security.

Does anybody know how to do that, what would be the most elegant way. Does anybody have a better idea?

you may create custom module
https://stackoverflow.com/questions/3434134/restrict-node-with-captcha

combine hook_node_view_alter with
http://drupalcontrib.org/api/drupal/contributions!captcha!captcha_api.txt/7


Meta tags, title and description not showing up on home page I have a regular page set as the home page on my site. The Meta Tags, Title and Description are all set on the node, but do not show up on the home page.

Any ideas why?

Try printing

<?php print render($page['content']['metatags']); ?>

in your page.tpl.php or page--front.tpl.php if youre using Meta tags


Is it possible to add CSS to theme without a subtheme? I am using a contributed theme and I would like to add a bit of CSS.

The theme uses a lot of stuff that isn't inherited by sub-themes (settings, colors, etc), and I don't want to create a sub-theme just for the small amount of CSS I need.

What would you suggest in this case?

My understanding is to never use hook_init if possible. It's a hook that's call in the early stages of the bootstrap process and can produce some funky results. The API docs clearly state:

  To add CSS or JS that should be
  present on all pages, modules should
  not implement this hook, but declare
  these files in their .info file.

I'd suggest adding a stylesheets[all][] entry in the .info file -> Adding style sheets


Content teaser view, Read more shows only in admin mode I manage a Drupal 7 site with custom theme and I have no FTP access and was not involved in development but I have to manage the content and have every right on the web surface.

The situation

I created some content based on the type article (which has a Body of "Long text and summary" field type and of "Text area with a summary" widget), and a view to show this content.

In the view display (created both Block and Page), Format is set to "Unformatted list" (Force using fields is disabled at the settings), and Show is set to "Content | Teaser". Check the image for the settings.

With these settings, the content on the editorial view is fine for me: title, a picture, a text and a read more link. Check the image for the result.

Unfortunately, "Read more" does not appear on the page shown for the visitors. Not even not shown, it cannot be found in the html source code.

Note: Read More Control and Read More Link modules are not installed.

Question

Is this behavior intended? Is there a bug in a module? Did I miss something, and there's a way to show "Read more" on the page for the visitors too? Can you please tell me how can I manage to show a "Read more" link to the visitors with the same view settings? I neither understand why modifying the Block style implies the modification of the Page Display, i.e. I modify one of them (like the displayed fields), the other display is modified too automatically.

I already have a workaround, but it is not a solution. What I've done is that I changed the setting and checked the box "Force using fields" at Format: unformatted list and manually added the title, image, text, a manual texted link to read more and a horizontal rule.

The "Read More" link is part of the contextual links for each post. So, you need to simply tell Views that you do not want the links shown.

Go to: Format, Show, Teaser (the first image you showed in your question).
Under the dropdown for "view mode", you will see a checkmark for Display links. Uncheck that and they should disappear.


How to NOT turn element read only when waiting for '#ajax' callback in Drupal 7 forms? I need a simple '#type' => 'textfield' field. When a user types in it, I want to update another section of my form. Just a more elaborate version of built-in autocomplete field, really. So I added:

'#ajax' => array(
  'callback' => 'mymodule_tag',
  'wrapper' => 'edit-tags',
  'method' => 'replace',
  'effect' => 'fade',
  'event' => 'input',
),

The only problem is - it turns my field disabled when waiting for the server's reaction. This is unacceptable: User's input should never be blocked, that's a priority. I bet the solution is simple, but googling for it gives me a lot of results about how to disable field, and none about keeping it enabled. Too much noise for my search skills. Any suggestions?

I'm not sure I agree with your premise (interesting question, nonetheless). If performing a second operation while the first is already running would cause a problem client/server side, then that operation should definitely be blocked in my opinion.

If the only issue you have is that the blocking is done by way of disabling the text field, consider that it's just a matter of good UX. If the field wasn't disabled, but the functionality was, then there's no feedback to the user, who is left wondering why nothing's happening even though they're typing into a text field that has some rich functionality a few seconds earlier.

That said, if you want to override the behaviour of Drupal's AJAX have a look in the /misc/ajax.js file. You'll need to re-implement at least:

Drupal.ajax.prototype.beforeSend
Drupal.ajax.prototype.success
Drupal.ajax.prototype.error

Those functions set/remove the disabled attribute on the element. It should be reasonably straight forward to re-assign those functions in a custom JS file, and you can just remove lines like this:

$(this.element).addClass('progress-disabled').attr('disabled', true);

Or tweak it to something more palatable for your use case.


How to force users to log in with OAuth My site forces users to log in with a specific OAuth provider for some reasons. Users should not be able to log in using their username and password pairs. Only the site managers can have accounts independent of OAuth.

When first creating an account with OAuth, the 'pass' field is set to an empty string ''. My first question is whether it is the right and most secure way to prevent logging in using password.

The second question is about requesting new password via email. I implemented hook_menu_alter to customize user and user/login and to unset user/password. Now users cannot access user/password, I wonder if there is a bypass for it. This question is less important since almost all users would never bother with or even know the possibility of requesting new password.

If you disable email notification of new accounts, the OpenID module will set a random password when users register. See openid_form_user_register_form_alter(). If that is not what you want, you use hook_form_alter() to do the same thing under your desired conditions.
If you want to intercept user_pass_reset() so it cannot reset passwords, try using hook_form_alter() to add a form validation function.


Only require comment approval when an image is attached I am working on a project that allows user commenting without administrator approval if they post only text; however, if the user decides to attach an image to their comment, the comment should require approval first before being published. What is the best way to approach this?

I got this working using the Mollom module.

In Mollom's configuration, you can enable spam filtering and set up your own blacklist terms for the spam filter. I created blacklist terms for <img and "media-image" (TinyMCE's encoded image class). Then I told Mollom to "Retain the post for manual moderation" if it gets detected as spam.


Change the default image based on certain condition I wonder if I could provide two default images -one for boys & other for girls.

In the registration form they can choose their sex from a Boolean field.

Is it possible with conditional fields ? How?
I'm not  a programmer, so please make your answer detailed.

I would suggest using Rules as follows:

You can either include Conditional Rules for a single Rule, or use two rules:

Event: After user registration

Condition: image field is empty (only want it to run if they don't upload an image)

Condition: sex field is girl

Action: set image field to url location of girl default image

New Rule:

same as above except for the condition of sex changes to boy

  The Rules module allows site administrators to define conditionally
  executed actions based on occurring events (known as reactive or ECA
  rules). It's a replacement with more features for the trigger module
  in core and the successor of the Drupal 5 workflow-ng module.


How to alter the search api views exposed form field value? I have a search api view. Which has an exposed some exposed filters.

The exposed filters contains postal code, city and latlong field.

The user will enter the city and postal code and then in the code I will get a latlong from that address and will assign to the latlong field.

I have tried the following code but it is not working.

function mymodule_form_views_exposed_form_alter(&$form, &$form_state, $form_id) {
  if ($form['#id'] == 'views-exposed-form-id') {
    array_unshift($form['#submit'], 'mymodule_maps_exposed_form_submit');
  }
}

function mymodule_maps_exposed_form_submit(&$form, &$form_state) {
  $address = $form_state['values']['zipcode'] . ' ' . $form_state['values']['city'];
  $latlong = somefunction($address);
  // Tried all of these options but nothing is working.
  $form_state['values']['latlong'] = $latlong;
  $form_state['input']['latlong'] = $latlong;
  $form_state['view']->exposed_input['latlong'] = $latlong;
  $form_state['view']->display_handler->handlers['filter']['latlong']->validated_exposed_input = $latlong;
  $form_state['view']->display_handler->handlers['filter']['latlong']->value = $latlong;
  // This line adds the value to the form field but the filter doesn't apply.
  $form_state['complete form']['latlong']['#value'] = $latlong;
  $form_state['complete form']['latlong']['#default_value'] = $latlong;
}

Is there any trick I am missing? Can someone guide me? Anyone who can give  a hint?

I have found an answer. I am sharing it here so that it can help someone.

Instead of form_alter hook, we can use hook_views_pre_view.

Here is the code

/**
 * Implements hook_views_pre_view().
 */
function mymodule_views_pre_view(&$view, &$display_id, &$args) {
  if ($view->name == 'my_view_name') {
    $address = 'some address';
    $latlong = somefunction($address);
    $view->get_exposed_input();
    $view->exposed_input['latlon'] = $latlon;
    $view->execute().
  }
}


How do I find the correct plugin? As an Drupal 7 developer I'm currently trying to get into Drupal 8.
I got a problem finding the right plugin.

For example, I simple want to change the text of a node link "read more" into "read more >".

Leaving the templates out, I would google for Drupal 7 something like "drupal hook -what I want- alter" and found the correct hook. How can I find the correct plugin?

Especially for this case, there hook_node_links_alter(). Should I use this, or is it just for legacy and I should prefer a other way?

In the specific example you make, there aren't plugins involved. The hook in invoked from NodeViewBuilder::renderLinks(), which executes the following code.

  $links = array(
    '#theme' => 'links__node',
    '#pre_render' => array('drupal_pre_render_links'),
    '#attributes' => array('class' => array('links', 'inline')),
  );

  if (!$is_in_preview) {
    $entity = Node::load($node_entity_id)->getTranslation($langcode);
    $links['node'] = static::buildLinks($entity, $view_mode);

    // Allow other modules to alter the node links.
    $hook_context = array(
      'view_mode' => $view_mode,
      'langcode' => $langcode,
    );
    \Drupal::moduleHandler()->alter('node_links', $links, $entity, $hook_context);
  }
  return $links;

To know if a plugin is involved, you need to read the documentation. Plugin API in Drupal 8 give the general documentation, but then you need to read more specific documentation pages, for example Block API in Drupal 8.
A plugin could be annotated, so in some cases you can find any plugin implemented by Drupal core by looking at the classes annotated with a specific class, which is what happens with form input elements, which are classes annotated with \Drupal\Core\Render\Annotation\FormElement. The documentation page gives a list of the classes annotated with that Annotation class, so you can find any plugins of that type.

Then, as @CLive said, if you are simply wondering if you should use a hook, just look at the documentation page for that hook: If it has been deprecated, the documentation reports that, and tells you exactly what you should use: a different hook, a plugin, a specific class.
Also, as said from @mradcliffe, change records reports the changes done in Drupal, and for which version. They are helpful if you want to look at the changes that could interest the code you are writing.


Getting "The form has become outdated" error I have a multistep node form.
Half way through the form through a popup dialog user is asked to login if they have not logged in prior.

Upon successful login when proceeding with next page of the node form, I get this validation error:

  The form has become outdated. Copy any unsaved work in the form below and then reload this page.

I understand it is because drupal_validation_form() verifies $form['#token'] and $form_state['values']['form_token'] are the same.

How do I avoid this, as this is a special use case (and it's not forgery by some external stuffs).

Any input on this front?

Your post just saved me from serious misery. Don't quite know how that connection was made but your post lead me to a small change in my module code. Easy to understand why the "The form has become outdated" error was occurring now though. So see if this might jog your thoughts and help for your case.

My page admin/mymod had a menu item set up that included the following.

'page callback' => 'drupal_get_form',
'page arguments' => 'mymod_main',

In mymod_main($op = '') I am conditionally building one of 2 forms but each build is of course a new form, e.g. $build['mymod_admin'] = drupal_get_form('mymod_admin') or $build['mymod_delete'] = drupal_get_form('mymod_delete').

No problem when the page admin/mymod first loaded and mymod_admin is called. But when the submit button created in mymod_admin is clicked then mymod_delete is called and creates it's form. There comes the "The form has become outdated" error that ruined the form processing. The fix is simply to use mymod_main() as page callback.

Now there is no crossing up of forms when the admin/mymod page reloads for each of the forms as there is not a starting form from the manu callback and then the second form defined in $build.