voting entity reference field I have two content types, game and player. Each game can have a number of players assigned to it. I would like to have the capability to give votes to each player in a game. What are some ways to do this? Is there documentation, or blog posts with detailed examples?

It's hard to recommend something without more specifics. How are you imagining the way people can vote? Are they voting for their favorite player for that game, and can only vote for one player per game? Do they give "thumbs-up" to as many players as they want? Do they assign X out of 5 stars to a player?

The Fivestar module is very popular, and has pretty good documentation.

The Rate module is also popular, has a lot of different ways of voting, and there is a YouTube video showing how to use it.


Select list set default value does not work I have referenced filed, which works like select list, I want first value be always default value in content edit page. Now N/A is always selected.

function theme_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {

  $form['field_my_name']['und']['#default_value'] = 1;
}

This is my code, but it does not work

To set the default value of field change the default value inside the widget like the following :

 $form['field_my_name']['widget']['#default_value'] = 1;


Download count module does not work for me I installed the Download Count module for Drupal 6. The automatic views were normally generated by the module. One of these views is file_download with a page format. The view should generate statistics, but I find no statistics generated by the view. I opened the view and I found everything is normal, unless there is something I am not aware of.

Did I miss anything?

Try setting your file field to use private file system instead of public.


Where is $node->rendered being set? Given the following code:

function hook_search_execute($keys = NULL, $conditions = NULL) {
  // Build matching conditions
  $query = db_select('search_index', 'i', array('target' => 'slave'))->extend('SearchQuery')->extend('PagerDefault');
  $query->join('node', 'n', 'n.nid = i.sid');
  $query
    ->condition('n.status', 1)
    ->addTag('node_access')
    ->searchExpression($keys, 'node');

  // Insert special keywords.
  $query->setOption('type', 'n.type');
  $query->setOption('language', 'n.language');
  if ($query->setOption('term', 'ti.tid')) {
    $query->join('taxonomy_index', 'ti', 'n.nid = ti.nid');
  }
  // Only continue if the first pass query matches.
  if (!$query->executeFirstPass()) {
    return array();
  }

  // Add the ranking expressions.
  _node_rankings($query);

  // Load results.
  $find = $query
    ->limit(10)
    ->execute();
  $results = array();
  foreach ($find as $item) {
    // Build the node body.
    $node = node_load($item->sid);
    node_build_content($node, 'search_result');
    $node->body = drupal_render($node->content);

    // Fetch comments for snippet.
    $node->rendered .= ' ' . module_invoke('comment', 'node_update_index', $node);
    // Fetch terms for snippet.
    $node->rendered .= ' ' . module_invoke('taxonomy', 'node_update_index', $node);

    $extra = module_invoke_all('node_search_result', $node);

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

Where does $node->rendered come from? Where is it defined and what does it contain?

$node->rendered is set in node_search_execute():

$build = node_view($node, 'search_result');
unset($build['#theme']);
$node->rendered = drupal_render($build);

It contains the rendered node display for the search_result view mode.


HTTP request status fails, but update checking works manually I have a problem with my Drupal 7 (multi-site) installation on a root-server. The HTTP request status shows "failed" on the status page. However, I am able to check for updates manually when logged in without a problem, so Drupal actually is allowed to access other sites.

I am having problems with automatic update-checks via cron though. Sometimes they work, sometimes they work only partially. This results in an error-report being sent sometimes via email, which is quite annoying since I only want this for security updates.

Does anyone know how to solve this? We do have a root-server, however I'm not the admin and other non-drupal sites run on it too, so I can't just play around with server-settings, I would have to request changes (I can see phpInfo() though, if that helps).

The weird thing is that updates do work manually, and at least partially when checked via cron (I also disabled any external cron-job, so it's only triggered via poor-man's-cron). Could it be a Drupal core problem after all, maybe related to this: https://drupal.org/node/965078?

-- Drupal 7.27, all modules up-to-date

This is most likely caused by an old issue, a time-out of 5 seconds which is easily exceeded when checking for updates via poor-man's cron on sites with more than a few modules. See this issue.

Easiest solution is probably to use real cron jobs if possible to avoid this altogether, although there are other suggestions on the linked site. Drupal 7.28 finally increased the limit to 30 seconds, in many cases this might suffice. However it may lead to a page load slow-down, so imho it's better to avoid poor man's cron.


Remove required field in validation form If I have a multiple field (ajax) required: FIELD_A (N), and I want it not required if: FIELD_B has a certain value. How can I do ? Any function in $ form_state?

Use states to style the input as required. This won't actually perform any validation but will add the required asterisk to the field when field B has a certain value.

$form['FIELD_A']['#states'] = [
  'required' => array(
    ':input[name="FIELD_B"]' => array('value' => 'foo'),
  ),
];

Then use custom validation to actually check FIELD_A has the correct value depending on the value of FIELD_B.


How do you update a Live drupal server without overwriting the contents? I have a site that is live and people are actively putting in content.  However, I have had to make some changes in the development environment, which has taken me a couple of weeks to do. The changes required new modules to be installed and old ones to be removed, which of course changed the database contents and structure.

My question is how do I upload this site back to the live environment and update the database without overwriting the new content new users that have been added over the last two weeks?

Thomas Zahreddin is right. But depending on what has changed ("has taken me a couple of weeks ... "), there are more things to consider.

Did you add/change content types. Try to export and import them. Make sure you are not losing contents.
Did you add/change views? You can safely export and import them.
Module Updates. Test them on current data. There's always a chance that user data breaks an update.
Module configuration changes. If it's not too much, take notes and redo them. Else try the features and strong arm modules. Another option is to figure out the exact variable names and write the values into the settings.php.
You have additional content in the dev system. Here things get really hairy. You can try the deployment module or node export. But they are no silver bullets.

If you don't have trivial case, I sugest to test your procedure beforehand. And of course take backups of files and data before you start on the live system. (Backup and Migrate comes in handy here.)


How do I select the most recently created entity item in Rules I have in Drupal Commerce products the price of which needs to calculated based on a value that is updated daily. (For the curious: the prices that are stored are worked into a formula that includes current copper sell prices and a copper price to total price ratio). I have used the Entity Construction Kit to create a small entity type to store copper prices - basically just date and price.

I'm having trouble selecting the most recently added copper price entity though.
Right now I'm looking at action "Fetch entity by property" (out of Entity Rules) and selecting by the current date. This would mean though that each day the customer would need to think to add a new price for tomorrow - which would definitely cause trouble.
Is there a module that offers to sort a list and select the last/first item in Rules?

If one 'price entity' is created based on the daily prices per day, you could use the 'after saving new content' action, restricted to your price entity type (provided you entity can be seen as a node.)  Then, calculate the values for your products at that time, using the values within the newly created price entity.

Otherwise, you could put a 'last entry' field on you entity and use another rule to set this field to 'true' on a newly created entity and 'false' on all other entities.  Then, set a condition on the original rule that filters entities based on this field.


How can trusted host patterns be set dynamically? I'm working on a site which uses the Groups module that will allow users to create groups on the site. The site will then allow for users to point custom domain names at the site, with the content for their group being available at that domain.

I've got this set up, except for the trusted host patterns. At the moment I have to manually add the domains to $settings['trusted_host_patterns'] in settings.php. I do not want to have to handle this manually however and would like to set these trusted host patterns dynamically based on domain names stored in a field in the database.

I've been looking at DrupalKernel::initializeSettings(), and I've found that it does not appear any method exists to override the settings:

// Initialize our list of trusted HTTP Host headers to protect against
// header attacks.
$host_patterns = Settings::get('trusted_host_patterns', []);
if (PHP_SAPI !== 'cli' && !empty($host_patterns)) {
  if (static::setupTrustedHosts($request, $host_patterns) === FALSE) {
    throw new BadRequestHttpException('The provided host name is not valid for this server.');
  }
}

So I'm thinking maybe I could use a kernel event, adding trusted host patterns to the settings before the trusted host patterns are called, but I'm starting to think I may be out of luck, due to trusted hosts being set before the database connection is initialized, meaning I won't be able to set trusted host patterns from DB variables.

Does anyone have an ideas of how to get around this?

By design you can't access the database from a non trusted host within Drupal. The kernel checks the trusted host patterns when the settings are read from file, but without the settings you don't have the credentials to open the database connection.

There are a lot of ways to work around this. As mentioned in the comment by @NoSssweat you can write the trusted hosts to a file and include the file in settings.php. Or you can access the database from outside of Drupal and invoke this PHP script in settings.php. Or use a wildcard trusted host pattern matching all possible domains and then enhance security by adding a second check against the custom domain names in a kernel event subscriber when the database is available.


get all parent terms of a term using php - Notice: Array to string conversion I have term with tid=9 (sublevel 3). It is nested under 2 other terms. I use following code to get names of its parent terms:

    <?php
//term id of term that you are checking for top parent
$term_tid = '9';
//this will be your top parent term if any was found
$top_parent_terms = array();

$parent_terms = taxonomy_get_parents_all($term_tid);

//top parent term has no parents so find it out by checking if it has parents
foreach($parent_terms as $parent) {
  $parent_parents = taxonomy_get_parents_all($parent->tid);
  if ($parent_parents != false) {
    //this is top parent term
    $top_parent_term[] = $parent;
  }
return $top_parent_term;
}
?>

Problem: As a result I am getting "array" with error: "Notice: Array to string conversion in php_eval() " instead of terms names.
I tried bunch of other solutions but none of them work or I get same error (for example here https://api.drupal.org/comment/59421#comment-59421)

I think this is closer to what you want:

<?php
    //term id of term that you are checking for top parent
    $term_tid = '9';
    $parent_terms = taxonomy_get_parents_all($term_tid);

    //top parent term has no parents so find it out by checking if it has parents
    foreach ($parent_terms as $parent) {
      $parent_parents = taxonomy_get_parents_all($parent->tid);
      if (empty($parent_parents)) {
        //this is top parent term
        return $parent;
      }
    }
?>

Explanation:

You don't need the $top_parent_terms variable. You can return the first $parent you encounter that doesn't have a $parent_parent.
You were also probably having issues because you declare $top_parent_terms, but reference $top_parent_term (missing an 's').
Also, this bit $top_parent_term[] = $parent would produce a result like this:
$top_parent_term = array(0 => $parent) when you probably want $top_parent_term = $parent.
Note that the returned $parent variable will be an object, not an array. taxonomy_get_parents_all returns an array of term objects.


Why are these filters producing different results? I'm working on a view, and I'm trying to apply a global filter (based on a field known as School Year). I've set up the contextual filter and I've added the block used to set the filter, but after setup, I receive completely different results - they have very few similarities, and the contextual filter narrows the view down to about 20% of the expected results.

On the other hand, when I do a standard Views filter using School Year (this time, determined locally), it gives all the expected results.

Basically, my confusion stems from this: if I'm trying to use the same data, stored either globally in a block or locally in a standard filter, why does that give me different results? How can I fix that?  What might I be missing?

EDIT: Despite my answer below this seems to only be working on one of my views - but even though I replicated the steps on another view, it provides the same unexpected behavior, so it only applies to half the views I need it to work on.

I actually figured it out - as it turned out, I missed a small but important detail. The original (local) filter included a relationship to a content type within the view, which was providing the correct results. When I went back to edit it, I'd noticed that when I created the contextual filter, I hadn't provided the relationship to the filter. Upon adding the relationship, everything worked out the way I'd intended - getting all the expected results. I still don't know why I was getting that unexpected behavior, though.


How to hide a Fivestar field in a comment when the user didn't vote? The comments on my articles have a Fivestar field called 'Stars', but rating nodes isn't always required (see: How to hide rating field when adding comment to own node?). When the user didn't rate the node on which he/she is reacting, 0 stars (not saved in the database) are now being displayed in his/her comment, but I don't really like that.

How can I hide the stars when the user didn't vote?

Edit: I'm trying to find a workaround with flags. I've created a flag called 'Reaction on own' and a rule that flags a comment when the comment's author equals the author of the commented node. In my case, it's sufficient that the 'Stars' field isn't displayed when a comment is flagged with 'Reaction on own'. This is the code of my custom module:

function hiderating_comment_view($comment) {
  $flag = flag_get_flag('reaction_on_own');
  if ($flag->is_flagged($comment->cid)){
    unset($comment->field_stars);
  }
}

Unfortunately, this isn't working. What's going wrong?

Note: In fact, the edit above isn't entirely true in my case, because 'zero' stars appear when a user reacts on his/her article or when the user has commented before. I've provided an answer for both cases.

You could try an approach like this (untested) but may work

/**
 * Implements hook_comment_view
 */
function hiderating_comment_view($comment) {
  if($flag = flag_get_flag('reaction_on_own')){
    // Debug comment to find field to hide, check dblog / watchdog
    debug($comment);
    if (!$flag->is_flagged($comment->cid)){
      unset($comment->field_stars);
    }
  }
}


Drupal 6 with custom OAuth Server Quick question,
Has anyone made their own OAuth server and then tied drupal logins into it?

My boss is asking me if it's possible to run our own internal OAuth server that we can use for multiple things, mobile app, internal app and our website. but they don't want to use the drupal site for the oauth service.

Everything i've found so far is a module that lets you use OAuth in drupal but it makes drupal the OAuth server instead of having Drupal hit an external oAuth service.

Any help would be appreciated.

Drupal 7 has the oauth2_server module that allows you to run an OAuth2 server. It is well documented and integrates a well known and stable PHP library.
OAuth2 is probably a better option for you than OAuth1 because it has grant types optimized for different usage scenarios (mobile app, web app, etc).

If you're limited to Drupal 6, your only option is the OAuth module (also available for D7), but keep in mind that Drupal 6 is basically a deprecated version so when it comes to contrib support and bug fixes you are pretty much on your own.


View the original price, the discounted price and the discount percentage I am currently working on a newsletter and I want to display the prices of my products there. How to recover the original price, discounted prices and the discount percentage. I wish to put three different value to place my letter and apply a different style.

With this line print render($content['product:commerce_price']);
it displays the three values. But I would separate them.

So what line of code do I type to get the original price, then to get the discounted price and then to get the discount percentage?
here is a product page of my site enter link description here

thank you

If this is Drupal 7, you can use the Commerce Price Savings Formatter.  This extends the price field to show the "list price" and "sale price" and automatically calculates the percentage.

The module page links to a video explaining how to use the module.


dump() not working in Drupal 8 (blank page, debbugging is enabled) I want to use dump() in my .twig template (inside custom theme).

The problem is, when I place {{ dump() }} the page is just blank.

I have had:

Set twig.confing debug: true in services.yml.
Cleared cache.

The moment I remove {{ dump() }} everthing works.

After hours of googling I've found some information about mystery $settings['twig_debug'] = TRUE; here (I don't even have such line in my file, but adding it doesn't change a thing) and $twig = new Twig_Environment($loader, array(... (where to find it even?).

I work on clean & fresh Drupal 8 installation, turing debbuing on (step 1.) does include comments in source code (as it should) but use dump() once and all you see is just an blank page.

I agree with the comment left for the question: It seems you have an out of memory issue. Check the error log for the server.

I had the same problem with dump() and kint() in an implementation of template_preprocess_views_view_field(), while trying to output the content of a row, on a clean and fresh Drupal 8 installation.
I found a workaround for kint(), which seems to temporary fix the memory issue. Add the following settings in the config.default.php file for the Kint module.

/** @var int max array/object levels to go deep, if zero no limits are applied */
$_kintSettings['maxLevels'] = 4;

Take it as a hint: Print a specific variable, not the whole array of variables.


Call a drupal behavior method from inside another behavior How do you call a drupal behavior method from inside another behavior? My example below

(function ($) {
  Drupal.behaviors.exampleOne = {
    attach: function (context, settings) {
      $('.example', context).click(function () {
          $(this).next('ul').toggle('show');
      });
    }

    exampleMethod: function (context) {
      console.log('test');
    }
  };

  // call exampleOne from inside exampleTwo
  Drupal.behaviors.exampleTwo = {
    attach: function (context, settings) {
      $('.example-link', context).click(function () {
          Drupal.behaviors.exampleOne.exampleMethod(context);
      });
    }
  };
})(jQuery);

See how I try to call exampleMethod() that belongs to behavior exampleOne inside behavior exampleTwo? I would think I can call it like that but I keep getting undefined when I call it. Though if I call it like this console.log(Drupal.behaviors.exampleOne.exampleMethod);, I get the function written out.

Working example from https://web.archive.org/web/20150320092121/http://dropbucket.org/node/943:

1. ) Be sure you have included JS files in your Drupal module files.

  $form['#attached']['js'][] = drupal_get_path('module', 'module_A') . '/module_A.js';
  $form['#attached']['js'][] = drupal_get_path('module', 'module_B') . '/module_B.js';

2. ) module_A.js file

(function ($) {
  Drupal.behaviors.module_A = {};
  Drupal.behaviors.module_A.my_function = function(selector) {
    // Your code.
  }
})(jQuery);

3. ) Call the function in module_B.js file
(function ($) {
   Drupal.behaviors.module_B = {};
   Drupal.behaviors.module_B.attach = function(context) {

   // This is the main part here. You have to respect the namespace of module A.
   Drupal.behaviors.module_A.my_function('.my-selector');
  }
})(jQuery);


How to order views by taxonomy term name? for some reason the sort criteria by taxonomy term field do not work properly.

This is the view:

Here you can see the field I order by.
The options of the field is the default. Only one taxonomy term per node.

And this is the result:

As you can see the '2005' node is at the end and not a the start of the view's result.
I have no idea why this happened.
I tryed to delete the node and create a new one, delete the taxonomy term and recreate this but nothing happned.

Can someone help me to understand what is happening? I do not want to add queue module and order the view by queue order..

NEWS

SELECT ... ORDER BY field_data_field_edizione_field_edizione_tid ASC
The view order by tid and not by weight T___T
Now I understand what is the problem.. how can I create a new views sort criteria?

Solved!
I create a relationship beetween the nome and the taxonomy term using the term weight to order the nodes ^^
Now it works!

Thank you Mołot to let me see the SQL query ^^


How to force caching to work for View with filter by date offset? Faced with a strange situation: if a View uses filter "Post date" (or similar) with an offset (eg, "> = -1 month"), this View won't cache.

Example: I create a simple View with Block display.

Field: "Content: Title"
Caching: "Time-based | 1 hour/1 hour"
Block caching: "Cache once for everything (global)"

Of course, global setting "Cache blocks" is on.

If I place this block on a page, it is cached properly.

I want to filter nodes for a certain period of time. I add filter with an offset from the current time: "Content: Post date (>= -1 month)". And this block will no longer be cached! Every time I load a page with this block, there is a new call to the database ("SELECT node.title AS node_title ..."). In addition, the table "cache_views_data" is filling with multiple records like "my_view:block_1:results:1a2s3d4d" and "my_view:block_1:output:m0n9b8v7".

How could I force caching of this block to work?

In Drupal caching system, there's an option to cache pages/blocks for anonymous users only, maybe it's the same thing for Views. Check if it works with a not logged in user.


How can I create a D7 View that groups and aggregates a "Rendered Node" field by date, grouping multiple instances for each grouped date? I'm creating an event calendar and have run into this challenge. Say I have these events:

Concert A:
1/5/2016
1/6/2016
1/8/2016

Concert B:
1/6/2016
1/7/2016
1/8/2016

I want my view to display like this:

1/5/2016
Concert A

1/6/2016
Concert A
Concert B

1/7/2016
Concert B

1/8/2016
Concert A
Concert B

Right now I have a view which only shows the first instance of an event by date, and groups/aggregates distinct instances by date. Using the above data, this is my view now:

1/5/2016
Concert A

1/6/2016
Concert B

I'm currently grouping by a Date field which is set not to display. A second "Rendered Node" field displays the node using a view mode. This is driving me nuts. Anyone pull this off before?

You don't need the aggregation settings to get the result you want. Instead, I think you want the "Grouping field" option under the settings of "format".

Here is the export of a full View that I think yields the results you want:

$view = new view();
$view->name = 'date_group_test';
$view->description = '';
$view->tag = 'default';
$view->base_table = 'node';
$view->human_name = 'date_group_test';
$view->core = 7;
$view->api_version = '3.0';
$view->disabled = FALSE; /* Edit this to true to make a default view disabled initially */

/* Display: Master */
$handler = $view->new_display('default', 'Master', 'default');
$handler->display->display_options['use_more_always'] = FALSE;
$handler->display->display_options['access']['type'] = 'perm';
$handler->display->display_options['cache']['type'] = 'none';
$handler->display->display_options['query']['type'] = 'views_query';
$handler->display->display_options['exposed_form']['type'] = 'basic';
$handler->display->display_options['pager']['type'] = 'full';
$handler->display->display_options['style_plugin'] = 'default';
$handler->display->display_options['style_options']['grouping'] = array(
  0 => array(
    'field' => 'field_date',
    'rendered' => 1,
    'rendered_strip' => 0,
  ),
);
$handler->display->display_options['row_plugin'] = 'fields';
/* Field: Content: Title */
$handler->display->display_options['fields']['title']['id'] = 'title';
$handler->display->display_options['fields']['title']['table'] = 'node';
$handler->display->display_options['fields']['title']['field'] = 'title';
$handler->display->display_options['fields']['title']['label'] = '';
$handler->display->display_options['fields']['title']['alter']['word_boundary'] = FALSE;
$handler->display->display_options['fields']['title']['alter']['ellipsis'] = FALSE;
/* Field: Content: date */
$handler->display->display_options['fields']['field_date']['id'] = 'field_date';
$handler->display->display_options['fields']['field_date']['table'] = 'field_data_field_date';
$handler->display->display_options['fields']['field_date']['field'] = 'field_date';
$handler->display->display_options['fields']['field_date']['settings'] = array(
  'format_type' => 'long',
  'fromto' => 'both',
  'multiple_number' => '',
  'multiple_from' => '',
  'multiple_to' => '',
  'show_remaining_days' => 0,
);
$handler->display->display_options['fields']['field_date']['group_rows'] = FALSE;
$handler->display->display_options['fields']['field_date']['delta_offset'] = '0';
/* Sort criterion: Content: date (field_date) */
$handler->display->display_options['sorts']['field_date_value']['id'] = 'field_date_value';
$handler->display->display_options['sorts']['field_date_value']['table'] = 'field_data_field_date';
$handler->display->display_options['sorts']['field_date_value']['field'] = 'field_date_value';
/* Filter criterion: Content: Published */
$handler->display->display_options['filters']['status']['id'] = 'status';
$handler->display->display_options['filters']['status']['table'] = 'node';
$handler->display->display_options['filters']['status']['field'] = 'status';
$handler->display->display_options['filters']['status']['value'] = 1;
$handler->display->display_options['filters']['status']['group'] = 1;
$handler->display->display_options['filters']['status']['expose']['operator'] = FALSE;

And a screenshot of the rendered View:


Using another html.tpl.php for specific page I have googled this alot but none of the suggestions I found works for me.

I want to use another html.tpl.php template for a specific page, preferably matched with the url-string to that page, but the id works aswell.

This is the code I'm trying now (in template.php):

function mytheme_preprocess_html(&$variables) {

    $nid = arg(1);

    if ($nid == '1715') {
        $vars['theme_hook_suggestions'][] = 'html__test';
        echo "testing testing";
    }
}

My custom template file is named: html--test.tpl.php.

The echo part does print on the page so the $nid is correct.

mytheme is not the actual name of my theme, but I replaced it here.

Note, there's already template suggestions for html.tpl.php generated by template_preprocess_html (see last lines in the function there)

For a specific node page, you can use html--node--1715.tpl.php where 1715 is the target node id.


custom number field input on yaml forms I need to ask the user for an 8-digit number within a yaml form.

the number I need is 12345678 and goes is this layout: 1.234.567-8

is it possible to ask the user for this 8-digit number field and display it as 1.234.567-8 ?

ideally the field would be rendered to the user as: _ . _ _ _ . _ _ _ - _ while it's being filled.

thanks in advance

The YAML Form module supports inputmasks which can be configured to handle any desired input format. The submitted value will match your input mask. If you need to submitted value to be converted to a number, you will have to write an update hook to do the conversion.


Drupal Commerce: Print order? Is there any module that would give option to print order in commerce?

Im trying to create option to print orders for packaging department but can't find a way that would allow customer details and order line items.

Through Rules module you can achieve this:

First step create a custom rule at /admin/config/workflow/rules/reaction/add
Select the React on event: "Completing the checkout process"
Add a new Action: "Send mail"
Once you add the email addresses from/to, than add the replacement fields in the body text of the email. I suggest: [commerce-order:order-number], [commerce-order:type], [commerce-order:commerce-line-items]. But you can figure that part out.

Save your Rule.

Get a Beer and celebrate you are now forwarding new orders to your customer fulfillment department.


Views Dropdown List of valid items I'm looking to add an exposed filter that only contains existing user inputed value.

For example.  I've create a content type called 'Items'.  Inside that content type there is a field called 'Team name'.  The user can freely enter the Team name and add multiple items associated with that Team.

When the user is viewing items, I'd like for them to be able to filter based on that Team Name, but rather than force them to type in the name, I'd like for the exposed filter to contain a list of Team Names that have been added into the nodes.

How to make an exposed filter that only contains existing database values?

It really sounds like the team name is a tag based on a Taxonomy Term. You could make a taxonomy called Teams and add a term_reference to your node type. Views can then make an exposed filter based on the term reference.

Using the autocomplete widget for the field will auto create non-existing team names. For more UI flexibility see Autocoplete Deluxe.


setting checkbox Checked in user_registration_form Array
(
[account]
   [notify] => Array
                (
                    [#type] => checkbox
                    [#title] => Notify user of new account
                    [#access] => 1
                )

)

I want to checkbox on user_registration_form must be checked by default.
I did $form['account']['notify']['#default_value'] = array(1); but it does't work.Suggest something.

Please Try this

$form['account']['notify']['#default_value'] = TRUE;

Thank You.


How to subtract two columns with db_select()? I have a db_select query that outputs two columns.  I want to find the difference between these columns, output to another column, and then put a condition on this third column.

Here is a mysql query that I want to convert into db-select:

"SELECT *, `column1value`-`column2value` AS `difference` FROM `mytable` WHERE `difference` > 55"

You're looking for MySQL's HAVING, which permits SELECT level aliases.

So this:

SELECT *, `column1value`-`column2value` AS `difference`
FROM `mytable`
WHERE `difference` > 55

Becomes this:

SELECT *, `column1value`-`column2value` AS `difference`
FROM `mytable`
HAVING `difference` > 55

Which in Drupal-ese is:

$query = db_select('mytable')
  ->fields('mytable')
  ->having('difference > :floor', array(':floor' => 55));

$query->addExpression('column1value - column2value', 'difference');

For a simple calculation like this example performance would be better using the expression directly in a WHERE clause. In the example you've given in your answer, I suspect HAVING would be quicker (although MySQL's pretty smart, it may be able to cache that calculation)


How to redirect page to specific url? How to redirect page to specific url suppose blog-landing page to blog-landing/all page

How to target specific page /blog-landing page when user enters url into browser user should redirect to blog-landing/all

What i have tried :

 function bootstrap_preprocess_page(&$variables) {

 $request = \Drupal::request();
 $current_path = $request->getPathInfo();
 $path_args = explode('/', $current_path);
 $first_argument = $path_args[1];
  if($first_argument =="blog-landing")
  {
    $response = new Symfony\Component\HttpFoundation\RedirectResponse('/node/12/edit');
 $response->send();
return;

}

else
{

 echo "sorry not redirected";
 }
}
}

Use a default parameter (for example blog_id) in your routing.yml file:

mymodule.route_name:
  path: '/blog-landing/{blog_id}'
  defaults:
    _title: 'Show blogs.'
    _controller: '\Drupal\mymodule\Controller\BlogController::viewAction'
    blog_id: 'all'

If the blog_id parameter is omitted the default value ('all') is used.

After your edit:

If you are redirecting via the RedirectResponse() class you should call the send() method in order to redirect.


Adding a webform in a webform confirmation I've been given a requirement to allow for a webform to be inserted into another webform's confirmation page.

At first I tried this with a token I could insert into the confirmation message, the form appears fine, but of course, the new webform is inside of the "parent" webform, which strips out the form tag.

So now I have overriden a few of the webform and webform submission entities handlers, so I can write my own custom getCustomForm function, I can get the new form appearing, but the submit behaviours are weird.

I've tried many things including:

return Webform::load(
    $webform->getThirdPartySetting('my_module', 'webform')
)->getSubmissionForm();

and

$form['confirmation'] = [
    '#type' => 'webform',
    '#webform' => $webform->getThirdPartySetting('wwf_fields', 'webform'),
    '#source_entity' => $webform,
    '#message' => [
        '#type' => 'inline_template',
        '#template' => $webform->getSetting('confirmation_message')
    ]
];

Is there some combination of code I'm missing, or am I trying to bend the system a little too much?

Thanks!

Could you not just redirect after a submission so it goes to a node page that has the other form on it? Rather than trying to put the webform into the message? As that message content could be in a drupal message rather than page content


Custom Twig Template for Custom Content Type In my custom modules I am creating a custom content type. I also need to apply a twig template for this custom content type, but I can't seem to get it to actually apply.

in myModule.module file I have:

function myModule_theme($existing, $type, $theme, $path) {

return [
    'faculty_bio_node' => [
      'variables' => [],
    ]
  ];
}

and I have a custom twig template named :   faculty_bio-node.html.twig

The content types machine name is faculty_bio

If you want to load the template from the module folder you are in the right hook, but you need to use the correct base hook. This means you have to start the template name with the base hook and a double underscore node__ and declare the base hook in theme_hook(), see Store template in module.

hook_theme():

function myModule_theme($existing, $type, $theme, $path) {

return [
    'node__faculty_bio' => [
      'base hook' => 'node',
    ]
  ];
}

The Twig template path and name would then be mymodule/templates/node--faculty-bio.html.twig.


Trying to create a custom block Hi I am trying to create a custom block but it is not appearing in the block listing is there something missing in my code.

   <?php

  $view = views_get_view('schedule_list2');
  $view->execute();
  print $view->render();

  $view = views_get_view('next');
  $view->execute();
  print $view->render();
/**
 * Implements hook_block_info().
 */
function custom_block_block_info() {
  $blocks = array();
  $blocks['my_block'] = array(
    'info' => t('My Custom Block'),
  );

  return $blocks;
}
/**
 * Implements hook_block_configure().
 */
function custom_block_block_configure($delta='') {
  $form = array();

  switch($delta) {
    case 'my_block' :
      // Text field form element
      $form['text_body'] = array(
        '#type' => 'text_format',
        '#title' => t('Enter your text here in WYSIWYG format'),
        '#default_value' => variable_get('text_variable', ''),
      );

      // File selection form element
      $form['file'] = array(
        '#name' => 'block_image',
        '#type' => 'managed_file',
        '#title' => t('Choose an Image File'),
        '#description' => t('Select an Image for the custom block.  Only *.gif, *.png, *.jpg, and *.jpeg images allowed.'),
        '#default_value' => variable_get('block_image_fid', ''),
        '#upload_location' => 'public://block_image/',
        '#upload_validators' => array(
          'file_validate_extensions' => array('gif png jpg jpeg'),
        ),
      );
      break;
  }
  return $form;
}

/**
 * Implements hook_block_save().
 */
function custom_block_block_save($delta = '', $edit = array()) {
  switch($delta) {
    case 'my_block' :
      // Saving the WYSIWYG text
      variable_set('text_variable', $edit['text_body']['value']);

      // Saving the file, setting it to a permanent state, setting a FID variable
      $file = file_load($edit['file']);
      $file->status = FILE_STATUS_PERMANENT;
      file_save($file);
      $block = block_load('custom_block', $delta);
      file_usage_add($file, 'custom_block', 'block', $block->bid);
      variable_set('block_image_fid', $file->fid);
      break;
  }
}
?>
<?php
/**
 * Implements hook_block_view().
 */
function custom_block_block_view($delta='') {
  $block = array();
  switch($delta) {
  case 'my_block' :
    $block['content'] = my_three_upcoming_events();
    break;
  }
  return $block;
}
/**
 * Custom function to assemble renderable array for block content.
 * Returns a renderable array with the block content.
 * @return
 *   returns a renderable array of block content.
 */
function my_three_upcoming_events() {
  $output = '';
  $now_events = views_get_view_result('schedule_list2');
  $upcoming_events = views_get_view_result('next');
  $max_events = 3;
  // Make a big list of events now; upcoming events will be on the end of this list.
  $all_events = $now_events + $upcoming_events;

  for ($i=0,$z=$max_events;$i<$z;$i++) {
    $node = node_load($all_events[$i]['nid']);
    $output .= '<div>' . l($node->title, '/node/'.$node->nid) . '</div>';
  }
  return $output;
}
?>

Make sure your module is named custom_block to match the function names you have used for your hooks. If you have to change the name of your module you will need to re-enable it.
Technically you should uninstall the module, then rename and re-enable - unless it isn't properly installed ans you can't uninstall it. This will keep unwanted data out of your database.

You also should not be printing things outside of functions in module files, like the views code at the top is doing.

Printing markup should be done at the theme level in templates, or in appropriate functions in your module (like you are going in your hook_block_view()).


Email validation for user signup form I am creating a website for submissions. I want the users to register only with "abc.def@mycompany.com". I want to avoid e-mail ids such as @gmail, @yahoo, @hotmail etc during registration.

True: email should be @mycompany

False: email with @gmail, @yahoo, @hotmail

What should I do to achieve the result?

Thanks in advance

Can be managed by strpos easily. Below code will be in validateForm function

 $email = 'abc.def@mycompany.com';
 if (valid_email_address($email)) {
  if (strpos($email, '@mycompany.com') !== FALSE) {
       // Set form error message
   }
 }


How to access phone contacts from PhoneGap in DrupalGap? I'm really new to DrupalGap and PhoneGap. I have a question, how can we access the phone contacts in DrupalGap? I want to list the mobile numbers and other contact details in the application. Then select some of the contacts and store in the Drupal database.

The steps I followed:

Installed PhoneGap
Created PhoneGap project
Contacts pulgin installed for the project
Copied the DrupalGap to the www folder of the project
Done the necessary settings changes
Created a custom module to access the contacts from PhoneGap in laptop

I found some code snippet to access the contacts in PhoneGap as follows:

function sync_contacts_get_contacts() {

    // specify contact search criteria
    var options = new ContactFindOptions();

    options.filter = "";      // empty search string returns all contacts
    options.multiple = true;  // return multiple results
    filter = ["displayName"]; // return contact.displayName field

    // find contacts
    navigator.contacts.find(filter, onSuccess, onError, options);
}

function onSuccess(contacts) {
    for (var i=0; i<contacts.length; i++) {
        if (contacts[i].displayName) {  // many contacts don't have displayName
            alert(contacts[i].displayName);
        }
    }
};

// onError: Failed to get the contacts
//
function onError(contactError) {
    alert('onError!');
}

How can I access this in DrupalGap module I created and store in Drual database?

SOLUTION:

Later in my research I realized one of my misunderstanding. Contacts, camera etc. are work only in device. That means "navigator.contacts" cannot test in the web browser. we have to build the .apk file and install that in the device and test.

Instead of writing the contacts getting code, we can use the PhoneGap plugin from this location: https://github.com/dbaq/cordova-plugin-contacts-phone-numbers.

Using the custom service I stored the contacts in Drupal database. Link: http://docs.drupalgap.org/7/Services/Create_a_Custom_Service

To create the .apk file we have to follow the URL: http://docs.drupalgap.org/7/Compiling_a_Mobile_Application/Preparing_PhoneGap/Installing_PhoneGap/index

Here's the approach I would take:

1 - Build a custom DrupalGap module.

2 - Implement hook_install() in the module:

/**
 * Implements hook_install().
 */
function my_module_install() {
  sync_contacts_get_contacts();
}

3 - Create a Custom Service Resource Endpoint

4 - In your onSuccess function is where you would send the contacts JSON data up to your Drupal resource.

What (and how) you store the data in Drupal is up to you and your custom Drupal module(s).


Getting WSOD for non-LDAP User with Domain and LDAP modules enabled I am using Domain and LDAP modules on Drupal 7, and upon login as a non-admin non-LDAP user, e.g., "author01", I get a blank screen. Upon viewing source on said blank screen, I can see the HTML for the "Welcome to your new Acquia Drupal website!" page—it is just not rendered in the browser (Safari, Chrome, FF).

When logged in as admin, I can switch to "author01" using the "Switch User" block of the Devel module without issue and the Welcome page appears without issue.

The LDAP module is enabled using "mixed mode authentication," Drupal first and LDAP second; LDAP user are able to login without issue, while Drupal-only users get this blank screen upon login. The Domain module is enabled, and but I haven't added any new domains.

I suspect this issue first started after I installed the domain module and "Rebuilt Permissions." Mixed mode authentication was working fine before that.

I've tried various combinations of enabling/disabling and installing/uninstalling the LDAP and Domain modules, clearing cache, rebuilding permissions, and the only time the "author01" user can login is when LDAP authentication is disabled. I've tried enabling error reporting based on Drupal's WSOD page, but the blank pages continue to appear. Apache access and error logs are fine.

Under reports (admin/reports/dblog), I see these log messages (read it bottom up):

ldap_authentication 04/22/2011 - 11:01  Error: users found with uid=author01 under dc=gwu...
ldap_authentication 04/22/2011 - 11:01  author01 : Success at connecting to devldap
ldap_authentication 04/22/2011 - 11:01  author01 : Trying server devldap where bind_method = 1
ldap_authentication 04/22/2011 - 11:01  author01 : Exisitng Drupal User Account not found. ...
ldap_authentication 04/22/2011 - 11:01  author01 : Drupal User Account found. Continuing on...
ldap_authentication 04/22/2011 - 11:01  author01 : user_load_by_name(author01)

The user "author01" definitely exists in the "user" table, has a role ("Content Author"), and the role has permissions.

So I guess I am stumped here, Do you have any idea on what else I can try to troubleshoot and fix this?

Of course, shortly after I post this, I am able to fix it by deleting and recreating the entry for the ldap server. Hope this helps someone else save lots of time (-:


fbconnect module invite issue This is a test site where i have installed fbconnect module I am facing issues while Inviting Friends:

What i am doing:
1. Connect to site through Fbconnect (by clicking on Login with Fb button)
2. Click on Invite Friends link which goes to fbconnect/invite/friends
3. Select Friends i want to invite.
4. Click "Send FB APP NAME Invitation"

Now, the Invited person gets a notification

Naushad Shaikh
Invited you to FB APP NAME. Try Now

URL Points to : http://www.facebook.com/games#

However nothing happens and the invitation does not succeed as it should.

Please let me know what should i do / what am i doing wrong.

This issue has been resolved.

After a lot of research, i came to know that the Facebook Application for FbConnect did not have a Canvas URL and Secure Canvas URL

So i did below:

Added Canvas URL to the Application as domain.com
Added Secure Canvas URL as Fb's changed policy required so added https://www.domain.com
Now, i could click the Application and it opened In Fb IFRAME,
I wanted it to redirect on the website, (NOT ALLOWED AS PER FB TERMS & COS)
Solution an Image Pointing to External link (www.domain.com)

Thanks for the viewers of this question. I got a Tumbleweed badge for this question.


Get domain from a URL field I have a link field in a content type, field_source. I created a computed field (field_source_domain) in the same content type, which should contain the domain for the link in field_source.

I tried with $value = parse_url('https://subdomain.example.com/foo/bar', PHP_URL_HOST); and it works, but when I tried $value = parse_url('$entity->field_source->value', PHP_URL_HOST); or $value = parse_url('$fields['field_source']', PHP_URL_HOST);, I didn't get anything.

How do I get the domain name using a computed field?

I found the solution to my problem:

$field_source = $entity->get('field_source')->getValue();
$url_link = $field_source[0]['uri'];
$parse = parse_url($url_link);
$value = $parse['host'];


Can I have a webform in sidebar block reload current page I have a webform in my sidebar as a block. If I set Redirection location to No redirect (reload current page), it loads the form url in the main content. I can understand why it's doing this, but I would like it to reload the current page instead (or submit the form with AJAX but that's not necessary). Is there any simple way of achieving this?

This is an old question, but it comes up high in search results, so I thought I'd provide an answer.

The behavior you've described is the intended behavior. The module maintainer states that the original implementation of the No Redirect option was designed "under the assumption that if you were starting a form you'd enter minimal information (such as an e-mail address) to start the form, then you'd want the rest of the form on a larger page."

To achieve your desired behavior (i.e., reload whatever page the block form is submitted from), you need to take one extra step: From the block configuration page, check the box for Show all webform pages in block and save the configuration.


Disable email to admin on new user registration When a new user registers, an email is sent to the admins. I can't work out how to turn this off. There doesn't seem anywhere where I can alter it.
In Home » Administration » Configuration » People » Account settings

Who can register accounts? "Visitors" is checked (not "Visitors, but administrator approval is required")

There are a module for control this emails sendings:
MailControl


Unable to debug $items variable in hook_menu_alter(&$items) I want to print out $items variable (the argument of hook_menu_alter) for debugging the menu properties in various pages.

I tried:

/**
 * Implement hook_menu_alter()
 */
function mymodule_menu_alter(&$items) {
  debug($items);
  kpr($items);
}

cache cleared.

but $items are not printed out on the page. Any ideas?

It is not working because hook_menu() and hook_menu_alter() are invoked when the menu list is rebuild. This generally happens when a module is installed, or uninstalled, but modules can force the menu to be rebuild setting a Drupal variable, as with the following code:

variable_set('menu_rebuild_needed', TRUE);

When hook_menu_alter() is invoked, Drupal could also not serving a page that is visible on the browser. The function that rebuilds the menu, menu_get_tem(), is called by menu_execute_active_handler(), which is called every time Drupal bootstrap, even when an AJAX callback is invoked. In that case, the output of the debug function is not visible (nor would JavaScript get it).

In such cases, I think it is preferable to write the output to the database using watchdog(). The output is not immediately visible, but will be logged even when an AJAX callback is invoked.


Panopoly with no views I've just installed Panopoly 1.14 and I can't add views to my panels.

I create the view block normally without any problem; I can see the view, inside the block section, but when I try to create or edit the panel, I can't see views at all in the left side of the add-content screen where it should be.

I checked the permissions and I have all the administrative ones. What am I missing?

Go to admin/structure/panels/settings and check Make all views available as panes.


Can you set an image that is part of a custom content type as the background image in a view? Hoping someone can help me.  I have a custom content type that contains a bunch of fields with one of them being an image field.  I'd like to have the view display the image field as the background and the rest of the fields to overlay that image as text.

Can anyone make any recommendations on the best approach here?

Any guidance would be appreciated.

Set all of your field to hidden, then add a Global: Custom text field (not hidden). In that field you add all of your fields back via the replacement patterns, making sure to wrap them in divs (or appropriate tags) with appropriate classes, and that your image is contained in the outer div. something like this:

  [image]

[title]

Then apply CSS to get the overlay effect to your liking. Text Blocks Over Image


Removing edit menu link How can I remove the "edit" link on this page on the manage menu page (Structure > Menus > My menu > List links)?

hook_form_alter() can take care of this by setting #access element on menu item operation links.

function MYMODULE_form_menu_overview_form_alter(&$form, $form_state, $form_id) {
  foreach($form as $key => $value) {
    if(strpos($key, 'mlid:') !== FALSE) {
      $form[$key]['operations']['edit']['#access'] = FALSE;
    }
  }
}


Why does PhpSpreadsheet fail to identify my Xlsx file in public://? I'm working on a module that imports a Xlsx file and inserts the rows to database. Everything works fine, except PhpSpreadsheet throws the error Unable to identify a reader for this file when my uploaded file is in public. This error doesn't happen when the file is in base_path(). Why is this happening? Below is my code:

public function submitForm(array &$form, FormStateInterface $form_state) {
    $connection = \Drupal::database();
    $fid = $form_state->getValue("xlsx_upload");
    $input = File::load(reset($fid));
    $input->setPermanent();
    $uri = \Drupal::service('file_system')->realpath($input->getFileUri());
    //$uri = '/home/joe/file.xslx'; <--- this works perfectly.
    $reader = \PhpOffice\PhpSpreadsheet\IOFactory::createReaderForFile($uri);
    $spreadsheet = $reader->load($filename);
    $dataArray = $spreadsheet->getActiveSheet()->toArray();
    $connection->truncate("mitacan")->execute();
    $connection->query("SET NAMES utf8");
    foreach ($dataArray as $dataItem) {
      $connection->insert('mitacan')
      ->fields([
        'stokkodu'      => $dataItem[0],
        'logo'          => $dataItem[1],
        'resim1'        => $dataItem[2],
        'grupkodu'      => $dataItem[3],
        'grupadi'       => $dataItem[4],
        'grupindex'     => $dataItem[5],
        'paketadedi'    => $dataItem[6],
      ])
      ->execute();
    }
    drupal_set_message('Excel verisi veritabanına eklendi.');
  }

EDIT: The above code throws "PHP message: Uncaught PHP Exception InvalidArgumentException: "File "" does not exist ." at File.php line 137", even though line 137 throws an exception saying it's not a file, but \dpm(is_file($uri)) returns TRUE.

Looks like PhpSpreadsheet can't read URIs, but only file paths.
You need to find the path to the file on the system.

$real_path_to_file = \Drupal::service('file_system')->realpath($file->getFileUri());

(Ideally you'd inject file_system and not call this service statically.)


How to get different languages of the site to appear in that language's Google search results I would like,when a user searches english terms the english version of the site to appear in google search results.
When a user searches the same terms but in a different language e.g. german ,the german version of my site to appear in google search results.
How can I do this?Which modules can I use?thanks

The i18n module, which can be used for various localization tasks, includes a redirect submodule specifically for SEO.  If you read the i18n documentation and set up your site carefully, you can create a site in which the English versions show up in English Google search, and the German version in German Google search.

One way to speed this process up is to use the XML Sitemap module and create a sitemap for each language; this will help Google learn which pages of your site belong to which language (although Google certainly doesn't need this, and can determine it automatically; it will just take longer to index your site).


adding jquery at the very bottom I know how to add or attache a jquery/javascript file on the specific page.

My problem is that I'm trying to add jQuery file (included in theme) at the end of every thing in the body tag so any other file or module would not override it but can't figure out yet.

Is there any way to do that?

Example:

You need to set a dependancy on your library definition. e.g. if you want your custom.js after geofield then in the library you define custom.js you need to set a dependancy e.g.:

mylibrary:
version: VERSION
js:
  js/custom.js: {weight: 0}
dependencies:
  - geofield_gmap/geofield_gmap


how to log downloaded files I have a content type with a (private) file field. Content is protected by a node access module.

I would like to log (in a particular way) when a user is about to download a file.

hook_file_download looks like it will do the trick, but on the other hand, its stated purpose is to "control access". I'm letting Drupal Core control access; I just want to log a (successful) download.

Is there a better hook to do this with?

hook_file_download() is invoked in two occasions:

When Drupal is verifying the users have access to the file they are trying to download

function file_download_access($uri) {
  return count(file_download_headers($uri)) > 0;
}

When Drupal is returning the headers for the file to download (and then the data for the file to download)

function file_download() {
  // Merge remainder of arguments from GET['q'], into relative file path.
  $args = func_get_args();
  $scheme = array_shift($args);
  $target = implode('/', $args);
  $uri = $scheme . '://' . $target;
  if (file_stream_wrapper_valid_scheme($scheme) && file_exists($uri)) {
    $headers = file_download_headers($uri);
    if (count($headers)) {
      file_transfer($uri, $headers);
    }
    drupal_access_denied();
  }
  else {
    drupal_not_found();
  }
  drupal_exit();
}

In both the cases, the function invoking the hook is file_download_headers().

function file_download_headers($uri) {
  // Let other modules provide headers and control access to the file.
  // module_invoke_all() uses array_merge_recursive() which merges header
  // values into a new array. To avoid that and allow modules to override
  // headers instead, use array_merge() to merge the returned arrays.
  $headers = array();
  foreach (module_implements('file_download') as $module) {
    $function = $module . '_file_download';
    $result = $function($uri);
    if ($result == -1) {
      // Throw away the headers received so far.
      $headers = array();
      break;
    }
    if (isset($result) && is_array($result)) {
      $headers = array_merge($headers, $result);
    }
  }
  return $headers;
}

Watching the Drupal code, I cannot assure the hook is always called twice in row, during the same page request; if it were so, you could take the necessary action when the hook is invoked for the second time.

I would rather change the callbacks for $directory_path . '/styles/%image_style' (where $directory_path contains the value returned from file_stream_wrapper_get_instance_by_scheme('public')->getDirectoryPath()), system/files/styles/%image_style, system/files, and system/temporary to verify when a file is going to be downloaded, and log what happening.

This is not going to change in Drupal 8, as it doesn't split hook_file_download() in two hooks.


Render tabs as vertical tree How do I render $tabs used in page.tpl.php, not horizontally, but as a vertical tree so the secondary tabs will be placed under/in the parent?

This is what I got:

Primary tabs

Item 1

Item 2

Secondary tabs

Child item 1

Child item 2

This is how I want it to be:

Primary tabs

Item 1

        Item 2

Secondary tabs

Child item 1

Child item 2

How do I achieve this without using javascript? I'm currently using render($tabs); to get something similar to the output above.

Basically after examining the code example from the example module, I've found that the vertical_tabs are the container of the different fieldsets, and the title of the fieldset is the vertical tab's title.
All tabs are connected to the vertical_tabs through the  #group attribute. It's that simple...

$form['additional_settings'] = array(
         '#type' => 'vertical_tabs',
         '#weight' => 99,
      );

      $form['vertical_tabs_example2'] = array(
      '#type' => 'fieldset',
      '#title' => t('Example vertical tab2'),
      '#collapsible' => TRUE,
      '#collapsed' => FALSE,
      // The #group value must match the name of the vertical tabs element.
      // In most cases, this is 'additional_settings'.
      '#group' => 'additional_settings',
      // Attach the javascript for vertical tabs.
      '#attached' => array(
        'js' => array(
          'vertical-tabs' => drupal_get_path('module', 'vertical_tabs_example') . '/vertical_tabs_example.js',
        ),
      ),
      '#tree' => TRUE,
      '#weight' => -2,
    );

      $form['vertical_tabs_example'] = array(
      '#type' => 'fieldset',
      '#title' => t('Example vertical tab1'),
      '#collapsible' => TRUE,
      '#collapsed' => FALSE,
      // The #group value must match the name of the vertical tabs element.
      // In most cases, this is 'additional_settings'.
      '#group' => 'additional_settings',
      // Attach the javascript for vertical tabs.
      '#attached' => array(
        'js' => array(
          'vertical-tabs' => drupal_get_path('module', 'vertical_tabs_example') . '/vertical_tabs_example.js',
        ),
      ),
      '#tree' => TRUE,
      '#weight' => -2,
    );


Creating a complex home page layout I was wondering about what might be the best approach to creating a complicated home-page layout along the lines of http://www.time.com/time/

I am attempting to do so. Here is how I'm approaching it:

I'm using views primarily and defining tons of custom regions (I was hoping that there might be a better way)
I have created a custom vocabulary called "Channels". I am using this for NewsFeed, U.S., Politics and so on. Articles are placed into one of these channels
I have modified the "Article" content type and added a field for Channel. Also, I have added checkboxes to mark an article as "Editor's Pick", "Must Read" and "Featured Article". I am then using this as a filter in Views. That was the best way I could think of for categorizing the articles on the numerous boxes on the home page.
Additionally, I'm marking articles with the "headline" tag so that they show up in the "Headlines" box on the upper right corner of the http://www.time.com/time/ home page.
Images are scaled based on where I will be using them. (I'm using Drupal's in built functionality to scale images)

This is how far I've gotten. Since I've just started using Drupal, I was wondering if there might be a better way to do things. Appreciate any inputs.

Views, Panels are your friend.

https://drupal.org/project/panels

You can also go with Omega Context and Delta

https://drupal.org/project/omega

https://drupal.org/project/context

https://drupal.org/project/delta

There are many ways to Rome....


How do I rename Company field and remove Address2 field in a multiple value field in Addressfield module I was able to remove the Address field with hook alter when it's single value field but don't know how to do it when it's a multiple value field. Same with renaming the fields. Thanks.

There's a patch for this in the Addressfield issues queue but it's still under discussion and doesn't work with the latest dev.  You could look at the code in the patch though; it may provide you with insight on how to do what you want.


Image gallery as a field, not a content type? Tutorials I've found seem to only cover creating Image Gallery content types. Any suggestions on how to make an image gallery as a field, rather than as a content type?

Ideally, I'd like to have something similar to the Photoswipe responsive galleries, but with captions, and appearing inside another content type, be it an article, basic page or in this case a new content type.

Perhaps there's simply something I'm missing about embedding one content type within another?

Make a View for your gallery and put that view in a block. Then activate that block for the desired content type; putting that block in the region you want it to appear.


Trying to print results of Apache Solr Search I'm trying to print to Drupal message, the indexed items as an object in Drupal.

Here's what I have so far:

function resource_library_search_apachesolr_process_results(&$results, DrupalSolrQueryInterface $query){
    drupal_get_message(print_r($results, true));

    }

I'm not seeing any results on any of my search pages - am I doing anything wrong? How do I get information on the indexed items as an object?

If you want to print to the drupal messages, you need to use drupal_set_message instead of drupal_get_message first.


Use Optional Arguments in a Panels Path I am porting an existing custom form that takes optional arguments from the URL to preload some fields. I can not use the ?q= method because I must maintain backwards compatibility. For example, both of these URLs are valid:

shop/barn
shop/barn/small/white/red/double/tin

The problem I am running into is how to setup this with Page Manager to accept an optional argument. If I set up my url to be:

shop/barn/%settings

and map %settings to a string, I can get it load the optional arguments! But ... shop/barn does not work. The only way I've figured out to resolve this so far is to create two pages with the exact same panel setup. I would really like to condense this down to one.

I have a feeling the answer lies in something to do with making a custom ctools arguments plugin as the author posted for Panel Pages and Taxonomy Term Arguments. I have tried modifying line 48 in the simplecontext_arg.inc in the ctools_plugin_example module with the following to accomplish this:

if (empty($arg)) {
  $arg[0] = '123';
  return ctools_context_create('simplecontext', $arg);
}

Unfortunately, this displays a blank panel when I visit ctools_plugin_example unlike visiting ctools_plugin_example\123.

This is being implemented on a Drupal Commerce site, so in a perfect world I would also like my panel pages to override the node/%node path with the optional argument so that I can more easily and consistently change the path of my product displays in the future instead of having to manually maintain a bunch of URLs.

I am also open to suggesting something other than Panel Pages, such as overriding the node--barn.tpl.php files.

My final solution was to create a Page Panel with the following path:

shop/%product/!optionalArgs

% indicates a required argument, ! indicates an optional argument

In order to grab all of the "arguments" or URL path after the product (ex: barn), go to Settings » Arguments, select Settings for optionalArgs, and make sure Get all arguments after this one is checked. Click Finish.

In order to use this with a Clean URL, the panel path needs to be some derivative of the Clean URL because panels does not have access to it. For more details, see merlinofchaos's explanation in the following Panels Issue: Panels, Pathauto and Arguments

  Let's say I have a url. It can be any URL, but for this example it's "node/12".

  Let's say I have an alias and it's generated by pathauto, and it's
  something like video/type/12/this-is-the-title-of-the-video and it's
  aliased to "node/12"

  If I visit
  http://example.com/video/type/12/this-is-the-title-of-the-video then
  what Drupal thinks the URL was was, in fact, 'node/12'. Panels never
  has a chance to do anything with video/type/12/foo because that URL
  doesn't really exist.

  The reason, then, that adding some other piece to the URL makes it
  work is that aliases don't accept arguments. They must be exact. So
  the problem, in that case, is the alias itself is actually taking the
  page away from where you want it to go.


views aggregation - number of results per group I have a content type - lets say favorite color - where you can choose blue, green, red ....

One node of favorite color has red
Another node of favorite color has green
Another node of favorite color has again red

and do so on

I would like to show in views3.7 the name of the color and how often it occurs:

red: 10
green: 6
blue: 3

How do I do this? I think its aggregation but I cant display the number of each result...

If what you're trying to show is the number of nodes tagged with a certain term (I'm assuming that color field is a term, not a select text field), then the following Drupalwoo tutorial has detailed step-by-step instructions on creating a view that shows the number of nodes per term.

Here are the basics - just without the screenshots.

Your view should be setup to display taxonomy terms, not nodes.
Add a relationship that is 'Taxonomy term: Content using <term name>', in your case the term name will be something like 'Color'
Configure the relationship to be required or not: depending on whether you want to show colors even if there are no nodes tagged with that color
Select to use aggregation in the view's advanced settings
Add a node field to this view that is excluded from the display, but is used to count the number of node instances under each term.  I would select the 'Node: nid' field for this purpose.  Make sure to use the relationship setup above
Finally - select 'Count DISTINCT' as the type of aggregation for this field
You'll probably want to style the output a little: in your example you want to use a colon between the term and the count, while in the blog's example above there are parentheses!  Feel free to style however!


Openid account validation without password reset I enabled Openid, and installed the OpenID selector module.  When a user logs in via openid, they have to validate their email, and the way to do so is by drupal sending them a one-time login link to reset their password.  Is there any other way to validate the email address?  Sending a password reset link is confusing for users.

If you want your users to be able to setup their own password, check out LoginToboggan. It adds password fields on the front-end user registration page and optionally links non-verified accounts to a "temporary" role on the site, if you want to limit their behavior/actions until they confirm the email.
It also features a lot of other goodies and tweaks, which make the registration/login process much easier.

Another option is Email Verification, which checks if the domain or host of the email address exist, and tries to validate the account by sending HELO/MAIL FROM/RCPT TO to the host's SMTP server.


How do I create slideshows for Youtube videos? Like this website, I want to make a slideshow of you tube videos as done in LATEST VIDEOS section.

In order to achieve this:

I created a view of content type Video (in my case), added the field which has the video in the field's section.
To have the same videos as pager, I added the video field in the pager. But there is no option to resize the video to a smaller size so that it can be used as a pager.
And lastly, videos are also not getting displayed as expected in case of "SLIDESHOW"  formatter, vertical list of videos is getting displayed.

Follow these steps

Install and enable these four modules:[

CTools
 Views
 Views Slideshow
 Libraries

You're also going to need a single file that contains a JQuery slideshow script. This will need to be uploaded manually.

Visit link
Click the Download the Cycle Plugin link. It's hard to spot so i had highlighted it on the image below:

Download the file which will be called jquery.cycle.all.js
Access your site files.
Browse to the /sites/all/ folder.
Create a folder called /libraries/ so that the path is /sites/all/libraries/
Create a folder called /jquery.cycle/ so that the path is /sites/all/libraries//jquery.cycle/
Upload the jquery.cycle.all.js file into that last folder.

Step 2: Views

We're going to create our slideshow using Views.

Go to Structure > Views > Add new view.
Check Create a block
Choose Slideshow for the Display format
Choose 1 for the Items per page

Click Add.
Select video.
Click Apply (All displays).

Check the box which says Exclude from display.
Click Apply (All displays).

Find the Format area on the left-hand side of the Views page.
Click Settings next to Slideshow.

Scroll down to the cycle options.
Click Apply (All displays).


Display any discounts only at cart / checkout stage I am selling furniture, I also sell furniture accessories.

Both of these have their own Product Types.

I use 'Commerce Discount', 'Commerce Discount Extra' and a 'Workflow Rule' to offer a 20% discount on the accessories, but only when an item of furniture exists in the cart.

This rule composes of:

EVENT: Calculating the sell price of a product.
CONDITIONS:

Product Types: Furniture Accessories   AND
Order Contains Products: [a list of SKUs of every furniture item I sell]

ACTIONS: [The name of the discount I set up in 'Commerce Discount'] (which applies the 20% discount on any 'Furniture Accessory' products)

My problem is:

As soon as I add a piece of furniture to my cart, any furniture accessory product display price is discounted across the site.  I'd like the prices to remain at full price when viewing the product display node, but only discounted once viewing the cart or the checkout process is underway.

It feels like their should be another Event, perhaps "Starting the checkout process" or "Viewing the cart"

When product sell prices are calculated via Rules, they are done so in the context of either a temporary line item (for products not in the cart) or the line item on an order (for products in the cart). This means you can check to see if the commerce-line-item:line-item-id is empty or not using something like the "Data value is empty" condition. In your case, you'd want to negate that condition so that if the line item ID is empty, the discount is not applied.


Ask visitor if he want to view page on his language I use Internationalization module on Drupal 7 for multi-language content and my default language is English and I have one more language.

The thing I have to do is:

To check if visitor is from country that primary language is my second language on website (there are four countries that language is spoken), I think that this checking can be done by IP address of visitor.
If visitor is from one of that countries there will be shown modal popup with the question if the visitor wants that page to be shown in his language. If visitor answers affirmative that page will be shown in his language, but if he answers negatively the page will be shown in default language (English).
It is necessary to remember visitor choice so that the modal popup doesn't show up every time, I think that it could be done by saving the cookie in visitor's browser.

Is this possible to be done through some module or the combination of modules or it is necessary to be done programmatically?

Any idea or help where to start is welcome, also the suggestion of some different concept would be nice.

Just some ideas: I remember a WordPress multilanguage plugin setting that I had the option

  Detect the language of the browser and redirect accordingly.

That must work similar for Drupal. So, I'ld guess you would try that browser language approach. D6 even had an own function for this language_from_browser. I bet there must be something in D7 for that as well.

Once you have the language you might conditionally display the modal window from that. Inside the modal then there'ld be a little form, maybe just two submit buttons "Yes language", "No language", something like that.

Inside your form submit function you may find a way to trigger the redirect to the chosen language. Finally you might want to save the user's answer in a $_SESSION variable and bind that as a condition for the modal display also.

Put all of that in a little custom module and let us know how you've done!


Need a simple Google Maps solution; lost in the labyrinth of modules First of all, let me just state that I don't care which version of Drupal I'd have to use (6 or 7). I have experience with both versions I just didn't need to work with Google Maps till now. The requirements are pretty basic (from what I understand):

1) Have a node for every company that I want to add in the map

2) In the node edit form I would like to add an address and have it added in a custom google map (or maybe copy-paste the link of a google map location)

3) Have a search function to find the nearest company for a given location

There are like tons of different modules out there, and I would like to be pointed to the right direction instead of looking through 15+ different modules just to finally realize that I need to write a custom module for myself.

Thanks in advance.

I have created a Drupal feature that implements this using OpenLayers ( See http://drupal.org/project/ol_locator ) or you can use the following walk-through to set up your own.

Download and enable the following Modules:

OpenLayers
OpenLayers Proximity
Chaos tools
Views
Address Field
Geocoder API
Geofield
geoPHP
Libraries

Enable sub-modules:

Geofield Map  7.x-1.0-alpha5
Views UI  7.x-3.0-rc1
OpenLayers UI 7.x-2.0-alpha2
OpenLayers Views  7.x-2.0-alpha2

Go to admin/structure/types/add and create new content type called "Location"
Go to admin/structure/types/manage/location/fields and add the following fields:

Label: Address > Field name: address > Field type: Postal address > Widget: Dynamic address form

Select which available countries you would prefer from the list. Leave blank to allow all of them.
Check off "Address form (country-specific)"

Note: The countries and their associated fields are handled by the Addressfield module. If you do not see your country or if it does not have the appropriate fields you need to file an issue with that module http://drupal.org/project/addressfield (Check to see if there is an issue in the queue about your missing country first before posting)

Label: Geofield > Field name: geofield > Field type: Geofield > Widget: Geocode from another field
Go to admin/structure/types/manage/ol_locator_location/display and change the Default display for Geofield:

Label: Hidden > Format: OpenLayers

Click on gear icon and select the following:

OpenLayers Preset: Geofield Formater Map > Data options: Use full geometry

Go to admin/structure/openlayers/layers/settings and set the following:

Google Maps API version: v3.2

Let's test to see if the Geocoding is working by creating a Test Location

When creating a test content type, make sure you are using a well established address. If Google doesn't know about your address, then neither will your new site.

Go to admin/structure/views/add and create a new view with the following information

View name: Proximity Search > Description: Displays geocoded locations on a dynamic map for users to do proximity searches. > Show: Content of type: Location sorted by: Unsorted > Continue & edit

Add the following fields and keep their default values, except where noted:

Content: Title > Check off Create a label: "Title"
Content: Address (Address)
Content: Geofield (Geofield) > Exclude from display
Proximity: Distance (Distance)

Add the following Filter Criteria to the existing:

Content: Published (Yes) and
Content: Type (= Location)
Proximity: Great-circle (exposed) > Expose this filter to visitors, to allow them to change it > Label: Proximity > add "10" to Value field > Unlock unit of measurement > Unlock location

Header > Global:Text area > Display even if view has no result

"Find a location near you. You can search using your city, province/state or a postal/zip code."

No results behavior > Global: Text area and add the following:

"Sorry, no results found.
1.) Verify the accuracy of your postal/zip code
2.) Check the spelling of your city, province or state
3.) Increase the proximity distance"

Submit button text: Search
Add new display: "OpenLayers Data Overlay"
Format:

Settings >  Apply this openlayers (override) > Map Data Sources: WKT > WKT Field: Geofield > Description Field >  > Apply (this display)

Save the view
Go to admin/structure/openlayers/maps
Clone the default map
General information > Name: location_map . Title: Location Map > Map Description: This is the default location map.
Layer & styles > Overlay layers (select the view we just created) Locations "Enabled" "Activated" Do the same for Placeholder for Geofield Formatter
Behaviours > Pop Up (have to come back and "Select layer to apply popups to." later) > Zoom to Layer "Select layer to zoom to when the map is loaded" > Point Zoom Level : 20 ****
Save the map
Go back to the view we just created

admin/structure/views/view/proximity_search/edit

Add display "Page"

Path: /locator
Format: OpenLayers Map > Apply (this display) > Map: Locations Map (The one we just created in OpenLayers) > Apply

Save the view (We should now see our map in the preview pane at the bottom of our view, with any test content
Add display: "attachment"

Format: Table > Apply (this display)
Attach to: Page
Inherit exposed filters: Yes
Remove the Header > Global: Text area > Apply (this display)
Items to display: Display a specified number of items | 5 items
Inherit pager: Yes
Render pager: Yes

Save View
Behaviours > Pop Up > Layers > proximity_search_openlayers_1 (The views Openlayers map we just created)
Zoom to Layer > Zooms to the extent of a given layer on map loading. > proximity_search_openlayers_1
Return back to admin/structure/types/manage/location/display > click gear icon and change Open Layers Preset to the Location Map that we just created > Update > Save

Voila! Done


is there a module for status updates in drupal 7 I am looking for a module that will allow users on my site to post status updates similar to Facebook and twitter. Or is there a way to configure the heartbeat module to allow users to post status updates? i am using the zen sub-theme in drupal 7.

Somthing along the lines of statuses?  It doesn't have a stable release yet, so is DEFINITELY not ready for production.  I've not used Heartbeat, so I can't help any more than that I'm afraid :(


Find a particular menu item within the primary links Let's say we have a menu inside the primary links, in my case the Misc menu.

As it seems under Misc menu it can be any Content Type (of course and on every other menu)

The question is how can I make it to appear ONLY the Misc menu somewhere in my website without reconstructing it as a separate menu?

I want it to stay in the primary links.

So far I've tried it with the context module, but seems that is not working properly with the sub menus under the Misc menu. It works only for the Misc page.

Even if I do this: menu_set_active_menu_name ('primary-links') it's still working only for the Misc menu, not its childrens.

Creating a block with only the needed menu item and the use of the template_preprocess_block is another approach but not recommended, while I have to refer to the block through the block ID ($bid).

Menu block - it provides configurable blocks of menu trees starting with any level of any menu. So if you’re only using your theme’s Main menu links feature, you can add and configure a “Main menu (levels 2+)” block. That block would appear once you were on one of the Main menu’s pages and would show the menu tree for the 2nd level (and deeper) of your Main menu and would expand as you traversed down the tree. You can also limit the depth of the menu’s tree (e.g. “Main menu (levels 2-3)”) and/or expand all the child sub-menus (e.g. “Main menu (expanded levels 2+)”).


Facet Api and acive filters In my website, I'm using ApcheSolr with facet api and with some configuration I listed facets blocks and it works fine!

But now I want to create a block that list to me the active filter chosen by user

I read some facet api documentation but I'm lost !!

Can anyone help me!

Tanks in advance.

Enable Current Search submodule, you can also install Current Search Links

  Extension to the Facet API current search blocks module. Instead of just showing the current search it turns the current search keywords into links that you can drop from the search.


Why isn't my service found? I'm trying to load a service into my Drupal module, but even after checking twice whether I did something wrong, I can't seem to find any error in my code as I did everything as the documentation said and Drupal still gives me a non-existent service error.

Here's the my services.yml file:

services:
  rb_weather.wunderground:
    class: Drupal\rb_weather\WundergroundWeather

Here's the config form code (the part loading the service):

class RBWeatherSettingsForm extends ConfigFormBase
{
/**
 * @var WeatherInterface
 */
private $wunderground;

public function __construct(ConfigFactoryInterface $config_factory,    WeatherInterface $wunderground)
{
    parent::__construct($config_factory);

    $this->wunderground = $wunderground;
}

public static function create(ContainerInterface $container)
{
    return new static(
        $container->get('config.factory'),
        $container->get('rb_weather.wunderground')
    );
}

I have included the classes using the "use" command as PhpStorm doesn't complain about that, however, Drupal does not want to recognize it.

My service classes as well as the services.yml file are placed under rb_weather/services folder.

Thanks a lot.

Not certain, but it sounds like your files may not be in the correct places based on your description.

The services.yml should be in the root of your module, not in a sub folder.

Also, your service classes should be in a /src/ folder. It would be okay to have them in a /src/services folder if you want, but module namespaces in drupal start in the module's /src/ folder, not in the root; the reason for this is because drupal uses the PSR-4 naming conventions, which specify that structure. You can find more info about how drupal modules should be structured here: https://www.drupal.org/node/2156625


Rules: Steps to trigger a rule when a field is updated I am using the rules module to send an email when a particular CCK field field_test is changed. These are the steps I performed:

Event: After updating existing content
Condition: Field has changed

Under Field I chose field_test.
Under DO I chose the action as email.

My issue is that even if any other field is updated under that content type, it still triggers my rule, under debugging it shows Condition Updated content's field 'field_test' has been changed evaluated to TRUE.

I'd appreciate any help on this.

Thanks.

I figured what my issue was. I had an earlier version of the CCK module (6.x-2.1) and once upgraded to the latest version (6.x-2.9) the rule behaves as expected.

Thanks to jordojuice for pointing me in the right direction.


How to automatically generate anchor ids to CKEditor added headers How can i automatically generate anchor ids to h2 and h3 added using ck editor ?
I need it for making a table of content.

in JS, id set from the h2 label two first words :
const headings = document.querySelectorAll(
  ".article--full h2, .article--full h3"
);
const tocElements = createTocElementsArray(headings);

function createTocElementsArray(headings) {
  const tocElements = [];
  for (const item of headings) {
    if (item.id === "") {
      item.id = item.firstChild.data
        .split(" ")
        .slice(0, 2)
        .join("-");
    }
....
}


How to display view with context filters as a block in sidebar? I'm trying to display a view in a block, the content of which is based on value of one of field of currently displayed node. I found out that I must use Views content panes and Mini panels modules. I created appropriate view in format "content pane" and I'm stuck. I can't find how to proceed any further. I tried to create new mini panel but I don't see how to associate one with another.

Clarification

I choose Panels after quick research because I want to display view in a block, which takes arguments from it's context: field value of current node. Nodes are displayed using standard template and Display Suite.

Clarification 2

What I exactly want to do: take field value from currently displayed node and in a block in sidebar display list of nodes that also have same value in that field.

I got it!

Create views block type display that requires context filters.
Create block with PHP filter content type.
Put into it code:

<?php
  $node = menu_get_object();
  $field = field_get_items('node', $node, 'field_NAME');
  echo views_embed_view('VIEW_NAME', 'block_1', $field[0]['value']);
?>

(this eventually can be moved into custom module to avoid using PHP filter)


Force login through mysql I have a local install of a Drupal 7 site that will only display admin pages over https such as login and admin type pages. I was unable to disable them before downloading the database. In settings.php I have set secure pages to 0. However when i attempt to login the page simply refreshes and the form is displayed again and i am unable to visit any admin pages. Is there a way to login using mysql instead of having to go through Drupal?

EDIT:

finally got drush running correctly and used
    drush cc all
after attempting to sign in i got the error message:
Warning: Cannot modify header information - headers already sent in _drupal_bootstrap_page_cache()
Warning: Cannot modify header information - headers already sent in drupal_send_headers()

the latter is repeated 7 times, the page simply refreshed again.

I ended up creating a temporary sign-in using drush command:
    drush user-login

Sounds like you need to do the following:

Set the securepages_enable to 0 in settings.php
Open a MySQL Client, like HeidiSQL or SQL Pro
Truncate the cache_ tables
Reload local site in browser

This should rebuild the variables and then your runtime value will be respected.

Also, check the .htaccess file to see that you are not being redirected to HTTPS.


Ban users from their IP I need to install a module that permit me (on my site) to ban IP. I have searched on Drupal.org and Google.com, but seems that there is not a good solution. All modules seems abandoned, so I ask here if someone use one of these modules and which one use. I don't want to start a thread about which is the best, only know which one I can use.

The built-in IP blocking (at /admin/config/people/ip-blocking) works just fine, but if you're looking for some slightly more advanced functionality, like blocking ranges of IPs, I've used IP Ranges with a great deal of success:

  IP Ranges is a module that let's you completely ban both single IP-addresses as well as
  full ranges from your site. The ban is triggered already at the early bootstrap phase, so you
  can get rid of unwanted visitors as early as possible without wasting server resources.

  You can also define whitelists that override blacklists, both single and ranged.
  The UI is similar to core ip-ban, so you will feel like home immediately.


Set default radio button on webform I have a standard contact page created using webform, which has a set of radio buttons.

Is it possible to change the pre-selected radio option based on the referring page?

With Webform you can pre-populate form default values via the url with tokens:

Setting Default Values from the URL (7.x-3 and earlier)

The %get[key] supported by Webform allows form values to be populated from the URL.

Setting Default Values from the URL (7.x-4)

To set the default values of a component to use either:

Query Format: For urls formatted like http://example.com/node/120?key=bar use [current-page:query:key] to return key value.,

Args Format: For urls formatted like http://example.com/node/120/key use [current-page:url:args:2] to return key.

Taken verbatim from webform docs


How to pull active user name from drupal 6 Is it possible to pull the active user name or active ldap user from my drupal site, and store this in a separate DB, as i would like to use it because the login limits who can access the site, but I want to know who is submitting x,y,z data into my forms? so at the top of the form maybe a field that pulls their username?

Drupal 6 supports multiple DBMS connections easily in settings.php (to the same type of DBMS, eg 2 Mysql DBs, not 1 MySQL and 1 SQLServer).

You can use a function like hook_user to track who has logged in and feed that username into your 2nd database using the database api and for instance the db_query function. You also likely need db_set_active.

EDIT

I'm not sure exactly what your trying todo. You can always use php's ldap functions to talk to ldap and look for info on the "user" (if they're not logged in yet I have no clue what you'd grad from ldap ...). You could always use hook_form_alter to assign additional submit handlers on any default drupal form to perform custom tasks.

Having used ldap_integration for D6. You should realllly think about moving the site to D7 as the new ldap module is pretty nice and lets you save off ldap queries as re-runnable things :).


Reminder module recommendation I am after a "reminder" module, which will enable the site users to subscribe to nodes/content types in order to receive reminders of closing dates and notifications of when the node has been updated/changed.

Any help would be greatly appreciated.

Checkout this module Subscriptions

  This module enables users to subscribe to be notified of changes to
  nodes or taxonomies, such as new comments in specific forums, or
  additions to some category of blog. Once enabled, all nodes will have
  an additional link that allows the user to change their subscriptions.
  Users have tab on their user screen to manage their own subscriptions.
  Users can also set an auto-subscribe function which notifies the user
  if anyone comments on posts they have made. Admins can turn this on by
  default.


Upgrade Backup and Migrate from 2.x to 3.x Is it possible to upgrade without losing profile settings?
Or is it simply uninstall 2.x, install 3.x and recreate profile settings?

It is possible to do that upgrade without losing any data.


Why would my import of multiple selections work in one content type but not the other? I've got two content types that both have one off CSV file imports. They both have fields where you can select multiple values. The csv is comma delimited and the multiple selection data, for the field in question, is separated from the rest of the data by quotation marks, within the quotation marks there are no spaces between values; each value is instead comma separated.

For one of the content types this works perfectly, multiple values are put into the field. This field is a node reference.

However for the other content type this doesn't work instead if there are multiple values in the csv no values are given to the content, there are no error messages in any logs. This field is a multi check-box/radio input. I've checked and double checked to make sure the are no spelling discrepancies and I've ensured the field is set up correctly. If you manually create a new node of this content type you can allocate multiple values within this field.

Both fields are set to take unlimited values.

Eventually finding no solution to the problem I decided to replicate the multiple field selection import that was working.

I made a new content type which contained nothing but the data items I wanted to be able to select and then used a node reference from the original content type. This isn't the most opportune method as whenever this data is displayed it is displayed as a link, a link which then takes you to a page which has nothing on it apart from the name of the data. However imports correctly put the desired data into the the field.

My suspicions regarding this issue are around how the node reference handles multi-fields. Perhaps handling them in a similar way to the import, as in [datafield1,dataf2,"dataf3,dataf3,dataf3",dataf4](as clarification, the previous example is how the csv is laid out). However I've no idea whether or not this actually has any grounds.


Views RSS post date removal What is the best way to remove the post date from a views created RSS feed? I have a calendar that I have created a feed for, but it is being sorted by a cck date value, making the post date not necessarily accurate.

Is there an easy way to remove this from within views (D6), or would this need to be a template change?

This approach should work. I've tried it in the past and it did exactly what I needed.

Quoted from the above-linked comment:

Put views-view-row-rss.tpl.php in your theme directory

and replace print $item_elements;

with

$item_elements = preg_replace('<pubDate>.*</pubDate>', '', $item_elements);  // removes pubdate
$item_elements = preg_replace('<dc:creator>.*</dc:creator>', '', $item_elements);  // removes author
$item_elements = preg_replace('<category .*</category>', '', $item_elements);  // removes terms

$item_elements = preg_replace("!^\s+(\D)!m", "\\1", $item_elements);  // removes some blank lines

print $item_elements;


The "php" plugin does not exist I got this error after migrating from Drupal 6 to Drupal 8.1.3.

  Drupal\Component\Plugin\Exception\PluginNotFoundException: The "php" plugin does not exist. in Drupal\Core\Plugin\DefaultPluginManager->doGetDefinition() (line 52 of core\lib\Drupal\Component\Plugin\Discovery\DiscoveryTrait.php).

How can I fix this error?

It's a guess, but the php module was removed from core in D8 and is now supplied by a contrib module: PHP

You will need to install it additionally.

Edit 1:

If you don't intend to use the module in the future, enable it only temporarily, find alternatives for the fields/text formates currently using it (if needed, the filter may be available but not actually used for php) then uninstall it again once you are done.