Why does the Login Destination module not redirect to page? I installed and enabled the Login Destination module, and added a login destination rule.

In Internal page or external URL I added myhomepage which is a basic page URL that I want to show after a user performs a login. If authenticated user login then it would not redirect to default page.

My default dashboard page is /cms and dashboard page after user login is cms/96/dashboard (96 in it is the uid of the user).

I have a three types of users:

authenticated user
administrator
employee entry form

And I want authenticated user and employee entry form user to be redirect to cms/{uid}/dashboard (but not administrator users).

Some more details about my configuration:

Redirect upon triggers : I have only select the first one and that is Login, registration, one-time login link
Only the listed pages:

cms
cms/register
cms/*/edit

and under setting tab I have checked both checkboxes.

But when I try to login then user gets redirected to default page.

Any suggestions?

You can use Rules module.
Events: User has logged in.
Condition: User has role.
Actions: Page redirect.
Other Way through coding:
You can use hook_user_login
function hook_user_login(&$edit, $account) {
 if($account->uid == 1)
  drupal_goto('cms');
 else
  drupal_goto('cms/{$account->uid}/dashboard');
}

Updated rule:
{ "rules_after_login_rule" : {
    "LABEL" : "After Login Rule",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "ON" : { "user_login" : [] },
    "IF" : [
      { "user_has_role" : { "account" : [ "account" ], "roles" : { "value" : { "4" : "4" } } } }
    ],
    "DO" : [ { "redirect" : { "url" : "cms\/[account:uid]\/myhomepage" } } ]
  }
}

Look at these post as well.
How to rediret to specific page depends upon user roles
I want to redirect the user to profile page after they log in
Redirect user based on role and node content


"admin/content" filters not available anymore In the Content page (/admin/content), in Drupal 7 there was a feature allowing to filter by content type, status or language:

It doesn't seem to be available anymore in Drupal 8.

Someone know if there is a module recreating this feature?

You need just to install the Views module that is part of Drupal core. Once you install it, that page appears as the following, which is how I see it in my site.

If I uninstall the Views module, that page appears like the following.

Now that the Views module is in core, there are many pages that have been converted into views. As you see from the first screenshot, there is a new Files tab which is a view.

If you don't see the Views module listed between the modules, download again Drupal, because that means the archive used for the installation is missing some Drupal files, or they have not been correctly copied.


What's the difference between using $this->t('text') and t('text') in a block plugin I've noticed in many tutorials for constructing block plugins,

$this->t('text')

is used to create translatable text, especially in the block form function. However using

t('text')

doesn't produce any errors. Is there any difference between using either of these? And if there isn't, what's best practice?

To be exact on your question: there's no difference in internal implementation.

But as a best practice, you should be using $this->t instead of the global t wherever possible. If you check the function, t is returning a new TranslateableMarkup object.

If your class says $this->t is not defined, you can add the StringTranslationTrait to add the behavior or inject it as a dependency.

  Using this trait will add t() and formatPlural() methods to the class.
  These must be used for every translatable string, similar to how
  procedural code must use the global functions t() and
  \Drupal::translation()->formatPlural(). This allows string extractor
  tools to find translatable strings.

  If the class is capable of injecting services from the container, it
  should inject the 'string_translation' service and assign it to
  $this->stringTranslation.

So as a best practice rule, you generally do not want to mix procedural within OOP unless completely unavoidable (e.g. native PHP functions).


theme preprocess view I have a content type "Slide" that I use for a carousel in a view as a block. One of the field of the slide I have added is "country filter" that I intent to use as a filter for geo localisation. I use GeoIP2 for this.

My intent was to use a THEME_preprocess_SOMETHING() to alter the view and remove some of the slides that are not on the right country filter. For example some slides could be allowed to be shown only to user located in France. If the user is not located in France, I would remove those slides.

I tried to do this in a THEME_preprocess_view_view_fields() but I can seem to find a way to remove completely the slide. So I guessed I was not on the right hook.

Does anyone knows which hook I should use to do that?

I haven't found a way to do it in a THEME.theme file but I found a way to do it in a MODULE.MODULE file. The magic hook is MODULE_views_post_execute:

function feature_carrousel_views_post_execute(\Drupal\views\ViewExecutable $viewExecutable){
  /** @var \Drupal\views\Entity\View $view */
  $view = $viewExecutable->storage;
  if($view->id() == 'carrousel'){
    /** @var \Drupal\views\ResultRow $row */
    foreach($viewExecutable->result as $key => $row){
      $nid = $row->nid;
      /** @var \Drupal\node\NodeInterface $node */
      $node = \Drupal\node\Entity\Node::load($nid);
      if($node) {
        $country_filter = $node->get("field_country_filter")->getValue();
        $country_filter_tid = (reset($country_filter))['target_id'];
        /** @var \Drupal\taxonomy\Entity\Term $term */
        $term = \Drupal\taxonomy\Entity\Term::load($country_filter_tid);
        $name = $term->getName();
        $countryCode = getUserCountry();

        if(strtolower($name) != 'all' && strtolower($name) != strtolower($countryCode)) {
          unset($viewExecutable->result[$key]);
          $viewExecutable->result = array_values($viewExecutable->result);
        }

      }
    }
  }
}

Cheers


Translation "Global: Text area" in views footer I use Internationalization module for multilingual site.
Is there a way to translate custom text in views footer except of creating a new view for a second laguage?

Use PHP instead of text area, make the strings translatable by using t('MyString').

Update: usign PHP is not a recommended practice... Probably you could have a template for that view.
and inside a string inside t('My String')... Then you can use the translation interface.


How do I alter a function? I want to track taxonomy term tagging count in the database; for each taxonomy term, I want a term tagged count that stores the number of nodes using the taxonomy term. I know I can retrieve it with a query on taxonomy_index but it is too time consuming for me.

I've found taxonomy_build_node_index($node) and taxonomy_delete_node_index($node), which are called in taxonomy_node_insert(), taxonomy_node_update(), and taxonomy_node_delete() (node hooks).

I know a form can be altered with hook_fom_alter(). Is there a way to alter these functions as well?

Drupal doesn't have a way to generally replace a function in a module with a function implemented by another module.

In the case of hooks, you could alter the output of a hook with another hook, but in your case you don't even need this. Just implement hook_node_insert(), hook_node_update(), and hook_node_delete(), and add the code necessary for counting the tags used by nodes.

As said from Jaypan, you don't say in which way querying the taxonomy_index table would be too expensive. I am not sure it would be that expensive, since the table saves the taxonomy term IDs and the node IDs: You just need to count the table rows with a specific value for tid.


How to create a test configuration that can called in a test class? I am attempting to write a unit test by extending UnitTestCase. Below is how my code works, but I need a way to create a test (or mock) configuration that can be used to satisfy the testing.

How can I accomplish this?

To keep question short i am only adding pertinent code. Current issue is that my test cases are failing because the configuration is not valid.

Error message:

  Drupal\Core\DependencyInjection\ContainerNotInitializedException: \Drupal::$container is not initialized yet. \Drupal::setContainer() must be called with a real container.

mymodule/src/plugin/mymodule_field/provider/MyClass.php

class MyClass extends ProviderPluginBase {
  /**
   * {@inheritdoc}
   */
  public static function someFunction($input) {
    // Get the config.
    $config = \Drupal::config('mymodule.settings');
    $test_value = $config->get('test');

    if (!empty($test_value)) {
      /* process $test value */
      return True;
    }
    elseif (empty($test_value)) {
      /* do something else */
      return false;
    }
  }
}

mymodule/test/src/Unit/MyModuleValueTest.php

class MyModuleValueTest extends UnitTestCase {
  public function testIsEmpty($value, $expected) {
    /* I am stuck here on how to get the config */
    $this->assertEquals($expected, MyClass::someFunction($value));
  }
}

You are missing a couple of basic ideas of unit testing. I try to show them to you:

What is a unit?

Unit is most cases (95%+) a single class. This unit has some dependencies, using them and adding some extra logic to the whole.

In a unit test you only want to test the logic you provide in your class, but you want to make the dependencies as black boxes. A change to the implementation of the dependencies should NEVER make any difference to your unit test.
Only their interfaces what matters.

Clear Dependencies

One of the dependency injection main role is to make your class testable.
By injecting all the dependencies through the constructor you not just giving a nice list what services you class is relying on, but also make it easy to test.

Static methods should not be harder to test than object methods but they have a big drawback: you can't handle calling another static method inside them. Here is a nice explanation:

  Unit-Testing needs seams, seams is where we prevent the execution of normal code path and is how we achieve isolation of the class under test. Seams work through polymorphism, we override/implement class/interface and then wire the class under test differently in order to take control of the execution flow. With static methods there is nothing to override. Yes, static methods are easy to call, but if the static method calls another static method there is no way to override the called method dependency.

About your case

Either you need to eliminate the dependency by providing the value you need via argument, or you will have to give up unit testing on this one.
You still can write a kernel test tho. That will be of course slower, but you can also have a wider scope of functionality / integration to be tested.


Drupal 7 add calendar module. Doubleclick on a day to add calender item for that day Adding 50+ calender items to my drupal Calendar is a pain and takes a lot of time clicking and selecting the right date.
What would be awesome is that it would be possible to just doubleclick or click on a + or something on the day that needs a new calender item.
Does anyone have a clue on how to do this?
Or something similar.
I already added the link to add a calendar item above the calendar to add a calendar item from that view but then I still need to change the date unless it is the current day.

Thanks in Advance!

The Calendar module does not provide such a feature per se. There is also another calendar module, FullCalendar. This uses the FullCalendar jQuery plugin. By default the Drupal module does not provide this functionality, but from the demo pages it seems that it is a relatively easy one to implement by yourself. You would have to study the demo a bit.


Drupal7 creating breadcrumb from url of custom page template I have a template file: called: page--movies--movie-details.tpl.php

which make my url: http://mydomain.com/movie/movie-details/

question is: How can i make my own breadcrumb using that url:
My breadcrumb should like this:

ex: Home > movie > movie details

how can i do that in drupal7?

thank you.

The custom breadcrumbs module can handle adding breadcrumbs to views.

The readme has information on how to use it.

The recommended module for breadcrumbs is path breadcrumbs.


Changing library path with hook_library_info_alter I am having difficulties to change the library path defined by another module in *.libraries.yml via hook_library_info_alter

Essentially I have one module defining a library component in its *.libraries.yml like that:

# Font Awesome
fontawesome:
  version: 4.7.0
  css:
    component:
      /libraries/fontawesome/css/font-awesome.min.css: {minified: true }

How has my hook to look like to change to path to:

  /libraries/fontawesome/web-fonts-with-css/font-awesome.min.css

Thanks for helping me!

I pushed my patch for social icons module to add dynamic font awesome css here
https://www.drupal.org/project/social_icons/issues/2984954

This is helpful to you.

if (isset($libraries['font-awesome'])) {
     $library_key = key($libraries['font-awesome']['css']['theme']);
     $library_array = $libraries['font-awesome']['css']['theme'][$library_key];
     unset($libraries['font-awesome']['css']['theme'][$library_key]);
     $libraries['font-awesome']['css']['theme'][$font_awesome_url] = $library_array;
}


Taxonomy child terms list and product list view I would like to ask about product category vocabulary and different page views for parent and child terms.

This is my use case:
I have to build drupal 7 commerce based site, products are organised in taxonomy called "Product categories". Lets have these terms in here:

Category1

Subcategory1-1

Product1
Product2

Subcategory1-2

Product3

Category2

Subcategory2-1
Subcategory2-2

Product4

Subcategory2-3

Category3

Subcategory3-1

I need to make this behavior:
Main category list page: contains list of main categories [Category1, Category2, Category3]

Main category detail page: after clicking on main category (e.g. Category1) and page contains list of child categories [Subcategory1-1, Subcategory1-2]

Child category detail page: after clicking on sub category item (e.g. Subcategory1-1) and page contains list of products [Product1, Product2]

so in general: if you click on category without products -> display child categories list of particular parent category, and if you click on category with products assigned to them display list of products...

I was googling for a while and I don't find the right solution for my use case.

Can anybody help me with this?

Here's my tutorial video (I've published this step by step in many places): https://www.youtube.com/watch?v=y1jqu8JnLbU

STEP BY STEP

Create a Taxonomy Vocabulary here: admin/structure/taxonomy (And create a few terms)
Create a Taxonomy View here: admin/structure/views/add

  You want to make sure that you choose "taxonomy" entities.

Add a contextual filter for "Taxonomy term: Parent term"

  Make sure to select "Default Filter" and choose "Taxonomy term from url." Also, specify a "Default validation criteria" for "Taxonomy term" and choose "Convert taxonomy name to ID" and select "Transform dashes in url..."

Add a new page to this view, remove the contextual filter from this view and add a filter for "Taxonomy term: Parent term" and set it to "equal to" and leave the field there blank.
Save that view and create a new view here: admin/structure/views/add

  Make sure this view is a for "Content" of type "Product Display" (or whatever entity bundle has the field for your taxonomy terms).

Add a contextual filter for your taxonomy term, mine was called "Product Categories"

  Make sure this contextual filter displays "Contents of No Results." Also, specify a "Default validation criteria" for "Taxonomy term" and choose "Convert taxonomy name to ID" and select "Transform dashes in url..."

Add a "No results" item called a "View Area" and select "Page_1" from your first view (this is the second page we created)
Save this view and go back to the first view.
Add a "No results" item called a "View Area" and select the second view that we just made.
Make sure your title field in the Taxonomy View doesn't link to the taxonomy term, but it outputs the field as a link to "catalog/[name]" that way your catalog names are clickable :)
Profit!


How to use Devel module to see what creates an URL? I want to know what creates an URL of a site for example a view,panel etc.
Which command should I write on the Devel module on "Execute php" ?
Thanks

Not really sure what you are meaning by 'create url', but any url in Drupal is registered through hook_menu(). Don't let the name confuse you - this is a seperate concept to lists of urls (like the navigation menu). The menu system keeps a cache of url to callback function mappings, which you can inspect to see which function each url points to.

To view the menu cache, you can run this code:

dpm(menu_router_build());

You can then look through the array to see the details for each url.


How to create a menu option with HTML in its title from a module? HTML in a menu option would be very useful from a module too, i.e. inserting an image as a menu option. Is there a way to do use something like function MODULE_preprocess_menu_link(&$variables) inside a module, and not in template.php?

Modules can implement preprocess and process functions for theme functions using a template file; for theme functions not using a template file, Drupal 7 allows module to implement a preprocess function.
For example, the mymodule module could implement mymodule_preprocess_menu_link() which is a Drupal 7 preprocess function for theme_menu_link().

Preprocess and process functions are useful when the variables passed to the theme function need to be changed. If there is the need of changing the output of the theme function, then a module needs to implement hook_theme_registry_alter() and change the function called to serve the output of a theme function.

function mymodule_theme_registry_alter(&$theme_registry) {
  if (isset($theme_registry['menu_link'])) {
    $theme_registry['menu_link']['function'] = 'theme_mymodule_menu_link';
  }
}

With this implementation, theme_mymodule_menu_link() would be the function called when a module calls theme('menu_link', /* … */).

References

theme()


Add hyphen after field I have 2 fields; field_a and field_b.  When field_b is not empty, I need to append a hyphen after field_a.

EX: field_a - field_b

Then, when field_b is empty, it doesn't show the hyphen

EX: field_a

I have been trying THEME_preprocess_field and THEME_field in template.php, but can't get it to work.  This is what I have, but its basically just a copy, but I don't need all the extra stuff, and I need it to only show up on field_a when field_b is not empty.

function THEME_field($variables) {
  $output = '';

  $output .= '
';
  foreach ($variables['items'] as $delta => $item) {
    $classes = 'field-item ' . ($delta % 2 ? 'odd' : 'even');
    $output .= '
' . drupal_render($item) . ',' . '
';
  }
  $output .= '
';

  // Render the top-level DIV.
  $output = '
' . $output . '
';

  return $output;
}

You can keep it simple and just add the following to your css

.field_b:before{
  content:"-";
}

It will only show when there is a value for the b field.


Drupal 7 Form API - AJAX updates for multiple file uploads I have a Drupal 7 custom module form that uploads then processes multiple images.

I have an ajax callback that updates page content with the processed images. BUT, the page update happens when all uploaded files are finished and I would like to alter this to update when each uploaded file is processed.

Form creation:

function awsImage_form($form, &$form_state) {
  $form = [];

  $form['file'] = [
    '#type' => 'file',
    '#name' => 'files[]',
    '#title' => t('Upload files to test'),
    '#description' => t('TIFF\'s, JPG\'s, GIF\'s, and PNG\'s only, 20MB Max Size'),
    '#attributes' => ['multiple' => 'multiple'],
  ];

  $form['submit'] = [
    '#type' => 'submit',
    '#value' => t('Upload'),
    '#ajax' => [
      'callback' => 'awsImage_form_callback',
      'wrapper' => 'results',
      'method' => 'append',
    ],
  ];
  $form['results'] = [
    '#markup' => '
Results:
',
  ];
  return $form;
}

Form validation [error checking & save location [$destination] removed to keep it brief]:

function awsImage_form_validate($form, &$form_state) {
  //Save multiple files
  $num_files = count($_FILES['files']['name']);

  for ($i = 0; $i < $num_files; $i++) {
    $file = file_save_upload($i, [
      'file_validate_extensions' => ['tif tiff png gif jpg jpeg'],
    ]);
    if ($file) {
      file_prepare_directory($destination, FILE_CREATE_DIRECTORY | FILE_MODIFY_PERMISSIONS);
      if ($file = file_move($file, $destination, FILE_EXISTS_REPLACE)) {
        $form_state['values']['file'][$i] = $file;
      }
    }
  }
}

AJAX callback [image processing removed to keep it brief]:

function awsImage_form_callback($form, $form_state) {
  $form_state['rebuild'] = TRUE;
  $processed_out = '';
  if (is_array($form_state['values']['file'])) {
    foreach ($form_state['values']['file'] as $file) {
     // image processing stuff which builds and array: $img_reponse_details
      $output = '';
      foreach ($img_reponse_details as $key => $img_details) {
        // build front end $output
      }
      $processed_out .= $output;
  }
  // push output back to form.
  $element = $form['results'];
  $element['#markup'] = $processed_out;
  return $element;
}

Ideally, I would like to update the front end in the foreach loop in the ajax callback:

function awsImage_form_callback($form, $form_state) {
  foreach ($form_state['values']['file'] as $file) {
      // deal with each image
      // push output back to form.
      $element = $form['results'];
      $element['#markup'] = $processed_out;
      return $element;
    }
}

But as soon as I return the current result, that's the loop over and only the first file is displayed - which is correct as it is a return... but what I am really after is 'do the AJAX update and carry on with the rest' and I am not sure how to go about that part?

The AJAX updates I wanted was to provide some progress updates which I found out I can achieve form api #ajax['progress']. I guess if I had mentioned that in the original question it would have made life a bit simpler :) :

first create a url for the ajax progress update to call:

function awsImage_menu() {
  $items = [];

  $items['path/to/page'] = [
    'title' => t('Import progress'),
    'page callback' => 'import_progress',
    'access callback' => 'user_access',
    'access arguments' => ['access awsImage'],
    'type' => MENU_CALLBACK,
  ];

  return $items;
}

then update the form to use the progress path created in the hook_menu - note the type MUST be 'bar' and the url MUST have the starting forward slash

function awsImage_form($form, &$form_state) {
.....

  $form['submit'] = [
    '#type' => 'submit',
    '#value' => t('Upload'),
    '#ajax' => [
      'callback' => 'awsImage_form_callback',
      'wrapper' => 'results',
      'method' => 'append',
      'progress' => [
        'type' => 'bar',
        'url' => '/path/to/page',
        'interval' => 1000,
      ],
    ],
  ];
....

}

then create your progress function. In my original awsImage_form_callback function I created and updated a session variable: $_SESSION['awsImage']['import_status']

function import_progress() {
  // set up default progress status message
  $progress = [
    'message' => t('Starting import...'),
    'percentage' => -1,
  ];

  // check if there is any status data

    $completed = (isset($_SESSION['awsImage']['import_status'])) ? $_SESSION['awsImage']['import_status'] : false; // calculate progress percentage here

    if ($completed) {
      // there is status data, so build the status message
      $completed = unserialize($completed);
      $total_files = $completed['total'];
      $current_file = $completed['current'];
      $current_file_name = $completed['current_filename'];
      $completed_percentage = ($current_file / $total_files) * 100;

      $progress['message'] = t('Processing:' . $current_file_name);
      $progress['percentage'] = (int) $completed_percentage;
    }

  drupal_json_output($progress);
}

Now when I upload & process multiple files, I get an update every second on which file I am uploading and how much there is left to go... Most of the time, sometimes the progress bar does not do any updates then just shows 100% and completes... but that may be down to local files uploading to a local server and there is not enough time!


Show list of node titles from a certain taxonomy term <?php
    $result = db_query("SELECT {node}.title, {node}.nid FROM {node} INNER JOIN {term_node} ON {node}.nid = {term_node}.nid WHERE {term_node}.tid = %d ORDER by {node}.title ASC LIMIT %d, %d", 5, 0, 30);
    while ($node = db_fetch_object($result)) {
        $nodes[] = l($node->title, 'node/'.$node->nid);
    }
    foreach($nodes as $list) {
        print $list.'<br />';
    }
?>

I want to print node titles from a certain taxonomy term inside a node.
it doesn't prints anything, and print_r($nodes) shows nothing. What's wrong with my code?

You have to enclose table names in curly braces {} everywhere they appear, not just in the FROM and JOIN clauses. So the correct query would be

SELECT {node}.title, {node}.nid
FROM {node}
INNER JOIN {term_node} ON {node}.nid = {term_node}.nid
WHERE {term_node}.tid = %d
ORDER by {node}.title ASC

You can also use table aliases instead.

If you use table prefixes, your query should have resulted in an error. Turn on PHP's error reporting if you did not see any error message.

If you do not use table prefixes, then the reason is, that the database query simply returns an empty result set (i.e. no node is tagged with the taxonomy term that has 5 as tid).

Also note the following:

In the line

$nodes = l($node->title, 'node/'.$node->nid);

you overwrite the previous result and thus the previous result is lost. But if a result would actually exist, at least the last result should be printed. Nevertheless, use

$nodes[] = l($node->title, 'node/'.$node->nid);

to be able to use all results.
You pass three arguments to the query (5, 0, 30), but the query only has one parameter (term_node.tid = %d). Are you sure that 5 is the tid you are interested in? The other arguments are ignored.
If you create a new revision of a node that has the requested term and then remove the term from the new revision, the node will still appear in the result set. Join on the vid of the node instead of on the nid to prevent this.


The same rules, only one being triggered I am working on a website and one (maybe more) rule is not being triggered.

The rule that is not working is as follows

Event:
After updating existing content
Condition:
Content is of type...
Actions:
Show a massage on the site...
...
More actions

I tried to reproduce the problem with a following rule

Event:
After updating existing content
Condition:
Content is of type...
Actions:
Show a massage on the site...

But it works.

The rule used to work. The portal is under development. There are many added modules.
The rule weight is the same.

The only difference between the two rules is the name (I tried changing the name) and actions performed.

Any idea what can be wrong?

UPDATE
I tried cloning the faulty rule and the clone does not work.
Below I attach the code of the faulty and working rules.

Works

{ "rules_test_update_rule" : {
    "LABEL" : "test Update Rule",
    "PLUGIN" : "reaction rule",
    "REQUIRES" : [ "rules" ],
    "ON" : [ "node_update" ],
    "IF" : [
      { "node_is_of_type" : {
          "node" : [ "node" ],
          "type" : { "value" : { "test_case" : "test_case" } }
        }
      },
      { "data_is" : { "data" : [ "node:field-workflow-status:tid" ], "value" : "28" } },
      { "NOT data_is_empty" : { "data" : [ "node:field-workflow-reviewers" ] } }
    ],
    "DO" : [
      { "drupal_message" : { "message" : "Test case got updated", "type" : "warning" } }
    ]
  }
}

Does not work

{ "rules_tc_admin_review_v1" : {
    "LABEL" : "TC: admin review",
    "PLUGIN" : "reaction rule",
    "REQUIRES" : [ "rules", "privatemsg_rules", "windbench_workflow", "og" ],
    "ON" : [ "node_update" ],
    "IF" : [
      { "node_is_of_type" : {
          "node" : [ "node" ],
          "type" : { "value" : { "test_case" : "test_case" } }
        }
      },
      { "data_is" : { "data" : [ "node:field-workflow-status:tid" ], "value" : "28" } },
      { "NOT data_is_empty" : { "data" : [ "node:field-workflow-reviewers" ] } }
    ],
    "DO" : [
      { "drupal_message" : { "message" : "User has been notified.", "type" : "warning" } },

........ more in the "DO" section, should be irrelevant.....

That is a weird one.

I don't know what caused the problem but the fix was to export and import the rule.

The interesting part is that cloning the rule did not work, even when I simplified/changed the cloned rule to

{ "rules_tc_admin_review_cloned_" : {
    "LABEL" : "TC: admin review (cloned)",
    "PLUGIN" : "reaction rule",
    "REQUIRES" : [ "rules" ],
    "ON" : [ "node_update" ],
    "DO" : []
  }
}

The rule was never checked.
There seems to be a bug. Possibly in the rule cloning function.


Updating Commerce Kickstart’s Contrib Modules What is the recommended way to update outdated Drupal contrib modules? The Commerce Guys doing a great job to keep Commerce secure and updated. However there’s always a Contrib Module update around. For the most part this isn’t an issue. Most of the Contrib Module updates are maintenance fixes. However what about security fixes for Contrib Modules? Usually I don’t touch the /profiles/commerce_kickstart/modules/crontrib folder and I am waiting until a new Commerce Kickstart release is published.

Does Commerce Kickstart uses special Contrib modules? Can I update ctools, Webform myself?

First, you need to understand that Commerce Kickstart is a Distribution. So your goal is to learn how to update a Drupal distribution before their official release.

For the most part you would need to understand how Drupal Make works. Where is a great article ( Maintaining your installed Drupal distro.) that would explain you how to maintain Drupal distributions.

If you successfully was able to update your Drupal distribution (commerce_kickstart) using Drupal Make. You should created a patch and provide that patch to the commerce_kickstart issue queue.


How to change access callback of user entity when entity module is installed? (how to make sure my alteration is the last) I want to change the 'access callback' of user entity to my own access function or at least alter the original function 'entity_metadata_user_access'.

The problem is that 'entity module' which I need because of others' module dependencies already alters the 'user entity information' and changes the 'access callback' to its own function 'entity_metadata_user_access' and so when I alter it with my module, the entity module re-alters it to 'entity_metadata_user_access'.

To make it more clear, the entity module is alters the entity info after me which causes that the final value of the callback is not mine (does not come from my alteration) but its and therefore the callback is wrong.

I know that I could modify the module itself but I honestly don't want to do that because it makes later updates painful.

Here is a complete working example of overriding entity_metadata_user_access:

/**
 * Implements hook_module_implements_alter().
 */
function YOURMODULE_module_implements_alter(&$implementations, $hook) {
  if ($hook == 'entity_info_alter') {
    $group = $implementations['YOURMODULE'];
    unset($implementations['YOURMODULE']);
    $implementations['YOURMODULE'] = $group;
  }
}

/**
 * Implements hook_entity_info_alter().
 */
function YOURMODULE_entity_info_alter(&$entity_info) {
  $entity_info['user']['access callback'] = 'YOURMODULE_entity_metadata_user_access';
}

/**
 * Overrides entity_metadata_user_access function.
 */
function YOURMODULE_entity_metadata_user_access($op, $entity = NULL, $account = NULL, $entity_type = NULL) {
  // Include Entity API module's logic
  $return = entity_metadata_user_access($op, $entity, $account, $entity_type);

  // Do your own logic here:
  // $return = $return || ...

  return $return;
}


User Registration Disable Email Verification The issue is for non admins to only view a particular part of the user section. The current password and email address fields need to be hidden. I've tried the field permissions but that doesnt give an option.

Writing the hook makes sense to hide both the fields but the validation is what I'm having issues with. If I add optional mail or the mail control modules, I'm thinking its going to throw a few other things off.

You need to do a lot more than just unsetting the field if you want to change the way registration works. Out of the box, Drupal expects a valid email unique address for every user. This is why there are contributed modules for this purpose: it needs a fair amount of code to achieve.

Take a look at https://www.drupal.org/project/optional_mail for example.


Place a block inside a twig template I've got a custom content type 'professor', and a 'node--professor.html.twig' in my theme (derived from 'classy') to override the standard markup. The designer wants me to put a list (a view?) of the professor's 'courses' (which is another content type) between the professor's contacts and biography, basically, INSIDE the 'node--professor.twig.html'. Is there a Drupal-way to do it?

And, by the way, what is the main difference between a page with a custom content type and a custom content entity? Do I need to write a module and a content entity, or custom content type can do the trick?

Download and enable Twig tweak module:

  Twig Tweak module provides a Twig extension with some useful functions
  and filters that can improve developer experience.

And then on your twig template put:

{{ drupal_view('view_name', 'block_1') }}

{{ drupal_block('block_id') }}

Themers Little Helper

  Some of the Filters and functions, backported from TFD7 theme engine
  and other things that can help a themer getting stuff done without to
  much hassle :)

{{ drupal_block(block_delta) }}

Bamboo Twig

  The Bamboo Twig module provides some Twig extensions with some useful
  functions and filters aimed to improve the development experience.

  Bamboo Twig has a lot of advantages and brings a lot of new features
  to the Twig landscape of Drupal 8. It boosts performance by using lazy
  loading, improves the code quality with automated workflow. It also
  includes automated unit and kernel tests to ensure stability.

{# Render the `system_powered_by_block` block #}
{{ bamboo_render_block('system_powered_by_block') }}


Translating Views Pager Help, how to translate paginator in views? In my views I used a mini pager with tags backwards/forwards. Tried to do through translate interface, but nothing happened.

After Installing i18nviews Module, You should check admin/config/regional/translate/translate where you should search for the string

Here is a discussion going about it : Views pager translation not working


Get top 5 recent post by taxonomy term I am new to Drupal and I have started overriding Twig files in Drupal 8. I have a requirement where I want other top 5 posts by taxonomy term.

Suppose I have a category as JavaScript. And I am on the node where I am displaying a post on JavaScript. On the same page I need other posts on JavaScript.

I have looked for twig file theme/templates/content/node--article.html.twig and tried to override it.

I have even tried to debug the node using kint tool. I have looked for my requirements in node and content variable.

{{ kint(node) }}
{{ kint(content) }}

But no success. I need suggestion where can I can other posts of same category in twig file. Any suggestion is appreciated.

First of all, you say:

  I have started overwriting Twig files in Drupal 8.

I hope you mean "overriding" Twig files.

Rule #1: Don't hack core.

Secondly, as leymannx suggests in the comment above, this is better accomplished using Views rather than in a Twig template.


Simple twitter module recommendation Can anyone recommend me a simple twitter module which will enable me to include twitter feeds on my site? I am using a corporate clean theme and would like to display it in the middle column of the footer section.

You should use the Twitter module.

  This module provides API integration with the Twitter microblogging service. Out of the box, it allows users to:

  Associate one or more Twitter accounts with their Drupal user account
  List tweets in different ways thanks to Views
  Post to their own Twitter account or a site-wide Twitter account whenever they create new content or based on Drupal Actions or Rules
  Log in to your Drupal site via Twitter
  Format twitter @usernames and #hashtags as links to Twitter.com


How to update user fields from a custom module form? I need to simply update some user fields from a custom  module form.

I try this but it doesn't works :

/**
 * Submit the register form
 *
 * @param array $form
 * @param FormStateInterface $form_state
 * @return array|RedirectResponse
 */
public function submitForm(array &$form, FormStateInterface $form_state)
{
    // Create a new user
    $values = $form_state->getValues();

    // User from Drupal\user\Entity\User;
    $user = $this->ctrUserManager->getCurrentUser();

    if($user){

        $user->set('mail', $values['mail']);
        $user->set('field_last_name', $values['field_lastname']);
        $user->set('field_first_name', $values['field_first_name']);
        $user->set('field_civility', [$values['field_civility']]);

        $violations = $user->validate();

        if (count($violations) === 0) {
            $user->save();
            \drupal_set_message('Your profile has been updated');
            return $form;
        }
    }

    \drupal_set_message('Error during user profile update', 'error');

    return $form;
}

you are not saving the user correctly, you should call:

$user->save();

This is an example how to change the username:

$user->setUsername('new-username');
$user->save();

Here is another example to add a role to a user:

$user->addRole('administrator');
$user->save();

Can you try the following:

/**
 * Submit the register form
 *
 * @param array $form
 * @param FormStateInterface $form_state
 * @return array|RedirectResponse
 */
public function submitForm(array &$form, FormStateInterface $form_state)
{
    // Create a new user
    $values = $form_state->getValues();

    // User from Drupal\user\Entity\User;
    $user = $this->ctrUserManager->getCurrentUser();

    if($user){

        $user->set('mail', $values['mail']);
        $user->set('field_last_name', $values['field_lastname']);
        $user->set('field_first_name', $values['field_first_name']);
        $user->set('field_civility', [$values['field_civility']]);

        $violations = $user->validate();

        if (count($violations) === 0) {
            $user->save();
            drupal_set_message('Your profile has been updated');
        } else {
            drupal_set_message('Error during user profile update', 'error');
        }
    }
}


Dynamicly generated block_info? I am writing a module that enables admins to create entities. One of the fields on the entity is a cut-off date.

For each entity within the cut-off date a block is produced. I do this by means of a EntityFieldQuery inside hook_block_info.

The user can then configure those blocks to appear on certain paths.

This approach seems to be working, but I'm a little unsure:

is it safe (i.e. reliable)? I'm unsure how drupal handles all the config for blocks - if the block does not exist any more is its config all deleted?
is it an efficiency nightmare? Currently it's only searching a handful of entities for in-date ones, but I'm interested to know if there could be a more efficient way because I guess this will run for every single page load.

Thanks,

RE 1: If the block no longer appears in the hook_block_info(), then yes, the block's config will eventually be removed. I'm a little unsure of the timing (clearing cache / cron operation). You can use _block_rehash() to force an update of the available blocks.

RE 2: Not a nightmare, no. Keep an eye on your entities to ensure the list doesn't get out of control, but that's all you need to worry about. hook_block_info() doesn't get called on every page load, but rather only when:

the cache is cleared
the blocks administration page is loaded
another module calls _block_rehash().


Module builder as drush plugin I thought I had installed successfully module builder as drush plugin : typing help mb returns complete help story...

But when I try to use it, ie typing mb easyresponsive_panels ctools_plugin_directory menu  --write, it gives me the following error :

  Command mb-build needs a higher bootstrap level to run - you will need
  to invoke drush from a more functional Drupal environment to run this
  command. The drush command 'mb easyresponsive_panels' could not be
  executed. Could not find a Drupal settings.php file at
  sites/default/settings.php.

I have a multi site install, this is why no sites/default/settings.php is found.

I tried to specify root and site explicitly, as per these answers, running  --root=path/to/drupal --uri=mysite.com status, this returns the correct complete status :

Drupal version : 7.24
Site URI : visages_20131224:8082
Database driver : mysql
Database username : drupaluser
Database name : visages_20131224
Database : Connected
Drupal bootstrap : Successful
Drupal user :
Default theme : neptune
Administration theme : adaptivetheme_admin
PHP executable : php.exe
PHP configuration : C:\wamp\bin\php\php5.3.13\php.ini
PHP OS : WINNT
Drush version : 7.0-dev
Drush configuration :
Drush alias files :
Drupal root : C:\Users\Thierry\Sites\visages_20131224\
Site path : sites/visages_20131224
File directory path : sites/visages_20131224/files
Temporary file directory path : c:\windows\temp

(my dev config : Windows 7, Acquia Dev Deskstop, Netbeans, D7)

Related Q&A didn't enlightened me yet, any help is welcome.

Thanks to Clive comments, and as explained in Drupal, Drush aliases and how to use them, I solved it as following.

Add an alias conf file named sitename.aliases.drushrc.php in .drush folder in your home directory :

/**
 * Local
 */
// The site in sites/default/
$aliases['default.local'] = array(
  'uri' => 'default',
  'root' => '/path/to/drupal',
  'path-aliases' => array(
    '%dump-dir' => '/tmp'
  ),
);
// The site in sites/sitename/
$aliases['sitename.local'] = array(
  'uri' => 'sitename_URI',
  'root' => '/path/to/drupal',
  'path-aliases' => array(
    '%dump-dir' => '/tmp'
  ),
);

Don't forget to clear cache : drush cache-clear drush.

Test your alias : @sitename.local status.

Now you can run i.e @sitename.local mb mymodule hook1 hook2 --write

Really powerful !

See Drush multi-site aliases for complete configuration of local/remote aliases


Validate URL alias before saving Node I have a custom content type which has a url alias pattern of [node:type]/[node:title].

How can I validate the node form in order to prevent the url alias from becoming [node:type]/[node:title]-0 in case the same title is used somewhere else.

Basically, I would like to prevent the node from saving, and display an error message if the url alias will end up having a "-0" at the end.

How about using the Unique field module for this? Here is a quote about the module's project page:

  This module performs additional validation when a node is created or updated by a user to require that a node's title, author, language, and CCK fields are unique within a given context.


How can I alter the HTML output of a specific content-type in display mode via a module, without creating the node type in a module? I have a specific node-type: resource. The default display of a resource node is not quite what I want, so I need to over ride the themeable output - so far so good. The problem is, I've created my resource node-type through the Drupal 7 GUI. How do I write a module that just over rides the HTML output for this one content-type?

...and, in piggyback to that question - I will have many other node-types that I've created through the GUI, but need custom output for. Is there a way to create just a single module that will handle the custom output for all of these types?

Thanks.

IMO, a very good approach would be using Display Suite to generate the basic markup/layout and then add the appropriate styling to the theme.


How do I update a user profile with entity_metadata_wrapper()? I got an error while updating user profile data such as name,password and email. I am using entity_metadata_wrapper() for processing update.

  exception 'EntityMetadataWrapperException' with message 'Unknown data property original.' in C:\xampp\htdocs\phone_bay\sites\all\modules\entity\includes\entity.wrapper.inc:335\nStack trace:\n#0

This is my code.

require './includes/password.inc';
function commerce_services_user_update($uid, $data, $flatten_fields) {
    $user = user_load($uid);
    $wrapper = entity_metadata_wrapper('user', $user);
    dpm($wrapper->value());

    $name = $data['name'];
    $password = $data['password'];
    $email = $data['email'];

    if ($name != null) {
        $wrapper -> name  = $name;
    }
    if($password != null){
        $wrapper -> pass = user_hash_password($password);
    }
    if ($email != null) {
        $wrapper -> mail = $email;
    }

    try {
        user_save($wrapper);
        $message = "successessfully update!";
    } catch (Exception $e) {
        $message = "not success! -> ". $e;
    }

    $reply = (array('status' => $status,'message' => $message));
    return $reply;
}

Since you are using an entity wrapper, you must use $entity->save to save the updated user object. In your case, use $wrapper->save.
user_save() can be used when the user entity is loaded using user_load().


Migrated a drupal database from a preview site to a live site and am now getting an error Migrated a drupal database from a preview site to a live site and am now getting an error.

(I only moved the database)

The selected file /tmp/filethQvCf could not be uploaded, because the destination css/css_4b1c49411f8ee294df61cf73ebc413c6.css is not properly configured.

I should note that /sites/default/files/ctools/css is chmod 777

Figured it out. As admin:

admin > settings > file system

The Temporary directory was set to a different path that didn't exist in the preview site.


Deploying content updates from staging server to live server We are trying to deploy content updates from our staging server to our live server but are having difficulty finding a good way to do this. We need to be able to deploy new pages, page updates and occasinally page deletes. Our site also makes extensive use of the book module so the Deploy module doesn't work for us at this time. We are using features for large structure updates. So, our concern is just the daily content updates.

Are there any modules that can do this and handle book pages?

UUID and UUID Features allows you to export a Node to a Feature, which could be just what you're after, means no need to mess with the database.


limit access to some configuration pages (manage display and manage fields) I have editor and administrator role in my website, the editor role must have "Administer vocabularies and terms" permission (in admin/people/permissions page),

How can I restrict editors from "manage display" and "manage fields" without uncheck "Administer vocabularies and terms" , so they can't access to this page : admin/structure/taxonomy/VOCABULARY_NAME/display/?

I would probably go into one of my custom modules and:

invoke a hook_permission() with my new needed permission (administer display and fields) that will be granted only to admin.

Then invoke hook_menu_alter() to alter the access control on the menu path the taxonomy module creates.

This way on install admin will be granted automatically the permission and only the roles granted this permission will be able to access that page.


Control content type availability based on day and time I have a website that delivers products that are ordered during the day.  I would like the order form to only be available during business hours.  Outside of those hours, the form shouldn't be available for ordering.

I am using Webform but I can easily enough create my own content type if needed.  I've looked into using Rules, but I am not sure how to write the rules to accomplish this.

I thought there would already be a quick and easy module for this, but I have not been able to find one.  Any suggestions?

This is quite straight forward with rules.

Create a page called "Order Form Unavailable" with your message about products only being available during the day.
Enable the PHP Filter module.
Create a rule with event "Content is viewed" of type "Order form Webform" (Or whatever)
Add condition "Execute custom PHP code".

Add the following into the PHP text area...

if( (date('H') < 9) && (date('H') > 17) ){
 // before 9AM and after 5PM
 return TRUE;
}

Add action "Page Redirect" to redirect the user to the "Order Form Unavailable" page.


AJAX button - HTML in #value causes problems i have an Ajax button, the code looks like this:

class coolButtons {
  public function getFormFieldAjaxButton() {
    return [
      '#type' => 'submit',
      '#value' => t(' Ajax Button'),
      '#name' => 'ButtonAjax',
      '#submit' => ['ajax_submit'],
      '#ajax' => [
        'callback' => 'ajax_callback',
        'wrapper' => 'button-fieldset-wrapper',
      ],
      '#attributes' => ['class' => ['btn-primary btn-sm']],
    ];
  }
}

function cool_form ($form, &$form_state) {
  $buttons = new coolButtons();
  $form['fieldset-buttons'] = [
    '#type' => 'fieldset',
    '#title' => t('Buttons'),
    '#collapsible' => TRUE,
    '#collapsed' => FALSE,
    '#prefix' => '
',
    '#suffix' => '
',
  ];

  $form['fieldset-buttons']['button_ajax'] =
        $buttons->getFormFieldAjaxButton();
}

function ajax_callback($form, $form_state) {
  if ($form_state['triggering_element']['#name'] == 'ButtonAjax') {
    return $form['fieldset-buttons'];
  }
}

function ajax_submit($form, &$form_state) {
  if ($form_state['triggering_element']['#name'] == 'ButtonAjax') {
    drupal_set_message('You clicked a very cool ajax button!');
  }
}

The value of the button has HTML in it, which causes problems.

1.) I can't have more than one of these buttons with html in the #value in one form, because then every button will perform the first defined statement in ajax_callback and ajax_submit regardless of the if statements (and thus, regardless of fieldset, #name etc.).

2.) At the bottom of the form, text will appear in the following form:

Ajax Button" />

Is there a way around it, or is the only solution to not use HTML in the #value of the buttons?

I am using Drupal 7.

Edit:

The slightly altered functions in rdp_cellmodel.module:

/**
 * Implements @see \hook_theme_registry_alter().
 */
function rdp_cellmodel_theme_registry_alter(&$theme_registry) {
  drupal_set_message('Boop?');
  if (isset($theme_registry['button'])) {
    $theme_registry['button']['function'] = 'rdp_cellmodel_button';
  }
}

/**
 * TODO: Description
 *
 * @param $variables
 *
 * @return string
 */
function rdp_cellmodel_button($variables) {
  $element = $variables['element'];
  $element['#attributes']['type'] = 'submit';
  element_set_attributes($element, array('id', 'name', 'value'));

  $element['#attributes']['class'][] = 'form-' . $element['#button_type'];
  if (!empty($element['#attributes']['disabled'])) {
    $element['#attributes']['class'][] = 'form-button-disabled';
  }
  if (!empty($element['#glyphicon'])) {
    $glyph_name = $element['#glyphicon'];
    return '<button' . drupal_attributes($element['#attributes']) . ' /> '.
      $element['#value'] .'</button>';
  }
  else {
    return '<input' . drupal_attributes($element['#attributes']) . ' />';
  }
}

And here the form field in a class file:

/**
   * @return array
   */
  public function getFormFieldGeneratePreview() {
    return [
      '#type' => 'submit',
      '#value' => t('Preview Name'),
      '#name' => 'PreviewButton',
      '#submit' => ['ajax_submit'],
      '#ajax' => [
        'callback' => 'ajax_callback',
        'wrapper' => 'hpscreg-fieldset-wrapper',
      ],
      '#attributes' => ['class' => ['btn-primary btn-sm']],
      '#limit_validation_errors' => [],
      '#glyphicon' => 'refresh',
      '#suffix' => '

',
    ];
  }

Edit 2:

Here is the proper way of adding glyphicons to your buttons, you alter the button function and use a custom made one.

function mymodule_theme_registry_alter(&$theme_registry) {
  if (isset($theme_registry['button'])) {
    $theme_registry['button']['function'] = 'mymodule_button';
  }
}

function mymodule_button($variables) {
  $element = $variables['element'];
  $element['#attributes']['type'] = 'submit';
  element_set_attributes($element, array('id', 'name', 'value'));

  $element['#attributes']['class'][] = 'form-' . $element['#button_type'];
  if (!empty($element['#attributes']['disabled'])) {
    $element['#attributes']['class'][] = 'form-button-disabled';
  }
  if (!empty($element['#glyphicon'])) {
    $glyph_name = $element['#glyphicon'];
    return '<button' . drupal_attributes($element['#attributes']) . ' /><span
      class="glyphicon glyphicon-' . $glyph_name . '"></span> '.
      $element['#value'] .'</button>';
  }
  else {
    return '<input' . drupal_attributes($element['#attributes']) . ' />';
  }
}

Then all you have to is add #glyphicon element to the submit and assign it the glyphicon name:

  $form['submit_button'] = array(
    '#type' => 'submit',
    '#value' => 'Send',
    '#glyphicon' => 'envelope', // in your case use "refresh"
  );

Result:


How to create options in installation profile/ distribution to enable custom content types? I have created a custom installation profile/ distribution with exported config files of a site. I have 4 content types in this site from which two will be installed by default but for other two are optional.

I can see a couple of options:

Creating a custom module for each content type and putting related config files in it. (This does not allow any option at installation time although I can enable the module using info file of profile)
Custom form alter of installation form and add check boxes.(If I want to combine this with option 1 then how can I do that?)

Checkbox-> Content type 1 (This is disabled and checked)

Checkbox-> Content type 2 (This is disabled and checked)

Checkbox-> Content type 3 (Optional)

Checkbox-> Content type 4 (Optional)

All the related config files of checked content types should be enabled at installation.

I would like to go with option two and give user check boxes at the time of installation of profile but if there are any better ways to do it then please do suggest.

Thanks in advance.

I would think in either case, you should provide the Content types as modules and allow the user to enable them any time after installation. Otherwise, how do you expect them to enable the content types if he chooses to skip them during install?

The way to provide additional options during a profile install is hook_install_tasks(), also check this blog.


Earliest hook to generate content during user registration During the user registration process in Drupal 7, at which point can I access the newly created UID to create 'default content' for that user?  I would like to do this as early on as possible.  Preferably before the user has been approved by an admin or before they have verified their email address.

You can use hook_user_insert(), it should be early enough for you.

Technically speaking, hook_user_presave() is the first hook called from user_save() (even before the user is written to the database), but according to the documentation it is "primarily intended for modules that want to store properties in the serialized {users}.data column". More importantly, it is also invoked when a user account is updated, so that wouldn't fit your use case.


Programmatically translate a string in hook_update_N() Is there a function I can use to perform a string translation in hook_update_N()?

Yes, you can check in the locale module how it's done and replicate to use the same queries like this :

/**
 * Translating some pagination strings.
 */
function hook_update_XXXX() {
  $translations = array(
   'last' => array(
     'fr' => 'dernière page',
     'en-en' => 'last',
   ),
   'first' => array(
     'fr' => 'première page',
     'en-en' => 'first',
   ),
 );

 foreach ($translations as $string => $values) {
   $source = db_query('SELECT lid, source, context, textgroup, location FROM {locales_source} WHERE source = :string', array(':string' => $string))->fetchObject();
  if (!$source) {
    watchdog('update_hook', 'Translation of string "%string" failed.', array('%string%' => $string));
    continue;
  }

  foreach ($values as $langcode => $translated) {
    $translation = db_query('SELECT translation FROM {locales_target} WHERE lid = :lid AND language = :language', array(':lid' => $source->lid, ':language' => $langcode))->fetchField();
    if (is_string($translation)) {
      db_update('locales_target')
      ->fields(array('translation' => $translated))
      ->condition('lid', $source->lid)
      ->condition('language', $langcode)
      ->execute();
    }
    else {
      db_insert('locales_target')
      ->fields(array(
        'lid' => $source->lid,
        'translation' => $translated,
        'language' => $langcode,
      ))
      ->execute();
      }
    }
  }
}

I'm using such code to update strings in code instead of having to this manually when deploying code. So a simple "drush updb" can do the job for me.

OR as I've found out recently, a faster version exists like this :

/**
 * Translating some strings.
 */
function hook_update_X() {
  $report = array(
    'skips'=> 0,
    'updates'=> 0,
    'deletes'=> 0,
    'additions'=> 0
  );

  // Translate strings.
  _locale_import_one_string_db($report, 'fr', '', 'Your shipping address book is currently empty.', 'Votre carnet d\'adresses de livraison est actuellement vide.', 'default', '', LOCALE_IMPORT_OVERWRITE);
  _locale_import_one_string_db($report, 'fr', '', 'Your billing address book is currently empty.', 'Votre carnet d\'adresses de facturation est actuellement vide.', 'default', '', LOCALE_IMPORT_OVERWRITE);

  // Clear locale cache.
  cache_clear_all('locale:', 'cache', TRUE);
}

For Drupal 8, please see this answer : https://drupal.stackexchange.com/a/220608/61138


Want parent MENU_LOCAL_TASK tab to show when on a child page I have a set of local task menu items defined in my module. This includes the following items:

control => MENU_NORMAL_ITEM
control/jobs => MENU_DEFAULT_LOCAL_TASK
control/jobs/% => MENU_???
control/download => MENU_LOCAL_TASK
control/settings => MENU_LOCAL_TASK

The three menu items (jobs, download and settings), display as tabs, as I want. When someone clicks through to see a particular job, I want this to show as having the jobs tab selected.

If I add MENU_LOCAL_TASK to "control/jobs/%," the tabs show up, but I get notice errors (because Drupal is trying to define a link to % and can't know that).
If I don't, the specific job page does not have any tabs at the top.

Have I misunderstood anything? Can I achieve this in another way?

You can do what you want, but you need to change the url structure a bit. If I understand you correctly:

control/jobs: List of all jobs, should be MENU_NORMAL_ITEM
control/jobs/%node (You should have a load function for the job, if not a node than something else), should be MENU_NORMAL_ITEM
control/jobs/%node/view:  MENU_DEFAULT_LOCAL_TASK (doesn't have  a callback)
control/jobs/%node/download: The download page for a specific job, MENU_LOCAL_TASK
control/jobs/%node/settings: The settings page for a specific job, MENU_LOCAL_TASK

You can take a look at the node and user module to get an idea on how create tabs in Drupal


Creating multiple nodes of different content type at once Can someone tell me if there is a module that will allow a user to create multiple nodes of different content types within one form?  I have a base content type that can have a 1 to many relationship to another content type. I want the user to be able to create the base content type node along with 1 to n nodes for the second content type.

The module you are looking for is Node Reference Create. Here is a quote about it (from the module's project page):

... is an enhancement to the nodereference autocomplete widget that allows users to reference non-existent nodes.
When no matching node is selected, the new nodes are automatically created allowing for a seamless and intuitive user experience that is similar to free tagging.


How to programmatically add a field to all product types? In Drupal 7, I need to programmatically add a file field to all product types. I've tried the following in the enable hook for my module, but to no avail:

$field = array(
  'field_name' => 'my_name',
  'type' => 'file',
  'cardinality' => -1
);
field_create_field($field);

// Create the instance on the bundle.
$instance = array(
  'field_name' => 'my_name',
  'entity_type' => 'product',
  'label' => 'label',
  'bundle' => 'product',
  'required' => TRUE,
  'settings' => array(),
  'widget' => array(
    'type' => 'file_generic',
  ),
);
field_create_instance($instance);

What am I doing wrong?

The entity as defined by drupal commerce should be commerce_product:

function commerce_product_entity_info() {
  $return = array(
    'commerce_product' => array(
      'label' => t('Commerce Product'),
      ...
    ),
  );
  ...

  return $return;
}


creating users form in drupal 7 What is the easiest way to prepare separate admin panels for creating users of different roles/profiles e.g. 'add editor', 'add client', 'add subscriber' etc. that will have separate set of fields?

If you are familiar with drupal module development, I would recommend to write custom code. You may have 3 user roles - editor, client and subscriber. You can create user fields at admin/config/people/accounts/fields, but you cannot have separate set of fields by role. You can manage (hide/show) those fields upon user role selection from your custom module.

Please check this answer.


Trade-offs between Job Queue vs. Drupal Queue Anyone familiar with both Job Queue and Drupal Queue enough to offer an idea of the tradeoffs between the two?

In case it makes a difference, the site I'm working on uses Drupal 6. The queue I'll be creating will check a batch of user accounts with a REST API, to verify whether the users have logged into another system. Until the API gets updated (hopefully soon) each user requires a separate request, which is why I'm batching them.

Drupal Queue is a backport of Drupal 7's queue API for Drupal 6. It provides basically the same features as Job Queue. However a big advantage with Drupal Queue is that it uses the same API as Drupal 7 Core. This means if your module uses Drupal Queue in D6, your upgrade path to 7 will be effortless.


Rules Custom Condition for registration capacity I am trying to learn Rules and adding a custom condition. I need help to figure out what I am doing wrong.

My Condiiton set up:

function rules_example_capacity_condition_info() {
   $conditions = array(
     'rules_example_action_count_capacity' => array(
       'label' => t('Print capacity count on page'),
       'group' => t('Rules examples'),
       'parameters' => array(
         'count' => array('type' => 'value', 'label' => t('registration event count')),
         'capacity' => array('type' => 'value', 'label' => t('registration event capacity')),
         ),
       ),
     );
     return $conditions;
 }

and the function that calls it...

function rules_example_action_count_capacity($count, $capacity) {
    $reg_count = reg_count_load($count);
    return($reg_count->capacity == $capacity) ? true : false;
}

I am trying to determine the count (how many people have registered so far) and the capacity. When the count and capacity are the same send an email.

I am not a developer so this is a little bit of a struggle. I found this series (http://nodeone.se/node/28) which is helpful, however there are so many smaller things I might be missing. Please help if you can. I am hoping that this will help more then just myself.

Thanks
Tim

Looking at your function, I believe you need to rename it to something like mymodule_rules_condition_info. The hook you are trying to implement is hook_rules_condition_info(). Did you find that your custom condition was showing up when you were editing a rule?

function MYMODULE_rules_condition_info() {
   $conditions = array(
     'mymodule_event_is_at_capacity' => array(
       'label' => t('Event has reached maximum registrations'),
       'group' => t('MY MODULE'),
       'parameters' => array(
         'registration' => array(
            'type' => 'registration',
            'label' => t('The registration event'),
           ),
         ),
       ),
     );
     return $conditions;
 }

Semantically you may want to call your condition 'mymodule_event_is_at_capacity' and it should only need one parameter which is the capacity that you will provide in the Rules UI.

The function you will be writing mymodule_event_is_at_capacity($capacity) will query for the number of (active) users in Drupal, and if it is greater than or equal to $capacity, it will return TRUE.

All of this can be kicked off by add a new Rule that reacts on the "After saving a new user account" event.


Drupal 6 ubercart customise cart page I want to make a small modification to the ubercart cart page in my theme.

A typical item row on the cart page looks like this

[remove button] [product image] [product title] [quantity field] [row total]

All I want to do is move the [remove button] to the right hand side after [quantity field].

How can I do this?

You need to alter the default Ubercart's theming of the shopping cart form and increase the weight of "Remove" column so it is pushed to the end.
Add the following code to your theme's template.php file.

/**
 * Themes the uc_cart_view_form().
 */
function phptemplate_uc_cart_view_form($form) {

  // Increase the weight of Remove column, so it goes to the end.
  $form['items']['#columns']['remove']['weight'] = 100;

  // The rest of the code is default Ubercart's code you can see in:
  // theme_uc_cart_view_form() function in uc_cart.module.
  drupal_add_css(drupal_get_path('module', 'uc_cart') .'/uc_cart.css');

  $output = '
';
  $output .= drupal_render($form['update']);
  $output .= '
';
  unset($form['update']['#printed']);

  $output .= '
'
          . drupal_render($form['items']) .'
';

  foreach (element_children($form['items']) as $i) {
    foreach (array('title', 'options', 'remove', 'image', 'qty') as $column) {
      $form['items'][$i][$column]['#printed'] = TRUE;
    }
    $form['items'][$i]['#printed'] = TRUE;
  }

  // Add the continue shopping element and cart submit buttons.
  if (($type = variable_get('uc_continue_shopping_type', 'link')) != 'none') {
    // Render the continue shopping element into a variable.
    $cs_element = drupal_render($form['continue_shopping']);

    // Add the element with the appropriate markup based on the display type.
    if ($type == 'link') {
      $output .= '

'
               . $cs_element .'
'. drupal_render($form) .'
';
    }
    elseif ($type == 'button') {
      $output .= '

'
               . drupal_render($form) .'

'
               . $cs_element .'

';
    }
  }
  else {
    $output .= '
'. drupal_render($form) .'
';
  }

  return $output;
}


Which file do I need to edit to implement a 'Back to top' link? I am running a Drupal 6.22 site, with a custom template installed in /sites/all/themes/mytheme. Which template file should I edit to implement a back to top link?

It depends where you want the link to be, but your best bets would probably be page.tpl.php, node.tpl.php or a variation of those templates (specific to content types, etc).

For more on templates see Drupal 6 template suggestions


Message "Restricted HTML" on node/add page On node/add page for any content type(Article, Basic page. Custom)  message appearing "Restricted HTML" , not able to add content.

What shall a do to resolve this problem?

Please try again after raising xdebug.max_nesting_level to 500 or so.

Steps:

Know where is the php.ini:

In your drupal site go to admin/reports/status/php

Then edit your php.ini in this case, is on /etc/php5/fpm/php.ini

Search the xdebug section:

Change the variable xdebug.max_nesting_level to 500 or add it.

Restart the web server.


Adding dividers between list items in the menu.html.twig template How do I add dividers between each
 in the menu.html.twig template. Obviously with the code below, the divider also gets added after the last item, which isn't the desired result.

{% import _self as menus %}

{#
  We call a macro which calls itself to render the full tree.
  @see http://twig.sensiolabs.org/doc/tags/macro.html
#}
{{ menus.menu_links(items, attributes, 0) }}

{% macro menu_links(items, attributes, menu_level) %}
  {% import _self as menus %}
  {% if items %}

    {% for item in items %}
      {%
        set classes = [
          item.is_expanded ? 'menu-item--expanded',
          item.is_collapsed ? 'menu-item--collapsed',
          item.in_active_trail ? 'menu-item--active-trail',
        ]
      %}

        {{ link(item.title, item.url) }}
        {% if item.below %}
          {{ menus.menu_links(item.below, attributes, menu_level + 1) }}
        {% endif %}

    {% endfor %}

  {% endif %}
{% endmacro %}

See The Loop Variable in the Twig docs; you can use something like

{% if loop.last == false %}

{% endif %}


display image inside a panel I have a small jpeg image that I want to display in a panel.

I created a panel with the layout I desired but I am confused as how can I display an image inside one of the columns of the panel.

I tried adding a new custom content in which it presents a html text area. But not sure how would I add the correct url without hard coding the entire path (i.e: the host and sub directory etc).

Please enlighten me :)

You can use custom content option in panel to add HTML...

Step 1 : Click on Add Content

Step 2 : Click on New Custom Content

Step 3 : Add HTML and select filter as Custom HTML

Step 4 : Save Changes


How can i restrict /admin login page to a particular IP only? I want to restrict the http://www.mysite.com/admin login page to a particular IP only. Do you have any suggestion?

I think I would go for doing this at the Apache level before hitting Drupal.

Have a look at the Apache manual for doing this but you are looking at something like this:

# Only allow request for admin only from localhost.
<Location /admin>
  Deny from all
  Allow from 127.0.0.1
</Location>

So admin will be denied for all but allowed from 127.0.0.1 for example. Also take in to account cleanurls. You will need to deny access to ?q=admin aswell.


Why are MailMime images not embedded when sending an eMail via Rules? I'm sending an email using Mail Mime, based on a rule. I receive the email, and I can see in the HTML source that, the image has been translated,

E.g.   <img src="cid:8215e4a9ecb00ce2ead763b488ee529e@dev.intranet"

But the image is not attached to the email. Do I need to explicitly allow Drupal to add attachments? I'm using Outlook if that makes any difference.

Update:

On further testing, I've noticed that when I use an embed image in the content, using HTML as a text type e.g

it produced the following in the Outlook email,

Note the missing "+".

I've turned off all text filters.

When I use plain text as the format, I get the content as expect, but of course Outlook does not think the message is in HTML, so displays the saw markup.

Any ideas on what could be causing the "+" to turn into a space?

Double check your setting on the mime mail configuration page.

In recent versions of the mime mail module there has been options added in relation to embedded images.

The option is called "Link images only". Generally I would turn that on as I don't see the need for embedding images in emails. You will generally have less issues with remote images.

There is also a permission for the mime mail module that relates to attached images, so check out the mime mail permissions too. Edit That permission is only a drupal 6 thing.

Update

In regards to your plus - space issue, what happens if you comment out the line

  $url = str_replace('+', '%2B', $url);

in the  _mimemail_url function in the mimemail.inc file?


How do you change the title of a field collection edit form? Here is an example edit URL for a field collection I have field-photo-block:

  /field-collection/field-photo-block/65/edit

The title of this page is being set to the title of the field collection. How do I change it to something descriptive?

In a custom module (or even theme), you can add this function. Replace YOURMODULE with the name of your module or theme.

<?php
function YOURMODULE_form_field_collection_item_form_alter(&$form, &$form_state, $form_id) {
  drupal_set_title(t('Your title'));
}


Can i populate /fill a Views exposed filter with a Rules result I have a group of nodes which are delivery nodes -prices-location-type etc.

I can sort them with a View and exposed filters - 'country' 'type' 'weight' to out put a price - really happy with it so far.

This works great - however I wish to populate the weight field with a value 'calculated weight' calculated in Rules - leaving only the 'country' and 'type' field open to the user.

I have looked for days now and think I have module overload!

Really would be grateful for any insight!

Thanks

I don't know if it's possible with Rules, though most things are!

But that should be possible with the Computed Field Module. It allows you to do just that, compute fields based on others and you can use it in your views.

https://drupal.org/project/computed_field


How to expose Taxonomy term in drupal 7 can any one help me how to expose the taxonomy term filter in view in drupal 7. I have created a view with

   Fields:

     1. Title

     2. Body

    FILTER CRITERIA:

     Has taxonomy terms (with depth)

when i expose this filter it is not getting exposed.

can anyone help me how to expose the taxonomy term field.I need to see the content get filtered based on the taxonomy term.

When you select the filter 'Has taxonomy terms (with depth)' under your 'Filter Criteria' section, make sure you select the correct vocabulary on the first screen of your setup.  There is a section for you to determine which vocabulary's terms you are trying to select from.

On the second screen, make sure you check the 'Expose this filter to visitors, to allow them to change it' checkbox.  It is actually unchecked by default.

It should then show up at the top of your view in the preview window.


How to change node id in drupal 7? I'm very new to drupal. I'm using drupal 7 with ckeditor. I've created one block with 3 views (Link, Image, Link) in it and I've wrote jQuery on 2 links. Then, I've developed second block with same type of views and wrote same jQuery for 2 links in this new block.

But I found (in FireFox using FireBug addon) that all links have same node id. views-field-view-node for 1st link and views-field-view-node-1 for second link for both blocks. So when I click on 1 block's 1st link, action fires in both blocks because drupal received same link id for another block also.

How can I change/modify this node id of view? So I can give separate action.

Used jQuery:

drupal_add_js("jQuery(document).ready(function() {
    // change slideshow with your view name
    jQuery('.view-slideshow .view-content').cycle({
        fx: 'fade',
        speed:  'fast',
        timeout: 3000,
        next:   '.views-field-view-node-1', // problem is here. This id is same for both block's link
        prev:   '.views-field-view-node'
    });
});", 'inline');

Thanks in advance....

This is not a Drupal related problem.

Your 'next' and 'prev' selectors are not specific enough. You should write also the parent block id.

Every block in a page has a unique id attribute in HTML. You should find stuff like

<div id="block-3" class="block">

wrapping your slideshow.

Just declare a more specific jQuery selector, adding the block id.

Here's a modification for your code, assuming that the block has a "block-3" id:

drupal_add_js("jQuery(document).ready(function() {
    // change slideshow with your view name
    jQuery('.view-slideshow .view-content').cycle({
        fx: 'fade',
        speed:  'fast',
        timeout: 3000,
        next:   '#block-3 .views-field-view-node-1', // added a 'parent child' jquery selector
        prev:   '#block-3 .views-field-view-node'
    });
});", 'inline');


How to make a page the home page of another domain I have some pages with urls like this:

http://example.com/landing/abcd
http://example.com/landing/efgh

as menu items:

    $items['landing/%'] = array(
        'title' => 'Landing page',
        'description' => 'Landing page',
        'page callback' => 'mymodule_landing_display',
        'page arguments' => array(1),
        'access arguments' => array('access content'),
        'type' => MENU_NORMAL_ITEM,
    );

Now i want to use them as the home page of the domains:

http://abcd.com/
http://efgh.com/

I don't want to use a simple redirect.

What is the best way to do it ?

Use Domain Access: https://www.drupal.org/project/domain

Core Drupal + Domain Access can do this, you don't need any code or custom modules. Your Drupal can load different content on each configured domain name.

Point all domains in Apache/Nginx at the same Drupal install
directory.
Install Drupal using your primary domain.
Create your Landing Page nodes using the default Page Content Type.
Install Domain Access.
Add a new Domain at: http://example.com/admin/structure/domain/create
Edit the Domain settings at: http://example.com/admin/structure/domain/view/:id/config and specify the Site frontpage.
Done.

If you want it in code, you can export the entire configuration with the Features module: https://www.drupal.org/project/features


Accidentally Deleted Admin Menu Items Hi i hope someone can offer me a bit of advice here. I seem to have deleted all my admin menu items. Is there a way to restore them without losing any data on my site?

thanks

Your menu items are probably still there but disabled. In Drupal 6, navigate to admin/build/menu-customize/navigation and check if your administrative menu items are enabled. In Drupal 7 the path is admin/structure/menu/manage/management.

If you re-enable any menu items, make sure you scroll to the bottom of the page and hit the Save Configuration button to save your changes.


What is causing this error message when using search module? I have a website using drupal 7.  It has a site search that produces and error only when I search the word "application".

This is the error:

Fatal error: Cannot redeclare my_form() (previously declared in /home/leader40/public_html/modules/php/php.module(80) : eval()'d code:8) in /home/leader40/public_html/modules/php/php.module(80) : eval()'d code on line 257

Any ideas on how to solve this or why it's happening?

You are declaring my_form function in two places somewhere in your block / view / Node where you are using php as filter. That is causing above issue.

Since you see above issue only in search page it should be an issue with blocks that are enabled in search page or search content...

Search in your database with keywords my_form using phpmyadmin or some other tool on all tables that will give you an idea from where the php code is getting executed !


Editing the front page template I am trying to change the format of the content promoted to the front page. I want to move the display order of the title below the image. By default it's set to title, image and then Read More.

Editing the content type (manage field, manage displays) does not do anything in this regard.

Manage display: I've set the order from Image first then Body. (no effect)

Teaser: I've set it to only show the Image (body is hidden) (no effect)

I've read the docs to change the page.tpl.php to page--front.tpl.php but I don't see any options to move the title down below the image in this file. (I only see this code in node.tpl.php.)

I can move the title block under the content block and it works, but this affects all pages.

How can I change this only for the front page, so it doesn't affect all pages?

node.tpl.php

Title block

<?php print render($title_prefix); ?>
<?php if (!$page): ?>
 <h2<?php print $title_attributes; ?>>
  <a href="<?php print $node_url; ?>"><?php print $title; ?>

<?php endif; ?>
<?php print render($title_suffix); ?>

Content block

<div class="content clearfix"<?php print $content_attributes; ?>>
<?php
  // We hide the comments and links now so that we can render them later.
  hide($content['comments']);
  hide($content['links']);
  print render($content);
?>

There are many possible ways to customize your front page content.

One of the easiest would be to create a view with page display and set the field order as you like and give a path to the view. Now you can change your frontpage to the path of this view (Configuration > Site Information - Default front page).

If you want to go with the standard front page and rearrange in the template as you described you could use drupal_is_front_page() to have different parts of the template for frontpage and other pages.


Is there a way to change Views base table dynamically? I have a couple of Search API indexes for different server environments (test, qa, uat, prod) with different configurations.

Instead of create 4 views in the admin, I just want to use one, and depending on environment, swap the base table (index). That way I can have one view at one URL.

Is that possible in Drupal 8?

Just use configs overrides services like described here https://www.drupal.org/docs/8/api/configuration-api/configuration-override-system

Example:

if (in_array('views.view.config.name', $names)) {
  $overrides['views.view.config.name'] = ['base_table' => 'your_base_table'];
}


Custom field in XML with Views RSS module I need to create an XML using Views RSS module, and it's created correctly. But I want to add a custom field to the XML. For example, an item from the XML is:

<item>
<title>Liburu bat</title>
 <link>http://whatever.com/comercios/productos/1022/botak</link>
 <description>Produktu bat</description>
 <category>Forros para botas %% Espuelas %% Calzado</category>
 <guid isPermaLink="false">1022</guid>
 <source url="http://whatever.com/es/comercios/productos/whatever.xml">Escaparate Whatever</source>
</item>

And I want to add a custom field to that item, for example:
Something else

Any idea how can I do it?

You need to implement a hook_views_rss_item_elements() invocation if you're wanting to add a custom item element. For example:

/**
 * Implements hook_views_rss_item_elements().
 */
function MYMODULE_views_rss_item_elements() {
  $elements['my_element'] = array(
    'title' => t('My Element'),
    'description' => t('Provides a my_element to an item element in Views RSS.'),
  );
  return $elements;
}


How to embed Twitter  and E-mail links inside a webform? I want to embed inside a webform a Twitter and E-mail button,so
as the user to post/share the page to his Twitter account or e-mail it.
How to do that?
Thanks

There is a module for that, in fact there are many. Since a webform is a node, it makes the possibilities much greater. An example of a module that allows users to share your content in various ways is the Service links module.


"An illegal choice has been detected. Please contact the site administrator." with exposed sort fields I have a panel which displays a page that was created in views. When a user clicks the next button on the pager, it displays the error "An illegal choice has been detected. Please contact the site administrator."

I've tracked this problem down to being caused by my exposed fields I use for sorting: When the pager is clicked, it submits to a URL like http://mysite.com/reviews?myfieldtosort_tid=All&sort_by=&sort_order=DESC&page=0%2C0%2C1.

The problem is that sort_by is empty; if I remove that attribute entirely the problem goes away. Alternatively, if I use the exposed sort, it adds the sort field and also works correctly.

What can I do to still use the pager, but have it remove the sort_by field when it is not needed?

I've solved by setting a default value in the form alter callback for views exposed form

function mymod_form_views_exposed_form_alter(&$form, &$form_state) {
  if($form_state['view']->name == 'yourviewname') {
    $_GET['sort_by'] = 'default_sort_name';
    $form_state['view']->set_exposed_input($_GET);
    $form_state['input']['sort_by'] = $_GET['sort_by'];
  }
}


How do I migrate only the items that previously failed? I have a migration class that has imported 2000 items correctly, but failed to import 40 of them.

Now I have corrected the import class, but I don't want to do a rollback and a full reimport/migrate.

Is there a possibility to import/migrate only the 40 failed items?

Another possibility is to use the "--needs-update" option as "migrate-import Article --needs-update" .

You might need to status of needs-update field for these 40 records as needs_update=1.

This option is only needed when your Drupal DB is on a different DB server from your source data. Otherwise, these records get migrated with just migrate-import.


Relocate Views' pager I'd like to relocate the pager generated by views and put it, in my page.tpl.php part, in order to display it at the very bottom of the page.

Is this possible?

I tried copying this code from a view to page.tpl.php but it didn't work:

  <?php if ($pager): ?>
    <?php print $pager; ?>
  <?php endif; ?>

Copying this code snippet into your page.tpl.php won't help because the $page variable will not be defined for this template. You can only move it freely inside the views-view.tpl.php template.

You can add a similar $pager variable to your page template using your theme or module's implementation of hook_preprocess_page(). In this implementation, you can retrieve the current page's view (if any) using views_get_current_view(). See the template_preprocess_views_view() function in Views' include/theme.inc for how to generate the pager from a view object. In Views 3.x the pager is build by the query plugin.


How to Button a Rules Link URL I'm using Rules Link, via a Views block set in a user Panel page. At the moment it sits ready for a users click response to trigger an event and works fine in its approach.

Prior to major Theming/CSS, I would like to have the generic 'Blue' URL text link show as a graphic button (ie generic 'bootstrap' style), can anyone advise the quickest way to change this so I can get a feel of the layout and look. I presume it's a CSS template addition, can someone give me some tips (I'm using Bootstrap)
Thanks in advance for any help.

After study, I used the above css with a 'btn btn-primary btn-block' in the Other of my View (where the Rule itself goes) in the CSS information properties.  It for now gave me a working button, but it does need some further CSS, but I have my answer.

Additionally, I added :

/* Rules Link Post unvisited link */
.rules-link-post-classified
a:link {
    color: #FFFFFF;
}
a:hover {
    text-decoration: none;
}
a:active {
    text-decoration: none;
}

into my theme.css (using currently the Tweme Bootstrap).
As I wanted white text on a blue button, and then I used the above css with a 'btn btn-primary btn-block' in the other of my View in the CSS information properties.

Furthermore, I didn't want the 'hover' underline to show on the link when the user moved over it to click, so I used the text-decoration as 'none' to remove it under the 'a:hover' with 'a:active' elements above.
BINGO!

There maybe more functional CSS ways in the file.css, but hey we're learning!


Session values are getting populated only when the page is refreshed I have a webform. I provide default values to these webform using session token variables. These session variables are set using hook_form_alter(). The problem is that when users log in, and see the form, it is not populated. When they refresh the form, only the values get populated.

How can I solve this issue?

/** updates **/

I have custom module like

webform_options_form_alter(&$form, &$form_state, $form_id){
//here i set some values for session variables like.
$_SESSION['name']  = 'pradeep';
}

so in webform default value i put like %session['name']. This takes the value when page is refreshed.

I have the login form as block on the same page of the webform. As soon as the user logs in the webform should be filled with user data. This is not happening. When he refreshes the page after login only he sees his data.

It sounds like your problem is how/when the session variables are set (they are not available on the initial form load). You don't mention how this is done.

Some code example and greater details in your question will allow for a more detailed answer.


How to have recurring date events? It appears there is no End Date or Date Repeat options for the datetime field in Drupal 8.

Are there any contrib options for recurring events in Drupal 8?

As of 2016/03/04, these are open issues in Drupal 8.  See Support for end date and D8: Date repeat feature requests.  The decision was made to move these from contrib into core, but they are complicated issues, and unfortunately touch the exact same portions of code, so working on them simultaneously is difficult.

As of 2016/12/07, support for end date is officially part of core, starting with 8.2.0.  It is looking like the date repeat feature is going to end up in the datetime extras module as part of contrib, and not core.  However, work on this is still preliminary.


How to import Custom Post Types of wordpress into Drupal? I've a wordpress site with around 500+ posts of a Custom Post Type with some custom fields attached to them.

I want to migrate them to Drupal. I've tried using wordpress_migrate. But it doesn't seem to work! This module didn't even seem to recognize the Custom Post Types. How can I import them?

This isn't currently available in wordpress_migrate however there is a feature request open here. https://drupal.org/node/1580412

Your best option would be to write a custom migration using Drupal's migrate module. You would need to write a custom source to load your data from WordPress and you'd be able to look at wordpress_migrate for help as needed.


Rules help: After updating existing content First time using Rules to make a complicated rule. Would appreciate some help. I'm making rules to send an e-mail, to a pre-defined e-mail address, after an existing node is updated. This node is of a certain type, and this type has a taxonomy term reference field. When any node of this type gets updated, by a user with certain role, Drupal should send an e-mail, and in the e-mail it should attach the name of the taxonomy term.

tl;dr/problem: What I'm having trouble is, when creating a condition to check the user's role (the user who updated the content, not the author). There seems to be only the "Author" of the node available on the Data selector (see attached image). Is node:author the correct one to check for the user who updated the content?

For your task you need site:current-user token which corresponds to $GLOBALS['user'] (global $user) object.

  I'm not sure how reliable this is when multiple users are logged in to the system?

Webserver creates new PHP thread (or process) for each request so there are no sharing variables between requests.global $user variable is initialized by Drupal on every request.

When you have just updated a node you can use global $user to know who updated this node. At any time after updating you can get that user id from revision ($node->revision_uid).


How to get current language in html.html.twig of theme I need to get the current language in the html.html.twig file of my theme. In my page.html.twig I can use:

{% if (language.getId() == 'nl') %}

This does not work in my html.html.twig. Any ideas?

Add the following snippet in your .theme file:

function MYTHEME_preprocess_html(&$variables) {
  $variables['lang'] = \Drupal::languageManager()->getCurrentLanguage()->getId();
}

Then, in your html.html.twig file use:

{% if (lang == 'en') %}
  // Your action
{% endif %}


Possible to turn off Twig debug mode for a specific template? I have overridden a Twig template for an image field, which uses Image URL Formatter in order to remove the surrounding Div's.

Here is my Twig template for the field (field--media--field-image--image.twig.html):

{% for item in items %}
    {{ item.content }}
    {% if loop.length > 1 and not loop.last  %}
        {{ ', ' }}
    {% endif %}
{% endfor %}

The field is output to the src tag in the Twig template for my Media Bundle (media--image.twig.html):

    {% if href is not empty %}

    {% endif %}

    {% if href is not empty %}

    {% endif %}

However, the twig debug information outputs as part of the image URL:

Is there any way to turn off twig debug for a specific template?  Or any other way around this?

There is also this alternative found here and here where you can do something like this using the triple filter |render|striptags|trim :

<img src="{{ url_image }}" alt="{{ title|render|striptags|trim }}" />

It worked perfectly in my case (|escape didn't work)