Remove empty url argument from view with exposed filter I have a view with exposed filter "Has taxonomy term" (filter identifier: "topic") and exposed sort: Created (default one) and Rating.
On a view page, when I change sort option to Rating, url of a view page is becoming
?topic=&sort_by=rating

How to remove this empty argument from page url?

I tried

  $('#views-exposed-form-taxonomy-term-page').find(':input[value=""]').attr('disabled', true);

and

  $('#views-exposed-form-taxonomy-term-page').submit(function() {
    $(':input', this).each(function() {
        this.disabled = !($(this).val());
    });
  });

but it didn't work.

solved the problem:

(function ($) {
  Drupal.behaviors.citatyTaxonomy = {
    attach: function(context) {

      // disable blank input fields
      function disableEmptyInput() {
        $('#views-exposed-form-taxonomy-term-page').find(':input[value=""]').attr('disabled', true);
      }

      // on form submit
      $('#views-exposed-form-taxonomy-term-page').find('.views-submit-button input[type=submit]').click(function(){
        disableEmptyInput();
      });

      // view with auto-submit
      $('#views-exposed-form-taxonomy-term-page').find('.ctools-auto-submit-click').click(function(){
        disableEmptyInput();
      });

    }
  };
})(jQuery);


How to update table taxonomy_index when adding a node referencing a term? I have two node types: Lesson and Exercise. A lesson contains several exercises, which are children. Lessons have a category field which is a reference field of type taxonomy term. Exercises point to lessons through a Lesson reference field, which I suppose indirectly maps exercises to terms.

When I create a lesson, I use the following code:

    $node = Node::create([
      // The node entity bundle.
      'type' => 'lesson',
      'langcode' => 'en',
      'created' => $lesson->created,
      'changed' => $lesson->changed,
      'uid' => $lesson->uid,
      'title' => $lesson->title,
      'field_category' => $tid,
      'body' => [
        'summary' => $lesson->summary,
        'value' => $lesson->body,
        'format' => 'full_html',
      ],
    ]);
    $node->save();

Note the field_category field.

The above does not result in the taxonomy_index table being updated. I could update it with an sql query, but I would like to know how to do it via the above core approach.

And for the Exercise node type, I suppose I need to do likewise, unless my linking of an Exercise to a Lesson already accomplishes the hierarchy.

How do I alter the above to result in the taxonomy_index table being updated?

I ended up figuring this out. here is what I did:

$result=db_query("SELECT nid FROM node WHERE type = 'lesson'");
foreach($result as $row){
    $node=entity_load('node', $row->nid);
    $result =  taxonomy_build_node_index($node);
}

This ensures that my lesson node is tracked in the taxonomy_index table. I should probably start learning the class-based approach, but for now this works.


How to get the super user in a functional test? How can I get the information for the super user (uid 1) in a functional test?

I want to test the external auth logic I have written, and one of the steps is authenticating the Drupal superuser locally instead of in the remote system. I am not seeing a way to get the username/password of that user in order to simulate a login.

Test:

  /**
   * The superuser should not authenticate to Netforum.
   */
  public function testSuperUserUsesDrupalAuthentication() {
    $this->drupalGet('user/login');
    $edit = ['name' => $this->rootUser->getEmail(), 'pass' => $this->rootUser->pass_raw];
    $this->drupalPostForm(NULL, $edit, t('Log in'));

    $user = \Drupal::currentUser();
    $this->assertEquals(1, $user->id());
  }

Looking into BrowserTestBase I accidentally found $this->rootUser->name and $this->rootUser->pass_raw last week. These are being used in installParameters(). I have not tested it, but I suppose you should be able to use those in other functions as well.

rootUser appears to be a full AccountInterface object, so getName() and other methods should work as well..


The operators "Is one of etc" not working with exposed filters The "Is one of etc" operators do not seem to reduce the result set on exposed filters. So for example if I have all fruits and select only mango and apple with "is one of" - The result set only shows mangoes and apples if I do not expose the fruit filter. But if I expose the fruit filter, it shows all the fruits.  My view is based on a search index configured with search API.

Is this expected behaviour or am I missing something?

Expose the filter, then select the fruits that you need to show and then enable the "Limit list to selected items" option, so the dropdown list filter will only show the fruits that you want, not all of them.


How to reference a content-region block in node template? Scenario:

I have a basic node content type that has some fields. I also have a custom block that will appear in the content-region of this node content type.

How can I (is it possible) reference the rendering of the block from within the theme node--mycontenttype.tpl.php file?

In Drupal 6, you can do something like this:

$block=module_invoke(MODULE_NAME, 'block', 'view', BLOCK_NAME);

and now $block['content'] will contain the html content of BLOCK_NAME defined within MODULE_NAME.

I just noticed the -- in your template name, so in Drupal 7 it would be:

$block=module_invoke(MODULE_NAME, 'block_view', BLOCK_NAME);

and more details can be found here.


User roles and keeping their IDs when using features I have defined some user roles and I'm assigning them to users through the rules module. I have created a feature with the rules and the roles and moved them to another site. My problem is that the user roles get new IDs and that the IDs are hardcodet in the exportet rules. Therefore the rules assigns wrong roles and I don't want to fix that each time I install the feature.

Can I somehow hardcode the user roles programatically and let the rules module work on them? Is there a better solution for the problem?

It is more or less the same problem for taxonomies that also get assigned new IDs.

The Role Export module causes Role IDs to be hashes of Role Names — so the same Role Name will have the same Role ID on all sites.  Great in conjunction with Features.

For Taxonomies, the UUID Features module may be helpful.


How to Enter Fields in the Order Information form (and confirmation email)? I need to add additional fields in the customer's information form during checkout, such as Telephone number and "How did you hear about us?".  I don't see within the Commerce pull-downs in the Admin panel any way to do that similar to how fields are added in other Drupal forms.  I assume Commerce allows such customization.  Of course that data needs to be added into the database records as well.

In addition, how are those additional fields added to the email that is generated when the order is completed?  While the customer may not need it, other people within the ordering / fulfillment process are designated as getting copies of that email and need that information within the email.

Adding additional fields to the customer

You'll want to add the fields to the customer profile:

/admin/config/people/profiles/manage/customer/fields

Editing the email text

According to the Commerce documentation:

Use the template file located in /commerce/modules/order/templates/commerce-order-receipt.html.twig.


Get path parameter in views-view-fields--portfolio.tpl.php file I am working on project. In project I am using view. print $field->content; parameter print image with link. I want path variable value in variable.

borrowed from here

// field_video_image is the name of the image field

// using field_get_items() you can get the field values (respecting multilingual setup)

 $field_video_image = field_get_items('node', $node, 'field_video_image');

// after you have the values, you can get the image URL (you can use foreach here)

 $image_url = file_create_url($field_video_image[0]['uri']);


How to make get for drupal behaviors to run only once? Drupal.behaviors.js_mod = {
attach: function (context, settings) {
     //$('body', context).append(chart);
    // $( '#drupal-myradar', context ).once
     $.get( "/web/js/mod", function( data ) {
        console.log(data);
      });
}

    }
})(jQuery, Drupal, drupalSettings);

Essentially this code is running multiple times while grabbing information from my controller code. I only want this to print out once to the console when the page is loaded.

If your script is high-level, which is most likely, then only run it when the context is equal to the document.
I found this trick in the autologout module and use it almost everywhere now:
Drupal.behaviors.dosomething = {
  attach: function attach(context, settings) {
    if (context !== document) {
        return;
    }
    // Do stuff here but still use .once when attaching behaviors.
  ...


Number of users currently checking a node I need to build a view "preferably a nodejs_view" that could count the number of logged in users that are currently checking a node.

Lets say we have 10 users currently checking node/123, I need to create a view that shows something like this:

node: 123
viewers: 10

node:124
viewers: 2

Is there any modules that could provide that? any idea how to build such thing?

viewers ,though this module is in drupal 6 but it can give you a good start.


Stop send email attempt when cron is run I just took over a drupal 7 site and when cron is run I get the follow error
SMTP Error: Could not connect to SMTP host
WD mail: Error sending e-mail (from ???????? to ???????)

I know the previous developer turned some feature/function on that will send an email each time a cron job is run.  Does anyone know how or where to turn this off?

I have checked in the admin-> cron, but there are no settings there to adjust.

Thank you in advance.

It's likely defined as a hook_cron implementation in a custom module. Trying searching through your codebase for "_cron" to see what you can find. If you install Elysia Cron you should be able to get a full list of all cron jobs and could disable any jobs you don't way run.


How to make a popup on a node's content using the colorbox module? In Drupal 7, all I had to do to add a popup with colorbox was add the CSS class colorbox to the link to create a nice popup.  Now, using Drupal 8, I cannot figure out how to do this.

I can add colorbox to my fields, but I want to add it directly to the link <a class="colorbox" href"".../a> in the content body, but it is not working.  I cannot figure out how to use inline colorbox either, if that is the solution.

How can I add the popup?

For creating pop-up's in colorbox, you can simply use Bootstrap Modal Window.

Don't forget to include the below ones:
1. bootstrap.min.css
2. jquery.min.js
3. bootstrap.min.js

FULL WORKING CODE:

<!DOCTYPE html>

  <title>Bootstrap Example</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

Small Modal

  <button type="button" class="btn btn-info btn-lg" data-toggle="modal" data-target="#myModal">Open Small Modal</button>

          <button type="button" class="close" data-dismiss="modal">&times;</button>

Modal Header

This is a small modal.

          <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>


How to import content for content types with user-defined fields I've got a large amount of data I would like to turn into pages in Drupal. Most of the data to import correspond to custom fields I created in a new content type (let's call it directory).

For example, I have things like zip code, address, state, etc. that I would like to import as directory content.

I've been working with the feeds module, but so far I haven't been able to figure out if it can map to custom fields in a content type (I'm beginning to suspect that it cannot).

I'm using Drupal 7

I suggest you look into migrate module. This module is very flexible, very well documented and can  easily handle  and ease the pains of content migration.  Custom content, users, comments, etc .. and just about whatever you throw at it can be set up as 'migration tasks'.

Good-luck!


Google Analytics report on the website Is there a way of making the google analytics available for previewing on the drupal 7 site?

Try Google Analytics Reports module.

  Graphical reports include a dashboard widget for admins, a small
  path-based report in blocks, and a full path-based report.

  Prerequisites are the Google Charts API module and the OAth
  module. Do not forget to set the module’s permissions about who has
  access to the reports.


HTML tags after umlauts causing premature header sending - CK editor I'm maintaining some old Drupal 7 site (not created by me) and since couple of months ago it started acting strange (I didn't make any change on site):
Inside some content type there is a formatted text field that is edited with CKEditor.
If field contains just a plain text and I try to save it (when editing the node) it works well.
If I make some text bold at beginning of the whole text and try to save it works well also.
But if I try to make some text bold after first umlaut character (site contains German text) and try to save I get 403 error - forbidden?!?
In drupal's error log I see the error:

Warning: Cannot modify header information - headers already sent by (output started at /home/www/project_name/includes/common.inc:2776) in drupal_goto() (line 705 of /home/www/project_name/includes/common.inc).

I even suspected that site has been hacked but I don't see any suspicious new files there.
Any idea?
/**
 * Performs end-of-request tasks.
 *
 * This function sets the page cache if appropriate, and allows modules to
 * react to the closing of the page by calling hook_exit().
 */
function drupal_page_footer() {
  global $user;

  module_invoke_all('exit');

  // Commit the user session, if needed.
  drupal_session_commit();

  if (variable_get('cache', 0) && ($cache = drupal_page_set_cache())) {
    drupal_serve_page_from_cache($cache);
  }
  else {
    ob_flush();
  }

  _registry_check_code(REGISTRY_WRITE_LOOKUP_CACHE);
  drupal_cache_system_paths();
  module_implements_write_cache();
  drupal_file_scan_write_cache();
  system_run_automated_cron();
}

That 2776 row is ob_flush() call. 705 is header() function call inside drupal_goto() function.

Issue solved by server admin. It was about ModSecurity Apache2 settings. POSTs were rejected because they triggered new ModSecurity XSS alerts. So server admin excluded some rules. He found them in Apache2 error log and exluced them in Apache 2 conf file.


Print all the pages in the same level in a book I am have a book like this

About Us

  --Overview
  --Vision
  --Mission

I want there to be menu like this in the left side when the user is in any of there page.

  --Overview
  --Vision
  --Mission

Now the links are visible when in About Us page, thats the main parent page. I have spend 2 hours already in google and drupal documentation but no use.

This should work out of the box if you add the book navigation block to a region.

EDIT:

Sorry, I didn't realise that I was on on of the book pages so the book block expands in this case but not on non book pages. The way around this is to use Menu Block and create a menu block that starts at your About Us. Make sure you go into the advanced options of the menu block and select Expand all children of this tree.


option to promote to top of list in drupal I have a site that shows top music in a list, I have created a content type called "topMusic" and a view that will show all topMusic content types.

this View shows topMusic content in a row, first content created will get on top of the list, anything added after that will show below it.

I want to add a new button or trigger to the content type, that when its "on", this content gets on the top of the list.

Any idea's will be greatly appreciated.

By default, you will find a checkbox on every node-edit form called "Sticky at top of lists". It's under the "Publishing options". If you use that to identify the top content, you can add a sort criterion "Node: Sticky" (descending) to your view to make the selected nodes appear on top.

If you need even more control (ie. you want to specify the exact order) use a module like Draggable Views or Nodequeue.


role delegation module : how to fine-tune the 'edit-administer-users' permissions? Using role delegation module , i allow a user say 'mat' with a 'site_admin' role to assign other users to a 'VIP_role'.

The problem is role delegation needs apparentely 'administer users permission' being selected for 'assign' actions to work.

When logging in with 'mat' credentials that's been set with 'administer users permission', it gives some back office links that i would like to restrict.

How could I restrict 'role delegate' to editing existing users and assign them roles ?

The two modules you will need:

Rules:

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

and Context Redirect:

  This module provides a Context reaction which redirects to a given
  internal or external url if the context conditions are met.

  You could use this module to redirect users of specific roles to a
  page of your choice, or redirect them based on a path in the site
  (node/2, 'page.htm') to another page or external URL
  (ht-p://www.google.com). Dozens of conditions can be cooked up with
  Context and redirect users to where they need to go.

set up a new rule, have it react on a url (based on whatever url you want to restrict)
set a condition that the user be of the role for which you are trying to limit access
set an action - presumably a redirect to a different page, or perhaps a custom page that tells them they don't have permission to view that url


AJAX request failing each time I try to invoke php function from module I'm trying to invoke a AJAX request whenever someone clicks a download button on my drupal site.

In my module I have referenced the javascript file in the (my-module).info as follows:

scripts[] = js/my_module.js

my_module.js:

(function ($) {
  $(document).ready(function(){
    $(".book-purchase-button").click(
    function(){
        $.ajax({
        type: 'POST',
        url: '/foo/ajax/tag',
      success: function(){
        alert("AJAX Call Successful!");
    },
      error: function(){
        alert("AJAX Call Failed!!");
    }
        });
    });
  });
})(jQuery);

I figured I could do a menu callback to capture the AJAX request based on the url

my_module.module:

/*
*    Implements hook_menu().
*/
function my_module_menu()
{
  $items = array();
  $items['/foo/ajax/tag'] = array(
    'title' => '',
    'page callback' => 'my_module_tag_user',
    'access arguments' => array('access content'),
    'access callback' => TRUE, // allows access to any user
    'type' => MENU_CALLBACK,
  );
  return $items;
}

But for some reason the AJAX request keeps alerting me that the ajax call has failed... Is there something I'm doing wrong?

Routes don't have leading slashes:

$items['foo/ajax/tag'] = array(

Clear caches, and assuming the callback function exists and writes something to the buffer, it'll start working.


Why is my Rules data comparison not evaluating correctly? This should be easy, but I can't figure out what is going wrong. I have created a field on the user account called "User profile type." It has two options: "General user" and "Grant Network user".

I am trying to create a rule (using the Rules module)to apply a role to these options if they are selected upon saving or updating of the user account form.

However, despite everything I have tried, I can't get the data comparison to evaluate as TRUE:

I am selecting site:current-user:field-user-profile-type:0 as the data to compare.
Then, in the conditions field, I am given the option in the direct input method to choose the item I want.
I am trying to choose "Grant Network user" and it evaluates to FALSE every time no matter what I try.
I have set it up with an OR statement, so that I also am selecting site:current-user:field-user-profile-type:1 as well. But, neither of these will evaluate to TRUE.

The weird thing is that when I test these data selection values in a rule to show a message on the site, they both display a message of "Grant Network user."

So, I don't understand why the data comparison is evaluating to FALSE.

Any ideas? It's probably something simple, but I can't seem to figure it out.

Note: I have tried selecting the field without the colon, but it doesn't seem to work either. It makes sense to try that, but part of my problem is also that I want to be able to select for more than one item. I'd prefer to use a "contains" operator, but it isn't available, so I'm trying to use the "...:0" and "...:1" options with an OR statement to allow for both options being selected. Am I understanding this wrong?

As per the "site:current-user:field-user-profile-type:X" part of your question (X=0 or 1), it seems that your "User profile type" field is a multi value field. Whereas you're trying to use a Data Comparison rules condition. Sorry to say, but for a multi value field, you should NOT use a "Data Comparison", because that's like trying to compare an array with a single value (which doesn't make sense).

To get your rule to work like you want it to work, you should use these Rules Conditions (in the specified order):

Entity has field, for your "User profile type" field, to make it available for subsequent Rules Conditions and/or Rules Actions.
List contains item, whereas:

the list is also about that same "User profile type" field (since your field allows multiple values, it is also considered as a list).
the item you want to check for (if it is contained in the list) is (e.g) "Grant Network user".

With those 2 Rules Conditions, your Rules Actions should be performed as you want it to work. For the sake of (basic) unit testing, just (temporary) add a Rules Action like "Display a Drupal Message" (as the very first Rules Action), with whatever message text (eg: "bingo, Pierre is right ...").

For an example Rule (in rules export format) in which you can see this at work, refer to the answer to "How to check for product taxonomy term in Rules actions (Ubercart)". In that case it's about a list of taxonomy terms, but the idea is the same.

PS: I'm assuming this question is about D7 ...


Block loading behaviour in Drupal 8 in a performance sense through the visibility settings The following scenario:
- i have for example a standard block region through a pages of a site: "highlights"
- for the frontpage i have an additional region: "highlights_frontpage"
- i put a block into "highlights_frontpage"
- i have to put into the visibility textarea: ""

If i remember correctly for D7, otherwise the block is loaded everywhere even though he is only shown on the frontpage.

Has Drupal 8 the same behaviour in loading blocks?
My page has for each main menu page an own region, but it would be a little bit ugly for the editor if he has to place the block via the administration in one region and also has to set the visibility ...

thanks

The block is loaded (otherwise we could not check if he should be shown or not), but we do not call build() unless the block is visible and the user has access.

I'm pretty sure that was already the case in Drupal 7, it is only Drupal 6 AFAIK where it was building the blocks and then checking visiblity.


Custom field widget form - Multiple values I've create a custom field form widget for an entity reference field. When only one value is allowed it shows a (filtered) select list, but I want to allow user to assign multiple reference values to that field.

In my use case I want it to be shown as checkboxes when multiple values are allowed, but by default it shows my checkboxes in a 'add-another' fieldset.

How can this be accomplished?

Below some code, $type is now a field setting and is manually set.

// Construct element
$widget = $element;
$widget['#delta'] = $delta;
$type = $settings['option_limit_type'];

... extra logic ...

switch ($type) {
      case 'select':
        $widget += array(
          '#type' => 'select',
          '#prefix' => '
',
          '#suffix' => '
',
          '#options' => $options,
          '#delta' => $delta,
          '#element_validate' => array('_entityreference_hierachy_option_limit_validate'),
          '#default_value' =>  $saved_target_id,
        );
        break;
      case 'checkboxes':
        $widget += array(
          '#type' => 'checkboxes',
          '#prefix' => '
',
          '#suffix' => '
',
          '#options' => $options,
          '#delta' => $delta,
          '#element_validate' => array('_entityreference_hierachy_option_limit_validate'),
          '#default_value' =>  $saved_target_id,
        );
        break;
    }
return $widget;

You can use drupal form api attributes like

 case 'select':
        $widget += array(
          '#type' => 'select',
          '#prefix' => '
',
          '#suffix' => '
',
          '#options' => $options,
          '#delta' => $delta,
          '#element_validate' => array('_entityreference_hierachy_option_limit_validate'),
          '#default_value' =>  $saved_target_id,
          '#multiple' => $multiple,
          '#size' => $multiple ? min(12,count($options)) : 0,
        );
        break;

https://api.drupal.org/api/drupal/developer!topics!forms_api_reference.html/7#multiple


How to display my block on search results page only if nothing found? I want to place a webform block to make user able to inform about their special queries if no search results appeared.

To expose a webform as a block, go to the webform, and under the webform>>form settings tabs go to the bottom, open up the Advanced settings, and check 'Available as block'.

Then go to /admin/structure/block find your block and click on 'Configure'. The url will have the form /admin/structure/block/manage/MODULENAME/BLOCKID/configure (MODULENAME will be 'webform', and the BLOCKID will have the form 'client-block-$nid' where $nid is the node ID of the form). Keep a record of these.

Then copy the core template from the DRUPALROOT/modules/search/search-results.tpl.php to your theme directory, and edit it to look something like:

<?php if ($search_results): ?>

<?php print t('Search results');?>

  <ol class="search-results <?php print $module; ?>-results">
  <?php print $search_results; ?>

  <?php print $pager; ?>
<?php else : ?>

<?php print t('Your search yielded no results');?>

  <?php
    $block = block_load('MODULENAME', 'BLOCKID');
    print drupal_render(_block_get_renderable_array(_block_render_blocks(array($block))))
 ?>
<?php endif; ?>

This will print your block instead of the search help if there are no search results.

Now, so your theme can use this new template, you have to make it aware. Edit the theme's template.php file and look for a function called THEMENAME_preprocess_search_result(&$vars) If it exists, add the following code. If it does not exist, create it and add the following code:

THEMENAME_preprocess_search_results(&$vars) {

  // ..... Existing code

  $vars['template_files'][] = 'search-results-' . $vars['module'];
}

Hope this helps.


Comments not displaying for node that was added to a custom page I’m attempting to make it possible for users to add comments to a custom page that was created via Page Manager. My understanding is that it is not possible to set up and allow commenting for page but only for nodes. Therefore i created a special content type and corresponding node and added it to the page. i added via ‘Add existing node’ option.

I’ve added comments to this special node but they are not being displayed when viewing the node in context of the custom page. Does anyone know how i can get these comments to display?

My suggestion is to use the default 'Basic page' content type to create page and allow comments there. If you need to have custom path for it, you can setup url alias.
Also for additional customization or theming, you can opt for node specific template.

I hope my answer applies to your situation :)


How to quickly update/reinstall using Drush 4.x Whilst trying to update Drupal 7.0 core and installed modules using Drush 4.x I appear to have broken a project site (Ubuntu 11.04 box using pure LAMP) and hence I get the dreaded 'white screen' so cannot get past it or get into the backend of the site. I would like to simply get D7 core/and all current modules (which there is a good 40 modules or so) updated and back working. It is a project for learning but I have done a good fair amount of work on it over the past 6 months and really I don't want to trash the mySQL DB and start all over again as I'll lose a fair amount of hours work. Can anyone provide a Drush command to get it back up and running whilst also updating the D7 core/modules and get it back on track. I understand the concept of the Drush CLI, but am really a 'learning' novice at present across all of the Drupal framework. The modules included are the general Panels/Rules/Views (PRV) etc along with Ubercart and subscriptions etc so a fair amount of PRV work has already been done.

I also get the following:

  PHP Fatal error:  Class 'RulesIdentifiableDataWrapper' not found in
  /var/www/sitename/sites/all/modules/flag/flag.rules.inc on line 27
  Drush command terminated abnormally due to an unrecoverable error.

So what do I do now??, I really don't want to start the whole project all over again after spending a good 6 months on this project.

Concluding:
The whole process trashed my project site. Some 6 months work (with a lot of typing input) may have gone. the mySQL tables are still there and the data has been backed up, but whether I can get d7.14 and the current used modules and all the P/R/V and Ubercart user subscrition data to work is still to be seen. I'm sure this is NOT the way to be efficient in web building and management.

It's best practice to always backup your database first when updating modules (especially when working with -dev versions). A useful module is Backup and Migrate, when installed it also provides a Drush command to backup the database (drush bb). (But avoid GZ compression at the moment, bug introduced with version 2.3). Since you currently have a fatal error, you'll probably have to make a backup of your database via your database management tool in Ubuntu, or use something like phpMyAdmin. You should also note which modules you will update and what the currently installed versions are. If you do all upgrading via Drush, it creates a backup of all modules it updates (so you don't have to keep track manually), and if something goes really wrong you can go back to the previously working code and if necessary put your backed-up database in place.

It looks like the current version of your Flag module is throwing the fatal error which is preventing you from updating / accessing the site. I assume this is still an old version (cf. e.g. this report), and it's likely that if you put the latest recommended relase of Flag in place the error goes away (remove the current flag module folder and replace with the 7.x-2.0-beta6 version). (If this doesn't solve the Fatal error, you should provide some more details on what versions of Flag and Rules you were using previously, and what version they are at now).

Once you get the site back working, it's a matter of doing the regular Drush commands from your Drupal directory. For example:

# If you have many sites you can check to make sure you're working on the right site
drush status

# update all modules but not Drupal core
drush up --no-core

# make sure update.php is run (in my experience sometimes some updates aren't run)
drush updatedb

Now check that your site is still working properly and then update Drupal core.

drush up drupal

And check your site again. The status report will show you if all modules and themes are up to date and if there are any database upgrades that still have to be executed.

For more info on Drush also check out drush.org.


Form textfield on-click remove default values My objective is to automatically remove the default values within the form textfields upon either being selected/clicked on. Not really sure how to at the moment. Any suggestions?

What do you mean for "default value"? Do you need to save this value or just to use it as a placeholder?

In this case you can obtain the goal without javascript:

$form['Package']['FirstName'] = array(
  '#type' => 'textfield',
  '#maxlength'=> 255,
  '#required' => TRUE,
  '#attributes' => array(
    'placeholder' => t('First Name'),
  ),
);


Extra sorting criterium in case of ex aequo with Views My articles have a 'Ranking' field, which contains an integer. I have a view that sorts articles depending on this value: the article with the highest score is a the top. Now, when two articles have the same amount of points, I'd like the most recently posted article to get the highest ranking.

For example. Let's say I have 3 articles:

'Article A' (5 points - posted on 30/12)
'Article B' (5 points - posted on 21/12)
'Article C' (6 points - posted on 20/12).

The ranking should be:

'Article C'
'Article A'
'Article B'

How can I do this?

Add a new sort criteria, Posting date, set it to descending and make sure the order of your sort criterias are correct, first points, then date.


How to use the YML structure of routes to control access to Group Content I am using the Group module and would like to leverage each Group's permissions in my module's yml files.

I have a module.permissions.yml with something like

tam_api.group_gid_members_uid:
  path: 'group/{group}/members/{member}'
  defaults: { _controller: '\Drupal\tam_api\Controller\TamApi::getGroupMember' }
  methods: [GET, HEAD]
  requirements:
    _permission: 'access user profiles'
  options:
    _format : ['json']
    _auth: ['oauth2', 'cookie']
    parameters:
      group:
        type: entity:group
      member:
        type: entity:group_content

I would like to change access user profiles to the View individual group members for the given Group?

Can this be done within the Structure of Routes?

in group.services.yml you'll find access_check entries like:

  access_check.group.permission:
    class: 'Drupal\group\Access\GroupPermissionAccessCheck'
    tags:
      - { name: 'access_check', applies_to: '_group_permission' }
  access_check.group.member:
    class: 'Drupal\group\Access\GroupMemberAccessCheck'
    tags:
      - { name: 'access_check', applies_to: '_group_member' }

you can use these in your routes like:

tam_api.group_gid_members_uid:
  path: 'group/{group}/members/{member}'
  defaults: { _controller: '\Drupal\tam_api\Controller\TamApi::getGroupMember' }
  methods: [GET, HEAD]
  requirements:
    _group_member: 'TRUE'
# or    _group_permission: 'view group membership content'
  options:
    _format : ['json']
    _auth: ['oauth2']
    parameters:
      group:
        type: entity:group
      member:
        type: entity:group_content

Note: the parameter argument must be named {group}


Create a pager for views output How can I make a pager for views output to limit them at 10 entries?

$view = views_get_view('myview', 'default');
$view->override_path = $_GET['q'];
$view_output = $view->execute_display('page_1', array($tid));

Drupal Views module provides this functionality. You don't need to write the code for that.
See the image below
Here you can set item to display as want. It has many more options


what is "field_create_field" and "hook_field_info"? is there difference motive I want to create a field, i searched on drupal and find field_create_field can create a field but I also find that hook_field_info is also to create to field.

My question is what is basic difference between both of them?
Are they use for same purpose?

I need the difference and where both are used?

function field_create_field is used to create a field. When you debug this function you will get $field array with the id property filled in.

function hook_field_info defines Field API field types. For more info refer here.

For more clarification you can simply debug both these functions then you will get the all basic differences.


How to solve the warning of CAPTCHA session resuse attack I am using captcha module (7.x, 1.0 v), When i select the image & click on upload button. Then image uploaded successfully but show this warning message also.

How to solve this issue. Please help. Thanks.

This is a bug in CAPTCHA module you are using. Module should be compatible with core, and file upload is one of the core functionalities of Drupal. Please report this bug to module's issue queue.

But you are not helpless. As a workaround, you can use Multi-Step Registration module. Keep CAPTCHA on first step only, and put profile photo in a second step. It will keep conflicting fields on separate forms, preventing them from interfering with each other.


Flags, rules and node type situation got a situation with flags, rules and node type...

I have an event website where people can add events to their own calendar. Once the event is completed, they can then edit their "registration" to add comments and other details.

I am acheiving this using Event type, Flags and action.
Node type: Event
Node Type: Registration
Flag: Add to calendar (attached to the event)

When the event is flagged by the user, a rule is set to to create a registration and update some field to link to the related event and keep the flag id in the registration.
Another rule is triggered if the Registration is deleted, it unflag the event.

Not sure if there's a better way to do this? Any suggestions? Better practice?
It's working, but the problem I have is that it's taking a lot of time to load the edit form of the registration. I am going to try the token tree optimisation, but if there is a better solution, I'm willing to give it a try.
Also, using the current system, it creates a node for every event added to the user calendar.

Thanks

It sounds to me that you should have a look at the Entity Registration module as an alternative to simplify your current setup. Some more details about it, from its Community documentation:

The Entity Registration module provides the ability for users to register for any entity in Drupal. Registrations are fieldable entities and can collect any information you need from your registrants. By attaching a Registration field to any entity, you enable users to fill out a form containing customized fields to register for that entity.
Entity Registration currently has the following features:

Registrations are fieldable entities, so collect any information you need from your registrants
Unlimited types of registrations, or bundles.
Enable registrations of a given type/bundle on any entity type or individual entity through a registration field.
Per entity registration settings like capacity, reminders, etc.
Send broadcast emails to registrants.
Allow a single user to register multiple registrants.
Integration with Views and Rules via Entity API.


adsense code not working in drupal 7 I have put the following code from adsense in a block with full html filter :

<script async src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>
<!-- newad -->
<ins class="adsbygoogle"
     style="display:inline-block;width:728px;height:90px"
     data-ad-client="ca-pub-4076687304826472"
     data-ad-slot="1906412748"></ins>
<script>
(adsbygoogle = window.adsbygoogle || []).push({});
</script>

But I dont see the proper ads , The message comes with style :"display etc.. and some ads in very unformatted fashion . Is there some other way to put adsense code in drupal 7 ?

thanks for any help in this

full html isn't always enough to provide the necessary access.  go to /admin/config/content/formats and create a new format (I call mine 'Unaltered') with the following setup (make sure to restrict it to admin ONLY):

This will allow you to perform inline js, etc within a block, without requiring a new module. Also, make sure the style listed in the js you include matches the size of the block (or more accurately, that the block matches the size of ad you want to show), or you will have strange layouts where the ad doesn't fit the container.


Get user ids of group members I want to get a list of all users that are members of a group.
I can get the members using getMembers():
$members = $group->getMembers();
  foreach ($members as $member) {
    var_dump($member);
  }

But this returns not User objects but GroupMembership objects:
object(Drupal\group\GroupMembership)#2609 (1) {
  ["groupContent":protected]=>
  object(Drupal\group\Entity\GroupContent)#2667 (28) {
    ["values":protected]=>
    array(12) {
      ["id"]=>
      array(1) {
        ["x-default"]=>
        string(1) "1"
      }
      ["type"]=>

So how do I get the User IDs from the GroupMembership objects? Or is there an easier way?

Found the answer myself minutes after posting the question... so it goes :).
  $members = $group->getMembers();
  foreach ($members as $member) {
    $user = $member->getUser();
    $userids[] = $user->id();
  }


Saving and retrieving EntityAutocomplete value I'm building a block plugin that allows users to specify a menu to appear in a block plugin. I'm taking advantage of the EntityAutocomplete form element.

https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Entity%21Element%21EntityAutocomplete.php/class/EntityAutocomplete/8.2.x

Here is how the form is built.

public function blockForm($form, FormStateInterface $form_state) {
    $form['menu'] = [
        '#type'          => 'entity_autocomplete',
        '#target_type'   => 'menu',
        '#default_value' => $this->configuration['menu'],
    ];
    return $form;
}

It's able to display the form element just fine. And it allows users to select menus as well. I then save the item on submit like this.

public function blockSubmit($form, FormStateInterface $form_state) {
    $this->configuration['menu'] = $form_state->getValue('menu');
}

However after saving it and opening it again I receive this error

  InvalidArgumentException: The #default_value property has to be an
  entity object or an array of entity object

How do I successfully save or retrieve the menu? Do I need to put something like $this->configuration['menu']['value']?

Update: When I perform

die(print_r($this->configuration['menu']));

It just prints the machine name of the menu I selected. So maybe the issue is that the default value it's being supplied is just a string instead of the actual entity? But if so how would I get the entity from the machine name?

Update 2: I tried using

$menu = Entity::load($this->configuration['menu']);
die(print_r($menu));

But that didn't produce anything.

I was able to resolve the issue by loading the entity first like so

$menu = \Drupal::entityTypeManager()->getStorage('menu')->load($this->configuration['menu']);
    $form['menu'] = [
    '#type'          => 'entity_autocomplete',
    '#target_type'   => 'menu',
    '#default_value' => $menu,
];

The value of $this->configuration['menu'] was only the machine name, not the actual entity. So the entity had to be loaded and stored in a variable first.


Rules Add an item to a List overwrites existing data I have created a rule to add terms to an existing Term Field. The rule fires correctly, it's adding the Term to the Field. However, it's overwriting all the existing terms within the field.

I have tried to follow the steps from this similar question as well as this Tutorial, however, it's still a no go for me.

More details about my setup:

Vocabulary: Emails (machine name: emails)
Email Field: Email Field (machine_name: field_primary_email), which is a single value field.
Term Reference: Email Term Reference (machine_name: field_email_term_reference)

The requirement is to display Email communication basis of the Email address present in the node [ Contact Content Type].

I have a rule which picks up the primary email & creates a taxonomy term from it. The second rule, assigns the relevant terms basis of the email present in the node. The email address in the node may change, however, the terms are to remain to display the past communication. When the new email is updated in the node, the first rule creates a new taxonomy term basis of the updated email address. When the new term is created, the second rule picks up the term & assigns it to the Term reference field along with the existing ones. It is not to overwrite the terms already present in the field. Basis of the terms present in the node, I can display the email communication.

My rule I created so far (in Rules export format):

{ "rules_update_email_term_reference" : {
"LABEL" : "Update Email Term Reference",
"PLUGIN" : "reaction rule",
"OWNER" : "rules",
"REQUIRES" : [ "rules" ],
"ON" : { "node_view" : [] },
"IF" : [
  { "entity_is_of_bundle" : {
      "entity" : [ "node" ],
      "type" : "node",
      "bundle" : { "value" : { "candidates" : "candidates", "clients" : "clients" } }
    }
  },
  { "entity_has_field" : { "entity" : [ "node" ], "field" : "field_email_term_reference" } }
],
"DO" : [
  { "LOOP" : {
      "USING" : { "list" : [ "node:field-email-term-reference" ] },
      "ITEM" : { "current_term" : "Current Term" },
      "DO" : []
    }
  },
  { "entity_query" : {
      "USING" : {
        "type" : "taxonomy_term",
        "property" : "name",
        "value" : [ "node:field-primary-email" ]
      },
      "PROVIDE" : { "entity_fetched" : { "entity_fetched" : "Fetched entity" } }
    }
  },
  { "list_add" : {
      "list" : [ "node:field-email-term-reference" ],
      "item" : [ "entity-fetched:0" ],
      "unique" : "1"
    }
  }
]

}
}

Your rule in your question seems to have "a few" (not just one) issues that need to be addressed. So I'll build a list of these issues here (and will add more of them later on if needed) ...

Issue 1:

Think about this: "Why have that 1st Rules action (a loop), if inside that loop there is nothing happening (as per the "DO" : [] in it)?". Either the loop is just redundant, or there is some Rules action(s) still missing inside that loop (more research needed).

If it was me to decide, for now I'd delete that Rules Action. And if needed I'd restore it later on if I have a real reason to do so (i.e. if there is at least 1 Rules Action that I know I'd need, as part of that loop.

Issue 2:

At the core of your question, there is your "It is not to overwrite the terms already present in the field". The typical mistake in using Rules is that someone incorrectly uses a Rules Action like "Set a data value" (for a multi value field), and that will remove all existing values for that field. The correct way is to use a Rules Action "Add to list" (that will preserve existing values). Your last Rules Action does indeed perform a "Add to list" (as it should be done to achieve your goal), but what is suspicious in that Rules Action is that you use entity-fetched:0 ... That is a single value (as per the ...:0 part of it, but entity-fetched is a multi value list (it has to be like that, otherwise you wouldn't use that ...:0 part in it). But nowhere there is an indication why "the first value" in the multi value list  (stored in entity-fetched), is the actual value you want to add to your list.

Issue 3:

The rules event your using (= node_view), combined also with the Rules Condition, is rather suspicious also. For 2 reasons: (a) what if the event and/or condition are not satisfied (in that case none of the Rules actions get executed) and (b) if you're sure the Rules event and Rules condition is "always" satisfied, then you might be doing those Rules Actions over and over again.

Though there is possibly only reasons to do so in 1 specific scenario. I.e. for those situations related to your "I have a rule which picks up the primary email & creates a taxonomy term from it" (let's call that your 1st rule, as compared to your 2nd rule shown in your question). It seems to me that your 2nd rule (as in your question) should be reworked like so:

Create a new Rules Component, with Rules Conditions and Rules Actions as you already have in your 2nd rule here.
Add and extra Rules Action to your 1st rule, which is simply/only to perform (= trigger the execution) of your 2nd rule.
In doing this redesign, you may have relevant / interesting data available in your 1st rule (like node id, user id, eMail id, term value, etc), which you can pass on to the Rules Component as a so called "Parameter" for that component.
And by having such parameters available in your Rules Component, you might possibly simplify the set of required Rules Actions needed to achieve your goal.
Don't forget to at least disable (or even delete) your current 2nd rule, after you reworked it to such Rules Component.

Possible other issues to be resolved

The above issues are, for now, only some suggestions to help you come closer to your goal. It's well possible (actually I'm about sure ...) you'll need other issues to be resolved also. But pretty sure the above issues will help you come closer. Btw, debugging is the art of taking away all possible reasons why it doesn't work ... as you want it to work.


How can I allow editors to manage many taxonomies while choosing which terms to boost and which to make visible? The system I am working on has about 15 taxonomies. It may have 30 or more eventually.  We didn't want to add a field for every taxonomy since the editors would have hated that. Initially we went with one field called "Search term(s)" aka field_search_terms that lets editors reference multiple taxonomies.

Now the editors also want to be able to

Mark some terms as primary and others as secondary (Let them control which terms to boost in search)
Mark some terms as visible tags on the page while most will be hidden.

I can think of two options:

Make separate fields on the nodes for primary, secondary and visible_terms.
Unfortunately the editors will have to select visible terms/tags twice.
Make a custom "search_term_reference" entity with fields: {field_search_term, is_primary, is_visible} and then provide something like inline entity form to edit them.

Can anyone offer any practical guidance based on experience with the issue of allowing editorial control of search boost for individual terms? Feedback on how much custom code was needed for example?

My preference is to use 3 fields. I'm not sure I think it's ideal, but I think it's actually an easier UX and a better data structure than 1 field (or subentity) with taxonomy ref plus additional checkboxes for primary and display with each tag.

On the surface, it may seem like 1 field would be better, but I think that's actually an illusion. The two main users I'd consider here are developer and editor, and I think one complicated field is bad for both of them. For developers, it's going to be more difficult to determine the search terms or display terms when you try to get them in code with one complicated field vs 3 separate fields. It's also going to be more difficult for editors, they won't be able to scan and see all search terms or all display terms easily.

Field 1: Tags
This is the master field, it has all the tags that would be in either of the other two fields. If you're generally checking if the content has a tag, you'd check here.

Field 2: Display Tags
This field is a subset of Field 1 tags and its only purpose is determining which tags display.

Field 3: Search Boost Tags
This field is also a subset of Field 1 tags and its only purpose is boosting search results.

Custom Field Widget
Create a new field widget to be used with the display tags and search boost tags fields. This widget displays tags with checkboxes and is limited to only the tags in the first, master tags field. Also have the widget update its options via ajax whenever the first tag field changes.

This approach creates an easy interface for editors, keeps all the data easily accessible for developers, and limits special custom coding to just the field widget. (Bonus: you now have a cool field widget in your collection that you can use elsewhere in similar situations.)


How to check node authorship info in views I want to show users their published articles in a block. Those articles have their author name set in by Admin manually while the articles are created by Admin on behalf of the users.

In views I don't find any field in Node to compare authorship of the node with logged in user.

I've found a related article: http://drupal.org/node/228959
but no idea about how to look for following point in the article:

Go to 'Arguments' and select "User: UID is Author" and set the default
value to 'Return Page not found'.

I don't see "User: UID is Author". I only see "User:UID".

Add a filter to your view of User: Current.  This will filter the nodes to ones created by the current user.


How do I access the data of a field using PHP? I'm trying to print out different links to an e-mail based on the values selected in the in the multi-select field. I've used devel to make sure that the field is actually storing the values and it is, but it always goes to the default case in my switch. I am trying to access the information from a node.

    print("I am in the php tag");
    $field_lab = field_get_items('node', $node, 'field_lab_s_requested');
    for($i = 0; $i < 4; $i++){
       print("I am in the for loop" + "Count:" + ($i+1));
        $lab = $field_lab['und']['value'][$i];
        switch ($lab) {
            case "127":
                print("link");
                break;
            case "129":
                print("link");
                break;
            case "130":
                print("link");
                break;
            case "132":
                print("link");
                break;
            case "117":
                print("link");
                break;
            case "112":
                print("link");
                break;
            case "113":
                print("link");
                break;
            case "116":
                print("link");
                break;
            case "118":
                print("link");
                break;
            case "121":
                print("link");
                break;
            case "122":
                print("link");
                break;
            case "119":
                print("link");
                break;
            case "123":
                print("link");
                break;
            case "124":
                print("link");
                break;
            case "140":
                print("link");
                break;
            case "143":
                print("link");
                break;
            case "146":
                print("link");
                break;
            case "148":
                print("link");
                break;

            default:
                print("Hit the default case");
                break;
}

}

Language negotiation is handled for you by field_get_items, and the delta is above the field column in the array hierarchy (it goes $field[LANGUAGE][DELTA][COLUMN_NAME]).

So using und isn't necessary, and you need to change how you're accessing each field item.

Code similar to this should work:

$field_lab = field_get_items('node', $node, 'field_lab_s_requested');
foreach ($field_lab as $field_item) {
  switch ($field_item['value']) {
    case "127":

      break;
    // ...
  }
}


Clear managed_file field on submit I'd like to clear the managed file field each time the contents are sent off for further processing on submit.

The callbacks work fine, but I have repeatedly come unstuck in my goal of having a "fresh" form everytime I need to submit a new image.

The form is defined thus:

function mymodule_form($form, &$form_state) {

$form['Input type'] = array(
    '#type'=>'fieldset',
    '#title'=>'Upload your image'
);

$form['Input type']['file'] = array(
    //file left in non-permanent state for testing purposes
    '#type' => 'managed_file',
    '#title'=> t('Upload image'),
    '#description' => t('Choose an image to upload. Format must be gif, png, jpg, and may not exceed 2MB in size. Press Submit to confirm your selection.'),
    '#upload_validators' => array(
        'file_validate_extensions' > array('gif png jpg jpeg'),
        'file_validate_size'=>array(512*512*512),
    ),
    '#upload_location'=>'public://mymodule_uploads',
);

$form['Input type']['submit'] = array(
    '#type'=>'submit',
    '#value' =>t('Submit'),
    '#submit'=>array('mymodule_clear_image_submit'),
    '#ajax' => array(
            'callback'=> 'mymodule_update_image_callback',
            'wrapper'=>'somediv'
        ),
);
return $form;
}
function mymodule_update_image_callback($form,&$form_state) {
$picture_settings = array(
        'image' => file_create_url($form['Input type']['file']['#file']->uri)
        );
    drupal_add_js(array('mymodule' => $picture_settings),'setting');

    return;
}

function mymodule_clear_image_submit($form,&$form_state) {
$form_state['complete form']['Input type']['file']['#file'] = NULL;
$form_state['rebuild']=TRUE;
return;
}

Neither the submit nor the callback functions seems to be refreshing my form. Setting the file value to NULL has not had an effect either.

I don't know what else to try. Cheers!

I found a solution to this problem here: https://www.drupal.org/node/1578656

The idea is to add the following keys to the 'file_managed' field at the time you want to clear it:

$form[FORMKEY]['#file'] = FALSE;
$form[FORMKEY]['filename'] = array();
$form[FORMKEY]['#value']['fid'] = 0;

In your case it should be something like this in the form builder function:

if ( isset($form_state['storage']['reset-file-field'])
  && $form_state['storage']['reset-file-field'] === true
) {
  $form['Input type']['file']['#file'] = FALSE;
  $form['Input type']['file']['filename'] = array();
  $form['Input type']['file']['#value']['fid'] = 0;

  $form_state['storage']['reset-file-field'] = false;
}

And then in your submit handler:

$form_state['storage']['reset-file-field'] = true;

The if-block is necessary to prevent the upload field being reset when you press 'upload', thus making it useless.


How useful is it to use the latest Composer version to maintain my sites? I am trying to determine the best way to maintain a Drupal 8 site. I am new to Drupal, PHP and Composer, but I am learning.

I believe that my goal is to maintain my Drupal 8 site using drupal-composer/drupal-project (https://www.drupal.org/node/2718229).

I am using a shared hosting plan, but I have shell SSH access. I notice that my hosting provider already has /opt/cpanel/composer/bin  in my command line path. That version of composer is 7 months old. (Composer version 1.1.1 2016-05-17). I have PHP 5.6.29 via the command line.

It's possible for me to install the latest version of composer (1.3) in my user directory, and then to override the hosting service's path. I want to know whether it's worth the extra trouble to do so.

Purely from the standpoint of maintaining my Drupal sites (and not from the development point of view; I won't be making my own modules any time soon), how useful/critical would it be to have the latest stable version of Composer available to me?  My guess is that the hosting service won't be updating Composer often (maybe once or twice a year).

Does a somewhat out-of-date version of Composer impose limitations on how effectively it can manage Drupal and Drush updates?

drupal-project has a composer version check built in that currently requires 1.0, so you're fine with 1.1 for now:

https://github.com/drupal-composer/drupal-project/blob/94404dcbed7fe9eb9ea8d95016b661ae6d4f9e3f/scripts/composer/ScriptHandler.php#L75

That said, more recent versions have performance improvements I think and sooner or later, there might be a problem that will force you to update, and then it will be easier if you already are using a custom more recent version. On the other side, your hosting provider might also update that version from time to time, you might want to check that with him. E.g. in case of a security issue.

But no, for now, you're not required to do this.


Drupal 6 Can I use subdomain, for the dev instance of a site and use multiple site configs How do subdomains work in relationship to multiple sites? This seems to be danced around in the documentation that is out there.

more specifically. If I have...

primarydomain.com  as my site in the site folder.... and point the domain
dev.primarydomain.com at the drupal install without a dev.primarydomain.com folder will dev load the primarydomain.com or the default site?

The key behind this is I am trying to setup a 3 tier environment for drupal  (dev, test, prod) and want to have as few transformation processes to move things up the tier. So I am hoping I can simply put dev infront of the domain and everything will work.

Also if it does work can I do the same thing on a sub-subdomain? dev.blog.primarydomain.com?

Thank you for your help I am relatively new to drupal and working on putting an existing site into a dev environment to learn more safely.

Short answer is: if example.com exists in the sites folder and a settings.php file is inside it, that file will be selected to serve any request directed to *.example.com.

Long answer is:
let's say an url such as "an.example.com/something" is requested and such request reaches Drupal, here is what happens:

Does a settings file exist in a folder named an.example.com.something (inside the sites/ folder)?
Does a settings file exist in a folder named example.com.something?
Does a settings file exist in a folder named com.something?
Does a settings file exist in a folder named an.example.com?
Does a settings file exist in a folder named example.com?
Does a settings file exist in a folder named com?
Serve the default website.

If at any point of the process the answer to the question is yes, then that file is selected as the settings file.
Of course it will work with more complex subdomains and also more complex paths, as well as port numbers. Have a look at the official Drupal documentation on multi-site and at the conf_path() function for more details.


How to display most recent node in different Panel I have a magazine with two content types: Issue and Article. Regarding the Issue content type, I want one design for the most recent Issue and another design for all the past Issues. The past Issues are taken care of with Display Suite. For the current Issue I would like to use a panel/node variant. My question is, how do I display only the most recent node from the Issue content type without changing the design for all Issue nodes?

You can use Views module to have custom content or links and show as a separate page or a block.

check this link:
http://drupal.org/project/views


How to get only parent term ids of a given term, without loading the terms I want to find all parent ids of a given taxonomy term id recursively, without loading them. Existing taxonomy functions like taxonomy_get_parents_all() and taxonomy_get_parents() are loading the terms.

Since I will be using this result in an API function, it is important for me to get the parents with a minimum performance overhead. All I need to get the parents in a simple array like: $parents = array(6, 3, 2);

Have a look at taxonomy_get_parents() and taxonomy_get_parents_all().

You could copy most of the functions but skip

$parents[$tid] = taxonomy_term_load_multiple($tids);

to not load the terms.

/**
 * Load a terms parent.
 */
function MODULE_taxonomy_get_parents($tid) {
  $parents = &drupal_static(__FUNCTION__, array());

  if ($tid && !isset($parents[$tid])) {
    $query = db_select('taxonomy_term_data', 't');
    $query->join('taxonomy_term_hierarchy', 'h', 'h.parent = t.tid');
    $query->addField('t', 'tid');
    $query->condition('h.tid', $tid);
    $query->addTag('term_access');
    $query->orderBy('t.weight');
    $query->orderBy('t.name');
    // $tids = $query->execute()->fetchCol();
    // $parents[$tid] = taxonomy_term_load_multiple($tids);
    $tids = $query->execute()->fetchAll();
    $parents[$tid] =  $tids;
  }

  return isset($parents[$tid]) ? $parents[$tid] : array();
}

/**
 * Load all parents for a term.
 */
function MODULE_taxonomy_get_parents_all($tid) {
  $cache = &drupal_static(__FUNCTION__, array());

  if (isset($cache[$tid])) {
    return $cache[$tid];
  }

  $parents = array();
  if ($term = taxonomy_term_load($tid)) {
    $parents[] = $term;
    $n = 0;
    // while ($parent = taxonomy_get_parents($parents[$n]->tid)) {
    while ($parent = MODULE_taxonomy_get_parents($parents[$n]->tid)) {
      $parents = array_merge($parents, $parent);
      $n++;
    }
  }

  $cache[$tid] = $parents;

  return $parents;
}

If you don't need any access control or sorting you can just query the taxonomy_term_hierarchy table directly.

$query = db_select('taxonomy_term_hierarchy', 'h');
$query->addField('h', 'parent', tid);
$query->condition('tid', $tid);
$query->condition('parent', 0, '!=');
$tids = $query->execute()->fetchAll();
$parents[$tid] =  $tids;


Where can I see the options accepted by the field API for the widget type? Where can I see the options accepted by the field API for the widget type?

$instance = array(
  'field_name' => $field_name,
  'label' => 'Demofield Demo',
  'description' => 'This is a demonstration text field.'
  'widget' => array(
      'type' => 'text_textfield',
  )
);

There isn't a preset list of widget types; the widget types are the ones defined from modules that implement fields. Using the following code, you can get the list of all the widget types implemented by the enabled modules:

$array = module_invoke_all('field_info');

foreach ($array as $id => $info) {
  print $info['default_widget'];
}

The code essentially invokes all the implementations of hook_field_info(), and print what is defined as default widget.
If you have installed Devel, instead of print you can use dsm().

If you want to know the settings available for the field implementation, then you need to look for the implementation of hook_field_settings_form(), such as list_field_settings_form(), or text_field_settings_form().

function text_field_settings_form($field, $instance, $has_data) {
  $settings = $field['settings'];

  $form = array();

  if ($field['type'] == 'text') {
    $form['max_length'] = array(
      '#type' => 'textfield',
      '#title' => t('Maximum length'),
      '#default_value' => $settings['max_length'],
      '#required' => TRUE,
      '#description' => t('The maximum length of the field in characters.'),
      '#element_validate' => array('_element_validate_integer_positive'),
      // @todo: If $has_data, add a validate handler that only allows
      // max_length to increase.
      '#disabled' => $has_data,
    );
  }

  return $form;
}


How can I download a results set with a form built in Entity forms? We've tried entity forms for a project and the client wants that collected data in a spreadsheet. (This was never a mentioned spec before the project.)

Is this possible? Is there a way to download entity form submissions to a CSV or spreadsheet?

You can use Views Data Export: For downloading submissions, Entityform support that by default.


Drupal Commerce Paypal WPS I have a Drupal 7 site running the latest Drupal Commerce and Paypal WPS as a payment method.  Everything is working correctly.  When a customer is checking out and can pick between Paypal and credit card, the radio button for the area that lists the credit card does not show up.

Screen shot attached.

I've checked and re-checked every possible setting.  Is there a way to disable the Paypal only button and enable the credit card and paypal option?  Or just get the radio button to show up so users can pick.

I've inspected elements and the input tag is not present in the html.

Any help or guidance is appreciated.

PayPal WPS submodule of Commerce PayPal provides only one payment option, which redirects the user to PayPal for payment. Credit card icons are there to let users know that at PayPal's end they will be able to make the payment via PayPal balance or using listed credit cards.

You see only one radio button for PayPal WPS payment method because it is expected behavior. If you wish to allow your users to pay via credit card without leaving your website - enable PayPal WPP submodule.


Change View format in PHP I have a Drupal 7 site and I would like to change the view format with a button click, so I want to ask if it is a way to change the configuration of a View page with php.

In a view page configuration, the option is this:

Now it has "List without format" value.

It is possible to call a View using PHP code. It is also possible modify a view using code such as hook_views_pre_view() to change how a View is displayed dynamically.

I actually wouldn't do either for your request. Simply do the following:

In your View make 2 displays.

1 view display that shows the Grid format.
1 view display that shows the list format.

On the page in question use an HTML button, html link, or even a Rules Link that uses Ajax to reload the div on the page and calls the view with the correct display mode you want. Your ajax call will be calling like: $view = views_embed_view('MY_VIEW_NAME', 'display_id'); and updating the page with $view contents via Ajax.

So make 2 view displays, and learn how to call them using Ajax.


Drupal 7, creation of new node, how redirect to the edit page of the new node When I create a new node in my website, I want to be redirect to the edit page of the new node.
I see several hook, but according to this post its not possible use drupal_goto..

Is there a way for me ? I prefer a programming approach
Thanks =)

In a custom module, use this code, and don't forget to replace MYMODULE_ with your module machine name :

function MYMODULE_form_alter(&$form, &$form_state, $form_id) {
  switch ($form_id) {
    case 'my_content_type_node_form': // Replace my_content_type with yours
      $form['#submit'] = array_merge(array('MYMODULE_my_content_type_node_form_submit'), $form['#submit']);
    break;
}

function MYMODULE_my_content_type_node_form_submit(&$form, &$form_state) {
  $initial_values = $form_state['build_info']['args'][0];
  $form_state['redirect'][] = drupal_get_destination();
  $form_state['redirect'][] = array('destination' => 'node/' . $initial_values->nid . '/edit');

  unset($_GET['destination']);
  $_GET['destination'] = 'node/' . $initial_values->nid . '/edit';
  drupal_static_reset('drupal_get_destination');
  drupal_get_destination();
}


Do not create new nodes, only update existing I have a CSV feed that contains only prices and stock levels. The feed has to update only stock and price of existing products. What is the easiest way to block (just "in case") creating new products for the given feed?

First you need to ensure that each created node has a unique id associated with it that Feeds can use to identify it (eg as an existing node that needs updating).

You can set one (or more) of the fields to be unique in the node processor mapping section (admin/structure/feeds//mapping):

My example takes the generic 'Item GUID', I would suggest that you might instead map SKU to GUID and then set that to unique (make sure to click both update and save).

You then change the node processor settings to Update/Replace:


Drupal 7 views grid format slideshow I am using drupal 7, I want to show the two columns of image with previous and next button on the top. The previous and next button will be used to show the grid format images. I can tried with views grid format, but how can i show the previous and next link of the view? Thanks in advance.

Regards,
Sathish

You can create slideshows using Views Slideshow module. You can add thumbnail images below the main slide image. There is a setting already there in views slide show settings.

See this : Create an Image Slideshow with Drupal using Views


Some links in admin not working correctly I know this is a pretty "broad" issue, but I have several links in the admin interface that are not working correctly. One place in particular is in the Rules section of admin. When I edit a rule and add a new Condition, the "Data Selectors" fieldset text is not clickable (so I cannot expand it to see all of the available data selectors. Also, when I click in the "Data Selector" textbox field, the autocomplete is filled with "

" html wrappers around the data selectors. The attached screenshot shows both of these issues.

What would cause this? So far I have tried switching to Bartik theme (I use Seven as my default admin theme)... no change. I also updated all modules and updated Drupal core to the most recent version (7.27). My next step will be to disable modules, but I am quite hesitant to do so since I "need" all of the modules that are currently installed. I would appreciate any feedback and ideas on what might be causing this, and how it can be fixed.

Thanks!

I finally got an error message to work with (TypeError: this.jqObject.data(...) is undefined), which led me to this solution:  https://drupal.org/comment/8677587#comment-8677587:

Hi guys, I am pretty new to Drupal and programming in general, so pleas bear with me... I got the data selector working by configuring the jQuery_update module:
Default JQuery Version: 1.7
Alternate JQuery Version: 1.7
JQuery Compression Level: Development (I doubt this should make any differences)
JQuery and JQuery UI CDN : JQuery


Content types are missing I'm working with a drupal 7.50 installation on a local host.

My problem is that the basic content types are missing from my site. My custom content type is still visible and usable.

So far, I have checked under all menus to see if they've moved or been disabled, but I don't even see them. I've also tried clearing my cache, which didn't fix it.

Some of the modules I have enabled are drupal commerce, display suite, panels, and search api.

Any help would be much appreciated.

It seems like you are running a Drupal that was installed with the minimal profile. That profile does not create the Article and Basic Page content types. So, they are simply not there, clearing the cache will not help.

In order to get the content-types back you need to either:

a) Create them manually
b) Use the parts of the standard_install() function from profiles/standard/standard.install file that are additional to the minimal_install() function from profiles/minimal/minimal.install file to add the missing configuration. Kind of tricky, but not too much code there all in all.
c) Use the Features module to transfer the configuration of the content-types you are missing from another site installed using the standard profile.

N.B.: You know that already, but still, you should keep backups all the time, this may need a couple of try-n-error runs.

Good luck!


Using Ajax, how can I populate a div with Database Content from a form select? This is what I have so far. I can populate the select field just fine, however when another option is selected I can not get the data to populate in the ajax callback div.

function product_comparison_menu(){
  $items = array();
  $items['design_product_comparison'] = array(
    'title'            => t('Product Comparison'),
    'menu_name' => 'menu-main-menu',
    'page callback'    => 'drupal_get_form',
    'access arguments' => array('access content'),
    'page arguments' => array('product_comparison_form'),
  );

  return $items;
}

/*
* Display output
*/
function product_comparison_form($form, &$form_state) {

  //Query DB for Rows
$query = db_select('product_comparison');
$query->fields('product_comparison', array('id', 'OtherCombo',));
$query->condition('DropdownCategory', 'Exit Devices');
$query->orderBy('OtherCombo', 'ASC');
$results = $query->execute();

    //define rows
$options = array();
foreach ($results as $result) {
    $options[$result->id] = $result->OtherCombo;
}

$form['Exit Devices']['OtherCombo'] = array(
    '#type' => 'select',
    '#title' => t('Exit Devices'),
    '#options' => $options,
    '#ajax' => array(
      'wrapper' => 'product_comparison_ajax_wrapper',
      'callback' => 'product_comparison_form_ajax'
    ),
);

$form['results'] = array(
  '#type' => 'markup',
  '#prefix' => '
',
  '#suffix' => '
',
 );

 // If the form has been submitted, build up your results and display them
 if (isset($form_state['Exit Devices']['OtherCombo'])) {
   $row = db_select('product_comparison')
     ->fields('product_comparison', array('DesignHardware', 'DesignImg','DesignURL'))
 ->condition('OtherCombo', $form_state['Exit Devices']['OtherCombo'])
     ->execute();

   $header = array();

   $form['results']['#markup'] = theme('table', array('header' => $header,'rows' => $rows));
  }
  else {
    $form['results']['#markup'] = '
The results will appear here when you change the dropdown option.
';
  }

 return $form;
}

function product_comparison_form_ajax($form, $form_state) {
  return $form['results'];
}

You need to populate data in the ajax callback product_comparison_form_ajax and then return $form['results'].

Your code should be as the following:

Product comparison form

function product_comparison_form($form, &$form_state) {

  //Query DB for Rows
  $query = db_select('product_comparison');
  $query->fields('product_comparison', array('id', 'OtherCombo',));
  $query->condition('DropdownCategory', 'Exit Devices');
  $query->orderBy('OtherCombo', 'ASC');
  $results = $query->execute();

  //define rows
  $options = array();
  foreach ($results as $result) {
    $options[$result->id] = $result->OtherCombo;
  }

  $form['Exit Devices']['OtherCombo'] = array(
    '#type' => 'select',
    '#title' => t('Exit Devices'),
    '#options' => $options,
    '#ajax' => array(
      'wrapper' => 'product_comparison_ajax_wrapper',
      'callback' => 'product_comparison_form_ajax'
    ),
  );

  // removed result condition

  $form['results'] = array(
    '#type' => 'markup',
    '#prefix' => '
',
    '#suffix' => '
',
    '#markup' => '
The results will appear here when you change the dropdown option.
',
  );

  return $form;
}

Product comparison ajax callback

function product_comparison_form_ajax(&$form, &$form_state) {
  if (isset($form_state['Exit Devices']['OtherCombo'])) {
    $row = db_select('product_comparison')
      ->fields('product_comparison', array('DesignHardware', 'DesignImg','DesignURL'))
      ->condition('OtherCombo', $form_state['Exit Devices']['OtherCombo'])
     ->execute();

    $header = array(
      array('data' => 'Design Hardware'),
      array('data' => 'Design Img'),
      array('data' => 'Design URL'),
    );

    $rows = array();
    foreach ($result as $row) {
      $rows[] = array('data' => (array) $row);
    }

    // assign result to markup
    $form['results']['#markup'] = theme('table',array('header' => $header, 'rows' => $rows));

  }

  return $form['results'];
}


Change rendered content in template I created a custom node template in order to change what fields are generated.

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

        ?>

The above php code renders the following html:

 lindamanual.pdf

The problem is I only want the href to be rendered (not the image and the outer div). How can I do this?

In the display settings of your field, you can choose to display the "Rendered Content" (what you actually have) or only the URL of the file ("URL to file"). This should only give you the file URL.


Remove white spaces from inline form-inputs If there is a form generated by drupal form api in template file, is there a way how to remove whitespaces between .form-input html elements?

My template looks like this:

            <form action="" method="post" id="activit-grant-filter-form" accept-charset="UTF-8">

<?php echo render($form['organisation_type']); ?><?php echo render($form['locality']); ?><?php echo render($form['support_type']); ?><?php echo render($form['thematic_objective']); ?>

                    <?php echo render($form['submit']); ?>
                    <?php echo drupal_render_children($form); ?>

            </form>

As you can see I'm using comments between form elements, but they're still keeping whitespaces in between.

Set form font size 0 and increase font size of input

form {
    font-size: 0;
}

form input {
    font-size: 12px;


How can I allow users to send private messages without revealing sender's address? I have a community application which allows users to send private messages and it is built using 'Private Message' module. When a message is sent, the recipient sees the sender's original email address which he has used to register with the system. I would like to use a system generated email address without revealing sender's original email address.

The 7.x-1.x branch of Private Message has this setting in the PM Email Notify submodule. When enabled, there is a E-mail notify tab on the settings page (/admin/config/messaging/privatemsg) that allows you to configure the email's from header.

By default, if this is blank, it will use the site's default system email. It sounds like the module is configured with another token that's referencing the sender's init email.


Admin overlay intermittently fails I wish I could provide a more specific example of this, or some event that seemed to trigger it, but here's the best I can do:  I have happily used my admin overlay for most of my CMS work for months now in D7 with the Bartik theme.  And the other day, mysteriously it became the case that when I am browsing my site, I will "fall out" of admin overlay mode sometimes.

I just am suddenly on a page as an anonymous viewer would be, with neither the overlay, nor the standard edit, track, etc. content tabs of an admin user.  I can still hit the back button, to return to it, and I can still directly enter administrative menus, but an occasional page, and not always the same ones, cause me to fall out of admin mode.

Does this sound like any behavior anyone could identify, or help me identify a process in order to identify?

I think it was a PHP memory limit.  I upped that, and don't seem to have this problem anymore.


Views : hide thumbnail for all but one content Ive created a View called "most recent articles" that are made up of 4 contents. I have the thumbnail displayed along with title, body and tags for each content. This is sorted by Most recent article by published date. How can I only display the thumbnail for the latest content (1) but the other 3 articles not display the thumbnail at all?

The module Display suite gives the option to add different views mode for different rows. Here is a video tutorial ,in this lesson you cover how one can use view modes and display suite to allow multiple options of layouts for content display. This allows a user to have a different layout of the same content for different scenarios of the site. Combining this with views and you can start to see the power of display suite in action.


How do I assign 'all' term to a node? I have a vocabulary (lets name it as 'Brands') which is getting filled by adding terms while creating a nodes.

I have a view which shows me the list of those nodes. This view has an exposed filters including the one filters nodes by Brand. There are nodes which must relate to all 'Brands'.

It is not possible to assign manually all existing brands to node while creating it because the vocabulary is kinda dynamic. That means they should pass filter with any term checked. Not when 'All', but when any of existing. It seems to be obvious but I can't see any way I can do that.

it was so stupidly simple... Just don't add any term and add a filter to the view

having Brand one of .... OR having Brand empty(NULL)

I should definitely stop looking for a complex solutions for a simple questions. Thanks anyway


Inserting jQuery corresponding to a certain element ID I have a website in which I want to apply a custom drop down menu to a block. However, I have no idea how to go about doing this.

I posted this yesterday and came to the agreement that the jquery was to be added from a separate location, but I do not know where to implement it! I was wondering if perhaps this should be added to the /modules/block/ location or if it should be called elsewhere.

The content that I want to edit may be seen at mag-ds.com in the lower portion (the entries with #id=T_roll.

Help?

You can add a javascript file from a module or a theme, whatever is most appropriate. For scripts that should be loaded on (nearly) all pages, just add a line to the .info file of your module or theme:

scripts[] = somescript.js

For scripts that you only want to load in certain occasions, use the drupal_add_js module. See Managing JavaScript in Drupal 7 for details.

That said, there are a lot of modules out there for drop down menus, so that may even be easier. Check Comparison of various drop down menus for instance, or simply search drupal.org or drupalmodules.com.


Dynamic profile2 fields - User can add more fields while registration how to add dynamic user registration fields . I need a phone number field which can be added by users during registration by pressing "add more" button as many times he wants .

Is it possible ? or any other approach ?

thanks

I think you can use the Field Collection module.


Use calendar.module in my custom module I am creating a module with 2 tabs, a short term calendar and a long term calendar.
I made the tabs, but I'm already stuck..

How can I implement calendar.module to show a calendar on each tab?

This is the code of my tab:

  $items['planning/longterm'] = array(
    'title' => 'Long Term',
    'access callback' => TRUE,
    'page callback' => 'planning_page_longterm',
    'type' => MENU_LOCAL_TASK,
    'weight' => 10,
  );

In my callback function I try to call the calendar.module via this piece of code:

  if (module_exists('calendar')) {
    print theme('calendar_date_default_argument_alter', array('#item' => array('year' => '2013')));
  }

I would second the comment on trying out Views. You should be able to achieve what you want with the menu tabs and a specific calendar on that page with Views. Maybe try checking out the documentation. Without more detail in your question it is hard to say, but I'm pretty sure you don't need to make a custom module to do what you have written so far.

Also you probably should also specify which version of Drupal you are using. I'm assuming 7 but it is always better to let people know.


Drupal 7 db_query using CAST Does Drupal 7's DB API support SQL's CAST function? I have a varchar with numbers in it that I'm trying to convert to integers for proper sorting. Here's my statement:

$images = db_query('SELECT filename, caption FROM {iha_captions}
WHERE uid = :uid ORDER BY CAST(weight AS INT) ASC', array(':uid' => $userid));

And here is the error I get:

  PDOException: SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'INT) ASC' at line 1: SELECT filename, caption FROM {iha_captions} WHERE uid = :uid ORDER BY CAST(weight AS INT) ASC; Array ( [:uid] => 2814 ) in iha_search_profile()

It then causes a cascade of SQL failures in Drupal's session and cache queries. Is CAST supported, or am I doing it wrong?

It's not a Drupal error it's a MySQL error. CAST() won't accept INT as a valid type but does give you a choice between SIGNED and UNSIGNED to cast to an integer type.

The following query runs fine for me in Drupal:

SELECT * FROM node ORDER BY CAST(nid AS UNSIGNED)


How do I create a new variable? I want to use a new variable in a view using global PHP. Between the available variables, I have $row->my_field, and I want to put its value in a new variable.

$new = $row->my_field;
echo $new

I'm using this code in Output Code. I get the following error:

  Syntax error, unexpected 'echo' (T_ECHO) ...

I cannot even use array_unique().

Is it possible to add a new variable? and Is it possible to use a function like array_unique()?

Is it possible to add a new variable?

YES

  Is it possible to use a function like array_unique()?

Yes, as long as you have an array to pass as a parameter.

PS: You shouldn't be using Views PHP to begin with; you should create a template file for your view and add the PHP code there.

What are the downsides of using PHP Filter code in blocks, nodes, views-args, etc?


Change default Taxonomy value on form via form alter in D7 I am trying to alter a form with a taxonomy term select drop down field; I want to change the default term selected when the form loads.  I'm altering the form array via hook_form_alter; however, my changes do not seem to be taking effect.  I'm looking for an answer similar to this but for Drupal 7.

I'm expecting :

        $form['field_mytax_reference']['#default_value'] = array($taxTermId => $taxTermName);

to do the job but the form remains with the default specified when the field was created.

Thanks in advance.

It'll be something more along the lines of:

$form['field_mytax_reference'][LANGUAGE_NONE][0]['#default_value'] = $taxTermId;

If the field is a multi-select you would wrap the default value in an array, but there's no need to set a key for it:

$form['field_mytax_reference'][LANGUAGE_NONE][0]['#default_value'] = array($taxTermId);

Have a look at Why is hook_form_alter() so messy? for a bit more info.


Menu is not highlighted when viewing its corresponding page I'm using D7. In it, one of the menu in left sidebar is not highlighted when viewing its corresponding page.

Case 1 : If I gave the path to the menu link as node/15, it is highlighted but the anonymous user can't see the menu at all.

Case 2: If the path will be www.sitename.com/blah/blahbla means its not highlighted and the anonymous user can see this menu.

Since that page is not to be accessible by anonymous user, hence this problem?
Can any one help me to get rid of this?

I put a condition for that node and added the style for the menu in the page.tpl.I don't know is this is the right solution.But it worked for me.


Consume external API from custom block I am currently writing a custom module - block plugin for Drupal 8 - How do i go about consuming/sending external API data and displaying them using blocks?

Is this the standard way - consume/send external API data via plugin directly or through a controller and output it to a twig template?
If so, how do i send data from controller to a custom plugin block?

Any suggestion is welcome. Thank you.

I'd do it this way:

Create a custom module
Create a class inside the src folder that consumes the API
Create a custom block inside your module: call the class there

Mostly it is better to fetch f.e. each hour and save the api data to custom entities. In this way you can cache the content in the block which enhances performance.


How to implement menu in footer blcok I need a (D7) block print the main menu in the footer; It's not clear to me how the pieces fit together:

We implement block_info, block_view, a pre-process function and a template.

function MODULE_NAME_block_info() {
  $blocks['my-footer-menu'] = array(
    'info' => t('My Footer'),
  );
  return $blocks;
}

function MODULE_NAME_block_view($delta = '') {
  $block = array();
  switch ($delta) {
    case 'my-footer-menu'
     $tree = menu_tree_page_data('main-menu');
     $block = array( 'subject' => t('My Footer'),
                  'content' => theme('my-footer-menu', $tree),
      );
    break;
 }
return $block;
}

function MODULE_NAME_theme() {
  return array(
    'my_footer_menu' => array(
    'template' => 'my-footer-menu',
    'variables' => array('tree' => NULL),
  ),
);
}

function template_preprocess_my_footer_menu(&$variables) {
  $variables['tree'] = menu_tree_all_data('main-menu');
}

<?php
  for ($i = 0; $i < count($tree); $i++) {
    $menu = each($tree);
     if ($menu) {
        $link = array( '#theme' => 'link',
                'title' => $menu[1]['link']['link_title'],
               'href' => $menu[1]['link']['link_path']);
          print '' . $link['title'] . '';
        //  $output = theme( 'links', $link);  //this isn't right
        //  print $output;    //returns an empty string;
        }
      }
 ?>

The above gets the top level menu items on the page, but it's not clear how to get to the children of each menu item.   Sorry if it seems a bit muddled, just trying to cut my way through the weeds here.

You can create all of the code yourself, but you could also use the menu block module instead and save yourself a lot of work.


How can I control class="active" in a submenu I have a view with several exposed filters, they work fine. I added the unfiltered view in the main menu. Then I copied the urls of the filtered results to add them as submenu.

The "active" class is attibuted to the ‘better exposed filter’ links in the form I show to my visitors, ahead of the view.
But only one of the submenu links is attributed that "active" class, even though it doesn't fit the displayed result. Does anyone see where the problem can come from?

See for yourself: https://nature-et-sens.eu/boutique.

Edit ----
I figured that the problem is slightly different. Here is what the  submenu looks like (roughly):

…

…

    …

…

The only  item which is properly styled is the one contained within the
. I have no problem with that, my stylsheet complies accoardingly.

I would like to understand why this 'active-trail' class is always  attributed to the very same item, even though it is not the one I clicked.


How could I automatically delete accounts with a given criteria? My drupal site has a textarea field in the new user application that asks for the new user to explain what their interest is in wanting to join the site.  Some sort of machine bot is sending a dozen or so requests for accounts daily.  Characteristically, this machine bot is putting two random characters into this "interest" field.  Therefore, I know that any account with only 2 characters in this particular field is this computer bot since no answer to this question on the application could be acceptable with only two characters.

I would like to know if there is a way that drupal can delete such accounts with only two characters in this particular field automatically by using a set criteria (e.g. a field containing only two characters).  How could I go about this?  It would be ideal to have Drupal NOT send an email message at all that a new user has signed up when this occurs, but if that is not possible, then can I do something to automatically delete such an application when the length of the field is only two characters?  I am looking for a Drupal method of doing this rather than a cron job method of doing this.

I realize that one could just use a field validation to start with but that won't answer the question: Can Drupal actually use some sort of specific field rule (e.g. a certain field must have more than x number of characters) to delete accounts automatically so they wouldn't have to be deleted manually and constantly by the administrator.

You may not be able to stop the email being sent. But you can set up a rule to block the user to trigger on the event 'Before saving user account'.

You will require two conditions. First use the condiiton 'Entity has field' and check for the 'Reasons to join' field. This will make the field visible to subsequent conditions. The do a 'Data comparison' on account-unchanged:profile-main:user:field-reasons-to-join and check for your two charcter text. If the conditions are met use an action to 'Block a user' using account-unchanged:profile-main:user.

EDIT: Since your users are blocked pending admin approval, perhaps you should be looking at the Field validation module. With it you can specify a minimum length for the field (making sure you let your users know in the guidelines that the minimum length is required). You could also set up a field hidden with your css which you would require to be empty. Bots would likely fill it in with something.

You should also have a look at the Spambot module which uses the api at stopforumspam.com to catch known spammers. While it is not perfect (nothing is) it will certainly cut down on the number of bots that get through.


Add shiping cost on add product page Can some one please tell how it is possible to add the shipping prices from Add Product Page. Actually I want to add the field on product page where the store admin can define the rates for each specific product type.

I wrote a module that does this!

https://drupal.org/project/commerce_shipping_field

It allows you to define a shipping cost for each individual product. Let me know if you have any other questions!


How do I log in as a different user when there isn't a login link on the front page? I created a user with limited rights and logged in as that user.

Now I have discovered that I have not placed a login module on the front page.

How do I log back in as administrator?

Click logout - usually in the top right corner (but may vary depending on theme); /user/logout is the address.

Then log back in (from /user) with your administrator credentials.


Is there an option in the Views 3 UI to reset one section of a non-master display to the default state? I've got a view that contains several different displays.  When I override an option for a single display, the header for that section is displayed in italics.  For example, if I override the Filter Criteria for a single display, Filter Criteria is shown as Filter Criteria on that display.

Is there a way to revert overridden sections (Filter Criteria, Fields) from within the UI if I change my mind about overriding?  Of course I can manually re-create the settings to match those of the master, but this is a pain...

Yes, just edit a filter or field and choose "revert to default"


Alternative link to download modules from drupal.org I am unable to download these modules for Drupal 7. It shows the "Not Found" error.

https://www.drupal.org/project/search_api_solr
https://www.drupal.org/project/fuzzysearch

Is there an alternative link to download these modules?

Click on the version control tab on the module page and it will give you instructions to download it via Git.

To get up and running with Git look at Installing Git.