form jquery events fired multiple times after using AJAX Does anybody know how to avoid jQuery firing events multiple times after ajax has returned a form.

I have tried with .once() and i am still getting 3 click events from one click.

EDIT: this was my starting point

jQuery('.node_form .form-radio').live('click', function(event) {
  console.log(jQuery(this).attr('id'));
});

Can we unbind the click event when click event happens and just add the click event again after we receive some responses from Ajax.

The idea is something like this:

jQuery('.node_form .form-radio').live('click', function(event) {
    jQuery(this).unbind('click');
    //make some ajax calls and if it returns something. We will bind the click event again.
});


How do I check if a user has view access to a node, in a template file? I'm currently working on a simple LMS in D8 and have already defined the fundamental content types. Among them is a content type called Course, which can be considered "Premium" content, i.e. all users may access those fields that contain more general information, but the users will have to buy a subscription for accessing the full content.

To make that possible without any Premium module (which, at the moment, have not been ported to Drupal 8), I created a simple grid-view and deactivated "SQL rewriting", which works perfectly, so far. For displaying the nodes in this view, I have created a new view mode, called gallery, so that the nodes that are displayed can be styled in a template.
I would like to apply different CSS styles to those nodes in the view that the user may access. I'm not sure if this can be done in the view itself.

Anyway, I'm currently thinking of checking the view permission inside node--course--gallery.html and I would like to add a class to the article tag, if access is permitted.

Unfortunately, I can't seem to find the right function for this. I set it up like this:

{%
  set classes = [
    node.bundle|clean_class,
    node.isPromoted() ? 'is-promoted',
    node.isSticky() ? 'is-sticky',
    not node.isPublished() ? 'is-unpublished',
    view_mode ? view_mode|clean_class,
    user.hasPermission('view nodes') ? 'is-permitted',
    node.access('view') ? 'is-permitted',
    'clearfix',
  ]
%}

Neither user.hasPermission('view nodes') ? 'is-permitted' nor node.access('view') ? 'is-permitted' seem to have any effect.

Do you have any idea?

Not really an answer, more like a suggestion for an alternative suggestion where that problem should exist, at least not exactly like that.

They way I handled similar problems before (paywall for newspapers in my case) is to not use the node access system for this. In my case, I did it using logic in the template/preprocess as well as dynamically switching the view mode. If you can handle it on a field-by-field basis, then you can also implement hook_entity_field_access() and deny view access to just those specific fields.

That said, I would expect that the method isn't allowed to be called due to the twig sandbox that only allows is/get method calls, but then I'd kind of expect it to throw an exception.

I guess also with my suggestion, you'll need a way to check for something in the template but I would simply do that in hook_preprocess_node() then, add it as a boolean variable to $variables.


How to obtain a token based on a entity_reference field? I have a node type A with a entity_reference field named "field_subnode" pointing to a node type B:

A -> B

I'm using pathauto, with the following patterns setted up:

URL path for nodes of type A:
books/[node:title]

Now I need something similar to:
books/[node-type-A:title]/[node:title]
as path for my nodes of type B, to obtain urls like the following:

books/my-car-book/chapter-1

Which token I have to use to obtain what I want?

I've tried different tokens like for example:

books/[node:field-subnode:1:title]/[node:title]

but without success.

Thank you for helping me.

You need the Entity Tokens module, part of the Entity project: http://drupal.org/project/entity. Once it's enabled you'll see the available recursive tokens in the tree.


Print module's default setting is annoying We often use the print module to create PDF of nodes; most of the times, it works out-of-box.
For our requirements, however, one thing that makes me very annoyed is its default settings.

When the print module is installed, the "Print friendly page" option is enabled for all the available content types, even though it is required only for a few content types. Every time I have to disable it manually by editing the individual content type edit tab form.

Is there a global option I can use to disable the option for all the content types, and enable it for the content types I really need it?
Does this way works for everyone, or did I miss anything?

Looking at http://drupalcontrib.org/api/drupal/contributions--print--print.module/function/print_form_alter/6, it seems to use a constant called PRINT_TYPE_SHOW_LINK_DEFAULT for the default value. That in turn is hardcoded to 1, see http://drupalcontrib.org/api/drupal/contributions--print--print.module/constant/PRINT_TYPE_SHOW_LINK_DEFAULT/6.

So you don't have a way to change that without hacking the module.

You could try to submit a feature request in the issue queue: http://drupal.org/project/issues/print


How to display date and time inside a form #markup? I want to retrive a UNIX epoch (as returned by the PHP function time()) and display it as a formatted date as part of a text (i.e. a #markup element) in a form.  This is not a field where the user is supposed to enter a date. It is just showing the current date and time in a human readable format inside the form.

Is know that I can get a human readable date and time from a Unix epoch with the PHP date() function.

However, I am looking for the "Drupal" way of doing this. I think this means that I should display the date and time in the short format set by the site manager under Home » Administration » Configuration » Regional and language.

Is there a way to do this (or is there another way that is condidered "the Drupal way")?

Edit: Function format_date()  turned out to be the right answer.  It depends on a set of format variables (e.g. date_format_short) being set.  If this variable is undefined, you only get the US-centric formats hard-coded into format_date().  The confusing bit is that when you visit the  Home » Administration » Configuration » Regional and language admin page, it shows you some formats (and I therefore errenously assumed that these formats were those that were defined for the site). But these formats are not defined until you press Save configuration on that page.

Sounds like you want to use the format_date() function.

$now = time();
$date = format_date($now, 'short');

You can use it with any of the date formats that are defined in your system, or you can pass in a custom date string.


How do I use $form_state to return data from the from submission handler to the form builder? I am trying to populate a data based on $form_state right after submission.
What I am trying to do is to populate a form that takes a keyword and passes it to a function that gets the result from another site.

I can use $form_state['values']['keyword'] in MYMODULE_form_submit() but not in MYMODULE_form_page().

How can I achieve this?

function MYMODULE_menu() {
  // Module settings.
  $items['MYMODULE'] = array(
    'title' => 'MYMODULE',
    'description' => 'MYMODULE',
    'page callback' => 'MYMODULE_form_page',
    'page arguments' => array('MYMODULE_form'),
    'access callback' => TRUE,
  );
  return $items;
}

function MYMODULE_form($form, &$form_submit){
  $form['kname'] = array(
    '#title' => t('What would you like to search:'),
    '#type' => 'textfield',
    '#required' => TRUE,
    '#description' => t('Please insert the keyword you whish to search for.'),
  );

  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => 'Send',
  );

  return $form;
}

function MYMODULE_form_submit($form, &$form_state) {
  $keyword = $form_state['values']['kname'];
  $op = MYMODULE_simple_page($keyword);

  return $op;
}

function MYMODULE_form_page($op) {
  $build = array(
    'header_text' => array(
      '#type' => 'markup',
      '#markup' => '

',
    ),
    'example_form2' => drupal_get_form('MYMODULE_form'),
    array(
      '#type' => 'markup',
      '#markup' => '
'. $op .'
',
    ),
  );

  return $build;
}

function MYMODULE_simple_page($keyword) {
  // Query the external website.
  $data = drupal_http_request('API_ADRESS_JSON');

  // Decode JSON.
  $test = drupal_json_decode($data->data);
  $outitem = '';
  $output = '';
  // Loop through the array (converted from JSON) and view the list of the result as titles and images.
  if (isset($test)) {
    for ($i=0; $i<count($test['images']); $i++) {
      $imageName = $test['images'][$i]['title'];
      $variables = array(
        'path' => $test['images'][$i]['thumbnail_path'],
        'alt' => 'Test alt',
        'title' => 'Test title',
        'attributes' => array('class' => 'some-img', 'id' => 'my-img'),
      );
      $img = theme('image', $variables);
      $outitem .= '

'. $imageName .'

'. $img .'

';
    }
  }

  $output .= $outitem;

  return $output;
}

The only functions that get $form_state are form builders, form validation handlers, and form submission handlers.

To say the truth, your code doesn't need to use MYMODULE_form_page(): You can simply use the form builder function.

function MYMODULE_menu() {
  // Module settings.
  $items['MYMODULE'] = array(
    'title' => 'MYMODULE',
    'description' => 'MYMODULE',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('MYMODULE_form'),
    'access callback' => TRUE,
  );
  return $items;
}

function MYMODULE_form($form, &$form_state) {
  $form['header_text' => array(
    '#markup' => '

',
  );

  $form['kname'] = array(
    '#title' => t('What would you like to search'),
    '#type' => 'textfield',
    '#required' => TRUE,
    '#description' => t('Please insert the keyword you whish to search for.'),
  );

  if (isset($form_state['MYMODULE_result'])) {
    $form['footer_text'] = array(
      '#markup' => '
'. $form_state['MYMODULE_result'] .'
',
    );
  }

  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => 'Send',
  );

  return $form;
}

function MYMODULE_form_submit($form, &$form_state) {
  $keyword = $form_state['values']['kname'];
  $op = MYMODULE_simple_page($keyword);

  // Form submission handlers don't return any value.
  // If you need to return a value to the form builder, you should use the following code.
  $form_state['MYMODULE_result'] = $op;
  $form_state['rebuild'] = TRUE;
}


Entity Field Query - Most efficient way to get authors of nodes I have a content type which contains fields which I am filtering my results on. Of these results, I wish to get the email address of the user who authored the node.

Currently I am using an Entity Field Query to get the list of nids. There can be thousands of matching nodes.

To get the email addresses of the authors of the nodes I do a node_load_multiple with the nids of my EFQ, and then a user_load_multiple with the uids of those nodes.

Is there a way to cut out a few of those steps with EFQ? Or will performance not be as big of an issue as I think it is?

Here is a code example:

$query = new EntityFieldQuery();
  $query->entityCondition('entity_type', 'node')
        ->entityCondition('bundle', 'application')
        ->propertyCondition('status', 1)
        ->fieldCondition('field_one', 'value', $value1)
        ->fieldCondition('field_two', 'tid', $value2)
        ->fieldCondition('field_three', 'tid', NULL, 'IS NOT NULL');
  $result = $query->execute();

  if (isset($result['node'])) {
    $nodes = node_load_multiple(array_keys($result['node']));
    $uids = array();
    foreach ($nodes as $node) {
      $uids[$node->uid] = $node->uid;
    }
    $users = user_load_multiple(array_keys($uids));
  }

You are doing a lot of potentially unnecessary loads. Unless you need those nodes at some point on the page request, you will be doing a lot of unnecessary database reads.

I would EFQ to get the node list, and then do another query to just get the $uids. This example will retrieve the node list you're looking for:

$efq = new EntityFieldQuery();
$efq->entityCondition('entity_type', 'node')
  ->entityCondition('bundle', 'application')
  ->propertyCondition('status', 1)
  ->fieldCondition('field_one', 'value', $value1)
  ->fieldCondition('field_two', 'tid', $value2)
  ->fieldCondition('field_three', 'tid', NULL, 'IS NOT NULL');
$result = $efq->execute();

if (isset($result['node'])) {
  $query = db_query('SELECT DISTINCT uid FROM {node} WHERE nid IN :nids',
    array(':nids', array_keys($result['node'])));

  $uids = $query->execute->fetchCol();
  $users = user_load_multiple($uids);
}


How to grant permission to a node for an user programatically? I am using ACL module to set user wise permission . Its working fine and I am able to set permission user wise from admin access.

What I need:

I have the nid and uid and I wants to set node view access permission to that user programmatically.

You may want to program it yourself, you can have something like this, probably implementing hook_init():

function my_module_init() {
  global $user;

  $nid = 85; // We'll check node 85.

  // Users with access:
  $uids = array(
    3,
    9,
    11,
  );

  $node_path = 'node/' . $nid;

  // Check if the user is in the node detail.
  if (current_path() == $node_path) {
    // Check if the user is not in the list of allowed users.
    if (!in_array($user->uid, $uids)) {
      drupal_access_denied();
    }
  }
}


Create view to display a Gmap for locations on node you are currently viewing I am using Gmap 7.x-2.9 and Location 7.x-3.6 on my Drupal 7.34 site. I have setup a custom content type for "Locations". So if I, for example, added a new Location called "California" I could add in all of our California locations so when I go to the California page, I will get a Gmap displaying all of our CA locations. I am currently using the default block that comes with the Location module and set it up to display in the content area for my "Locations" custom content type nodes. This works and it indeed displays markers for all of the CA locations. The problem is nothing happens when I click a marker. I would expect to get a popup bubble with the address information for the clicked location. I see nowhere in any of the configuration for that block to change this behavior. You just don't get a popup. SO I figured what I could do is make my OWN view block and set it up where the content type is Location and only display it on the Location content type nodes. This also works, but when I go to any Location node, like California for example, it displays ALL of my locations in the entire system (other states). I want it to only display the locations for the location node I am currently viewing. I am thinking contextual filters? I just can't seem to figure out the right combination of settings in the view to display locations for the location node I am currently viewing. If I could figure this out, I can use the settings in the view to add the popup and decide what goes in the popup when you click a marker.

Thanks in advance for any help on this one.

Filter on 'Content: Nid' in contextual filters.
Under 'WHEN THE FILTER VALUE IS NOT AVAILABLE', choose 'Provide default value' and 'Content ID from URL'

This will look for a node id in the url and filter your view on that id.


Comment form doesn't submit I have inserted comment form to my custom node.tpl via print drupal_render(drupal_get_form("comment_node_{$node->type}_form", (object) array('nid' => $node->nid)));. It works fine, but form isn't submitted when I click on Save button. It submits the data correctly to comment/reply/<nid>, but data aren't saved correctly and I'm only redirected back to node page.

I'm using current D7.

It was my mistake. I forgot, that I need to enable commenting on individual nodes. Sorry for this stupid mistake. Thanks @rémy


Aggregation and grouping with dates and integers I am using Views along with Highcharts Module.

Here is my objective:

I have some integers that are contained in nodes 3 different integer fields to be exact.
These integers occur over a duration of time and are entered on various days.

What I am trying to do is sum all the integers that happen on the same day.

Example:

Day 1 - 5/24/12

node #1
integer field: 10

node #2
integer field: 10

node #3
integer field: 10

node #4
integer field: 10

node #5
integer field: 10

Day 2 - 5/30/12

node #1
integer field: 20

node #2
integer field: 20

node #3
integer field: 20

node #4
integer field: 20

node #5
integer field: 20

Desired output of data for highcharts would be:

Day 1 - 5/24/12
integer field: 50

Day 2 - 5/30/12
integer field: 100

I have tried to use grouping and aggregation but I could not get a desired display.
I could get all nodes to display but could reduced them down to the desired result.

Please let me know if I can clarify in any way or if this is even possible

thanks!

I was able to accomplish by setting my aggregation differently. I set it to sum and with value checked it began to work as documented. thanks. Let  me know if anyone is having trouble with aggregation its kinda tricky getting to function properly thanks!


How to dynamically pass a user field value to jQuery? I have a notification bar with a counter, it actually prints the user's "notifications" field value (if it's greater than 0):

Activity
<?php
global $user;
$user_fields = user_load($user->uid);
$user_notifications = $user_fields->field_notifications['und']['0']['value'];
if ($user_notifications > 0) {
echo '
'.$user_notifications.'
';
echo '
'.flag_create_link('unmark_notifications', $user->uid).'
';
}
?>

And a jQuery function that resets the value to 0 on click:

    (function ($) {
      Drupal.behaviors.scriptjs =  {
        attach: function(context, settings) {

        $('.activity_link').click(function() {
        $('.activity_menu').toggle();
        $('.blob').fadeOut('normal');
        $('.flag-unmark-notifications .flag-action').click();
        $('.flag-unmark-notifications .unflag-action').click();
    });
    }
   };
  })(jQuery);

The problem is that when a new notification is received you need to refresh the page to see it.

What I've thought to do is to pass the user's "notifications" field to jQuery and update accordingly..

Is this the best way to do it or should I think about using Node JS?

How would you listen for a field value change event and then refresh the counter?

You can use Block Refresh module. Put the notification's content in a block and using this module refresh block in some interval of time. In block template write your own condition or logic.


Taxomony menu - show all, vocabulary link are disabled I have a custom vocabulary which looks something like this:

Shops (vocabulary name)

Sporting Goods
Auto Parts
Computers
Etc. (15 items in total, 1 level)

My goal is to create a menu link to Shops and a drop-down sub menu that lists different types of shops (example - Auto Parts). Shops link must be in the main menu.

I have PathAuto installed and all term have their aliases. My problem is that the exact two options from Taxonomy Menu module while editing my vocabulary are disabled:

Add item for vocabulary (disabled)

Shows the vocabulary name as the top level menu item of the taxonomy menu.

Use 'all' at the end of URL (disabled)

This changes tid+tid+tid to "All" in term when Display descendants has been selected.
Only used if Menu path type is "Default path".
Works with default taxonomy page.

Menu path type is set to Default.

Why are they disabled ? Is this the appropriate module for this kind of menu ? Should this be constructed with Views module (haven't got round to it)

Since I am just beginning to learn drupal, I'd like to use as few modules as necessary, since there is probably a module for everything, but they would only probably bloat the site and I wouldn't learn anything.

Bonus question: are there any simple, widely used D7 themes with built in drop-down menus (currently using Bartik)?

I am currently working on an ecomerce project and faced same issue. This helped https://www.youtube.com/watch?v=iBdVW7fC2Tg me so I recommend watching it, For the listing I have used drupal nice menus module. You can use it from https://drupal.org/project/nice_menus. In my project, listing is now working fine and I have 4 different menu items with their respective sub-categories.

If you still face any issues I will be available to help!


User->id() or Node->id() do not give back an integer but a string? I have written a custom class contructor (classname UserHandler) where I want to have a parameter which can be an instance of Drupal\user\Entity\User, an integer or FALSE:

  public function __construct($user = FALSE) {
    if ($user && $user instanceof User ) {
      $this->account = $user;
    }

    if ($user && is_int($user)) {
      $this->account = User::load($user);
    }

    if (!$user) {
      $this->account = User::load(Drupal::currentUser()->id());
    }

    $this->setProfileId();
  }

When I instantiate this class by calling UserHandler() or UserHandler($someUserClassInstance) everything works fine. When I want to instantiate this class by using a user id to load the user object in the constructor it works just fine as well: UserHandler(65).

But the problem appears when I want to use the id from any kind of entity or accountproxy class. Example in a hook_node_access:

function custom_node_access(NodeInterface $node, $op, AccountInterface $account) {
  $profile = new IgbUser($account->id());
}

$account is a class instance of Drupal\Core\Session\AccountInterface. When I call $account->id() the value returned is a string not an integer. This leads to the problem that a check like is_int($account->id()) becomes false. This appears with $node->id() as well for example.

Maybe I did not get some basics in PHP classes but all the comments above the id() methods in all the classes state that they would return an integer?!

Best,
Tobias

The value is in integer (for most content entity types, that is). The variable type however is a string.

That has a simple technical reason, values loaded from the database are always strings, those put into the node object and never explicitly cast to something else. Doing so would be too expensive for what it brings.


What could stop a component appearing on the front end? I'm new to Drupal and have been given a task beyond my knowledge.

I am trying to transfer a component (simple image gallery) from one site to another. I've simply copied the component files (.tpl, .module, .inc) into the new site's equivalent directories.

The back-end appears fine: I can add the component to a Panel and adjust its settings. I've replicated exactly what was on the previous site. But nothing appears on the front end.

I've tried clearing the cache and rebuilding the registry, of course.

Would anyone know what file/function I should be looking at to get this working?

In this instance it was an error in the component's render function

gallery_grid_render($subtype, $conf, $args, $contexts) {

where it was returning the information to the block.

$block->content = theme('this_name_was_wrong', $tpl_vars);


How to automate the replacement of special characters in URLs? The standard behavior (*) for friendly URLs in Drupal is replacing special characters by a hyphen in the friendly URL.

For instance,  without any input from the user, versão becomes vers-o and  conteúdo becomes conte-do. However, we need the character to be replaced by their corresponding non-accent ASCII values, such as versao  and conteudo.

Currently, we manually edit the URL when creating content. Is there a way to automate it?

(*): I assume it's out-of-the-box behavior, but this Drupal instance had modules installed and configured by other persons, maybe it's not a default behavior.

Have a look at the Transliteration module. Here is a quote from its project page:

  ... it takes Unicode text and tries to represent it in US-ASCII characters (universally displayable, unaccented characters) by attempting to transliterate the pronunciation expressed by the text in some other writing system to Roman letters.

As a sample, it transforms an URL like mydomain.com/последние-новости-в-Украине-и-мире in something like mydoamin/poslednie-novosti-v-Ukraine-i-mire.

However, to actually make this work, you also need to enable the Pathauto module. After that, go to the Pathauto setting page and check "Transliterate prior to creating alias". For more details on that, refer to "D7 Pathauto transliteration". Attention: this does not "fix" already created aliases (those need to be deleted and recreated).


hook_theme_suggestions_hook_alter() not working for Views I'm trying to create a custom template for a view page in Drupal 8.3.x. It's going in a custom theme, and needs to be a view-level template (so not page- or node-).

I've been fighting with it for a while and figured it might be an issue with the specific name, so I've made the code as sparse as possible - still no luck.

I have the following code in mytheme.theme:

function mytheme_theme_suggestions_views_view_alter(array &$suggestions, array $variables) {
  $suggestions[] = 'test_template';
}

And the following file structure:

- mytheme
  ~ templates
    * test-template.html.twig
  ~ mytheme.theme
  ~ mytheme.info.yml
  ~ ... etc.

I know that the theme_suggestions alter function is working properly; I have Twig debugging enabled, and when I pull up my site and look at the code, I can see the following: (note the "X" next to views-view.html.twig showing that as the currently used Twig file)

<!-- FILE NAME SUGGESTIONS:
   * test-template.html.twig
   x views-view.html.twig
-->

So it's adding the suggestion. And the template file is named correctly. I know it's not a directory issue, because I have other .html.twig files in that /templates/ folder that are working correctly.

Does anyone know why the file name suggestion is working, but the matching file isn't?

Edit: Kevin pointed out a possible duplicate ticket in the comment below. That's only half-related. It does solve the symptom in this particular example - I have been able to pull in one of the templates mentioned here, and it works for this case.

However, the title of the ticket and general issue still holds. I can't get the hook_theme_suggestions_hook_alter() to work with my custom theme_suggestion / template. While it turns out the view I used as my example could be solved another way, there are other instances where that won't be the case.

Found the solution. As it turns out, for some reason Drupal doesn't play nicely with custom theme suggestions starting with a word + single dash.

I updated my HOOK_theme_suggestions_HOOK_alter() function to include $suggestions[] = 'test__template'; (with 2 underscores between the words) and updated my template name to test--template.html.twig (with 2 dashes to match the 2 underscores), and everything works as expected.


How to handle multiple forms' submission in a custom module by clicking on a link I have 2 forms in my custom drupal7 module.
The 1st one (mymodule_form1_form) is a normal form with a lot of fields and a submit button at the bottom.
The 2nd one (mymodule_delete_data_form) has 1 hidden field and there is no submit button.
There is a link at the end of the 1st form which triggers a javascript logic. The javascript logic submits the 2nd form.

My problem is that I can't catch the submission of the 2nd form. The page reloads, but it doesn't entry into the mymodule_delete_data_form_submit function and I can't run the special business logic that removes the data from the database in this case.

The 1st form

function mymodule_form1_form($form, &$form_state, $node, $cid)
{
    $form['field1'] = array(
        '#type'       => 'textfield',
        '#title'      => 'Name',
        '#title_display'  => 'invisible',
        '#size'       => 60,
        '#maxlength'  => 128,
        '#required'   => TRUE,
        '#attributes' => array(
            'placeholder' => 'Name',
        )
    );

    $form['delete_record_link'] = array(
        '#markup'     =>
            "

                I would like to delete my record...

",
        '#attributes' => array(
            'class'   => array('additional')
        )
    );

    $form['submit'] = array(
        '#type'  => 'submit',
        '#title' => filter_xss("Submit"),
        '#value' => "Submit",
        '#title_display' => 'invisible'
    );

    return $form;
}

The 2nd form

function mymodule_delete_data_form($form, &$form_state, $node, $cid)
{
    $form['#submit'][] = 'mymodule_delete_data_form_submit';

    $form['delete_record'] = array(
        '#type' => 'textfield',
        '#title' => 'Remove the data from the database',
        '#title_display' => 'invisible',
        '#size' => 60,
        '#maxlength' => 128,
        '#attributes' => array(
            'placeholder' => 'Remove the data from the database',
        ),
        '#value' => "0"
    );

    return $form;
}

The submit function of the 1st form (it works like a charm):

function mymodule_form1_form_submit($form, &$form_state)
{
    echo "submit function 1
";
    exit();
}

The submit function of the 2nd form (it doesn't trigger):

function mymodule_delete_data_form_submit($form, &$form_state)
{
    echo "submit function 2
";
    exit();
}

The javascript logic that submits the 2nd form, when you click on the link in the 1st form:

jQuery(function() {
    var delete_record_field = jQuery("#edit-delete-record");
    var delete_record_link  = jQuery("#mymodule-form1-form .delete-record a");

    delete_record_link.on("click", function() {
        // set the value of the hidden field to 1
        delete_record_field.val("1");

        // submit the form
        jQuery("#mymodule-delete-data-form").submit();
    });
});

What is wrong in my code? How can I catch the submission of the 2nd form?

Drupal requires a submit button to submit - it uses the value of the submit button to determine which form was submitted.

Add a submit button to your form, and instead of executing $.submit() on your form, execute $.mousedown() on the hidden submit button.


"attempt to write a readonly database" with BrowserTestBase Functional tests I have a functional test that is currently empty. I run it with the following command;
php core/scripts/run-tests.sh --sqlite /db/drupal.sqlite --php /usr/local/bin/php --verbose --directory modules/custom/

I have tried with and without the --sqlite command, as well as trying a non-existant file like tmpfs/drupal.sqlite, but I always get the same error:

Drupal\Tests\answers\Functional\AnswersTest::testAddContentPage
Exception: Drupal\Core\Database\DatabaseExceptionWrapper:
SQLSTATE[HY000]: General error: 8 attempt to write a readonly
database:

From that error I have gathered that the issue is that the user doesn't have write-access to the database, but without knowing where the database file is I'm not sure how to check this. I tried settings the permissions on /db/drupal.sqlite to 777 but this didn't help either.

I don't quite understand why this fixes the problem, but in my case the issue was caused by my executing the core/scripts/run-tests.sh script as root. By running it as www-data instead the issue went away.
I can only assume that the sqlite DB gets created by root and then the script switches itself over to www-data and can't access the DB anymore.


Multilanguage in IE does not allow to switch languages My drupal site is built with 2 languages English/Portuguese, and the default language is English.

But in IE the default language (English) is overwritten and it only displays the  Portuguese version, and if i click the English icon it does not change to English.

However if i browse with an English computer the English is displayed, but i can't still switch from Portuguese to English.

Some advice is appreciated.

This answer is as simple as ticking a checkBox for the browser language, that for some reason in IE and Edge override the manual language switcher.
The reason that i didn't find this before was that it was in a tab far from view.


Render the first image of an image field which allow to enter multiple images I have a template file for my blog page that renders a single image when the blog posts are listed. Originally, the field was for a single image, but it has been changed to accept more than one image and render only the first image. I would like to do within a template file instead of a view.
In that template file I used the following code, which doesn't work anymore since the image field has been changed.

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

Instead of that, I tried the following code, which doesn't work too.

<?php print render($content['field_blog_images'][0]); ?>

How should I render the first image of a field that accepts multiple images?

It's all about the structure of the image field. You're automatically going to the 0 index, but I bet if you were to do a dump of that variable, you'd find you were at the wrong position in the array. You'll need to loop through it or target the very specific element you're looking to render.
Check out this documentation comment for details and modify for your example. That comment shows the following code to loop through the images.
$node = node_load($nid);
$image = field_get_items('node', $node, 'field_NAME');
foreach ($image as $key => $value) {
  $output = field_view_value('node', $node, 'field_NAME', $image[$key], array(
    'type' => 'image',
    'settings' => array(
      'image_style' => 'thumbnail', //place your image style here
      'image_link' => 'content',
    ),
  ));
  print render($output);
}

That code is showing how to loop through the images in a different context, but the foreach() loop is the same that should be used in your code.
For that reason, it could be worth taking this up to template.php inside  hook_preprocess_node() to avoid adding logic in a template file.
function mytheme_preprocess_node(&$variables) {
  if($variables['node']->type == 'blog' {
    // My crazy logic to assign my image variable.
    $variables['blog_image'] = render($somevalue);
  }
}

The template file then just needs a single code line.
print $blog_image;


Is there node api hook in drupal 7 Is there still a hook_nodeapi in drupal 7 or do i have to try hook_node_load hook for appending some content to node?

hook_nodeapi() is split into multiple hooks in Drupal 7, so you should use hook_node_load()


Inserting tokens into a text field, such as body For many years I've used the excellent token filter module. However, viewing development activity on the module, (Seeking co-maintainers, Maintenance fixes only, and last updates are over a year ago) suggests that this module's future may not so bright. Which, in turn, suggests that there is another or better way of achieving similar functionality? For example, I commonly use token filter to construct the current year for the copyright mark. Other examples include referencing the site email or slogan.

What's the best "future-proof" method for inserting token-like content into text fields?

I think you are looking for Advanced Text Formatter module which allows you to enable token replace on fields you choose. The mantainer says it would have a Drupal 8 version too.


How to change this "Anonymous's Blog" link to another name? I am trying out the Education distribution. However, I cannot find where/how to change the "ANONYMOUS'S BLOG" link (shown in red box below) to another name, for example: "BLOGS". Where is the link's name stored?

The link name is derived from the author of that node. The variable should be $content['links']['blog']['#links'] array, which can be found in node--blog.tpl.php. You can manipulate the data at that point, which is best kept as simple as possible, due to being in the tpl file itself.

If you're looking to do complex changes, I would suggest a _preprocess_node in your template, which is probably ideal if you're doing anything more than an unset or simple truncation.

More information can be found at https://www.drupal.org/node/1783428 and Preprocess function for node.tpl.php file respectively.


How can I show a flag link only for the "deepest" terms for a field with multiple values using hierarchical select? On my site, users can add terms to their user profiles via a taxonomy field.  They can add multiple terms with multiple depths using the hierarchical select widget, like this:

Trees -> Fruit trees -> Apple trees
CMS Software -> Drupal

These terms are displayed on the user profile page using a view with the hierarchical select formatter.

I have a flag that allows users to flag taxonomy terms. I want to print a flag link after the last term on each line, like this:

Trees -> Fruit trees -> Apple trees (flag me)
CMS Software -> Drupal (flag me)

The code for this is in hierarchical_select/modules/hs_taxonomy.module:

function theme_hs_taxonomy_formatter_lineage($variables) {
  $output = '';
  $lineage = $variables['lineage'];
  $separator = theme('hierarchical_select_item_separator');

  // Render each item within a lineage.
  $items = array();
  foreach ($lineage as $level => $item ) {
    dpm($item);
    $line  = '';
    $line .= drupal_render($item);
    //this adds a flag link to every term, not just the last term
    $line .= flag_create_link('hobbies_and_interests', $item['#options']['entity']->tid);

    $line .= '';
    $items[] = $line;
  }
  $output .= implode($separator, $items);
  return $output;
}

As I commented in the code above, currently I am showing a flag link for every term, not the last term in each row. This output (which I don't want) looks like this:

Trees (flag me) -> Fruit trees (flag me) -> Apple trees (flag me)
CMS Software (flag me) -> Drupal (flag me)

This is ugly; I just want the "flag me" link to appear at the end for the final term in each line.  However, I don't know how to target only the last term in each row.  I tried using end() but $output appears to be a string, not an array, so I'm lost at how to proceed (the answer may be obvious, but I'm a PHP novice).

Have you tried checking the $level variable? I have never used this module but the fact that there is a variable named $level suggests to me that this could be checked to only apply your flag link to the last 'level'.

edit in relation to comment:

Try this.

function theme_hs_taxonomy_formatter_lineage($variables) {
  $output = '';
  $lineage = $variables['lineage'];
  $separator = theme('hierarchical_select_item_separator');

  // Render each item within a lineage.
  $items = array();
  foreach ($lineage as $level => $item ) {
    dpm($item);
    $line  = '';
    $line .= drupal_render($item);
    //this adds a flag link to every term, not just the last term
    if(!count(taxonomy_get_children($item['#options']['entity']->tid))){
      $line .= flag_create_link('hobbies_and_interests', $item['#options']['entity']->tid);
    }

    $line .= '';
    $items[] = $line;
  }
  $output .= implode($separator, $items);
  return $output;
}


Google Analytics Reports: how to remove pageviews for Top Pages and add published date I've installed google analytics reports to be able to see the most viewed nodes of my website. I were able to add the Top Pages view to my home page but i wanted to know how can i :

add published date
remove the number count and leave the title only.

See image

You're looking a one difficult task & one simple one. Starting with the simple one (reverse order):

The Top Pages area is a block that's installed with the module. The Google Analytics Reports Summary (Google Analytics): Top Pages view can be configured in the Views UI (/admin/structure/views/view/google_analytics_reports_summary/edit/attachment_top_pages). To remove the views count you can click the Page Tracking: Pageviews field and use the Remove button or Excluded from display checkbox to get rid of it.
Adding the publish data is a bit harder because what the underlying View is querying. The view is querying data tables from your Google Analytics account. As such, there is no Drupal node data to display from the query. Normally, the Views way to solve this would be to add a relationship with the node table then reference the publish date. However, the module doesn't provide a relationship handler to node content so you're looking a couple things here:

Select a Google Analytics field that can be joined on the node table. Page Tracking: Page is a close candidate here as it contains a unique path used for the node link. Nid would be better, but that data isn't sent to Google Analytics by default (you'd have to configure a GA custom variable).
Once you have a selected joined field. You'd have to build your custom relationship handler on which you can join to the node table to retrieve the publish date.


Add two items with different shipping methods to basket / checkout in drupal commerce I am currently using drupal commerce to build a
website for my partner who sells jewellery. I consider myself a fairly
confident drupal user and have built various websites using the platform.
This is the first time i have used commerce though.

So my issue is with shipping. I have three shipping package types defined in
a taxonomy, and a nice way to select which of these 3 package types the
product should be shipped by using a term reference field in product
creation. I have successfully got commerce to reference to this term
reference using Commerce Taxonomy Conditions. So far I have 3
shipping package types set up and 3 world zones and can get the correct
shipping cost associated to each of these options to come up fine in the
checkout pane.

So i have 9 shipping services (3 package types x 3 world zones)

BUT

The problem comes when there are two different package types (taxonomy terms)
added to the basket and therefore there should be two prices added together and in checkout it comes up with "No valid shipping rates
found for your order, and we require shipping service selection to complete
checkout."

How can I get this to work please? What am I missing?

I have tried OR and adding to that the taxonomy term which is true and the two taxonomy terms which are false and now i can get two package types displayed in shipping in the check out pane but not getting them adding together?

This is currently doing my head in, any help would be gratefully received.
Thanks,

Currently, shipping is set on an order-basis. If you want to have per line-item shipping that would be something you'd have to build custom. Line items are entities so you can add new fields to them (including shipping profiles) and then create a shipping module or ruleset that properly configures shipping.


Best Practices? Create dynamic links with static titles on node full view page As with anything drupal, there are a million different ways to do something. I am asking this question for 1) Because I actually have to do something similar and 2) Because I would like to know all the different ways this could be achieved and the pros and cons of each. Is creating a custom field the way to go or should you just dump some dynamic code in the node-album.tpl.php template? Which way is the most flexible? Which is the most non-coder friendly?

Scenario: You have two content types (say, photo and album) where photo has a file field for an image and album is a collection of photo nodes.

If a user is viewing an album node type, how would you go about creating a "add photo" link on the full node view to add a photo to that specific album? Using the entity reference prepopulate module.

So how would you give users a way to click on a link/button for:

http://www.domain/node/add/photo?field_album_reference=[node:nid]

This is how I do mine if it's entity reference prepopulate:

<?php
        $l = l( t('Add Photo'), 'node/add/photo',   array('query' => array('field_album_reference' => $nid)  ));
        echo $l;
?>

But I usually use node reference widget when for example adding an album coming from venue content type. Code example:

<a href="<?php print url('node/add/venue-photo-album/' . $node->nid); ?>">Add Photo album


Access denied for admin page, after moving site from sub-folder to root folder Not able to access administration site after moving files from sub-directory to root folder.

With the help of google search, I have made below changes in settings.php under default folder, but that also didn't helped.
$base_url = 'http://example.com'; //Changed to site name

Actually base_url is commented in my settings.php file, I have tried enabling it.

Drupal version: 7

Got it! I was using url as ?q=admin instead of ?q=user url.


How to programmatically set views format? On install I'm trying to set my commerce_products view from table to list. Where and how do I do this? I also need to add a class to the list.

I'm a Drupal noob so if answers could be detailed that would be appreciated.

From your comments it sounds like you want to change the style_plugin from your theme.  You need to implement hook_views_default_views_alter() in your theme.

Something like this:

function themename_views_default_views_alter(&$views) {
 if (isset($views['commerce_products']) {
  $views['commerce_products']->display['default']->display_options['style_plugin'] = 'table';
 }
}

I'm not too familiar with commerce so you might not want to target the default display if that display is used elsewhere; you might just want to target the 'page' display.


How do I hide /sites/default/files from URLs? I want to upload files to their normal directory under /sites/default/files/. So let's assume I have example.pdf uploaded to sites/sites/default/files/manuals/example.pdf.

I want the links to files look like http://example.com/manuals/example.pdf. I think it's simpler and looks more professional.

How can I achieve it with Drupal?

File Aliases module allows you to use token customizable aliases for your uploaded files, giving you the ability to keep your file system organized as per usual while providing clean looking paths (i.e., no more '/sites/default/files/').

  Customizable File Alias field using Node tokens.
  Support for:

  Drupal core Upload module.
  FileField module.
  ImageField module.
  Image module.
  Comment Upload module.

  Support for Private and Public file systems.
  Support for Views output (Fields and Nodes).
  Support for FileField Paths Retroactive and Active Updating.


How can I put a checklist button in a views table to run some code on selected rows? I want to select some rows in views table and run some code for selected rows(nodes) by submit button.
How can i do that?

It sounds like you want to use the views bulk operation module.


Programatically trigger a click on an AJAX enabled form field (button, select, etc) Using jQuery, I need to programmatically click / select Form items (radios, select lists, checkboxes, etc). This field item has an '#ajax' action / callback defined using Form API.

The following code from a similar question works for submit buttons (Programatically trigger a click on an AJAX enabled form submit button):

jQuery('#edit-submit').mousedown()

However, this does not work for radio buttons. I have also tried creating a copy of the element and making my own AJAX call using the following code from another similar question (Use Drupal7 AJAX goodness programmatically):

          base = 'edit-my-radio-button';
          element = '<input type="radio" id="'+base+'" name="cat-selector" value="garfield" class="form-radio ajax-processed">';
          element_settings = Drupal.ajax[base].element_settings;
          myAjax = new Drupal.ajax(base, element, element_settings);
          myAjax.eventResponse(element, 'click');

The AJAX call is made, but the screen does not update as if the user clicked it. How can I programmatically select a radio button or select list using jQuery and cause Drupal to execute the AJAX call?

Please note: I have purposely kept this question as open ended as possible. My hope is that there is a more general way to do this for all form element types and that future answers regarding these can be considered relevant so that we have a single resource for this problem.

In order to select radio buttons using jQuery I came up with the following solution:

base = 'edit-my-radio-button';
id = '#'+base;
$(id).click();
Drupal.ajax[base].eventResponse($(id), 'click');

After some digging around in misc/ajax.js, I found that Drupal AJAX stores the result of new Drupal.ajax(base, element, element_settings) in the Drupal.ajax[] JavaScript Array. This led me to realize that I did not need to create a fake element or an element_settings object as the Use Drupal7 AJAX goodness programmatically answer suggested. While that simplified my code, and eventResponse() created a successful AJAX request, the AJAX commands being returned still did not execute.

On a hunch, I decided to use .click() followed by .eventResponse() because I noticed that false was being printed on the console.

After looking at the .eventResponse() code, I am not 100% sure where it is looking for the element to be currently selected. After stepping through the function calls, I believe jquery.form.js is checking to see if the item is selected, but since this file is minified by default, I have not gone through it yet. If anyone else can shed light on this or be willing to step through the function calls, that would be great!

FYI: If I run these commands manually in the console, .eventResponse() still returns false, so don't be alarmed when you see that.


Drupal Forum Solutions? Contemplating a new forum for a D7 site. There are many options floating around out there, and it's not very clear which of the solutions listed below would be the best direction for our use case. And which are still current (some posts and projects are quite old). Advice?

Features we're looking for:

• Has staff moderation. Volunteer moderators can be assigned.

• Private messaging between members.

• Users can earn or be given “badges” and have a nice leaderboard – we would like to use it to create an "expert" vs "new user" atmosphere for Q&A threads, with new contributors asking more seasoned ones (or staff moderators) for advice

• [Advanced] A stub of the most popular discussion(s), i.e. linked title (# of replies) can be pulled into a relevant landing page, using categories or similar to define which forums belong to which landing pages. This is important to bring user generated content into landing pages. An extra bonus would be the feature of over-riding the 'most popular' discussion with another staff featured discussion at landing page level.

• Doesn't require subdomain or iframes to integrate - can reside at something like domain.com/forum/thread or domain.com/landingpage/forum/thread

• Clean and modern UI out of the box or can be themed, responsive for mobile

• Can use Drupal user authentication or replace/supplement it with OpenID or Facebook/Twitter logins

• Includes spam control, though this isn't a deal breaker.

• [Advanced] Comments can get upvotes for helpfulness

And here are the choices that seem to be out there:

1) Core forum module - probably can't do a lot of the above?

2) Advanced forum module - how much of the above can it accomplish? If it can do most, this seems like it could be the easiest option to integrate ...

3) VBulletin - some of the larger Drupal sites with really active forums use vbulletin, typically implemented as a subdomain. There's also DrupalVB https://www.drupal.org/project/drupalvb ; phpBB is also an option

4) Acquia Commons Drupal project/modules

5) Harmony Drupal project/modules

6) Discourse - https://www.drupal.org/project/discourse . New and cool, but maybe their Docker isn't easy to integrate into a complex existing Drupal site.

7) A third party konwledgebase platform like GetSatisfaction or Zendesk. These have nice UIs, a lot of the required features from above, and Drupal integration modules already exist - but integration may still be quite complex...

Ease of integration is important, but so is how full-featured the solution is. And whether it's got a nice, modern UI.

The Advanced forum module might be a good starting point, since Drupal has a modular approach you'll have to use a lot of building blocks (drupal contrib modules) to get to the extended functionality that you desire. There might be some custom code needed. In short: there is no out of the box solution for this nor a short answer to help you build this forum but here is a good start:

Has staff moderation. Volunteer moderators can be assigned.
-> Use Workbench
Private messaging between members.
-> Use Privatemsg
Users can earn or be given “badges” and have a nice leaderboard – we would like to use it to create an "expert" vs "new user" atmosphere for Q&A threads, with new contributors asking more seasoned ones (or staff moderators) for advice
-> Badge/score system might be custom, the overviews you can build with Views
[Advanced] A stub of the most popular discussion(s), i.e. linked title (# of replies) can be pulled into a relevant landing page, using categories or similar to define which forums belong to which landing pages. This is important to bring user generated content into landing pages. An extra bonus would be the feature of over-riding the 'most popular' discussion with another staff featured discussion at landing page level.
-> Probably some custom code with also views to pull the lists
Doesn't require subdomain or iframes to integrate - can reside at something like domain.com/forum/thread or domain.com/landingpage/forum/thread
-> Use PathAuto and again views for the landingpages overviews with dynamic urls
Clean and modern UI out of the box or can be themed, responsive for mobile
-> Omega's example theme Ohm might be a good starting point or you could build a child theme from scratch on omega
Can use Drupal user authentication or replace/supplement it with OpenID or Facebook/Twitter logins
-> Try OpenID connect, Facebook connect, not sure if there is something like this for twitter
Includes spam control, though this isn't a deal breaker.
-> Use Mollom or Honeypot
Comment upvoting
-> Use Vote Up/Down


ImageBlock Module- Responsive/Fluid images I am using the ImageBlock Module to upload/insert images into a block, which works great! However I am designing a responsive/fluid website. I have no problem with this if the image is stated in CSS, but for some reason I can not get the ImageBlock to treat the image that was uploaded as responsive/fluid.

How can the image that I uploaded to the ImageBlock I created, be responsive/fluid in a website that is designed to be fluid?

Thanks!

Figured it out. In order to make a image that is a part of a imageblock, responsive/fluid, you need to:

1.) Use firebug to find the image block class for the imageblock.
2.) For me I added this to CSS

#block-imageblock-### .imageblock-image{
    width:100%;

}

This will make your image that you've uploaded into a ImageBlock responsive/fluid to any screen resolution


Drush on an already existing project First, I apologise for this question, it'll probably look very simple to a lot of you, but I am quite new at this and can't seem to figure it out.

I am working on a project that requires that I import a lot of data from a wordpress site. For that I want to use wordpress migrate. This module recommends me to use drush to transfer the data.

After having had quite a lot of problem installing it (thank you windows) I finally managed it. Now I'd like to use drush on one of the projects that's in my wamp\www file.

How do I do that? I've been looking but can't find the solution

I tried the commands from this: https://www.drupal.org/node/1958170
but it says :
"Command variable-set needs a higher bootstrap level to run - you will need to invoke drush from a more functional Drupal environment to run this command.
Command variable- set requires Drupal core versu=ion 6 or 7 to run."

I am working with drush 7 and I am hoping to use it on a drupal 7-*...

Please help!!!!!

==== EDIT ====

Once I'm in the right place I no longer get the "needs a higher bootstrap level".

After reading a few things to sort out my problem (and probably messing things up) it came back, even if I am inside the sites folder.

I can download new modules but cannot enable them
I cannot activate the migrate module and commands

and I don't see the PDO drivers listed when I do drush php-eval "phpinfo();"

What's wrong with drush ?

The "needs a higher bootstrap level" error means that you're not in the right directory to call drush.

Where's your drupal source directory ? cd to that directory , and try your drush command again...


Uploading Image as part of product I am working on a website for a youth organization. They desire to sell sponsorship for organization on site, and we are using Drupal 8.

We are able to create a product and a product variation. We can't find out how to create a field that will accept an end-user submitted image when added to the cart.

How can we achieve this?

Documentation & Background Knowledge is Limited

It's the truth, we are an organization moving from Ubercart on Drupal 6 to Commerce V2 on Drupal 8.  There's a steeeep learning curve.

So, our situation is that we want local businesses to upload a graphic as part of their sponsorship.  Eventually, we will use this image as part of an advertisement block, but at the moment, our question, HOW do we get this image upload as part of a product.

Assumptions

Drupal 8 installed, with Commerce installed V2.

Steps to Create Upload Field (Image)

Create Order Type - I created an Order Type "Sponsorship".  I used the Default workflow (might have to change in the future).  DONE
Create Order Item Types - I created an Order Line Type, named it "Sponsorship", and selected Order Type "Sponsorship".

Then I went to Manage Fields for the Order Item Type "Sponsorship" that I just created and added an Image field to that Order Item Type.
I named the Field "Ad" - as this should be an image uploaded by the sponsor.

Product Variation Type - Because I have other products, I wanted a stand along variation for the "Sponsorship".

I created a Product Variation Type - Advertisement, as I felt I had used Sponsorship too many times.  When I created that Advertisement variation, I ensured that I selected Sponsorship from the Order types.
I was a bit lost here, but a key point, create the product type variation BEFORE creating the Product Type.

Product Type - I then created the Sponsorship Product Type, selecting Advertisement as the Product Variation.
I finally created by product Front Page Sponsor and when doing so I selected Sponsorship as the Product Type, and completed the balance of the product as normal.

I hope this helps others as well..


Why would all theme background colors disappear after moving to different server? A site using MAYO 7.x-1.2 was moved from a Windows IIS to a Linux server. Shortly thereafter, all background colors defined in MAYO settings (and also any custom CSS) have disappeared. Also gone is the custom background color for dropdown Nice menus – it just goes transparent. Other than the bg color, main content and layout are OK. Perhaps there is no relationship of this to the server change, but in any case I haven't been able to debug this with anything I tried. The PHP version is now 7.2, maybe that is related, and I'm not sure what it was under the Windows server. Site needs to stay in D7 for now, although a D8 upgrade is planned.

Also note, I was aware that this is an old version of MAYO that should have been updated long ago. I hesitated to update because I had modified the template file to get an additional region, and wasn't sure how to apply the update while preserving the custom region. (Could use some advice there.) In reading the docs about the security update, it seems the circumstances for risk don't really apply for this site.

Advice on either of these issues will be much appreciated.

First , Check Administrator -> Configuration -> Media -> File System to personalize your tmp path. Make sure to use relative paths and have the right privileges for your webserver.

After than Check permission of the /sites/default/files and make sure it's writeable by your web server.


How do I use a "contains" operation as restful contextual filter for text fields I'm trying to create a restful view which takes a string as input, search specific content-type titles for similar nodes and return them as result.

The problem is I can't figure out how to configure the contextual operation to act as contains.

When you expose a filter, you can set a filter identifier.  This can be used to set the filter value via the URL, E.g.:  /search?keywords=foo or  /search?keyworks=foo+bar.

Note that if you need to hide this filter in a user view, you can do that with CSS or the Views Block View Filter module which allows you to move exposed filters to separate blocks that don't need to be placed on a user page.  Not part of your specs.. but nice to know if you need REST and user pages.

Also, given your requirements, you might want to consider either using the Search API module with it's views structure or code your own rest handler.

The Search API module will lets you easily set up full text searches and manage results order based on boosts, e.g. words found in titles are more important. The DB backend works well in D8, so you don't need Solr server for this.  (Though Solr has a lot of neat features).

Coding your own shouldn't be too hard with the D8 rest implementation.  You can then do any query variations you need.


Commerce Product Display Node using Multiple Fields? Hello after reading How do I display my products? I was impressed how easy it is to have a display node have a simple attribute system for a product.

For example Clothes can have a product reference field for different sizes.

For more complex use case can we have multiple fields?

For example Clothes size and color with each combination having a different product. I understand this requires many more products as a result.

Has anyone talked about this use case or know of a workflow / module here?

Yes you can do this. Just 2 list fields for your product type, 1 for color and 1 for size.

When creating your products, have the clothes of the same size use the same image.

When you create a product display node, you will see both of the select lists displayed. When you select a different color the image will change.

The issue I am having is that when selecting option 2 and then option 1, option 2 will reset back to its default value.  The risk is that a customer will not notice and order the wrong product.


Fields created by a Feature generated module remains after disabling the module In my-site-com I created a new feature to show the component: fields , then I added some fields, I download the feature as a module called my-feature-module, then I saved and enabled this module in other drupal installation my-site-2.com.

I get all the fields properly. So far so good.

Now I disabled the module my-feature-module in my-site-2.com and the problem is that the fields are not removed, they remain there. Is this normal? I mean, expected the fields to disappeared if I disable the module.

I make sure I cleared all caches and updated database, just in case it was a cache problem, but problem still persist.

Yes, this is normal. Some configuration items such as views can be implemented purely as code and some such as fields require database updates. Items in the former category will be removed when you disable a feature, those in the latter category will not. This is not necessarily a good thing but once you understand it, at least you know how to deal with it (manual removal of items).


form error Fatal error: Cannot use string offset as an array It's pretty stright forward, im trying to display the results of my form, Im having trouble finding something that explains how to display the results outside of the  drupal_set_message() code, I think I am close with my current code.However I am getting this error Fatal error: Cannot use string offset as an array

/**
 * Block info
 */

function zillow_block_info(){
    $blocks['zillow_block'] = array(
        'info' => t('Zillow Block'),
    );
    return $blocks;
}

function zillow_block_view($delta = ''){
    $block = array();
        switch ($delta){
    case 'zillow_block';
        $block['subject'] = t('Zillow Block');
        $block['content'] = drupal_get_form('zillow_form');
    break;
    }
    return $block;
}

/**
 * Api info
*/

function zillow_api_info($form, &$zinfo){
    set_time_limit(3600);
    $state = $zinfo['values']['state'];
    $zillow_id = 'XXXXXXXXXXX';
    $xml = file_get_contents('http://www.zillow.com/webservice/GetRateSummary.htm?zws-id='.$zillow_id.'&state='.$state.'');
    $zinfo = simplexml_load_string($xml);

    foreach($zinfo->response as $rates){
        $zinfo .= $rates->today->rate[0];
        $zinfo .= $rates->today->rate[1];
        $zinfo .= $rates->today->rate[2];
        $zinfo .= $rates->lastWeek->rate[0];
        $zinfo .= $rates->lastWeek->rate[1];
        $zinfo .= $rates->lastWeek->rate[2];
    }

    return $zinfo;
}

/**
 * Form
 */

function zillow_form($form, &$zinfo){

    $form['description'] = array(
        '#type' => 'item',
        '#title' => t('Get your mortgage rates'),
    );
    $form['rates'] = array(
        '#type' => 'fieldset',
        '#title' => t('Mortgage Rates'),
        '#collapsiable' => TRUE,
        '#collapsed' => FALSE,
    );

    $form['rates']['state'] = array(
        '#type' => ('select'),
        '#title' => t('Choose One'),
        '#options' => array(
            'AK' => t('Alaska'),
            'AZ' => t('Arizona'),
        ),
        '#required' => TRUE
    );
    $form['submit'] = array(
        '#type' => 'submit',
        '#value' => t('Submit'),
    );
    if(isset($zinfo['values'])){
        $form['page_output'] = array(
        'markup' => 'Submitted value:'. $zinfo['values']['state']);
    }
    return $form;
}

/**
 * Submission Output
*/

function zillow_form_submit($form, &$zinfo){
  drupal_set_message(t('this is the info the form has submitted. states=@states, todaysrates=@todaysrates', array('@states' => $zinfo['values']['state'], '@todaysrates' => zillow_api_info($form, $zinfo))));
  $zinfo['processed']['states'] =  serialize($zinfo['values']['state']);
  $zinfo['processed']['todaysrates'] =  serialize(zillow_api_info($form, $zinfo));
}

Edit** My code has been modified I am now only getting this error

The problem is here:

if(isset($zinfo['values'])){
    $form['page_output'] = array(
    'markup' => 'Submitted value:'. $zinfo['values']['state']);
}

Any element of a render-array that doesn't start with a # symbol is itself considered a child render-array by the drupal_render() function.

As drupal_render() expects an array when your array key is markup (without the #), it tries to treat the variable as an array. Since it's a string, PHP complains that it can't use the provided variable as an array...because it isn't one :)

This should work:

if(isset($zinfo['values'])){
    $form['page_output'] = array(
    '#markup' => 'Submitted value:'. $zinfo['values']['state']);
}

Have a look at Render Arrays in Drupal 7 and the FAPI #markup property for more information.

EDIT

There's a slightly bigger problem: in zillow_api_info() you're accepting the $zinfo parameter by reference, and then overwriting it with this call: $zinfo = simplexml_load_string($xml);.

That code overwrites the $zinfo variable in memory, so when you use it again in your submission function it will cause errors. It's also what's causing the last two lines not to work, and $zinfo['values'] to not exist when your form is rebuilt.

The easiest solution is to change zillow_api_info() to look like this:

function zillow_api_info($form, &$form_state){
  set_time_limit(3600);
  $state = $form_state['values']['state'];
  $zillow_id = 'XXXXX';
  $xml = file_get_contents('http://www.zillow.com/webservice/GetRateSummary.htm?zws-id='.$zillow_id.'&state='.$state.'');
  $zinfo2 = simplexml_load_string($xml);

  foreach($zinfo2->response as $rates){
    $zinfo2 .= $rates->today->rate[0];
    $zinfo2 .= $rates->today->rate[1];
    $zinfo2 .= $rates->today->rate[2];
    $zinfo2 .= $rates->lastWeek->rate[0];
    $zinfo2 .= $rates->lastWeek->rate[1];
    $zinfo2 .= $rates->lastWeek->rate[2];
  }

  return $zinfo2;
}

As an extra note, you do need $zinfo['rebuild'] = TRUE in your submit function too.

I'd really advise using the $form_state variable name throughout your code when it refers to the form state array, it'll make problems like this vanish instantly :)


Is there a way to order by COUNT('column') without returning an integer? I'm trying to make this query work correctly in Drupal 8. I want to return the events in order of most frequently occurring in the database table (Users vote for the event they prefer). But I only want to display the event name and not the number of times someone has voted. Here is my SQL query:

SELECT `event`
    FROM     `eventform`
    GROUP BY `event`
    ORDER BY COUNT(`event`) DESC

In SQL pro it returns correctly the following data.

Brewery
Conference
Concert
Dinner
Musical

With Drupal, I am getting the following data.

Brewery
10
Conference
8
Concert
7
Dinner
6
Musical
4

How can I make the following code return only the event names?

$query = \Drupal::database()->select('eventform', 'm');
$query->fields('m', ['event']);
// It doesn't return the correct order unless I use
$query->addExpression('COUNT(event)', 'count');
$query->groupBy('event');
// I want something like orderBy(COUNT('event'),'DESC'), but this
// returns incorrect ranking;
$query->orderBy('count','DESC');
$votes = $query->execute()->fetchAll();

Here is how I'm rendering:

 $rankings=array();
  foreach($votes as $key){
    foreach ($key as $value) {
      $rankings[] = $value;
    }
  }

    $build = [
      'rankings' => [
        'rankings_child_element' => [
          '#theme' => 'item_list',
          '#list_type' => 'ol',
          '#items' => $rankings,
        ]
      ],
      '#empty' => t('No votes found'),
    ];
    return $build;

}
}

Try this :

  use Drupal\Core\Database\Database;
  $connection = Database::getConnection();
  $sth = $connection->select('eventform', 'm');
  $sth->addField('m', 'event');
  $sth->addExpression('COUNT(m.event)', 'count');
  $sth->groupBy('m.event');
  $sth->orderBy('count','DESC');
  //- Execute the statement
  $data = $sth->execute();
  //- Get all the results
  $results = $data->fetchAll(PDO::FETCH_ASSOC);

you will get the $results as an array something like:

array:5 [▼
   0 => array:2 [▼
     "event" => "Brewery"
     "count" => "10"
   ]
   1 => array:2 [▼
     "event" => "Conference"
     "count" => "8"
   ]
   2 => array:2 [▼
     "event" => "Concert"
     "count" => "7"
   ]
   3 => array:2 [▼
     "event" => "Dinner"
     "count" => "6"
   ]
   4 => array:2 [▼
     "event" => "Musical"
     "count" => "4"
   ]
 ]

if you want to get only the event name loop thought the $results something like :

 $events_name = [];
 foreach ($results as $result){
    $events_name[] = $result['event'];
  }


Advagg Cache-Control > 1 year I am trying to use Advagg module. All's ok, but unshit.com states that all its css and js files Cache-Control is set more that a year.

In .htaccess

# Requires mod_expires to be enabled.
# Turn on Expires and set default to 0
ExpiresActive On
ExpiresDefault A0

# Set up caching on media files for 1 year (forever?)
<FilesMatch "\.(flv|ico|pdf|avi|mov|ppt|doc|mp3|wmv|wav)$">
    ExpiresDefault A29030400
    Header append Cache-Control "public"
</FilesMatch>

# Set up caching on media files for 1 week
<FilesMatch "\.(gif|jpg|jpeg|png|swf)$">
    ExpiresDefault A2419200
    Header append Cache-Control "public"
</FilesMatch>

# Set up 2 Hour caching on commonly updated files
<FilesMatch "\.(xml|txt|html|js|css)$">
    ExpiresDefault A7200
    Header append Cache-Control "private"
</FilesMatch>

# Force no caching for dynamic files
<FilesMatch "\.(php|cgi|pl|htm)$">
    ExpiresActive Off
    Header set Cache-Control "private, no-cache, no-store, proxy-revalidate, no-transform"
    Header set Pragma "no-cache"
</FilesMatch>

mod_expires and mod_headers are enabled.

I would be very grateful for any help.

http://tools.ietf.org/html/rfc2616#section-14.21 Thanks for pointing this out.
Answer will be in here eventually - https://drupal.org/node/2161115


How to use another theme's template file I have a template file for a entity type inside my theme's folder.

How can I use the same template file in the admin area which uses the Seven theme?

Thanks. M

Since it's always bad practice to hack core, you would have to do it with a custom module. This would be done with either template suggestion overrides or with template suggestions in a preprocess hook such as template_preprocess_node or template_preprocess_page.

Unfortunately this is not enough when you place the template file (tpl) anywhere but the theme's templates/ folder. Your custom module's template folder is not known by default so you will have to notify Drupal about. To do this, you will need to use hook_theme_registry_alter. Here below is an example from one of my projects in Drupal 7 (and it's live and works).

/**
 * Implements hook_theme_registry_alter()
 */
function CUSTOM_MODULE_theme_registry_alter(&$theme_registry) {
  // The Templates path in your custom module you want to add...
  $mod_path = drupal_get_path('module', 'CUSTOM_MODULE') . '/includes/templates';

  // ... or the Templates path in your custom theme.
  // If you use your already existing custom theme's path, make sure you remember that this
  // function exists when you alter or disable the custom theme.
  $mod_path = drupal_get_path('theme', 'CUSTOM_THEME') . '/templates';

  $theme_registry_copy = $theme_registry;
  _theme_process_registry($theme_registry_copy, 'phptemplate', 'theme_engine', 'pow', $mod_path);
  $theme_registry += array_diff_key($theme_registry_copy, $theme_registry);
  $hooks = array('node');
  foreach ($hooks as $h) {
    _CUSTOM_MODULE_insert_after_first_element($theme_registry[$h]['theme paths'], $mod_path);
  }
}

/**
 * Helper function for re-ordering arrays (needed by theme_registry_alter)
*/
function _CUSTOM_MODULE_insert_after_first_element(&$a, $element) {
  if(is_array($a)) {
    $first_element = array_shift($a);
    array_unshift($a, $first_element, $element);
  }
}

I've seen people advocate (or at least suggest) the use of theme_hook() instead, but I actually find the theme registry way a lot easier to handle. Especially when you add more templates at a later stage during the development process.


How can I modify the code in taxonomy feature to include terms I have created a feature to export my taxonomy vocabulary.  How can I programatically modify it to add the terms as well ?

Features can't export (and import) terms without "extension".
You could use UUID Features:

  The UUID Features Integration module provides a mechanism for
  exporting content (nodes, taxonomy, fields) into a features module.


How do I place a block with Twig Tweak? I've placed a view block via Twig Tweak in page-front.html.twig before and it worked fine. That was on Drupal 8, but now I'm on Drupal 9. This's what I would have done in Drupal 8.

{{ drupal_view('library_carousel ', 'block_carousel') }}

This is what I gather I'm supposed to do in Drupal 9.

{{ drupal_view('library_carousel ', 'block_carousel') }}

It's not rendering anything. In Views, it shows the view machine name as 'library_carousel'. Inside the view, it shows the block machine name as 'block_carousel'.
I've confirmed that if I place the block via the Drupal interface, it does render correctly. I just can't get it to render via Twig Tweak. And yes, I've flush all the caches multiple times. Also, I have other things in the page-front twig that render correctly so I know the template is rendering in general.
Why isn't working?

There's a section in the docs explaining how to print blocks even if they are disabled. Maybe that's your problem.

Disabled blocks won't be printed unless you suppress access control as follows.
{{ drupal_entity('block', 'block_id', check_access=false) }}

Is working on D9 for me.


calling a block views by ajax I have a views with three displays which sorts comments of a node in newest, oldest and most popular order. These views are shown below the content and works with contextual filters. I have used ajax_comment and rate and vote api module in order to add/reply comments by ajax and let users vote other people's comments too. Now I want to load one of these views at a time so I have created an HTML like this:

<select name="sort" onChange="return sort1()">
    <option value="newest">newest comments</option>
    <option value="oldest">oldest commenst</option>
    <option value="popular">most popular comments</option>
</select>

and a jquery code like this:

But it does not work.

I have tested quicktabs module too but comment reply link does not work with ajax_comment then. I have seen JQuery AJAX Load module too but it needs a url to load.

If my code is incorrect please correct it or if you have a better solution please let me know it.

I post my answer for anyone who is facing this problem. After all it worked by some changes:

newest comments

oldest commenst

most popular comments

<?php print views_embed_view('comments_views', 'block_3'); ?>

and jQuery code is:

function sort1(){
var nid='<?php echo $node->nid; ?>';
$.ajax({
    url: 'http://www.yoursitename.com/views/ajax',
    type: 'post',
    data: {
        view_name: 'comments_views', //view name
        view_display_id: 'block_3', //view display
        view_args: nid,   //view contexuall filter
    },
    dataType: 'json',
    success: function(response){
        //alert(response[1].data);
        $('#cm').html(response[1].data);
    }
});
    return false;
}

for each of the sort functions above it must be exist.


Use an Address Field with 3 lines for the street I'm working on an Entity where I created a field containing Address informations (like country, city and street).

The default Address Type in Drupal 8 supports only 2 lines for the street information. Is there a way to add an extra line?

I found a (partial solution), but new ideas are always well welcomed.
I used the field organization as third row and then I rearranged the weights of the fields in this way:

function mymodule_form_alter(&$form, FormStateInterface $form_state, $form_id) {
    if ($form_id == 'specific_add_form' || $form_id == 'specific_edit_form' ) {
        $form['field_address']['widget'][0]['address']['#after_build'][] = 'mymodule_weight_change';
    }

}

function mymodule_weight_change($element, $form_state) {
    $element['country_code']['#weight'] = -10;
    $element['address_line1']['#weight'] = -7;
    $element['address_line2']['#weight'] = -5;
    $element['organization']['#weight'] = -2;
    $element['postal_code']['#weight'] = 5;
    $element['locality']['#weight'] = 10;

    return $element;
}

Endly I put the css of the organization label as display: none.


Change Drupal Views Rows before they were rendered I want to change the output of a view. More precisely i want to reduce the resulting list to exact 3 matches: one specific row and its previous and next row.

As far as I understand I need to generate the whole list first, because otherwise i cant find the previous row. So I thought I have to do something in the views-view.tpl where all the rows will printed.

My question then is: How can I get the content of a specific field in each row in $rows so i can check for that specific row and its surrounding rows?

Or is there any better way?

ps. ( i am a php noob )

A custom module which implements hook_views_pre_render() will give your that ability:

<?php
MYMODULE_views_pre_render(&$view) {
  if ($view->name=='myview') {
    // limit the results to 3
    array_splice($view->result, 3);

    //other modifications can be done as well:
    foreach($view->result as $r => $result) {
      // do something
    }
  }
}

to find a specific row you'll have to code a bit, but that's not drupal related, check https://stackoverflow.com/questions/1019076/how-to-search-by-key-value-in-a-multidimensional-array-in-php for further informations.


how to get the node author link In the node.tpl, how do i just get the $author profile page url?

with the $submitted, it prints out other things, all i need is just something like this:

$author

I've also used $name, but this only gives the name without a link.

I would also like to get the link to the current user's profile. Again, just need the username with their profile url only.


Pass variable from theme page template to commerce-product file I am new to drupal and this is my first website in drupal.
I am looking to pass a variable from newtheme.theme to commerce-product.html.twig but I am not able to do so.

Here is my code (newtheme is name of my theme)

function newtheme_preprocess_page(&$variables) {
 $variables['product_cta'] = 'Static Text';
}

in commerce-product.html.twig

{{product_cta}}

but this is not working  the product_cta will be a call to action which will be calculated programmatically and passed to the product single page.
I am using Drupal 8 and Commerce 2.X.X

Any help is really appreciated.

You can use the next function in your theme / module:

function YOURT_HEME_preprocess_commerce_product(&$variables) {
 $variables['product_cta'] = 'Static Text';
}

function YOURT_MODULE_preprocess_commerce_product(&$variables) {
 $variables['product_cta'] = 'Static Text';
}

And show the variables in the commerce-product.html.twig file:

{{ product_cta }}

;)


hook_boot and Varnish I have a module that implements a hook_boot(), and it checks if user is going to access home page and if user does not have a specific cookie. If both verifications are true, it redirects user to a /welcome page and set cookie. So the second time a user tries to access home page, it will see that user has the cookie and will not redirect.

Recently, I installed Varnish on my site, and everytime I try to access home page, I get to /welcome page. It never skips.

I'm not sure but it looks like the first time I access home page, when I still don't have cookie, it caches the home page, shows /welcome page and set cookie. Then, second time I try to access home, it gets the cached page (which thinks I don't have cookie) and redirect again to /welcome page, even though I have cookie.

I tried not caching home page but it didn't work.

Any thoughts?

If you use Varnish - you must consider that for anonymous users PHP code will not execute at all - they will retrieve only static HTML.

In you case solution can be as following:

On welcome page set cookie by JavaScript not PHP.
Using Varnish vcl script check if user loads homepage and has cookie. If not - then redirect it to welcome page.

Now item #2 is made in PHP code but you need rewrite it using Varnish.
You can also write item #2 using JavaScript but it will work much slower and user will see browser redirection.


How can I edit the contents of the printable invoice for Ubercart order? I need to add some text and a few extra order fields (and user profile fields, if possible) to the printable invoice that is accessed via a link like this: http://mysite.com/admin/store/orders/12345/invoice/print

I used grepWin to find all instances of the phrase "Purchasing Information:" (which is on the invoice), and that phrase was found in two files: uc-packing-slip.tpl.php and uc-order--customer.tpl.php. Unfortunately, changes to those files have no effect on the printable invoice (I tried placing the modified tpl files in my theme's templates/ folder as well as in their original location.

The only way I could get a "reaction" was to change the contents of the file uc_order-invoice-page.tpl.php. However, its contents are merely as follows:

<?php

/**
 * @file
 * Default theme implementation to display a printable Ubercart invoice.
 *
 * @see template_preprocess_uc_order_invoice_page()
 */
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="<?php print $language->language ?>" lang="<?php print $language->language ?>" dir="<?php print $language->dir ?>">

<head>
  <?php print $head; ?>
  <title><?php print $head_title; ?></title>
  <style type="text/css">
    .buttons {
      text-align: right;
      margin: 0 1em 1em 0;
    }
  </style>
  <style type="text/css" media="print">
    .buttons {
      display: none;
    }
  </style>
</head>
<body>
  <div class="buttons">
    <input type="button" value="<?php print t('Print invoice'); ?>" onclick="window.print();" />
  </div>

  <?php print $content; ?>
</body>
</html>

I tried adding some of the order fields to that file, replacing <?php print $content; ?>, but it did not work. I suppose if I can find out the source of the "content" that is being "printed", I would be in good shape. Can anyone help?

Thanks!

Try Ubercart Register Invoice, this will allow you to define new email templates for invoice emails ... these same templates should also be visible/useable by your sites Theme.

  Registers invoice templates with Ubercart so they appear on and can be
  selected for the Ubercart "E-mail an order invoice" Rules action.

  Registers invoice templates with Drupal so they can be used to theme
  the invoice data.

  Provides extensive instructions and feedback on how to configure
  invoice templates.

See the README. You name your template: uc-order--*.tpl.php and it will be seen by the system. Also see the built-in help (prior and after creating a template) at http://mysite.com/admin/help#uc_register_invoice


Alter Header Status Response to 410 I have several urls with "/tag/" string; some of them have content and some of them don't, so they return 404.
How can I force them to return a 410 only for those that have no content?
I need a filter: has "/tag/" in URL and returns 404 -> redirect to 410.
I tried in theme_preprocess_html(&$variables) like this:
if ($pattern2){ //it has "/tag/" string
      $status = \Drupal::requestStack()->getCurrentRequest()->attributes->get('exception');
      if ($status && $status->getStatusCode() == 404){
          $response = new Response();
          $response->setStatusCode(410);
          return $response;
      }
}

It filters is working but nothing it's not redirecting to 410.
Thank you for your help!!

Yes, definitely higher up. When you are already inside of a 404 subrequest it is too late.
You could put the code in on404() of an HttpExceptionSubscriber, check the path and then replace the 404 with 410:
$event->setException(new HttpException(410));

See https://drupal.stackexchange.com/a/231263/47547


Deadlock on cache table drupal My client site has huge data, which they want to download into CSV through View data export module, when multiple users are trying to download the csv file, its resulting in an error.

In log messages I can see error like-

PDOException: SQLSTATE[HY000]: General error: 1205 Lock wait timeout exceeded; try restarting transaction:

When I am trying to see my innodb status through:
 mysqlengine innodb status\G;
its showing deadlock for insert into cache table.

Can anyone help in this?

https://www.drupal.org/project/apdqc is a pretty good solution for the issue you're describing. Install the module and go to the status report page (admin/reports/status); it will then run a gamut of tests and give you advice on things to change in your settings.php, php.ini, and my.cnf files.

The root cause of most of the cache deadlocks is that a truncate query and insert query are in conflict with each other.


assigning a role to a user programatically I have been looking around for how to assign a role to a user programatically and there is some discussion. Basing my code a little off of https://drupal.org/node/28379, will this work?

    global $user;
    $myuser = user_load($user->uid);
    $myuser->$role[4] = 'Member';
    user_save($myuser);

where I already know that the Member role is stored at key 4 (I did a print_r on user who is assigned that role and I see

 [roles] => Array ( [2] => authenticated user [4] => Member )

$uid = 123;// User ID of user that you want to add role to.
$role_name = 'Role to add'; // The name of the role to add.
if ($role = user_role_load_by_name($role_name)) {
  user_multiple_role_edit(array($uid), 'add_role', $role->rid);
}

Is how you should do it in Drupal 7. See https://api.drupal.org/api/drupal/modules%21user%21user.module/function/user_multiple_role_edit/7


Category tags like drupal.org (Drupal 7) I am wondering how to create tags like they have on the main drupal site:

I assume drupal.org is designed using Drupal :)

Can anyone tell me if this is somehow built in to drupal?  The only options I see for term reference fields are list, text fields (which only allow the user to input one tag) or hierarchical reference fields.  Is there some module that allows for the use of these more sophisticated tags?

There are a number of modules such as:

Nice Tags, here is an excerpt about it from the module's project page:

  ... improves seamlessly the UX for taxonomy tags input fields.

  No 3rd party JS libraries are required, as it works out of the box with jQ version shipped with Drupal.

Active Tags, here is an excerpt about it from the module's project page:

  ... adds a new option to free tagging taxonomies. If selected the taxonomy widget is replaced by a new jQuery enabled tag entry widget.

  Works with core Taxonomy module and Content Taxonomy module.

  This module came about through work on a site where some users found separating tags with commas confusing. Some users got it, and some didn't. This resulted in a site littered with concatenated tags. Wordpress has a similar tag entry mechanism where tags are entered separately. It has been implemented here using jQuery to rewrite the standard taxonomy entry form.

You can also use your taxonomies as tags as well if that's something you are interested in.


Listing all entity properties identifying unique entity instance? Is there a generic way of knowing what collection of properties on an entity identify it as a unique instance?

For example, a node has a node id, and a revision id. Some entities do not have the revision id, other entities might require further keys.

Usecase example: Storing various entities in an external system, one wants to be sure to store enough data to be able to uniquely identify the resources in that system.

I have always assumed that when you do

$entity_info = entity_get_info('foo');
$table = $entity_info['base table'];
$schema = drupal_get_schema($table);

and then examine $schema['primary key'] and $schema['unique keys'] you get a tuple to represent uniqueness.

I would also assume that you can do

$entity_info = entity_get_info('foo');
$keys = $entity_info['entity keys'];

and this would represent a tuple to uniquely identify an entity.  However, this gets a little confusing.  For example, if you have UUID installed, then there is a uuid and revision uuid in the results.  These are not needed within one system, but will guarantee uniqueness between systems.


Strange log message and node not found for anonymous I have a node found at the teaser of front-end for both admin and anonymous users. However, going to the node details page using anonymous user leads to 404 error while it works fine with admin.

The log message details is strange as shown in the following screen shot:

What is custom_404_page? I'm afraid of it is a hacking against the website.

I tried to clear all cache, I disabled XMLsitemap module. I could not able to determine where is the origin of custom_404_page.

Also in the log and after clearing it, and the trying to visit this node's details, this is the only log message available. i.e there is no other messages or warnings.

Check your custom 404 configuration at admin/config/system/site-information.

Also check if this custom configuration is directing users to a Panels page (check Structure > Panels or Structure > Pages if you have Panels and Page Manager installed). They may be handling different custom 404 pages for different roles. Perhaps the Panel variant that handles the 404 page for anonymous is missing or redirecting to a non-existing page.


In Drupal 7, how do I display my taxonomy term fields while creating content when using a checkbox field? I currently have the following below as a taxonomy reference field in one of my content types as a checkbox list widget during content creation.

Currently its only showing the term name, but I want it to show the term name and its fields. My end results would be something like this:

nc - North Carolina

nj - New Jersey

ny - New York

How can that be done?

I don't think there's a way to do this using the UI, but you should be able to do this using template_preprocess_field().

Store the full version of each acronym as the description on each of your taxonomy terms. The acronym would be the title.

Then you'll want to do something like:

*note that this is all pseudo-code as I don't have a version of Drupal handy to test this, but with some kpr() or var_dump() calls you should be able to debug it for your needs*

<?php
function my_theme_preprocess_field(&$vars) {
  $element = $vars['element'];
  // Modify the output of the taxonomy term field
  if ($element['#field_name'] === 'field_my_taxonomy_term') {
    // Get the title and description
    $item = $vars['items'];
    $acronym = $vars['items'][0]['title'];
    $description = $vars['items'][0]['description'];

    //create the html you want
    $html = '<span>'.$acronym.' - '.$description.'</span>';

    //now replace the default field markup with your new markup
    $vars['items'][0]['#markup'] = $html;

  }
}
?>


“Illegal Choice has been detected” I want to prevent validation check on the field_abc ?
How can I prevent validation for a field_abc

  function test_mail_menu() {
         $items['test-mail-1'] = array(
            'page callback' => 'drupal_get_form',
            'page arguments' => array('test_mail1_form'),
            'type' => MENU_CALLBACK,
            'access arguments' => array('access content'),
          );

    return $items;
    }
    function test_mail1_form ($form,$form_state) {
      $form = array();
      $form['field_abc'] = array(
        '#type' => 'textfield',
        '#title' => t('ABC'),
        '#validated' => TRUE,
     );

      $form['submit-button'] = array(
        '#type' => 'button',
        '#title' => t('sub'),
      );

      $form['#submit'][] = 'test_mail1_submit';
      $form['#validate'][] = 'test_mail1_validate';
      return $form;
    }

    function test_mail1_submit($form,&$form_submit) {

    }

    function test_mail1_validate($form, &$form_state) {

      if (!(is_numeric($form_state['input']['field_abc']))) {

        form_set_error('field_abc','ERROR');

      }
    }

If you don't want to validate that field, then remove the following function

function test_mail1_validate($form, &$form_state) {

  if (!(is_numeric($form_state['input']['field_abc']))) {

    form_set_error('field_abc','ERROR');

  }
}

And remove the following line from test_mail1_form

$form['#validate'][] = 'test_mail1_validate';


locking custom module function In my custom module, I would like to acquire lock on a particular function which will allow only one process to execute that piece of code at a time and then allow other process and so on. So that the code does not run in parallel.

Is it possible ?

Drupal provides its own locking mechanisms.

  In most environments, multiple Drupal page requests (a.k.a. threads or processes) will execute in parallel. This leads to potential conflicts or race conditions when two requests execute the same code at the same time. A common example of this is a rebuild like menu_rebuild() where we invoke many hook implementations to get and process data from all active modules, and then delete the current data in the database to insert the new afterwards.

  This is a cooperative, advisory lock system. Any long-running operation that could potentially be attempted in parallel by multiple requests should try to acquire a lock before proceeding. By obtaining a lock, one request notifies any other requests that a specific operation is in progress which must not be executed in parallel.

  To use this API, pick a unique name for the lock. A sensible choice is the name of the function performing the operation. A very simple example use of this API:

function mymodule_long_operation() {
  if (lock_acquire('mymodule_long_operation')) {
    // Do the long operation here.
    // ...
    lock_release('mymodule_long_operation');
  }
}

  If a function acquires a lock it should always release it when the operation is complete by calling lock_release(), as in the example.

A function that has acquired a lock may attempt to renew a lock (extend the duration of the lock) by calling lock_acquire() again during the operation. Failure to renew a lock is indicative that another request has acquired the lock, and that the current operation may need to be aborted.
>
If a function fails to acquire a lock it may either immediately return, or it may call lock_wait() if the rest of the current page request requires that the operation in question be complete. After lock_wait() returns, the function may again attempt to acquire the lock, or may simply allow the page request to proceed on the assumption that a parallel request completed the operation.

In Drupal 8, the example code would not be much different.

function mymodule_long_operation() {
  $lock = \Drupal::lock();
  if ($lock->acquire('mymodule_long_operation')) {
    // Do the long operation here.
    // ...
    $lock->release('mymodule_long_operation');
  }
}

See  \Drupal\Core\Lock\LockBackendInterface for the interface exposed by the locking service.