Importing SQL databases The website I am creating needs to import a medium sized database into my new Drupal system.  I will be able to do an SQL export on the old database but I am wondering if there is a good module that my facilitate this kind of transfer.  Also, I might like to make some changes to the structure of the database, for example one table I will need to import has 39 integer that I would like to move into one single vector, is this something I could do with an existing module or would I need to write some php code to handle this?

The Migrate module, not to be confused with Backup & Migrate, can provide this functionality. The project page says it better than I can.

  The migrate module provides a flexible framework for migrating content into Drupal from other sources (e.g., when converting a web site from another CMS to Drupal). Out-of-the-box, support for creating core Drupal objects such as nodes, users, and comments is included - it can easily be extended for migrating other kinds of content.

Deliberately, it's fairly complicated module. Here's a talk on it from DrupalCon denver


Can't seem to get my plugin class include to load? If I keep my plugin class in the mymodule.module, then the plugin works fine. However moving it out to mymodule.context.condition.inc prevents the condition from working.

I have added file[] entry to mymodule.info and I have added the following to my hook_context_plugins:

function mymodule_context_plugins() {
  $plugins = array();
  $plugins['mymodule_context_condition_bonus_discount'] = array(
    'handler' => array(
      'class' => 'mymodule_context_condition_bonus_discount',
      'parent' => 'context_condition',
      'path' => drupal_get_path('module', 'mymodule'),
      'file' => 'mymodule.context.condition.inc',
    ),
  );
  return $plugins;
}

As mentioned, if I shift the code into the .module file, and remove the 'path' and 'file' lines from hook_context_plugins, then the condition is recognized by context and runs without issue.

SOLVED:

Looks like my class definition should not have had a capital "C" in "Class". Quite frustrating since I'm using drupalcs which complains about the lower case "class".


If a pager is missing, then appears when using another theme, does that narrow the problem to the original theme? I have a pager missing from one page, while visible on another. These pages are generated by my custom module. I'm working with a custom theme that's been hacked together (wasn't me!) When I switch the theme to Bartik everything works as expected.

Here is the query function:

function query_activities($tid = NULL, $did = NULL) {
  $record_count = variable_get('promo_list_count');
  $query = db_select('node', 'n')->extend('PagerDefault');
  $query->fields('n', array('nid', 'title'));
  if ($tid) {
    $query->leftJoin('taxonomy_index', 'ti', 'ti.nid = n.nid');
    $query->condition('ti.tid', $tid);
  }
  $query->condition('n.type', 'activity_promo_list');
  $query->condition('n.status', 1);
  $query->groupBy('n.nid');
  $query->orderBy('n.sticky', 'DESC');
  $query->orderBy('n.promote', 'DESC');
  $query->orderBy('n.changed', 'DESC');
  $query->orderBy('n.created', 'DESC');
  $query->limit($record_count);
  $results = $query->execute()->fetchAll();
  return $results;

I have a function that wraps the query results in theme arrays and can post the whole thing if needed (it's 120 lines) but I think the only relevant part is:

  $content['pager'] = array(
  '#theme' => 'pager',
  '#weight' => $count,
  '#quantity' => 5,
  );
  krumo($content['pager']);
  return $content;

The krumo() dump shows the pager array populated on both pages (pager visible & pager missing).

Does this narrow the problem to theme layer?

What should I look for to fix or diagnose the missing pager?

I stumbled on tostinni's answer in Pager disappears when adding "GROUP BY" in the SQL query.

  Your query with the GROUP BY is incorrect, MySQL is lax enough to let you write this kind of queries but it is by no way recommended. When you use a GROUP BY clause you should group all the columns without a aggregate function.

I then fixed two queries that have poorly formed GROUP BYs, but my pager was still missing. I bust out Devel's query logging feature; the offending SQL query resulted to be used by the Nodequeue module. I checked the bug reports for that module, and found the one about that query: Grouping error" when creating a simple queue (PostgreSQL).


record of email notifications sent out (webform / postfix) I have a webform with example.com/node/123/webform/emails set to send email notification from info@example.com to several email addresses when a submission is received.

Is there a way to see a record of email notifications sent out ie with date and time etc to verify that the notifications have in fact been sent?

Thanks...

Webform doesn't provide default functionality for it.

you can use either of these modules to log outgoing mail:

Mail Log
Email Log


Specified template file for user-profile-form based on role I use drupal 7.x and field_group and nultiple registration module.
How I can use a template file (.tpl) for user-profile-form only based on roles.
in other words when a user with A role login to site and go to user/%/edit page see a specified form with specified fields. and When user loged on with B role have another form for edit information.field permissions control fields but field groups is visible yet because field_group module have a bug with field_group_multiple module.

So , I want to use specified tpl file for user-profile-form (no registration page or profile page - only user-profile-form )  by role  .
Can you help me ?

You can simply load $user variable in your template file and check which role current user is having and simply based on the role print your form.
for e.g

if ($user->roles[4] == 'role1') {
  print render $form['form_field1'];
  print render $form['form_field2'];
}
if ($user->roles[5] == 'role2') {
  print render $form['form_field_field1'];
  print render $form['form_field_field2'];
}

In the end don't forget to print the following

print drupal_render_children($form);


add watermark to all images uploaded in the site I am trying add watermark to all the images uploaded by users. Is there any preprocessor for the same? or any module to achieve it ?

Module ImageCache Actions is a well supported module that can add watermarks for Drupal 5,6,7.  It does this all by caching the image using imagecache.


Use dropdown in views exposed filter on text fields with entity not node? A very kind soul posted some code here for a small module that allows drop down fields in views for text fields on nodes

I was wondering how I can alter this so it works on an entity I created?

This is the particular field name on this example field_exact_location

My entity type is called "site_object"

function dd_city_form_views_exposed_form_alter(&$form, &$form_state) {
$field_id = 'field_exact_location';

// Only alter forms with the necessary field
if (isset($form[$field_id .'_value'])) {
// Build a query to get all node ids having the specified field
$query = new EntityFieldQuery();
$results = $query->entityCondition('entity_type', 'node')
                  ->fieldCondition($field_id, 'value', 'NULL', '!=')
                  ->fieldOrderBy($field_id, 'value', 'ASC')
                  ->execute();

// Attach the field values to the nodes
$nodes = $results['node'];
field_attach_load('node', $nodes, FIELD_LOAD_CURRENT, array('field_id' => $field_id));

// Add a default so the filter is optional
$options = array('' => '<select>');

// Buld the options array based on the query results, overwriting duplicate entries
foreach($nodes as $nid => $node) {
  $value = $node->field_exact_location['und'][0]['value'];
  $options[$value] = $value;
}

// Alter the field
$form[$field_id .'_value']['#type'] = 'select';
$form[$field_id .'_value']['#options'] = $options;
$form[$field_id .'_value']['#size'] = 1;
}
}

Think I found a solution at last. It works in my local test environment for the exposed filters in views:

function dd_city_form_views_exposed_form_alter(&$form, &$form_state) {
  $field_id = 'field_selected_field';

  // Only alter forms with the necessary field
  if (isset($form[$field_id .'_value'])) {
    // Build a query to get all node ids having the specified field
    $query = new EntityFieldQuery();
    $results = $query->entityCondition('entity_type', 'model')
                      ->fieldCondition($field_id, 'value', 'NULL', '!=')
                      ->fieldOrderBy($field_id, 'value', 'ASC')
                      ->execute();

    // Attach the field values to the nodes
    $entities = $results['model'];
    field_attach_load('model', $entities, FIELD_LOAD_CURRENT, array('field_id' => $field_id));

    // Add a default so the filter is optional
    $options = array('' => '<select>');

    // Buld the options array based on the query results, overwriting duplicate entries
    foreach($entities as $id => $entity) {
      $value = $entity->{$field_id}['und'][0]['value'];
      $options[$value] = $value;
   }

    // Alter the field
    $form[$field_id .'_value']['#type'] = 'select';
    $form[$field_id .'_value']['#options'] = $options;
    $form[$field_id .'_value']['#size'] = 1;
  }
}

I only had to change a tiny bit more, than I posted before.
Summary for the above code:

Rename 'field_selected_field' to your field. Example: If it is called 'city',
then rename it to 'field_city'.
Change 'model' to the name of your entity. In your case 'site_object'
These are the places:

$results = $query->entityCondition('entity_type', 'model')
$entities = $results['model'];
field_attach_load('model', $entities, FIELD_LOAD_CURRENT, array('field_id' => $field_id));

Save the file to your module, upload it and enable it in Drupal.

A few screenshots of my test environment:

Here my example configuration for a view with an entity named 'model' with the field 'selected_field'.

If you go to the respective view (in my case /modeltestview), you get the following (the screenshot is only part of the screen). The left part is the starting part,you get the right part if you click on the dropdown list. To show there actually is something in the dropdown list.


How alter page content before printing? In my project, I am using "Printer-friendly pages" module in order to add print button to my project.

for example when a user is in "checkout/5/review" page, print module create a page with "print/checkout/5/review" address.

this process works fine but I want to alter the created page for printing "print/checkout/5/review"

I tested hook_page_alter but it doesn't work.

The print friendly module uses the theme system to output your print friendly page. So you need to do this on theme layer using a preprocess function. Use THEMNAME_preprocess_page or THEMENAME_preprocess_print in your template.php. Check the theme_hook_suggestions for more options. From the module

 $variables['theme_hook_suggestions'] = array();
 187   $variables['theme_hook_suggestions'][] = "print__node__{$type}";
 188   $variables['theme_hook_suggestions'][] = "print__node__{$type}__{$nid}";
 189   $variables['theme_hook_suggestions'][] = "print__{$format}";
 190   $variables['theme_hook_suggestions'][] = "print__{$format}__node__{$type}";
 191   $variables['theme_hook_suggestions'][] = "print__{$format}__node__{$type}__{$nid}";


Get next node in nodequeue I have a nodequeue named work_order.

If I am in a page which belongs to this queue, is there a way I can get the next node that will be there in the nodequeue?

I looked at most of their API functions, but I did not find one that does this.

I am using drupal 7

Should be something like getting the nid of the current node and then being $nid the node id of the current node and $sqid the queue id:

$pos = nodequeue_queue_position('work_order', $nid);
$nodes = nodequeue_load_nodes($sqid, FALSE, $pos+1, 1, TRUE);

It's untested so maybe you need to tweak the position and so.


How can I limit the number of upload files programmatically? I need to limit the number of upload files programmatically because the max number of files is 10 or unlimited and I need 14 upload files. Is it possible? I found the Upload max files module, but my question is if it is possible, programmatically.

I have installed Drupal 6.

I assume you use filefield module for attachment, if so, use this:

/**
 * Implementation of hook_form_alter().
 */
function YOURMODULENAME_form_alter(&$form, $form_state, $form_id) {
  if ($form_id == 'content_field_edit_form') {
    $form['field']['multiple']['#options'] = array(1 => t('Unlimited'), 0 => 1) + drupal_map_assoc(range(2, 14));
  }
}


Default customer profiles re-added on order edit, even without address field present My site uses 2 custom profile types for a particular set of customers. For these, I have the default billing and shipping profile panes completely removed on the order edit screen via Customer Profile Type UI, yet any edit to an order (manual or programmatic) still re-adds them to the profile on save (resulting in 4 profiles for the order).

The address field has been identified as the culprit, but in my case, the default profile panes are not present in the form, so I don't understand how an address field that isn't there could trigger a new profile being added. Is there another mechanism in Commerce that would add default profiles if they are missing?

I think the typical issue is that because the address field value includes a country code by default, it's always assumed to have data ... so my guess is that whatever mechanism the Customer Profile Type UI is using to disable those sections of the order edit form isn't actually unsetting or otherwise removing them from the forms themselves. I don't have experience with the module in question, but if you have the ability, you'd likely be better off writing your own form alter to disable those portions of the edit form.


Knowing if the currently logged-in user has seen the list of nodes shown in a view I use the Views module to show a list of specific nodes. Is there a way to know if the currently logged-in user has seen the list of nodes?

I think that the best option for you is to write a mini module with  a simple DB table. If you need designing it i will help you.

Also try the checklist module

Maybe it could help you


Language fallback for unpublished translation on our Drupal 7, we have pages in 6 different languages. We'd like to remove the translation for some nodes.

I thought that users would be automatically redirected to the default (English) language when trying to access this unpublished translation, but this is not the case, they have a "not found" page.

I installed the language fallback module and configured all languages to fallback to English, but this did not help.

Is there something else I can do so that all traffic to unpublished translations is redirected to the default node translation ?

I never used it, but this module seems correspond to your problem https://www.drupal.org/project/multilink


display link after finishing coutdown time I am using Jquery Countdown module. In this, user can display text message after completing countdown. But I want to display a link after completing countdown.

Have a look at the project page. It says

You can use jQuery Countdown in two different ways, one is using theme('jquery_countdown'), the other is using jquery_countdown_add().

In the following example, we display an alert box saying "You are done!" after counting down from 10...

<?php
  echo '
10 seconds!
';
  jquery_countdown_add(".countdown", array("until" => 10, "onExpiry" => "finished"));
  drupal_add_js("function finished() { alert('You are done!'); }", 'inline');
?>

You can use the above example to achieve your requirement.


Programmatically set the value of a multi-value field from multiple arrays I have 3 taxonomy vocabularies:

Fruits
Vegetables
Drinks

On the Article content type, I have set a multi-value entity reference field field_article_all_items referencing all of Fruits, Vegetables and Drinks taxonomy vocabularies.

Using the Webform module, I have created a webform with 3 elements:

fruits_category which is a non-required, multi-value Entity Checkboxes element referencing the Fruits Taxonomy Vocabulary
vegetables_category which is a non-required, multi-value Entity Checkboxes element referencing the Vegetables Taxonomy Vocabulary
drinks_category which is a non-required, multi-value Entity Checkboxes element referencing the Drinks Taxonomy Vocabulary

Now on webform submit, I want to:

Create a new node of type article.
Set the values of field_article_all_items equal to all selected values
from fruits_category, vegetable_category and drinks_category.

In my customhandler.php file, I have tried:

// Get an array of the values from the submission.
    $values = $webform_submission->getData();

// Get 'Fruits Category' Value.
    $FruitsCategory = $values['fruits_category']; // Multi-value tid

// Get 'Vegetables Category' Value.
    $VegetablesCategory = $values['vegetable_category']; // Multi-value tid

// Get 'Drinks Category' Value.
    $DrinksCategory = $values['drinks_category']; // Multi-value tid

// Put all values in an array().
    $AllItems = array($FruitsCategory,$VegetablesCategory,$DrinksCategory);

// Create a new "Article" node.
    $article = \Drupal\node\Entity\Node::create([
        'type' => 'article',
        'title' => Test,
        'langcode' => 'en',
        'uid' => '1',
        'status' => '1',
        'created' => $current_time,
        'field_article_all_items' => $AllItems,
        ]);
// Save the created node.
    $article->save();

the above code created a new node but with field_article_all_items field empty.

Also I have tried:

// Get an array of the values from the submission.
    $values = $webform_submission->getData();

// Get 'Fruits Category' Value.
    $FruitsCategory = $values['fruits_category']; // Multi-value tid

// Get 'Vegetables Category' Value.
    $VegetablesCategory = $values['vegetable_category']; // Multi-value tid

// Get 'Drinks Category' Value.
    $DrinksCategory = $values['drinks_category']; // Multi-value tid

// Put all values in an array().
    $AllItems = array($FruitsCategory,$VegetablesCategory,$DrinksCategory);

// Create a new "Article" node.
    $article = \Drupal\node\Entity\Node::create([
        'type' => 'article',
        'title' => Test,
        'langcode' => 'en',
        'uid' => '1',
        'status' => '1',
        'created' => $current_time,
        //'field_article_all_items' => $AllItems,
        ]);
// Save the created node.
    $article->save();

foreach ($AllItems as $Item) {
  $article->field_article_all_items[] = $Item;
}

// Save the created node again.
    $article->save();

// Also I have tried the below method.
//   $article->field_article_all_items[] = ['target_id' => $AllItems]

  //Save the created node again.
//   $article->save();

But also this code created a new node but with field_article_all_items field empty.

How to set the values of field_article_all_items equal to fruits_category + vegetable_category + drinks_category ?

Educated guess: (The key was to merge the arrays by using array_merge())

// Put all values in an array().
$AllItems = array_merge($FruitsCategory, $DrinksCategory, $DrinksCategory); // use array_merge

foreach ($AllItems as $Item) {
  $article->field_article_all_items[] = ['target_id' => $Item];
}

$article->save();

Also it can be used within the node creation:

// Put all values in an array().
    $AllItems = array_merge($FruitsCategory,$VegetablesCategory,$DrinksCategory);

// Create a new "Article" node.
    $article = \Drupal\node\Entity\Node::create([
        'type' => 'article',
        'title' => Test,
        'langcode' => 'en',
        'uid' => '1',
        'status' => '1',
        'created' => $current_time,
        'field_article_all_items' => $AllItems,  // use array_merge
        ]);
// Save the created node.
    $article->save();


MySQL server has gone away - production site Possible Duplicate:
  Solving “MySQL server has gone away”, mysql error 2006

My website is moved from localhost to virtual hosting and after 1 week I receive an error 2006 2006 MySQL server has gone away. Now I can create/edit content but not content types and cannot clear the cache, I see white screen in this case. My hoster said that the max_allowed_packed size is only 1M and I cannot change it.

Is there a way to fix this error?

I deleted content types I don't use now and the problem has gone away... And now I can also clear the cache and edit other content types. What it was I cannot understand, it's beyond me

Culprit may be max_allowed_packet which is too little. Drupal Requirements page suggests 16M, but it depends on your site. If you are not able to get sufficient memory allocated, better change host.

  When using Drupal 5.x or later, particularly with contributed modules,
  it may be necessary to set the system variable max_allowed_packet to
  at least 16M. Some inexpensive hosting plans set this value too low
  (the MySQL default is only 1M). In that case, you may need to choose a
  better hosting plan. A value of 1M may be sufficient for 5.x.


How to trim the Node field is rendered in page.html.twig? I have rendered the node(custom) field in page.html.twig. Custom field is a summary text field.

And now, I want to trim the text field.

I have tried the below code,

{% set summary = node.field_custom|render|striptags %}
{{ summary|length > 10 ? summary|slice(0, 10) ~ '...' : summary }}

This is not working in page.html.twig. But its working only in the node.html.twig.

Showing error like,

Uncaught PHP Exception Exception: "Object of type Drupal\\Core\\Field\\FieldItemList cannot be printed."

How do I trim the summary field which is rendered in page.html.twig.

Please help me to solve this ?

NOTE: I could not control it in the managed Display section. If the reduce the number in the Trim character section, its not working.

We had a similar issue on our site recently. You are trying to print a FieldItemList, which has no __toString function, and therefore cannot be implicitly converted to a string, as you are trying to do.

In your case, node.field_custom appears to be a FieldItemList. I know, you thought it was just a string value from a field -- but it's not. Drupal treats ALL fields as FieldItemLists in the API, even in cases where the field can't possibly contain more than one value. (This presumably makes the implementation cleaner.)

One quick solution to your problem, although this is a bit messy, is to call first(), to get a TypedDataInterface, getValue(), which returns an associative array, and ['value'], in your Twig template, like so:

node.field_custom.first().getValue()['value']

That should return a string. However, for those functions to be accessible in a Twig template, you need to enable them in settings.php and clear the system cache. Here's what worked for us:

$settings['twig_sandbox_whitelisted_methods'] = [
        'first',
        '__toString',
        'bundle',
        'id',
        'label',
];

But in your case, you may have to whitelist more methods to get what you want.

Here is some more information on discovering variables in Twig templates.


How to expose the quantity of list items to an action? Put another way.

Using a loop, how do I pass the number of items in a list to an action outside the loop?

I have created a loop and within the loop I have added an action to calculate a data value as follows

Data selector: 'loop_name:quantity'

Calculation: *1 = calculation_result

From within the loop I can access the new variable 'calculation_result' however I can not figure out how to expose the calculation result to other data selectors.

What steps am I missing?

You have to create a new variable BEFORE your loop.

And then select the type of variables in that list. For your example, perhaps a list of decimals?

Be sure to give it a good custom name for your loop:

Then, in your loop, you can add a new variable to an existing list:

Then, after your loop, you can access calculation results:

Note, that if you don't know explicitly which in your loop you want, then you will have to loop through your new calculation results and use a condition rule to return the one you need as (yet another) variable.


Form in custom template does not submit data I have a custom form which I render in a custom template. I render the elements separately but the submit button does not fire the data to the validation/submit function. When I render the whole form at once it works fine.

This does not work:

$form = drupal_get_form('my_module_form');
print render($form['title'];
print render($form['submit'];
print drupal_render_children($form);

This works:

$form = drupal_get_form('my_module_form');
print render($form);

This also works:

$form = drupal_get_form('my_module_form');
print render($form['title']);
print render($form);

So apparently I'm missing something but can't find what. Can somebody give me a hint what I'm doing wrong?

Check the html your template outputs - I am pretty sure it is missing the <form> tag around your fields - without that element your form wont submit however as it contains necessary data (post methode and action to name two).

drupal_get_form() retrieves the entire render array for a functional form, but you only pick two form elements to print to screen. It does display the elements because they are themselves valid render arrays, but the functionality of the form is lost that way.

If you really want to ommit fields in the template try to unset the fields you do not want to display. E.g. unset($form['field_to_hide']). This leave the render array of the form intact.

That said, hidding fields is commonly done in a preprocess function and not in the template itself. Since it is a custom form you can do it directly in your form declaration.

$form['field_to_hide']['#access'] = 0;
$form['field_to_hide']['und']['#disabled'] = TRUE;

You can use this approach to set custom data you want to save with the form and the user isn't supposed to see. It's basically a hidden field.

If you just want to seperate the fields to add additional wrapper elements or classes you can do that in the form as well:

$form['your_field'] = array(
  //[...]
  '#prefix' => '
',
  '#suffix' => '
',
  '#attributes ' => array('class' => array('element-class'));
);

Check the Form API page to see for which element the two options are available for: FAPI


Create a cron job to automatically clear cache I'm trying to clear cache automatically with a cron job but it didn't work.
I'm debugging simply on the browser at this link website-url/cronjob.php.
I think it's a problem with the syntax, I have tried to truncate the tables from database.

As you can see in the code attached below, I've tried two methods, but neither one works.

\Drupal::database()->truncate('cache_config')->execute();
mysql_query('TRUNCATE TABLE yqxq_cache_config');
mysql_query('TRUNCATE TABLE yqxq_cache_container');
mysql_query('TRUNCATE TABLE yqxq_cache_data');
mysql_query('TRUNCATE TABLE yqxq_cache_default');
mysql_query('TRUNCATE TABLE yqxq_cache_discovery');
mysql_query('TRUNCATE TABLE yqxq_cache_dynamic_page_cache');
mysql_query('TRUNCATE TABLE yqxq_cache_entity');
mysql_query('TRUNCATE TABLE yqxq_cache_menu');
mysql_query('TRUNCATE TABLE yqxq_cache_render');
mysql_query('TRUNCATE TABLE yqxq_cache_toolbar');
?>

What do I need to change to make this script work?

This is an example of query from the statistics view, which doesn't update if I don't run clear cache.

<?php
$count_users_tot = db_query('SELECT COUNT(uid) FROM {users}')->fetchField();
print $count_users_tot;
?>

Thanks to @No Sssweat, @kiamlaluno, @Rick B, I've got an answer.
Firstly, I learned that is not a good practice to clear cache automatically every minute or so often.
Secondly, I figured out that I can solve this problem without using a cron job at all, but I have to understand these tag based caching mechanisms.

The problem was as in the image attached below, Page-Caching was Tag Based, so selecting None option solved my issue.


How do I get the userpoint description to include clickable node link? I would like to get a clickable link of the current node stored in the description parameter of the userpoints_userpointsapi

Am using the code below at the moment. Its working fine  but the link shown under the user profile is not clickable.

How can I make this link clickable whenever its displayed in anywhere else on the site for example under the user profile list of points by that user:

$params = array (
    'points' => round($percentage/10),
    'tid' =>16,
    'description' => ''. $node->title .''
    );
userpoints_userpointsapi($params);

You can reference the node using the entity_type => 'node' and entity_id => $node->nid arguments, then the description will automatically be linked to the node.


add a webform in a product checkout I would add a webform in the checkout step of a particular product. I need this feature because sometimes the products that i offer needs more information and sometimes the information that i need are different, so the webform that i should show could be change.

I would show the webform during the checkout, i don't want to have a webform that redirect to checkout (commerce webform module i think)

As per my understanding of your question you should follow below steps:

Create a form using Webform and then in Webform >> Advance settings mark that webform as "Available as block".
Now you can see that webform as a block in Blocks page.
In block configuration you can set the option to display that block on specific page.

Let me know when you implement it.


How do I get the full URL of the current page? I need to get the full URL of the currently opened page. I use the following code, but it returns http://localhost/mysite/page_name.

$path = isset($_GET['q']) ? $_GET['q'] : '<front>';
$link = url($path, array('absolute' => TRUE));

It's not enough for my code to complete; I want to get the values that are passed with the URL as http://localhost/mysite/page_name/value1=value&value2=value.

How can I do that?

Have you tried using request_uri()?

$_SERVER['HTTP_HOST'] . request_uri();

It should do the trick. I haven't tried it myself, and I may be off a bit, but I suggest you give a try.
From JavaScript, you could use the window.location.href variable.


Programmatically check if a D8 version exists for all site modules I am listing all modules used by site on our platform. Given a module name, how could I programmatically check if a Drupal 8 version is available?

For non programmatical way.

Download and install the Upgrade Status Module


How to automatically assign a (sequential) number to a user-created node I'm designing a website for a group of academics.  I've created a content type, called "Preprints," where users enter information about a paper they have recently submitted to an outside journal for publication. When created, these nodes are then listed on a Views page, also called "Preprints." The users, however, would like some way of tracking the order in which they submit their Preprint. Thus, I'd like to figure out some way of automatically assigning each node a number or a code. (For example, the first paper of the year would be assigned the code LPS13001, the second would be LPS13002, and so on.)  My first thought was to do this through a custom field, but I haven't been able to figure this out. Any help would be greatly appreciated!

The Serial module allows you to do exactly that. You can simply have an integer number that is incremented per content type and if you wanted a prefix you could do that in the display formatter.

  Unlike Drupal's built-in auto-increment node ID, which is global and
  shared by nodes belonging to all content types, serial fields are
  managed per content type (D6) / entity (D7). For example, the serial
  field of an Invoice instance will generate a unique sequential number
  (starting at 1, then 2, etc.) exclusively for Invoice instances.


Best practice: Twig template for custom module's block I'm looking to provide a template for a custom block in my custom module. There are two ways to go about this: provide a template for just the block's content, or provide a template that extends block.html.twig. I've returned empty-handed in my search for a best practice. Let me clarify the two options to provide a template for my custom module's block:

Option 1: provide a template for the block's content

<?php
/**
 * Implements hook_theme().
 */
function mymodule_theme($existing, $type, $theme, $path) {
  return array(
    'mymodule' => array(
      'variables' => array('var' => 'test'),
    ),
  );
}
?>

The template named mymodule.html.twig looks like this:

This is my content: {{ var }}

Option 2: extend block.html.twig

<?php
/**
 * Implements hook_theme().
 */
function mymodule_theme($existing, $type, $theme, $path) {
  return array(
    'block__mymodule' => array(
      'base hook' => 'block',
      'variables' => array('var' => 'test'),
    ),
  );
}
?>

The template named block--mymodule.html.twig looks like this:

{% extends "block.html.twig" %}
{% block content %}
This is my content: {{ var }}
{% endblock %}

Looking for a best practice

The documentation on Twig Template naming conventions is quite clear on this: for a block, the name should be block--module.html.twig. However, is that the filename a themer would use to overwrite my block content (option 1) or is it the filename I should use for the template I provide for my custom module (option 2)? I haven't found a clear answer on this so as far as I can see there's no best practice on this yet.

I would prefer option 1. Theme the inside of a block in a custom template with custom variables or build a render array with render elements. Use the block template only to theme the outside of the block, for example add a wrapper div.

Option 2 is not a good idea, because it uses this block template:

{% extends "block.html.twig" %}
{% block content %}
This is my content: {{ var }}
{% endblock %}

Normally a block template looks like this:

{% extends "block.html.twig" %}
{% block content %}
This is my content: {{ content }}
{% endblock %}

By ignoring {{ content }} in a block template no cache metadata can bubble up. See https://www.previousnext.com.au/blog/ensuring-drupal-8-block-cache-tags-bubble-page

You could try to add the cache metadata with block methods. But this is not good practice, because if later someone tries to add block content and is not aware of that the block template doesn't use the base hook variables this person will have a hard time debugging this.


Updating other modules schema when creating custom module I need to add a information to a content types within my module. Generally, is it good practise to update node_type schema or is it better to create my own and join it to the node_type via primary key?

Thanks.

You should make use of the hook_schema_alter to update entity schema of existing schema's.

function YOURMODULE_schema_alter(&$schema) {
  // Add field to existing schema.
  $schema['users']['fields']['timezone_id'] = array(
    'type' => 'int',
    'not null' => TRUE,
    'default' => 0,
    'description' => 'Per-user timezone configuration.',
  );
}


Acquia Desktop & MAMP: No Drupal site found, only 'drush' cache was cleared Usually I use MAMP for my local development server which already has all of my shortcuts and stuff configured the way I like it.

A client was on Acquia Cloud and to prevent conflicts with other developers we are all using the Acquia Dev Desktop for local. Acquia Dev Desktop comes with Drush within its own package.

When running my drush cc all I was getting the following error:
No Drupal site found, only 'drush' cache was cleared

After running drush status I noticed that Drush was trying to use my MAMP version of drush and thus resulting in no site found.

To fix this answer I created a new Alias called adrush which points to the Acquia DevDesktop Version.

In my .bash_profile file in my home directory I added

alias adrush='/Applications/DevDesktop/drush/drush'

now when running drush commands for sites that are in my Acquia DevDesktop environment I enter adrush cc all


Use content panes as blocks I am currently working with drupal 7 and I'm using page manager to edit different pages on the site.

I tried creating a mini panel and adding it to a region, but i do not know how to add content panes to it. Is it possible to use content panes as blocks and add then to regions ? the reason I wanna try doing this is i don't want to choose a layout from page manager and add content panes to it instead i wanna add then to the drupal regions.

A mini panel acts like a block, except that it has subregions.  To add content, select the mini panel for editing and select the "content" editing display.  Next pick the gear in the upper right corner of the desired region in the mini panel and select 'add content'  The pop-up will give you the selection of available content that can be placed in the panel.

Once you have the mini panel configured, you place it in a theme region just as you would a block.  You select the mini panel from the admin/structure/blocks page for your theme.  It can be found in the list of disabled blocks at the bottom of the layout page form.


Expiration date on product variation How can I set an expiration date on a product variation?
I am building a webshop and my goal is to have an expiration date on a product variation, meaning the after a scheduled date, the product would no longer be available to sell, so it would automatically unpublish. Also, vice versa, the product variation might have a publishing date.
Currently I am looking at scheduler, but that is for nodes, not for products. Is there another way of doing this?

Job Scheduler
Provides an API to schedule jobs. Where you can programmatically unpublish product variation in worker callback.
Simple example:

// Declare scheduler.

  function example_cron_job_scheduler_info() {
    $schedulers = [];
    $schedulers['example_unpublish'] = [
      'worker callback' => 'example_unpublish_nodes',
    ];
    return $schedulers;
  }

// Add a job.

  $job = [
    'name' => 'example_unpublish',
    'type' => 'story',
    'id' => 12, // must be unique
    'crontab' => * 3 * * 0, // Every Sunday at 3 AM
    'periodic' => TRUE, // set to false if you want to just run once.
  ];
  $service = \Drupal::service('job_scheduler.manager');
  $service->set($job);

// Work off a job.

  function example_update_users_total(\Drupal\job_scheduler\Entity\JobSchedule $job) {
    // Do stuff.
  }

There is more examples & info in the READ.ME, so read it.

Ultimate Cron
Provides a UI where you can schedule all the cron jobs. You can implement your own hook_cron and then schedule it using Ultimate Cron.


How do you deploy a change to a main menu? We have a small D7 site. We want to deactivate a main menu item.
On dev server I was able to deactivate it in /admin/structure/menu/manage/main-menu

I believe The menu is stored in the DB, right. Also in a config file? So you only need to deploy those two things and it is done.

Is that correct? If not, what are the steps to deploy a main menu change?

Menu items are saved in the DB, therefore you must update them using update hooks.

Something like this should work:

function MODULE_NAME_update_N() {
  $menu_link_id = 1;
  $menu_link = menu_link_load($menu_link_id);
  $menu_link['hidden'] = 0;
  menu_link_save($menu_link);
}


How to hide a field group fieldset programmatically in drupal 8? I have a Field Group fieldset named group_p_payment as machine name. I want to hide this based on the user. I tried the following code:

        $user = \Drupal::currentUser()->getRoles();
        if(!in_array("Administrator", $user) ||  !in_array("administer", $user)) {
         $form['group_p_payment']['#access'] = FALSE;
        }

But it didn't work it. How can I hide the fieldset?

The field group module is no longer storing grouped fields as a fieldset in Drupal 8. It's storing metadata on each group in an array called #fieldgroups which is used in a pre-render function.
The logic of the module doesn't render the fieldset if all its children elements aren't visible. Hence, you can hide all the children elements to have the same effect. For example:
foreach ($form['#fieldgroups']['group_p_payment']->children as $form_element_id) {
  $form[$form_element_id]['#access'] = FALSE;
}

The logic will have to change if you have nested groups, but the approach will remain the same.
Note that the above code can go in a form alter, but you should ensure that your form alter runs after Field Group does its work.
Here is complete working code, for a module named example in the example.module file:
/**
 * Implements hook_module_implements_alter().
 */
function example_module_implements_alter(&$implementations, $hook) {
  if ($hook == 'form_alter' && isset($implementations['example'])) {
    $hook_implementation = $implementations['example'];
    unset($implementations['example']);
    $implementations['example'] = $hook_implementation;
  }
}

/**
 * Implements hook_form_BASE_FORM_ID_alter() for node_form.
 */
function example_form_node_form_alter(&$form, FormStateInterface $form_state, $form_id) {
  foreach ($form['#fieldgroups']['group_b_payment']->children as $form_element_id) {
    $form[$form_element_id]['#access'] = FALSE;
  }
}


Print field from reference of reference (node) I use the module "entity reference" and I ave "Inline Entity Form" in the node. The first reference has another reference inside. In total there are 3 nests, a grandfather, a father and son.
In node.tpl the first parent node how can I print a field of his nephew?

- Node.1
-- Ref. Node.2
--- Ref. Node.3

I want to print a Node.3 field's in Node.1

Thanks so much!

There is always more than one way to solve a problem in drupal.  How easy those ways are is up for debate, but they exist.

You could:

Make a view with those reference fields as relationships and a nid context filter that would recognize the Node.1 end of the relationships.  Set this view to have a block display, and A) put the block on the page with a context or B) summon the view to be rendered by name in your tpl. Or with the function views_embed_view
Make database fetches or entity field queries directly in your node.tpl.php.  This is uncouth, as such logic should not be put in the theme layer, but functional.
Forget about node.tpl.php entirely and do this in panels.  I'm pretty sure it supports using referenced fields.

The echo $view->render('block_view'); method would be my suggestion to you.  Views is a very powerful module, has built in theming overrides (and more if you want more tpls) and can do all sorts of rewrites and manipluations while laying things out for you.  Add the ability to conjure it's database bending powers from your tpl with just 6 lines of code, and it is stupendous.


How do I use a different template for the anonymous users? If the user is the anonymous user or an authenticated user, I want to use the page1.tpl.php; with other roles, I want to use page.tpl.php.
How do I write the code?

If you want to handle different templates for different scenarios the context module is a great tool. This case is quite simple, so you could handle it with code like suggested. But using the context module, makes it a bit more manageable, and allows you not only to decide what template to use, to also what blocks to insert. It's a great module and is one of those I use for almost all of the sites I make.


Is relationships scalable? I have a Drupal 8 site using the OpenSocial profile. It's a social profile and users can follow other users. This is implemented using the Flags module.

In the site, I created a view for users to see contents of the users they are following and it uses  a relationship to user entity, and lists the content of user flagged by the current users.

As the site the content differs for each users, it can't be cached. What will be the best way to scale in this case? Is there a different method to follow other than a relationship?

Is there a way we can use a search_api based index view for this purpose?

As the site the content differs for each users, it can't be cached.

Well, that is not entirely true. At least for Drupal 8 the options for caching have improved drastically. Previously we could cache a query and its output, but Drupal 8 comes with tag-based caching.

Every entity in the system can (and core entities by default) expose a cache tag. This allows individual entities to be cached. Views tag-based caching in turn uses these tags to determine if the cached view output can be served or should be rebuilt.

This means that the view query will still be executed, but all the individual nodes can be served from their individual caches. If none of the nodes has been updated, the rendered output of the view will be served from cache too.

As for scalability (SQL vs NoSQL is not really a Drupal question), there is a tradeoff (but I really do not know enough of this to provide a good explanation). A views relationship is nothing more than an SQL join, this means that all data exists once and is merged into a data set on request. If you do not want to use relationships but a search_api based approach, the same data set should be composed elsewhere. Since you do not want to use relations you should fetch all nodes of all followed users in one run.

Depending on how your view and search database are configured, this could result in every node getting stored once in the dataset of every follower. With a lot of users and a lot of content this can grow in size very fast. It will likely be faster though because you'll only have to lookup one id instead of all the id's of the entities on the joined tables.

TL;DR
It depends on what you show and how you build the index.


How to make an entity reference field an editable field in views I have a view that displays entity references. Entity references are assigned via select list and are filtered by a seperate entity reference field.

I installed the Editable Views module so that I can directly edit the field from the view.

Even though the admin user has all the right permissions set up, they are still only able to see the entity reference field displayed on the view, but not actually edit it. Is there a conflict between the two modules? Or is there some kind of extra setting that I am missing.

All I need to do was to change the format of the view from "Table" to "editable table" :/


Set new theme setting to default on theme update Working

We have a custom base theme.
There are custom theme settings with default values.
When the theme is initially installed, the theme settings are correctly set as default. Good.
This custom base theme is now on our many live sites.

Not working

We added a new custom theme setting to the base theme, and set a default value.
When we update the base theme on a site, the new theme setting is there. Good.
However, the default value is not filled in.

Question
How do I set the default value of a new theme setting when the theme is updated?

From what I can tell, themes do not process update hooks since they do not have a schema value tracked in the key_value table. So a hook_update_N is not possible in this case.

This means that you have a couple of options.

Option 1

If the theme is going to be updated in code, but not updated right away through the UI form, you will probably want run a drush command as part of the theme update.

drush config-set THEME.settings NEW_SETTING NEW_SETTING_VALUE'

Reference: https://drushcommands.com/drush-8x/config/config-set/

This will allow you to set it once and then any future updates/overrides can be handled as usual through the configuration system.

Option 2

If you are talking about a theme that is part of a distribution, and you don't have access to the system to run the drush command, then you could set a default value on the hook_form_system_theme_settings_alter function. This would not provide the value to the system when it loads the config, but it would provide a default to users when they update the theme and save the settings form.

If you did it that way, you would need to provide a fallback in your theme for if/when that value is not present to prevent unexpected behavior if the new setting value isn't yet set in the site's settings file.

Option 3

If you have access to the codebases for the affected systems, like in a site factory, then you could technically provide the new value in the exported configuration file itself and then it would be picked up upon config import.


Twig template suggestions for user default, compact, and user account view modes Is there a way i can create a diffrent template than user.html.twig to have a diffrent View mode when i use default, compact or user account

Something like user--compact.html.twig ?

You can do this by creating a theme suggestion alter hook in your theme.

/**
 * Implements hook_theme_suggestions_user_alter().
 *
 *   An array of alternate, more specific names for template files or theme
 *   functions.
 */
function MYTHEME_theme_suggestions_user_alter(&$suggestions, $vars, $hook) {

  // Define the view mode.
  $mode = $vars['elements']['#view_mode'];

  // Create a theme hook suggestion which has the view mode name in it.
  $suggestions[] = 'user__' . $mode;
}

Note, $vars['elements']['#view_mode']; was derived from using kint($vars) under this function to see the view mode array in user.

You can add this code to your theme's .theme file and then clear cache. Once you clear cache, you will then see the new theme suggestions appear within Twig debug.

Note, in my case, I am in "full view mode so that's why user--full.html.twig shows up. If you are view the user in compact mode, then a suggestion of user--compact.html.twig will show up.


How to limit access to a view based on the contextual filter I have a view that uses a contextual filter and I want to limit access to that view based on the filter.  To give it some context:

I have a content type that represents minutes from previous meetings.  These minutes can belong to a handful of committees.  The user selects which committee the minutes belong to when creating the node, and the view then uses that as a contextual filter.

I would like to know if there is something out there that would allow me to filter access to the view based on the contextual filter.  So if someone tries to access minutes/mycommittee vs minutes/notmycommittee they would be allowed and denied respectively.

Thanks in advance.

If you are using Drupal 7 and Views 3.x, then for each contextual argument, you can specify a validation criteria from the Views UI. Look for this checkbox under the When the filter value IS in the URL or a default is provided section for a given contextual argument.

Suppose your committees are taxonomy terms in a vocabulary, say, Committee, then you can use the Taxonomy term validator. Otherwise, you can simply use the PHP Code validator and key in the custom logic that defines access to your view.

Think of this custom logic as a boolean method from which you can access the view object and the raw value of the argument and then based on this context, allow or deny the current user's access to your view accordingly.


Use node_load via Ajax I'm using horizontal parallax jQuery plugin and have a page--front.tpl.php file. That's my structure:

MENU:

news

When I click this menu item, go to DIV:

    <?php
    $view_mode = 'full'; // Or 'full' for example
    $node = node_load(52);
    $view = node_view($node, $view_mode);
    print render($view);
    ?>

But I have a big problem. When i click my site adress, loading all content and items in one time. So, my site is slowly. I thinking use node_load function via Ajax. Searched site and drupal.org but not found a good info.

Is it possible? What can I do for my site speed? Ajax is a good solution?

Ajax could actually complicate your situation further, since you'd be asking your site to bootstrap once again asynchronously in order to serve the node. Not to say it isn't an option, you can write your own method to retrieve only the information you need via ajax.

I would personally look into caching methods. If your site gets anonymous traffic, try boost. Easily the best improvement for Drupal performance (in my opinion) is APC cache. Hopefully you have root access and can install the APC extension for PHP and then the APC module, the site starts flying after that, for both auth and anon traffic. I'm afraid you might already know this so I'll stop there.

If you still wanna do AJAX stuff, you could install views datasource to output JSON, and add a jquery call the page with $.get and push the content into the DOM. Using views gives you some native caching options as well.

Hope it helps.


Remove reply link in comments How can you remove the reply button under each comment in Drupal 8? I understand there is an option "Show reply form on the same page as comments", but I am not trying to remove this form. Only the reply button.

How can the reply button be removed?

You could use the hook_comment_links_alter()

use Drupal\comment\CommentInterface;

/**
 * Implements hook_comment_links_alter().
 *
 * Unsets the "Reply" link of a comment.
 *
 * @param array &$links
 *   A renderable array representing the comment links.
 * @param \Drupal\comment\CommentInterface $entity
 *   The comment being rendered.
 * @param array &$context
 *   Various aspects of the context in which the comment links are going to be
 *   displayed, with the following keys:
 *   - 'view_mode': the view mode in which the comment is being viewed
 *   - 'langcode': the language in which the comment is being viewed
 *   - 'commented_entity': the entity to which the comment is attached
 */
function mymodule_comment_links_alter(array &$links, CommentInterface $entity, array &$context) {
  // Unset the "Reply" link
  if(isset($links['comment']['#links']['comment-reply'])) {
    unset($links['comment']['#links']['comment-reply']);
  }
}


Add class to image field I'm looking for a way to add a class field to Drupal's image field (field_image). At the moment my images are displayed using code like this:

I'd like to add a class field so that the code would be like so:

I think I could achieve this by adding a field to the content type to store the class name - I could then use views to add the class value to the image's parent DIV. However, I suspect there's a way to add a class field to the image field itself - it's not uncommon for images to have classes ;)

I've tried the File Entity module, which according to the documentation allows you to create custom file types. Sadly it doesn't explain how.

Any pointers / suggestions would be much appreciated.

Edit: To clarify, I'd like to be able to add classes on a per image basis. Some images might need the classes portrait floatLeft, others might need landscape floatNone and so forth.

Consider looking at the Image Class module, which extends the Image formatter by adding an option to add an element class.

It requires the Field formatter settings module (dependency).


Access published date via node_load() The node created field is not the same time as when it was finally published (or I guess maybe promoted, instead of published).

I've loaded a node using node_load() in my module code, how can I access when this node was actually published?

The node object does not store the "publication date", install this module to create that field http://drupal.org/project/publication_date
Some details from the module's project page:

The Publication Date module adds a "Published on" date for each node, containing the date when it was first published.
Without this, the only dates available for nodes are their created date and changed date, but these are often insufficient to meet the needs of publishing workflows. Sorting nodes by their created date doesn't account for content which is held in draft form for a time while being readied for publication. Sorting nodes by their changed date fails to account for content needing minor corrections after being published.
The "Published on" date can be used in any templates, or views. Publication date also incudes integration with the Display Suite module and has entity wrapper support, so it can integrate with modules like Rules that use the Entity API module.
The "Published on" date can be edited through the node edit form, allowing a custom published date to be set. If a custom date is set prior to publication, it will be respected when the node is published. The publication date is also retained when a node is unpublished and then republished.


How can I get rid of this error? The error that I am getting is as follows

  Strict warning: Only variables should be passed by reference in include() (line 73 of /Applications/MAMP/htdocs/.../sites/all/themes/bootstrap/templates/page.tpl.php).

The code producing this error is

<?php
$path = drupal_get_path_alias($_GET['q']);
$block = block_load('block','2');
if ($path == 'home') {
  print render(_block_get_renderable_array(_block_render_blocks(array($block))));
}
?>

I don't know why this error is coming up because the code is working perfectly.

Could anyone Helo me please?

The solution for this will be to do the same thing with the code below.

$region = _block_get_renderable_array(_block_render_blocks(array($block)));
print render($region);

After changing your code make sure that you clear your cache. And try refreshing. Also make sure you have made this changes every where.

So you know what the problem is:
The render() function takes a parameter by reference. In that case you must pass in a variable, not a function call, because the function call is not something that can be passed as a reference.


How do I add variables to a module's hook's existing render array and have them available as template variables? As an example, the hook_search_execute function returns the following array:

$results[] = array(
      'link' => url('node/' . $item->sid, array('absolute' => TRUE)),
      'type' => check_plain(node_type_get_name($node)),
      'title' => $node->title,
      'user' => theme('username', array('account' => $node)),
      'date' => $node->changed,
      'node' => $node,
      'extra' => $extra,
      'score' => $item->calculated_score,
      'snippet' => search_excerpt($keys, $node->body),
    );

'link' and 'title' are required and the others are optional. However, what if I wanted to add my element to the array like 'photo' and then have that available in the $search-result.tpl.php file?

Whe I add that element to the search results array, I indeed see it when I do a dump of $variables in _preprocess_search_result(). If it's available there, then how to I make it available as <?php print $photo; ?> in search-result.tpl.php?

According to template_preprocess_search_result you have the $result variable available, so if you've already injected your custom field into the result you can just use

print $result['photo'];

In the template file.

Or if you're absolutely set on just having a $photo var, you need to add it to the variables for the template:

function MYMODULE_preprocess_search_result(&$vars) {
  $vars['photo'] = $vars['result']['photo'];
}


Theme search-result pages individually? We can theme the search-result pages within search-results.tpl.php and search-result.tpl.php. But as far at it is possible to create multiple search pages(e.g. in apache solr module), is it possible to theme each page individually?

Example:

search-results--page1.tpl.php
search-results--page2.tpl.php

It is possible.

Apache solr search module introduced tpl files for each search page.

If your custom search page's machine name is simple search, the search results tpl for that page will be named as

    search-results--apachesolr-search--simple-search.tpl.php

Replace simple-search with the machine name of your search page, with underscores converted to hyphens.


How can I show images upon click in a lightbox using the Full HTML text format? I'm using the Lightbox 2 module on Drupal 7.  I have added an image field to my Basic Page content type.  On one particular page, I have uploaded several images into that field, which I then inserted into the body (text format: Full HTML) using the Insert module.

Since the images are small, I want to allow users to click on them to open them in a lightbox on the same page.  I read through the lightbox documentation but it seems like it hasn't really been updated for Drupal 7.

I tried the following:

However, in this case, when I click the image, nothing happens.  When I add some text, however, like this:

click here for the image

The lightbox appears when the text is clicked.  However, I want to show the lightbox when an image is clicked, not when text is clicked.  How can I do this?

I think the Lightbox is not really the best choice for Drupal 7. Have a look at the very powerfull Colorbox Module.


Difference between text filter types? When creating text filter, there are several "type" options (see here). What is the difference between these two?

FilterInterface::TYPE_TRANSFORM_IRREVERSIBLE: Irreversible transformation filters.
FilterInterface::TYPE_TRANSFORM_REVERSIBLE: Reversible transformation filters.

Are there some examples when to use them? For example, when I add a class to a HTML element without any class or specific attribute, is that reversible or irreversible?

Per the Filter API docs:

  Every filter plugin must specify a filter type in its annotation. Filter types were added specifically to support in-place editing. There are four filter types:

  FilterInterface::TYPE_MARKUP_LANGUAGE — Non-HTML markup language filters that generate HTML. The filter converts something that's not HTML to HTML in a way that is not compatible with WYSIWYG editing.
  FilterInterface::TYPE_HTML_RESTRICTOR — HTML tag and attribute restricting filters to prevent XSS attacks. The filter restricts the HTML allowed, for example, to protect against XSS.
  FilterInterface::TYPE_TRANSFORM_REVERSIBLE — Reversible transformation filters. The filter performs a transform for which a WYSIWYG plugin exists to perform the same transformation (and its reverse) client-side. For example,  may be (reversibly!) transformed to

Druplicon

.
  FilterInterface::TYPE_TRANSFORM_IRREVERSIBLE — Irreversible transformation filters. The filter performs a transform for which a WYSIWYG plugin does not exist to perform the transformation client-side (especially, the reverse of it); instead, the WYSIWYG editor displays the unfiltered text. For example, Token Filter.

The type examples given are pretty descriptive of when to use them.

If you CAN take the filtered output and put it back into its original form via a WYSIWYG plugin (e.g. structured markup like XML -> JSON -> XML), use FilterInterface::TYPE_TRANSFORM_REVERSIBLE because the filter output can be reversed.

If you CANNOT take the filtered output and put it back into its original form via a WYSIWYG plugin(e.g. a token filter that prints the node title), use FilterInterface::TYPE_TRANSFORM_IRREVERSIBLE because the filter output cannot be reversed.


How to automatically generate multiple aliases for one node? I'm using Drupal 7.22. I'm running four site versions in same Drupal installation.

eg:-

example.com/site1
example.com/site1

and its mobile versions:

example.com/mobilesite1
example.com/mobilesite2

I'm using URL aliases to meet the conditions. I have created patterns for each content type.
Suppose I have content type called site1_projects and  site2_projects, and created aliases for each site content type like site1/site1_projects and site2/site2_projects.

How can I automatically set an aliasing for these content type for mobile, like mobilesite1/site1_projects and mobilesite2/site2_projects?

In canse you didnt found it, you need to use the module Rules and follow these steps:

**Delete Node Aliases Ruleset**
- Delete all aliases that point to system path
- Delete all aliases that point to system path
- ... (and so forth)

**Create Node Aliases Ruleset**
- Create alias #1 to point to path A
- Create alias #2 to point to path B
- ... (and so forth)

**Triggered Rules**
- IF new node created (and any other conditions) THEN call Create Node Aliases ruleset.
- IF node deleted (...) THEN call Delete Node Aliases ruleset.
- IF node updated (...) THEN call Delete Node Aliases and then call Create Node Aliases


Weirdness in views when grouping by a field, and a user has more than one entry in that field I have a view that shows users. Users are associated with an Area in the organization.  The view groups by Area (a vocabulary) and gives a list with nice area headings, with a list of Users inside it.  Unfortunately there is one executive in the organization that is also in charge of another Area, and he needs to appear in both places.  When I assign both areas to his account (entity reference field), we get the following (problematic user in bright blue):

What should happen, is that the blue user should appear once in the Executives area and once in the PMO area.  Instead as you can see, he appears twice in his own special Executives \n PMO area.  It would even be ok, if he only appeared in the Executives area here.  What can I change to get this view to be nice to me?

In your hidden entity reference field's setting in Views, scroll down to Multiple field settings and uncheck Display all values in the same row.

When grouping, the content / user will get shown twice instead of what your screenshot shows.


I use jQuery to alter the exposed form select options. Got error: "An illegal choice has been detected." How to bypass validation? I have a view that has three expose filters (Manufacturer, Type, Model), three options list (term reference to Printer vocabulary) .

Vocabulary: Printer (3 levels)

-- HP
---- xxx
------ xxxx
-- Apple
---- xxxx
------ xxxxxx
-- Dell
---- xxxx
------- xxxxx
-- ...
-- ...
(thousands of terms)

Since Form API AJAX doesn't work on views expose form, I am unable to make the them dependent select for exposed form fields. So I used jQuery to make the exposed form fields "dependent select / cascading select".

Basically, I empty all the options in views_exposed_form_alter() firstly:

$form['manufacturer_id']['#options'] = $form['type_id']['#options'] = $form['model_id']['#options'] = array();

then populate the option lists with my jQuery code accordingly.

However I get "An illegal choice has been detected." on page load, and form submit.
Form submission is prevented due to Drupal form validation mechanism .

It's the form validation detect the options generated by jQuery are not come with the original form data, as I removed the options in form alter. Value of a select box is not present in its defined options .

So I tried to remove form validation in form alter as:

unset($form['#validate']);

still doesn't work, the illegal choice error remains.

============ UPDATED =================

Inspired by @kiamlaluno 's answer below, the only solution I came up is hack/patch the core.
Here is what I done:

Edited /includes/form.inc : (line 2014)

I removed the code:

$element['#needs_validation'] = TRUE;

and added:

// if not these fields, mark for validation as usual.
// so if are these fields, validation will be passed.

if ($element['#name'] != 'manufacturer_id'  &&
    $element['#name'] != 'type_id'          &&
    $element['#name'] != 'model_id' ) {

  $element['#needs_validation'] = TRUE;
}

It works, the exposed form select option bypassed the validation.

But my solution is very ugly which modified the core.

I wonder if there is any other solution without touching the core?
How can I bypass the validation of these exposed form fields?

Thanks!

The function that shows those errors is _form_validate(), which contains the following code.

  // Validate the current input.
  if (!isset($elements['#validated']) || !$elements['#validated']) {
    // The following errors are always shown.
    if (isset($elements['#needs_validation'])) {

      // ...

      if (isset($elements['#options']) && isset($elements['#value'])) {
        if ($elements['#type'] == 'select') {
          $options = form_options_flatten($elements['#options']);
        }
        else {
          $options = $elements['#options'];
        }
        if (is_array($elements['#value'])) {
          $value = in_array($elements['#type'], array('checkboxes', 'tableselect')) ? array_keys($elements['#value']) : $elements['#value'];
          foreach ($value as $v) {
            if (!isset($options[$v])) {
              form_error($elements, $t('An illegal choice has been detected. Please contact the site administrator.'));
              watchdog('form', 'Illegal choice %choice in !name element.', array('%choice' => $v, '!name' => empty($elements['#title']) ? $elements['#parents'][0] : $elements['#title']), WATCHDOG_ERROR);
            }
          }
        }

        // ...
      }

The function is always executed, whenever the form has a validation handler, or not.

You could set $form['#needs_validation'] to FALSE, but _form_builder_handle_input_element() sets it to TRUE. The function is called from form_builder(), which is then called from drupal_process_form(), or drupal_rebuild_form().

  // Mark all posted values for validation.
  if (isset($element['#value']) || (!empty($element['#required']))) {
    $element['#needs_validation'] = TRUE;
  }

After _form_builder_handle_input_element() is called, form_builder() calls any #process function set for the form element.

  // Handle input elements.
  if (!empty($element['#input'])) {
    _form_builder_handle_input_element($form_id, $element, $form_state);
  }
  // Allow for elements to expand to multiple elements, e.g., radios,
  // checkboxes and files.
  if (isset($element['#process']) && !$element['#processed']) {
    foreach ($element['#process'] as $process) {
      $element = $process($element, $form_state, $form_state['complete form']);
    }
    $element['#processed'] = TRUE;
  }

It also calls any #after_build functions set for the form element.

  // The #after_build flag allows any piece of a form to be altered
  // after normal input parsing has been completed.
  if (isset($element['#after_build']) && !isset($element['#after_build_done'])) {
    foreach ($element['#after_build'] as $function) {
      $element = $function($element, $form_state);
    }
    $element['#after_build_done'] = TRUE;
  }

You could set a #after_build function that executes code similar to the following one.

function mymodule_remove_validation($form_element) {
  unset($form_element['#needs_validation']);

  return $form_element;
}

I am using unset($form_element['#needs_validation']) because the if-statement in _form_validate() checks isset($elements['#needs_validation']), instead of !empty($elements['#needs_validation']).

In this way, the form element would not have #needs_validation set to TRUE, and Drupal would not check the returned value for the form element is one of the possible values it can get, nor is the length of a textfield string longer than required.
It doesn't avoid the form validation handlers are run, thought.


Rendering Commerce Order API function commerce_order_build_content was deprecated, but I couldn't find one that was supposed to replace that. How do I drupal_render() a loaded commerce order? As of now, I'm getting "call to undefined function" commerce_order_build_content

Use entity_view:

$build = entity_view('commerce_order', $order, 'full');
$markup = drupal_render($build);


How do I delete cookies when users log out? How do I delete cookies when users log out? How can I do this with out modifying any core module?

Imlement hook_user_logout($account) and call user_cookie_delete($cookie_name).

For example:

function mymodule_user_logout($account) {
  user_cookie_delete('name');
  user_cookie_delete('mail');
  user_cookie_delete('homepage');
}


Dropdown menu of node titles that are made by a view I'm trying to create a dropdown menu that is a list of titles created by a view.

So I've made a view that creates a list of titles of a content type. I would like that list of titles to be in a dropdown menu.

I am using Superfish now, but I am not fully committed to it. If you can suggest a menu that will make this work I'm open to that.

I thought Menu Views would be an easy fix combined with Superfish. Menu Views has this to say

  By design, this module only provides basic HTML structure for
  inserting a view into the menu system. It does not actually style your
  [mega-]menu. If no styling exists in your theme or is not provided by
  a contributed module, the view will appear next to your menu item
  (which can often be a little confusing at first). It is up to the
  theme or contributed module to actually style the view to appear
  inside your menu. If the contributed theme or module implements drop
  down menus, using CSS or JavaScript, a new child selector (li > .view)
  must be included. The view can then be styled appropriately from
  there.

I'm not sure where to start with the child selector.

Any advice on how to get the dropdown menu to display the node titles? Feel free to recommend any other modules that may help

I don't know if or how the Superfish module integrates with Menu Views. Off the top of my head I kind of suspect it doesn't...

The simplest solution is to use CSS to hide the view except during the parent's :hover state. You can pick up a simple js to make that function in IE7 and below. There are of course plenty of other, mostly javascript or jQuery-based, solutions.


Country specific nodes Let's say we navigate to http://example.org/ch/de/node/1 (with pathauto enabled /ch/de/hallo-welt)

Now I want to specify somewhere the country Switzerland (ch) and set the available languages to de (for German), fr (for French), it (for Italian), rm (for Rhaeto-Romanic)

So when I navigate to that link above, there should be a language switcher that shows me all translations for that country.

But now I have other countries specified. For example Canada (ca) with the languages en and fr but en should not be visible on node/1
And of course now I have a node at /ca/en/hello-world with a translation in fr. Now the other languages should not be visible on that node.

How can I do that with modules?

I would suggest you look at
This helps you translate whatever you need to have translated

Internationalization

The default language is always enabled as a detection method and that will  give you a fallback language if none of the other language detection methods are available.

(if your using Entity Translation)
You will have to enable the translation of nodes or entities that would be translatable at admin/config/regional/entity_translation.

After that you should :

  Be able to enable "Multilingual support: Enabled, with content
  translation" on the content type edit form under "Publishing options".
  For example, for a content type named "example", this would be at
  admin/structure/types/manage/example/edit in the "publishing options"
  fieldset.

// Randy Fays answer to this

Try to check out this, It might also be helpfull depending on how you want to go about it

Entity Translation

Title module will help you translate node titles

Sources I used in this answer

Randy Fays blog - Multi Lingual (thank you, for making this great post

I found this helpfull too.

Multi Lingual Setup Guide

I hope it was helpfull

Best regards


AJAX callback on form item generated by AJAX I'm trying to add AJAX callback to form element that was previously rendered by AJAX but with no luck. Code below.

A bit of description. There are three main methods here:

buildForm - base form
extraField - AJAX callback attached to ['month']
choosePerson - AJAX callback attached to: ['week_day']['hour']

In the buildForm method I create base form with AJAX callback on 'month' select element. In the AJAX callback you can find an extraField method. This method contains form element called 'hour' ($form['week_day']['hour']) and this element renders well. But this element also contains AJAX callback, which doesn't work, it does not generate 'person_container' element and the 'person' select.

Any idea how to ajaxify elements that previously were rendered by ajax?

class ReservationForm extends FormBase {

  public function getFormId() {
    return 'reservation_form';
  }

  public function buildForm(array $form, FormStateInterface $form_state) {

    $form['month'] = array(
      '#type' => 'select',
      '#title' => $this->t('Select month'),
      '#options' => array($this->t('January'), $this->t('February'), $this->t('March')),
      '#ajax' => array(
        'callback' => array($this, 'extraField'),
        'event' => 'change',
        'wrapper' => 'week-day',
      ),
    );

    // Disable caching on this form.
    $form_state->setCached(FALSE);

    $form['week_day'] = [
      '#type' => 'container',
      '#attributes' => ['id' => 'week-day'],
    ];
  }

  public function extraField(array &$form, FormStateInterface $form_state) {
    $month = $form_state->getValue('month');

    $hour_options = array();

    if ($month == '0') {
      $hour_options[0] = $this->t('08:00');
      $hour_options[1] = $this->t('09:00');
      $hour_options[2] = $this->t('10:00');
    }

    if ($month == '1') {
      $hour_options[0] = $this->t('12:00');
      $hour_options[1] = $this->t('13:00');
      $hour_options[2] = $this->t('14:00');
    }

    if ($month == '2') {
      $hour_options[0] = $this->t('18:00');
      $hour_options[1] = $this->t('19:00');
      $hour_options[2] = $this->t('20:00');
    }

    $form['week_day']['hour'] = array(
      '#type' => 'select',
      '#title' => $this->t('Choose hours @month', array('@month' => $month)),
      '#options' => $hour_options,
      '#ajax' => array(
        // tried with that callback too: [ $this, 'choosePerson']
        'callback' => array($this, 'choosePerson'),
        'event' => 'change',
        'wrapper' => 'person',
      ),
    );

    $form['week_day']['person_container'] = array(
      '#type' => 'container',
      '#attributes' => ['id' => 'person-container'],
    );

    $form['week_day']['person_container']['person'] = array(
      '#type' => 'select',
      '#title' => $this->t('Choose person'),
      '#options' => ['John', 'Sarah', 'Peter'],
    );

    return $form['week_day'];
  }

  public function choosePerson(array &$form, FormStateInterface $form_state) {
    $form['week_day']['person_container']['person'] = array(
      '#type' => 'select',
      '#title' => $this->t('Choose person'),
      '#options' => ['John', 'Sarah', 'Peter'],
    );

   return $form['week_day']['person_container'];
  }
}

The Link 4k4 posted in the discussion of the question gives the solution:

  Create a callback function (named by the #ajax['callback']). This is generally a very simple function which does nothing but select and return the portion of the form that is to be replaced on the original page. Note, that as part of the Form APIs security system, you cannot create new form elements in the callback function, as they will throw errors upon submission, and any #ajax on elements created in the callback will also not work. If you need to create new elements on ajax submit, they must be added in the form definition. You can use the values in $form_state to determine whether the form build process is the initial form load, or an #ajax initiated load.

So the following code example is working.

class ReservationForm extends FormBase {

  public function getFormId() {
    return 'reservation_form';
  }

  public function buildForm(array $form, FormStateInterface $form_state) {
    $form['month'] = [
      '#type' => 'select',
      '#title' => $this->t('Select month'),
      '#options' => [
        $this->t('January'),
        $this->t('February'),
        $this->t('March'),
      ],
      '#ajax' => [
        'callback' => [$this, 'extraField'],
        'event' => 'change',
        'wrapper' => 'week-day',
      ],
    ];

    // Disable caching on this form.
    $form_state->setCached(FALSE);

    $form['week_day'] = [
      '#type' => 'container',
      '#attributes' => ['id' => 'week-day'],
    ];

    if ($form_state->getUserInput()['_triggering_element_name'] == 'month') {
      $month = $form_state->getValue('month');
      $hour_options = [];

      if ($month == '0') {
        $hour_options[0] = $this->t('08:00');
        $hour_options[1] = $this->t('09:00');
        $hour_options[2] = $this->t('10:00');
      }

      if ($month == '1') {
        $hour_options[0] = $this->t('12:00');
        $hour_options[1] = $this->t('13:00');
        $hour_options[2] = $this->t('14:00');
      }

      if ($month == '2') {
        $hour_options[0] = $this->t('18:00');
        $hour_options[1] = $this->t('19:00');
        $hour_options[2] = $this->t('20:00');
      }

      $form['week_day']['hour'] = [
        '#type' => 'select',
        '#title' => $this->t('Choose hours @month', ['@month' => $month]),
        '#options' => $hour_options,
        '#ajax' => [
          'callback' => [$this, 'choosePerson'],
          'event' => 'change',
          'wrapper' => 'person-container',
        ],
      ];

      $form['week_day']['person_container'] = [
        '#type' => 'container',
        '#attributes' => ['id' => 'person-container'],
      ];

      $form['week_day']['person_container']['person'] = [
        '#type' => 'select',
        '#title' => $this->t('Choose person'),
        '#options' => ['John', 'Sarah', 'Peter'],
      ];
    }

    if ($form_state->getUserInput()['_triggering_element_name'] == 'hour') {
      $form['week_day']['person_container']['person'] = [
        '#type' => 'select',
        '#title' => $this->t('Choose person'),
        '#options' => ['Hans', 'Frank', 'Emma'],
      ];
    }

    return $form;
  }

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

  public function extraField(array &$form, FormStateInterface $form_state) {
    return $form['week_day'];
  }

  public function choosePerson(array &$form, FormStateInterface $form_state) {
    return $form['week_day']['person_container'];
  }

}


Get list of taxonomy terms for current node through Views I've been trying this for awhile, and I keep finding answers that are close - but not quite.

If there is a node with taxonomy terms attached to it, I want to create a block in Views that I can place in the sidebar that will load the terms that are attached to THAT node.

I want to do it through Views so I can rewrite the URL with a custom query using the term IDs.

I'm open to other suggestions as well! I've also tried Display Suite, but I didn't want to go too far down that path just yet. The attached image is ideal, where the category taxonomy terms are being loaded based on terms that are attached to the node.

Ideal Wireframe Example

Come on it's not that hard!
I'm assuming you want to display all taxonomy terms across multiple taxonomy reference fields/vocabularies.
You can however filter the list of taxonomy terms that the View returns using Vocabulary filters.

Create a new view on Taxonomy table. You are basically showing taxonomy terms.
In the View creation page, uncheck "create page" and check "Create block". Give it a title "Categories". Click "Continue and Edit".
In the Views UI, add a new Relationship  Taxonomy term: Content with term, and uncheck "require this relationship".
Add a new Contextual filter : Content: Nid  and choose the just-created relationship as the relationship, Provide default value > Content ID From URL under When the filter value is NOT available. Also add basic validation check to the contextual filter.

5 .  Save the View and put the block where you want to display.

You can check the view by entering a test node ID to the preview field. It should show all taxonomy terms attached to THAT node.


How to disable error messages to screen while mysql service is down Our production environment got a problem and the mysql service was down. The all our drupal based sites show the error messages below which expose to many information.

  PDOException: SQLSTATE[HY000] [2002] Can't connect to local MySQL
  server through socket '/var/run/mysqld/mysqld.sock' (2) in
  lock_may_be_available() (line 164 of
  /home/workspace/drupal7/includes/lock.inc).

I find this page (via) about how to disable drupal errors, but have no effect when mysql is down.

Any one can give me a hand?

Having just run across the same issue, to avoid hacking the core files you can set the default error reporting level in your site's settings.php by adding the following line:

$conf['error_level'] = ERROR_REPORTING_HIDE;

Since the error_level variable is normally set from the database the setting otherwise defaults to DISPLAY_ALL if MySQL is down.

Note: this means the error level can no longer be configured through the admin interface (admin/config/development/logging).


How do I use AND condition in Rules to add shipping to sales tax? The default sales tax Component Rule calculates sales tax on all line items... so it was (for us) correctly adding sales tax to products and shipping line items. We started using Userpoints_Discount and I created a new Product Type 'Points' to allow users to purchase Userpoints. I then edited the Component Rule as below. So now, it calculates Sales Tax on the product which are NOT 'Points' (good) but it has stopped calculating sales tax on shipping (bad).

Can someone look at this Component Rule and explain why the Shipping Line Item is no longer having sales tax calculated?

The logic should be:

IF Commerce Line Item IS IN bundle Products OR bundle Shipping
  AND Commerce Line Item Product Type IS NOT 'Points'

I am using Commerce Kickstart 2.

{ "commerce_tax_rate_state_of_washington" : {
    "LABEL" : "Calculate State Of Washington 9.5%",
    "PLUGIN" : "rule",
    "OWNER" : "rules",
    "TAGS" : [ "Commerce Tax", "sales_tax" ],
    "REQUIRES" : [ "rules", "inline_conditions", "commerce_tax" ],
    "USES VARIABLES" : { "commerce_line_item" : { "label" : "Line item", "type" : "commerce_line_item" } },
    "IF" : [
      { "AND" : [
          { "entity_is_of_bundle" : {
              "entity" : [ "commerce-line-item" ],
              "type" : "commerce_line_item",
              "bundle" : { "value" : { "product" : "product", "shipping" : "shipping" } }
            }
          },
          { "NOT commerce_product_has_type" : { "commerce_line_item" : [ "commerce_line_item" ], "type" : "points" } }
        ]
      }
    ],
    "DO" : [
      { "commerce_tax_rate_apply" : {
          "USING" : {
            "commerce_line_item" : [ "commerce-line-item" ],
            "tax_rate_name" : "state_of_washington"
          },
          "PROVIDE" : { "applied_tax" : { "applied_tax" : "Applied tax" } }
        }
      }
    ]
  }
}

NB: As so often happens with Drupal, apparently I was asking the wrong question. IMO this is such a -basic- part of any eCommerce system used in USA/Canada, but the answer is buried in a support request on Drupal.org. This is -terrible- documentation and I hope the Commerce Guys are duly ashamed. Doesn't matter how cool the code is if one can't easily figure it out.

Apparently what one has to do is add the rule into

Admin -> Store Settings -> Shipping  (Calculation Rules) -> Configure Component

Please see here (#29)
https://www.drupal.org/node/1243218#comment-6732098

...and also (#42).

What one does is add a new Rule to Shipping
Event: Calculate Shipping
Condition: Order Address Component Comparison
Actions: (Your Salestax Component Rule goes here)

For the Action you simply use the same sales tax component rule you used for

Admin -> Taxes -> Configure Component

...in my case 'Sales Tax WA'

So I suppose if you live in a jurisdiction with many possible taxes, you'd create a separate component rule for each under shipping, using exactly the same Order Address Comparison and Action Rule you used for the Taxes section.

What confused -me- was that I thought one could use use the IF/AND/OR under Taxes to differentiate between Shipping and Product line items. Apparently this does not work. That would be a MUCH better solution (reduce duplication of effort, cut down on errors.) If someone knows how to do this, PLEASE post here!

So, in one sentence, you have to apply all the same sales tax component rules in two places: in Taxes (for product line items) and then in Shipping under Calculate Rules to apply tax to the freight.

And here is the exported rule:

{ "rules_apply_taxes_to_shipping" : {
"LABEL" : "Apply Taxes to Shipping",
"PLUGIN" : "reaction rule",
"OWNER" : "rules",
"REQUIRES" : [ "commerce_order", "rules", "commerce_shipping" ],
"ON" : { "commerce_shipping_calculate_rate" : [] },
"IF" : [
  { "commerce_order_compare_address" : {
      "commerce_order" : [ "commerce-line-item:order" ],
      "address_field" : "commerce_customer_billing|commerce_customer_address",
      "address_component" : "administrative_area",
      "value" : "WA"
     }
   }
 ],
 "DO" : [
   { "component_commerce_tax_rate_state_of_washington" : { "commerce_line_item" :
     [  "commerce-line-item" ] } }
       ]
   }
}


How can I include a simple php in a Drupal 8 twig file? I'm making a custom theme, and I just want to include this in my twig file.

<?php echo date("l H:i"); ?>

Do I need make a twig extension? How can I do it?

One way to do it would be to add the variable in a preprocess function, and print that out in the chosen twig template as {{ your_variable }}.

function yourtheme_preprocess_page(&$variables) {
  $variables['your_variable'] = \Drupal::get('date.formatter')->format(args);
}

I'm not sure where you are doing this, so your use case could be _page, _node, _html, _block for the preprocessor.

Since you are not passing a timestamp to date, it will assume current time and print that. If that is your intent, you should consider that when caching mechanisms are enabled, it won't show the current time anymore, and you should consider a Javascript based solution to keep that accurate (something like momentjs?). Again, don't know your full use case here.

edit: see https://api.drupal.org/api/drupal/core%21includes%21common.inc/function/format_date/8

and https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Datetime%21DateFormatter.php/class/DateFormatter/8


very simple form in block rendering incorrect values I have a very simple code in block :

if ($vocabulary = taxonomy_vocabulary_machine_name_load('caller_details')) {
  module_load_include('inc', 'taxonomy', 'taxonomy.admin');
  $output = drupal_render(drupal_get_form('taxonomy_form_term', $vocabulary));
}
echo $output;

the problem is that it sets the value of "name" in my form to taxonomy vocabulary name by default. Why is that?

Thanks for any suggestions!

That form expects an array representing the current term as edited as its first argument. The vocabulary is the second argument. Add an empty array as first argument and you should be OK.


Issue with Registration codes module in Voucher mode, trying to fix I am having serious issue with Registration codes module and searching for solution to fix it. It is described here:
http://drupal.org/node/797602

There is a patch to the issue, but author of the code stated that it may be "serious regression and borked a bunch of other modules, like simplenews and profile, anything that expects data to be in $edit."

That patch is very simple:

-  regcode_user('insert', $edit, $account);
+  user_save($account,$edit);

Module works well when used in normal mode, but in "voucher" mode, it does not apply role to user who submits it. To greater misfortune, the rule that this module came with, which could help do it another way, is also broken.

I think this module is not actively maintained as i do not recieve response for about an month on series of my request.

I would be very grateful if someone knows what approach i could take to resolve the issue, knowing how to rewrite patch to avoid harm to other modules functionality.

Thanks for clues!

This is more of an advice than a clean solution to the problem: hack the module and apply the patch if it works for you without interfering with other modules.

As you said, the module isn't maintained well and it is not updated recently (last commit was almost a year ago). If you don't have enough time to go over everything yourself, it is better to just fork it than hope that the maintainer will fix it.

Create a new folder under "sites/all/modules" called "fork" and move the module there. This will make sense later on for you or anybody else working on the site.


Is it safe to delete 'sites/modules.sav'? After the upgrade to the newest Drupal v7.31 I've found a new directory called sites/modules.sav with some subdirectories like

entity
entityreference
securelogin
securepages
session443

What is the purpose of this directory?

Can I safely delete this entire directory 'modules.sav' after the successful upgrade?

Yes, as far as Drupal is concerned, it's safe to delete that folder. Whether it's needed for something outside of Drupal I obviously couldn't say.

Drupal didn't put it there, and unless you've got a very abnormal setup (which you'd undoubtedly know about already), it's not going to be looking in that folder for any files.

It's probably a remnant of whatever automated method you used to update Drupal; if you'd done the upgrade manually that folder wouldn't have appeared.

To be sure, take a full backup, remove the folder on a dev version of the site, and run the usual tests you would after a normal upgrade. If those all pass, you'll know 100%.


how to use hook_cron_queue_info in a custom module? I am retrieving remote data by clicking an update button. I want to make it automatic. I read many articles about it but I didn't find a good example for using hook_cron_queue_info in my module. can anybody help me?

You can look at the example code shown in the documentation from hook_cron_queue_info(), which still needs an explanation on how it is used.

function hook_cron_queue_info() {
  $queues['aggregator_feeds'] = array(
    'worker callback' => 'aggregator_refresh',
    'time' => 60,
  );
  return $queues;
}

The code show is actually the implementation of hook_cron_queue_info() made from the Aggregator module. (See aggregator_cron_queue_info().)

"aggregator_feeds" is the name of a Drupal queue that is filled with items that need to be processed; "aggregator_refresh" is the name of a function that will be called when Drupal executes cron tasks, once for each item contained in the "aggregator_feeds" Drupal queue. aggregator_refresh() gets the item taken from that Drupal queue as first parameter.

The question you would ask at this point is: When are the Drupal queue items added to the queue?

The Aggregator module does that in its hook_cron() implementation, but any function could add items to a Drupal queue, including other hooks (with the exception of hook_cron_queue_info() and similar hooks*), form submission handlers, page callbacks, or any function called from those functions.

* By "similar hooks" I mean all those hooks that return information, and that are not invoked to handle an event or after/before an event occurred/occurs (as in the case of hook_node_delete()). In the list of "similar hooks," I would add, for example:

hook_menu()
hook_entity_info()
hook_field_info()
hook_archiver_info()
hook_tokens_info()


What is the best way to make some content only available to authenticated users? I'm currently trying out Drupal 8, but I'm wondering what is the best way to make some content (content types and some specific nodes) only available to authenticated users?

I'm using 2 content types, private and public, with both using the same taxonomy, but I would like one type to be published public and one private.

You can use the combination of ACL and Content access modules to achieve this. ACL + Content access give you better control over access to content: You can make certain types accessible to certain roles, or even specific nodes accessible to specific users.

Now here comes the tricky part:

Both the Acl and Content Access modules have no D8 release yet and have patches in their issue queues, which convert them to D8. For some reason the maintainers have not created D8 branches yet, but I'm using the patched versions of both the modules on my company site - they work perfectly.

ACL patch can be found here.

Content access patch can be found here.


How to strip html from Elasticsearch and search API index? I'm also using the search API autocomplete module. When I start typing, the autocomplete shows fields with html code.

What settings do I need to set to get the index to store correctly?

i had the same problem.
The solution for me came from unchecking the 'Elasticsearch direct link' checkbox in the edit form of the autocomplete tab in the search api index.


Trying to create user programmatically, running into issues I'm attempting to programmatically create a user. I'd like to be able to create the user, then set the current global $user object to this newly created user. Here is what my code looks like.

    $new_user = array(
        'name' => $form_state['values']['username'],
        'pass' => $form_state['values']['password'],
        'mail' => $form_state['values']['email'],
        'status' => 1,
        'init' => $form_state['values']['email'],
        'roles' => array(
            DRUPAL_AUTHENTICATED_RID => 'authenticated user'
        )
    );

    if ($saved_user = user_save(NULL, $new_user)){
        user_load($saved_user->uid, TRUE);
        $form_state['redirect'] = 'member/profile';
    } else {
        $form_state['redirect'] = 'member/join';
    }

The reason for me essentially wrapping the existing user page is that there is a lot of additional functionality needed. This code does create a user in the database, but it fails in two places: 1) It does not create any roles for this new user in the users_roles table, and 2) It does not log the current user in or adjust the global $user object.

Any ideas why this is failing?

EDIT: Using Drupal 7.9

EDIT2: I solved the user not being logged in issue by using the function user_login_submit. Roles still aren't creating correctly, however.

Drupal's anonymous and authenticated roles don't get saved in the users_roles table and you don't need to add the role yourself, all users are by default authenticated. Try editing your user in the backend, you'll see that it has authenticated checked off.
The code you list above where you send the roles array in the $edit will work fine with any other role.