Clear Varnish Cache (and maybe Views?) for Home Page when new story posted Drupal 7.

I run a site for a large publishing company.  We're on Acquia Cloud, using Varnish to serve cached pages to anonymous users.  Home page has a couple Views - one is a running list of news stories, and the other a Featured slider.

My minimum cache lifetime is set to 5 minutes, and Expiration of Cached pages to 15 minutes. On each View I have Content-based caching enabled.

I'd like to have new stories immediately shown on the home page. I believe I should only have to worry about the Varnish cache, that Content-based caching on the Views should be handling those caches, though to be honest I'm unsure of how to accurately test all this.

I read up on some things, and I found modules like Cache Expiration or Purge, and I think I'll also need to install Rules and maybe Cache Actions.  I just figured I'd post here to see if someone else had experience with this and could offer some direction.

Install the varnish module and set the minimum cache lifetime to none at admin/config/development/performance Also be sure to add the tweaks to the settings.php from the varnish module page.

This should ensure that the cache is flushed when new content is added.  You may want things to be a little more granular (if a complete cache clear at every content update would overload your server and cause performance problems) so using here are some other steps you can take:

I found a nice article about using varnish which you might consider checking out.

The author recommends:

Go to the Varnish settings page (admin/config/development/varnish) and select "None" under "Varnish Cache Clearing". This will make sure that all pages are not flushed when content is altered.

Enable the Cache actions and the Rules UI module
Go to Administration => Workflow => Rules and click "Create a new rule"
Select "After updating existing content" under "Node" as the reacting event
Add the "Clear a specific cache cid" action
Select cache_page as your cache bin.
Put "node/[node:nid]" in the value text area.

Try to edit one of your nodes, everything should still work. The difference now is that we are actually only purging the entry of the particular node that has been edited not the whole page. You can try this by visiting another node, notice that it is still cached by looking at the Varnish headers.

You will probably also want to clear the views cache (for your relevant views) so they are updated instantly.  Testing should be relatively easy by adding new content in a browser and refreshing another browser window that isn't logged in.  You should see your new content appear immediately at refresh.


Can I use --remote-host without a site-alias? I am trying to use Drush to execute some commands as part of my CI/CD workflow. The problem is that due to it's flexibility I want to avoid using site aliases which would basically mean writing temporary files during the build process (I really want to avoid that).

However, I've been trying to use --remote-host, --remote-user and --root in-line (e.g. 'drush --remote-host=example.com --remote-user=exampleuser --root=/var/www/example.com') without success. I did some debugging with XDebug and it seems that even though Drush initially picks up the provided command-line options it later purges them again/overrides them at some point. Is that a Drush Bug or am I doing something wrong / missing something?

Will do some further debugging now but maybe someone knows the answer ;).

Drush internally converts site aliases into command line options before doing a remote dispatch, so I would expect that you should be able to make --remote-host work without creating an alias.

Here is something that I tried.

$ drush @live sql-conf -v
Calling proc_open(ssh -o PasswordAuthentication=no user@server.org 'drush  --verbose --root=/srv/www/drupal/htdocs --uri=http://site.org  sql-conf 2>&1' 2>&1);

$ drush --remote-host=server.org --remote-user=user --root=/srv/www/drupal/htdocs --uri=http://site.org sql-conf

The first version, with an alias, worked, but the second invocation with cli options got confused, and tried to execute the command locally.  I got the same result in 6.x and 5.x, so I guess this has been broken for a long time.  I created a bug report on GitHub for this:

https://github.com/drush-ops/drush/issues/369

Fortunately, there is one more option.  Drush will let you craft an alias on the command line, by combining the different elements of the alias record in a special form, "user@server/path#site".  So, I did this:

$ drush user@server.org/srv/www/drupal/htdocs#site.org sql-conf -v

That worked.


Custom Entity Not Showing in View Creation UI I started learning Drupal 8 this week. I followed this guide to create a new entity, which I then made available through REST using the following tutorial: https://drupalize.me/blog/201401/introduction-restful-web-services-drupal-8

CRUD operations on my entity work just fine. I can also issue my REST requests without any issues. What I'm trying to do now is fetch a list of all my entities via REST. From my understanding, I should create a view for that, but my entity doesn't show up in the view creation UI, so I can't. What do I have to do to make my entity show up there?

I'm not sure what code I should post, so don't hesitate to tell me what code you need to see.

You need to add a views_data handler, like this:

"views_data" = "Drupal\views\EntityViewsData"

That exposes your entity as views data.

That is the default implementation, which does a lot, but you might need to subclass that and extend the definitions if you need additional filters/fields/...


How to add an extra form action on the user login page? I would like to add a link to the user registration page on the user login page. As I want the link to be placed right next to the Login button, I thought that adding an extra form action would be the easiest way to do this.

Should I add/edit some template or is there a hook for this?

Use hook_form_FORM_ID_alter() in order to modify the specific form.
You can add the action or the link there.
The link can be added using the #prefix,#suffix attributes of either the form or of a specific element.

Prefix example:

$form['#prefix'] = l(t('Link text'), 'my link');

Action example:

$form['actions']['add'] = array(
  '#type' => 'submit',
  '#value' => t('Add'),
  '#submit' => array('_my_callback_function'),
);


What is hook_field_default_fields()? I'm looking through a Drupal 7 module code in an attempt to understand what it does. It implements hook_field_default_fields(), but I can't find any documentation on this.
What does this hook do?
I did find that the Field Types API seems to expose similar hooks such as hook_field_extra_fields(), but they aren't exactly the same.

It's a hook used from the Features module. Truly, the feature.api.php file, which should contain a description of all the hooks used by a module, contains a description for hook_field_default_fields_alter().

Deprecated as of 7.x-2.0.
Alter the default fields right before they are cached into the database.
@param array[] &$fields
By reference. The fields that have been declared by another feature.
@deprecated

Usually an alter hook is paired with a "normal" hook, but that is not always the case.
If you see that the hook is always invoked with drupal_alter('field_default_fields', /* the other arguments */), the module uses only the alter hook. Checking if the module itself implements hook_field_default_fields() or hook_field_default_fields_alter() would also help to understand which hook is used from the module. Unfortunately, in this case, the module doesn't implement neither one or the other hook. This is easily explained from the fact the hook has been deprecated. (A module should be the first one not to implement its own deprecated hooks.)


Publish nodes with drush? I'm faced with the situation of needing to be able to publish content with Drush.  Is there a way to use Drush to publish nodes?  If there is, how can it be done?

I am not sure if that is available by default (found no result on searching), but one thing that you can do is declaring your own Drush command in 3 easy steps:

Creating the Command File:

  ( Give the right name to the command file and place it into a folder that Drush will look, That name must end with .drush.inc (in our case it will be publish.drush.inc) and must be placed either in the folder of a custom module on your site (will work for that site if the module is enabled) or in the .drush folder in your server’s root directory).

Declaring the Command Function: To declare a new Drush command you have to invoke hook_drush_command() in the file you created above and below the php opening tag. Example as below:

  function publish_drush_command() {
    $items = array();
    $items['publish-content'] = array(
      'description' => 'Publish content',
      'aliases' => array('pc'),
      'arguments' => array(
        'type' => 'Nodes of this type will be published',
      ),
    );
    return $items;
  }

Note: This command is declared in a file that has been placed in the .drush folder that resides in the VPS’s root folder.

Here we have declared a new command called publish-content (a new key in the $items array). The description and what’s included in the arguments key is what you will see when you run the drush help publish-content command. What’s actually helpful here is that you can also specify an alias (or shortcut) that can be run instead of the longer publish-content version. In this case, drush publish-content will equal drush pc.
3. Declare the Command Callback Function: Now you need to write the code that you want Drupal to perform when you run the custom command. The name of the function needs to be in the format: drush_command_name. (Note: dash in the command name becomes an underscore in the function name).

function drush_publish_content($type) {
  $nodes = node_load_multiple(array(), array('type' => $type));
  $count = 0;
  foreach ($nodes as $node) {
    if($node->status == 0) {
      $count++;
      $node->status = 1;
      node_save($node);
    }
  }
  if($count > 0) {
    drush_print($count . " nodes of the " . $type . " content type have been successfully published.");
  }

  else {
    drush_print("No nodes of the " . $type . " content type were published.");
  }
}

This callback function takes as argument the machine name of the content type of all the nodes we want published. This gets passed as a command argument like so (Example: pulish the contents of blog content-type):

  drush publish-content blogs

Drush will then print out how many nodes have been published (displaying only the number of nodes that have been in fact affected by the command).

References:
https://www.digitalocean.com/community/articles/how-to-declare-your-own-drush-commands-with-your-vps
https://github.com/edvillan15/node-tools/blob/master/node_tools.drush.inc


Awarding points with Rules for uploading a user picture Does anyone know how to create a rule that awards points to a user for uploading an image?

Have a look at the "User Points" (https://drupal.org/project/userpoints) module.
It has rules integration (among many other modules) so this may be the one you're looking for. It also provides a hook API by the looks of it, so if you need more custom functionality than what it offers by default, you should be able to perform actions from within a custom module.


View restricted to a specific taxonomy term I have a custom content type called Property with taxonomy term fields set up for example for vocabularies Train Station, Style, and Area.

I would like to create a view showing only those Properties with a specific term within the taxonomy for example only the ones with the term London Bridge in the Train Station vocabulary.

I assumed this would be Filter Criteria in the view, however the only related option I can see is Content:Has taxonomy term which brings in all Properties that has Train Station - but I cant see how I can add the extra filter of only London Bridge within Train Station

Any ideas?

Assuming I understand the question correctly - potentially the easiest way to achieve this is to add a 'Term Reference' field to your 'Property' content type.

This needs to point at the taxonomy 'Train Station', and you can have multiple term references if you need other terms to describe properties.

You can then use this term reference field as a view filter. You'll be looking for "Content:term_reference_field_name" as opposed to "Content:Has taxonomy term" This will allow you to filter on a particular taxonomy term.

Good luck!


How do I tear out the existing menu in a theme and replace it with super-fish (v7.x) I know this is similar to the Bartik/menu question but I do not believe it is the same, here is the requirement. I am using "the morning after" theme in Drupal 7. This theme looks the way the client wants it but we need a drop-down ability on the "main menu", the menu that runs horizontally across the top of the page. This theme does not have a "navigation", "main menu" or similar region to pop super-fish into. I have tried all the instructions in the Bartik/Super-fish post and I can get super-fish to show up in an region but I have not been able to get it to REPLACE the existing embedded-in-the-theme menu. Any help is greatly appreciated.

This site would not let me post an answer, so as an edit, here is the answer I found.
This did not get me 100% where I wanted but found this on another post. It is for a different theme but it seemed to be essentially the same. hope it helps

Im using Drupal 7 with the Busy Theme and I can't figure out how to set Superfish to replace the existing main menu with itself. I can add Superfish to other regions of the theme and it works great, but there is no way to replace the main menu with Superfish that I can find. This may be a problem in that the main menu area of Busy doesn't seem to have a region set to it, so perhaps that could be the problem...

Thoughts? I want to use a drop-down menu for the main user menu, but nothing I do will allow Superfish to replace that main menu.

Description Login or register to post comments Comments

1
Posted by Mehrpadin on April 1, 2011 at 7:54pm Hey there,

Well, normally you should ask the theme developer, but as I see there are a number of similar requests in the issue tracker of the theme, I think I should help you myself:

Create a new region by putting the code below somewhere in busy.info regions[navigation] = Navigation You may need to rebuild your theme registry. /templates/page.tpl.php , line #52 to #58: $main_menu, 'attributes' => array('id' => 'main-menu', 'class' => array('links', 'clearfix')))); ?> Replace with this:
Voila!

Superfish will not override your theme's main menu. The only way is to make its block and place it on some region.

You can replace the theme's menu variable/function with a region variable in your page.tpl.php following a guide here.


How to add HTML5 attribute "autocomplete" to form fields? According to an accessibility test, I have to add the HTML5 attribute "autocomplete" an the proper tags to all form fields on my website where the user fills in his/ her personal data.

E.g. "Your E-Mail" > autocomplete="email", "Your Family Name" > autocomplete="family-name", etc. (The proper tags are listet in the WHATWG HTML standard https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#autofill)

Some of the fields are in Drupal core (like the user registration form), others are webforms (like an event registration).

What is the best way to achieve this in Drupal 8?

I think it's possible to add this attribute to all input fields using a bit of JS, something like this should work:

(function($, Drupal) {
  Drupal.behaviors.autocompleteFieldBehavior = {
    attach: function (context) {
      $(context).find('input').each(function () {
        var name = $(this).attr('name');
        if ($(this).attr('autocomplete').length === 0) {
          if (name) {
            $(this).attr('autocomplete', name);
          }
          else {
            $(this).attr('autocomplete', 'Default autocomplete value.');
          }
        }
      });
    }
  };
})(jQuery, Drupal);

The other solution would be alter all forms using hook_form_alter, see @berramou's comment.


How to clear cache externally? I'd like some help how to clear the cache using an external script. I have a script that adds nodes each night, and I'd also like it to clear the views cache so - without having to make out by myself the MySQL query.

If you are running a script, you'll likely benefit from using Drush.  With the Drush php-eval and php-script commands, you can easily call a snippet of php code (such as the examples shown in other answers to this question) after bootstrapping Drupal.  Without Drush, you would have to set up a web service and use wget or curl to run your code, or try to call the Drupal bootstrap code yourself.  Better yet, Drush even comes with a built-in command to clear the cache, so you don't need to worry about writing any php code at all, if that's all you want to do from your script.  Just use:

cd /path/to/drupal/sites/default && drush cache-clear all

You may also wish to learn about site aliases; if you define an alias called @site, then you can instead use:

drush @site cache-clear all


Right way to update a drupal distribution? I have a site which is a Commerce Kickstart distribution.

My distribution version is 7.x-2.0-rc1 and now the 7.x-2.0-rc2 version is available.

How do I update a distribution? I tried these method (both failed...)

1) I follow the update standar process using the drupal ui. I get this error message:

>     Notice: Undefined index: version_major in update_calculate_project_update_status() (line 595 of
> /Applications/MAMP/htdocs/mySite.com/modules/update/update.compare.inc).
>     Downloading updates failed:
>
>     commerce_kickstart-7.x-2.0-rc2-core.tar.gz does not contain any .info files.
>     Notice: Undefined index: version_major in update_calculate_project_update_status() (line 595 of
> /Applications/MAMP/htdocs/mySite.com/modules/update/update.compare.inc).

2) I downloaded the distribution and replace the folder mysite.com/profiles/commerce_kickstart
This didn't work neither.

¿Which is the right way to to do this?

You should try it with drush.

drush dl commerce_kickstart
drush updatedb -y

(I have not tried it for commerce kickstart; I just got the answer on drupal.org.)


Using Views to filter the content based on the current month I am building a site, using Views, that needs to filter the content for each month. I have created a date field on the custom content type, and I made a publish start and end date fields.

I need the view to change the content at the start of the new month. Can anyone please explain how to make a view only display content based on the current month?

In the latest versions of Views, you can use a date argument to do this.  For example, you could select the node post date as a date to use with the argument, and then if you passed 2011-12 as the argument, it would limit the display to only nodes posted in December 2011.  You can use any ISO date for this, too, so P1M, which means a period of 1 month, would create an argument for the current month.  Check out http://en.wikipedia.org/wiki/ISO_8601 for an indepth explanation of a lot of different ISO date formats.  All should work here, the only one you have to be careful of is the interval format; with drupal you need to use -- instead of / to separate them for hopefully obvious reasons.

If, however, you are wanting to group or aggregate your content by month, check out http://drupal.org/node/388140.


Unexpected MYSQl error 1286 I am using shared host and after some problems they restarted the server and my Drupal website shows the following error:

PDOException: SQLSTATE[42000]: Syntax error or access violation: 1286 Unknown table engine 'InnoDB': SELECT

This is the full log

Error message

  PDOException: SQLSTATE[42000]: Syntax error or access violation: 1286
  Unknown table engine 'InnoDB': SELECT
  field_data_media_gallery_expose_block0.entity_type AS entity_type,
  field_data_media_gallery_expose_block0.entity_id AS entity_id,
  field_data_media_gallery_expose_block0.revision_id AS revision_id,
  field_data_media_gallery_expose_block0.bundle AS bundle FROM
  {field_data_media_gallery_expose_block}
  field_data_media_gallery_expose_block0 WHERE
  (field_data_media_gallery_expose_block0.media_gallery_expose_block_value
  = :db_condition_placeholder_0) AND (field_data_media_gallery_expose_block0.deleted =
  :db_condition_placeholder_1) AND
  (field_data_media_gallery_expose_block0.entity_type =
  :db_condition_placeholder_2) AND
  (field_data_media_gallery_expose_block0.bundle =
  :db_condition_placeholder_3) ; Array ( [:db_condition_placeholder_0]
  => 1 [:db_condition_placeholder_1] => 0 [:db_condition_placeholder_2] => node [:db_condition_placeholder_3] => media_gallery ) in field_sql_storage_field_storage_query() (line 577 of
  /home/fossisor/public_html/techiestuffs/modules/field/modules/field_sql_storage/field_sql_storage.module).

What is wrong with the database ?

Sounds like your hosting provider does not support InnoDB. There are a few others like you, here is a discussion thread with some ideas on how to fix it http://drupal.org/node/1089724


Difference between "site:current-user:field-foo" and "account:field-foo" in setting a Rules condition? What is the difference between "site:current-user:field-foo" and "account:field-foo" in the Rules "Add a new condition"?

As I mentioned in the comments the variables you have available to you in a rule depend on the context it's in.

[site:current-user] is a global token available to any rule and will always return an object relating to the currently logged in user.

The [account] token is there because you're responding to the "After saving a new user account" event; that event passes an object relating to the user object that has just been saved (for obvious reasons).

I guess the main distinction is that the former will always give the currently logged in user, while the latter could be a different user object altogether (if, for example, an administrator had created the account).


Create "show all" link in Views pager I have created a view that displays titles of contents created by authenticated users. I have used pagination to display specified number of items per page. Besides this I want a "show all" link that when clicked displays all contents on single page I have enabled the views pager "more" link but this link redirects back to the same page besides displaying all the remaining contents.

How can I show a "show all" link in my pager?

The best way to achieve this is to create a separate page display for all content on a single page.  Then add a Footer to the title display with a link to the full page display.


Trouble recreating my site locally My online site gives "server encountered an unexpected error" and the shared hosting site (1and1) gives no log access. So I am trying to recreate my site at home.
I started with a clean install of D8.5, and installed my theme, which works. Then I replaced the database with the SQL dump I made on the host when my site was working. I also copied the modules directory to my site, and carefully copied sites/default/files, but just my image files.
But now my local version wants to reinstall from the start. How do I manage to recreate my site properly?
I could never use backup/restore on my host site--it had an error and would not activate.

So, without knowing more about your production and dev environments, it's hard to say.

Most people would probably advocate moving your codebase with GIT, rather than manually as FTP programs will usually not move files prefixed like your .htaccess file (which maybe causing your whitescreen). If you're going the manual route, I would rsync a copy of your production sites folder, zip it, and the move it to your local computer, install drupal from scratch, then move your files over, set up the db and settings.php for your local environment, run update.php, and profit.


Rebuild node access permissions How can I rebuild the node access permissions?

drupal node:access:rebuild returns the following error message.

  [Symfony\Component\Console\Exception\CommandNotFoundException] There are no commands defined in the "node:access" namespace.

I am using Drupal Console 0.11.3 and Drupal 8.2.0-rc2.

With Drush:

drush php-eval 'node_access_rebuild();'

With Drupal Console:

drupal node:access:rebuild

Which is of course similar to Chamil's answer, but accessible and copy pastable :)


Define relationship with a field? Is it possible to create a relationship based on a field?

In a field settings, I want to set the Relationship to be referencing another field. Does this make sense? I want to turn a field into a relationship.

An example: An integer field is meant to contain version id numbers. So have a relationship from the integer field to the node_revision table.

Per hook_views_data_alter, I came up with code along the lines of the following which seems to work for my example in the question:

$data['field_data_FIELDNAME']['dummy_name'] = array(
  'title' => t('Map field to other db column'),
  'group' => t('Custom mapping'),
  'relationship' => array(
    'base' => 'node_revision',
    'base field' => 'vid',
    'field' => 'FIELDNAME_value',
    'handler' => 'views_handler_relationship',
    'label' => t('Map field to db column'),
    'title' => t('Field to db map'),
  ),
);


Is there a way to show a message to specific users? I would like to programmatically set a message shown at least once for selected users or for all users with a specific role.

Copy the following snippet to your module, then you have to replace MODULE with your module machine name

/**
 * Implements hook_preprocess_HOOK().
 */
function MODULE_preprocess_page(&$variables) {
  $message = t("You have been served!");
        $request = \Drupal::request();
  $session = $request->getSession();
  $message_was_displayed = $session->get('mymodule_message_was_displayed', FALSE);
  if ($message_was_displayed === FALSE) {
    $messenger = \Drupal::messenger();
    $messenger->addMessage($message);
    $session->set('mymodule_message_was_displayed', TRUE);
  }
}


Storing variables in a theme outside preprocessing I have some variables that I want to store in my theme, but I cannot always use theme_preprocess() to set and subsequently gain access to them.

What is the best way to do this?

I would like to not use a module, but with my experience in the past, a module has a hook_install() where an can use variable_set(); Is there anything similar for a theme?

I'm not sure if that's exactly what you're looking for, but Drupal has the concept of theme settings, which allow to configure a given theme with variables.

See http://www.metaltoad.com/blog/how-add-theme-settings-drupal-7 for a great introduction to them.

And according to theme_get_setting(), you can for example store defaults in your theme's .info file, something like

settings[your_setting] = the_value

Should work.


How can I rewrite the output of image field to become a div with this image as a background image? I have a view to display a content that have an image field, and I need to display this image as a background image of a div so I can apply some CSS on it.

what I tried to do is to rewrite the output of this field using twig to be like this:

the problem is that Drupal strips style attribute so the output will be like this:

In D7 I used to fix this kind of issues by overriding the template for the specific field, but I couldn't figure out what is the name of the needed template in D8. when I enabled twig debug it turned out that the field is using the template file views-view-field.html.twig which is the default template for all fields in views, but I couldn't find the needed template name for this specific field in this view, I tried to rename it like in D7 to be views-view-field--page-image--field-image.html.twig (the view name is page_image) but it didn't work out.

any suggestions?

Set all fields to "Exclude from display", add a "Global: Custom text" field and then build your html there using the "Replacement patterns" available.

I assume this still works in drupal 8.


How to update one select element via Ajax when using node_add I have just created a new content type called pieza_musical. What I just want to do is update one select element via Ajax depending on another select choice, a dependant select.

I'm altering the form_node_add using hook_form_alter to inject the #ajax element and replace in the wrapper the previous select rendered by default in the content type.

Everything is working except when it comes to save. I think, due I'm replacing the select via $ajax['method'] = replace, maybe some token is missing and the content type can't be saved.

It show these error messages:

  An illegal choice has been detected. Please contact the site administrator.
  Género: illegal value.

This is my simple code:

function seven_form_pieza_musical_node_form_alter(&$form, &$form_state, $form_id) {
  $generos = taxonomy_get_tree(2,0,1);
  $values_generos = array();
  foreach ($generos as $genero) {
    $values_generos[$genero->tid] = $genero->name;
  }

  $form['field_genero']['und']['#options'] = $values_generos;
  // adds ajax
  $form['field_genero']['und']['#ajax'] =  array(
     'event' => 'change',
     'wrapper' => 'edit-field-subgenero-und',
     'callback' => 'subgenero_ajax_callback',
  );
}

function subgenero_ajax_callback($form, &$form_state) {
  $generoId = $form_state['values']['field_genero']['und'][0]['value'];

  $cat = taxonomy_term_load($generoId);
  $vid = $cat->vid;

  $generos = taxonomy_get_tree($vid,$generoId,1);

  $options = array();
  foreach ($generos as $genero) {
    $options[$genero->tid] = $genero->name;
  }
  $form['field_subgenero_ajax'] = array(
    '#type' => 'select',
    '#id' => 'edit-field-subgenero-und',
    '#required' => TRUE,
    '#name' => 'field_subgenero[und]',
    '#options' => $options,
  );
  return $form['field_subgenero_ajax'];
}

Is it possible to make this is a content type?
Should I create a new entity just for this little purpose?
Should I create a custom field?

Since you're dealing with fields created in by Drupal admin, You may want to check the option values you replaced in the fields that it matches in the field settings.

[EDITED]

Try the Hierarchical Select module. In the page, it also supports Taxonomies.


Taxonomy bulk edit in Drupal 7 I have been trying to find a good, working method to do some bulk taxonomy operations in Drupal 7.

The Administration Views module doesn't appear to work - I just get page not found errors when trying to access any of the views.

So, I have been trying to follow this guide here: http://learnbythedrop.com/drop/166 . However, this is for Drupal 6 and I can't find the corresponding options in Drupal 7. There is no Style option in the view dialog, and Format contains:
Grid
 HTML list
 Jump menu
 Quicktabs
 Table
 Unformatted list, But nothing for VBO.

Can someone help here? This is where drupal really falls down IMO - total lack of up to date documentation and lots of time spent trying to find modules to do simple things which should be in core.

I don't believe there is a really easy way to do this with d7 yet. Views bulk operations will probably be your best bet for the future, as there is work going on to provide this functionality (see: http://drupal.org/node/1142062).

In the meantime, vbo does work with the rules module, so it looks like it might be possible to use rules and vbo together to accomplish bulk taxonomy updates, although I don't think this is trivial. This screencast: http://vimeo.com/26884701 and this comment: http://drupal.org/node/1057158#comment-4792118 might help to get you started.


What happened with AHAH? I notice that all my AHAH forms (in the admin) don't work all of a sudden after I updated Drupal and jquery_update. Now that I am working with building a form with the Form API and want to make it dynamic with AHAH through ahah_helper, it hangs itself.

For example, if I type something into a textfield that is supposed to change on blur, the throbber pops up and I can see that the form is trying to POST the change, but then this error comes up:

  uncaught exception: Syntax error, unrecognized expression: /\x3e\n\x3c/div\x3e\n\x3c/div\x3e"

and it says it's from the jquery.min.js file. I am using 1.5.

I have heard that this can be because of conflicting files in other modules, and I have tried several different patches for those modules; none of them work.

Does anyone have an insight on this? Or should I use AJAX instead?

Better late than never...

Well the problem is in the Drupal server response, which is not valid json. You need to patch drupal_js function in commons.inc.

diff --git a/includes/common.inc b/includes/common.inc
index 80fc911..084b5fc 100644
--- a/includes/common.inc
+++ b/includes/common.inc
@@ -2551,8 +2551,8 @@ function drupal_to_js($var) {
     case 'resource':
     case 'string':
       return '"'. str_replace(array("\r", "\n", "<", ">", "&"),
-                              array('\r', '\n', '\x3c', '\x3e', '\x26'),
-                              addslashes($var)) .'"';
+                              array('\r', '\n', '\u003c', '\u003e', '\u0026'),
+                              str_replace("\'","'", addslashes($var))) .'"';
     case 'array':
       // Arrays in JSON can't be associative. If the array is empty or if it
       // has sequential whole number keys starting with 0, it's not associative


Fix for "'csrf_token' URL query argument is invalid" error during logout I am creating a set of API endpoints for a mobile app using Rest. For User authentication, I am using the default API endpoints supplied by Drupal. That would be

/user/logout?_format=json&token=<logout_token obtained from login api response.>

I wanted to remove the _format=json from the URL parameter and so I created a custom route with the existing controller just for this purpose. However, I am getting an error.

"'csrf_token' URL query argument is invalid

I am not able to figure out how to remove this error. I had added a csrf_token as an additional parameter with the one I got from successful login. It seems however that the csrf token being validated against is generated somewhere else.

I can remove this error by removing the csrf token entry from the routing file entry but that would be a security violation. How do we fix this error or is there a better way to handle the user logout api endpoint.

You can use POST method on /user/logout without params and token, the cookie will be deleted so the user will be logged out, but in the server-side Drupal will not destroy the session, so you'll end up by having a lot of unused sessions...

I wonder why do you want to remove the _format=json from the URL ?


How to use the table header instead of an exposed dropdown to sort a Views table? I have a view where the format display is a Table.

I exposed some field for sorting. The problem with that is, instead of activate the Table Header for the choosen sorting field in order to sort, that's created a dropdown where the user can choose the sorting field.

Is there a way to use to Table Header for sorting instead of this generated dropdown.

Go to Table Setting and check the column Sortable of the field (like the image) and then click the Apply button and Save your view.

You will see the link in the table header


Check if the page is a node using arguments in D7 In Drupal 6, to check if current page is a node, we use the following snippet:

if (arg(0)=='node' && is_numeric(arg(1))) { /* Do stuff. */ }

Since this is a frequently used statement, I wonder if there's a shorter way to do this in Drupal 7, such as something similar to the following:

if (is_node()) { /* Do stuff. */ }

Actually, there is a function that is available in Drupal 6 too: menu_get_object(). With the default values, it will return a node object if the URL for the current page starts with node/[node ID] (where [node ID] is the node ID), and FALSE in the other cases; the function is particularly useful if, after verifying the current page is a node page, you also need to access the node object associated with the page, and the function that is calling menu_get_object() doesn't get a node object between its arguments.

In Drupal 7, there is also another function, but its purpose is just to verify if the current viewed page is the full page view of the node passed as argument: node_is_page().


hook_init() equivalent for console command I have a module which subscribes to the kernel.request event to set some environment variables for use with LDAP. E.g. setting the LDAP_CACERT environment variable. I'm using it to replace hook_init() as recommended at https://www.drupal.org/node/2013014. However, I've noticed that it does not seem to set the environment variables at the start of Drush commands. E.g. I'd want the environment variables set in a PHP console or a cron run. This is part of a re-useable module so just adding it to settings.php is suboptimal.
What's the best way to execute code before any arbitrary Drush command runs?
I've found the console.command event which says:

The COMMAND event allows you to attach listeners before any command is executed by the console. It also allows you to modify the command, input and output before they are handled to the command.

I had hoped that would work with Drush 9. I've added it to my subscriber like so:
/**
  * {@inheritdoc}
  */
public static function getSubscribedEvents() {
  $events['kernel.request'] = ['setLdapEnvVariablesWeb'];
  $events['console.command'] = ['setLdapEnvVariablesCli'];
  return $events;
}

public function setLdapEnvVariablesCli(ConsoleCommandEvent $event) {
  $this->setLdapEnvVariables();
}

but unfortunately it never seems to be hit, even though I can see from drupal debug:event console.command that Drupal does recognize I am subscribed to it.
It would be nice if I could handle this in the same subscriber as for web requests but I am not set on it.

I've found out what's going on with this. It appears that Drush uses its own event dispatcher separate from Drupal's and that's where the console command event is actually dispatched. That means I need to manually add a listener to Drush's event dispatcher like so:
\Drush\Drush::service('eventDispatcher')->addListener('console.command', 'Drupal\mymodule\EventSubscriber\DefaultSubscriber::setLdapEnvVariablesCli');

Unfortunately there's still a problem: I need to add that subscriber somewhere that's called before the start of the command in order to be able to call things before the start of the command.
I ended up having to actually subscribe to the Drush event dispatcher event in settings.php:
if (function_exists('drush_main') && method_exists('Drush\Drush', 'service')) {
  \Drush\Drush::service('eventDispatcher')->addListener('console.command', 'Drupal\mymodule\EventSubscriber\DefaultSubscriber::setLdapEnvVariablesCli');
}

This isn't ideal but it does at least let me keep most of the actual logic in the subscriber.
then I made the CLI callback method and the common method static:
public static function setLdapEnvVariablesCli(ConsoleCommandEvent $event) {
  self::setLdapEnvVariables();
}

protected static function setLdapEnvVariables() {
  // ...
}

It's a bit ugly but it works. I'll just have to document that a settings.php change is needed in the module README.


How to use HTML tags in form error messages I'm using \Drupal\Core\Form\FormState::setError() in a form validation hook to display a message if the validation fails. I want to include some HTML on it, but the second parameter of setError(), the error message, is escaped. As a result, the HTML code is visible in the message box. How can I avoid this and have HTML in the box?

All errors added to the form state will be finally handled by drupal_set_message.
That means that you can either use strings, or any class that implements the MarkupInterface.
Looking at that list I would say that what you are looking for is FormattableMarkup or even better TranslatableMarkup.

An example would then be:

$your_error = new TranslatableMarkup('<b>@message!</b>', array('@message' => 'A bold error'));
$form_state->setError($element, $your_error);

Good luck!


How to add a theme suggestion to the textfield input based on the name of the view? I am using the following hook in a custom module:

MY_MODULE_theme_suggestions_input_alter(&$suggestions, array $variables) {

  $suggestions[] = 'input_'. $element['#type']. '__'. 'form_id__' $element ['#form_id']. '__'. $element['#name'];
}

With which I get something similar (In my case I have an exposed filter using search api):

input-textfield-form-id-views-exposed-form-search-api-fulltext.html.twig

How can I get the suggestion in the following way?

input-textfiel--viewName--search-api-fulltext.html.twig

Where viewName is the name of the view from which the field is exported.

How can I access the view information from this hook?

If the View is displayed as a page, you can get the View ID from the current route parameters:

$view_id = \Drupal::routeMatch()->getParameter('view_id');
if ($view_id) {
  $suggestions[] = 'input_'. $element['#type']. '__'. $view_id . '__'. $element['#name'];
}

If it's a block, I can't think of a nice way to do it generically. One non-nice way would be to alter the form, and add a property to each element which can then be picked up in the suggestions hook.

Something like this:

function MODULE_form_views_exposed_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {
  // You could check that the current display is a block here too if you need to
  $view_id = $form_state->getStorage()['view']->id();
  _MODULE_add_view_id_to_input_elements($form, $view_id);
}

function _MODULE_add_view_id_to_input_elements(array &$root_element, $view_id) {
  $input_types = ['textfield', 'submit', '...'];

  if (in_array($root_element['#type'], $input_types)) {
    $root_element['#MODULE_view_id'] = $view_id;
  }

  foreach (\Drupal\Core\Render\Element::children($root_element) as $key) {
    _MODULE_add_view_id_to_input_elements($root_element[$key], $view_id);
  }
}

And then in the suggestions hook:

if (isset($element['#MODULE_view_id'])) {
  $suggestions[] = 'input_'. $element['#type'] . '__' . $element['#MODULE_view_id'] . '__'. $element['#name'];
}

This isn't particularly pleasant, but the exposed form elements themselves don't carry any context so you have to wedge it in there somehow I guess. Hopefully there's a cleaner method out there somewhere.


How to set one of the fields displayed in the view to be a link to a webform submission? I'm using the Webform MySQL Views module to allow me to display webform submission data in views. This works really well; once you get it set up you work with the view just like you would a normal one.

So here's my question: how can I set one of the fields displayed in the view to be a link to the webform submission? There's an option to make a field a link in the Rewrite Results section:

But I'm not sure how to enter the path to the actual submission. The link I need to produce looks like this (copied from Content->Webforms->Submissions->View):

http://localhost/drool_calendar/node/1/submission/5

I'm guessing I don't need to specify the server or site name, but everything from node/ on.

This is an old post, so I expect you found your answer already.  You need to have the post's id number.  Try adding that field to the set, but excluding it from view.  Also, rearrange fields so it is earlier in the list than the field you are turning into the link.  You should then be able to use replacement tokens to make the path entry look something like:

/drool_calendar/node/[content:nid]/submission/[content:subid]

Starting the path with a / tells Drupal that you want this to stem from the site base url; discarding the leading slash tells Drupal you want this link to stem from the current page.


How to redirect a user on login? I have a registration form, when submitted, the user gets logged in automatically.

I want to redirect the users to a specific page on login. Whether they are logged in using the login form or through the registration form.

I used the following code first,

function yourmodule_user_login($account) {
  // We want to redirect user on login.
  $response = new RedirectResponse("yourpath");
  $response->send();
  return;
}

This is not working because it's called before submit handlers so this would prevent them from being called.

Then I added a custom submit handler to the login form and redirect the users in that submit handler.

$form_state->setRedirect('mymodule.mypage');

This works fine only when the user logged in using the login form but not working for the registration form. When I use a custom submit handler for the registration and redirect the user there, I think at that time the user is not logged when the redirection occure.

Is there any other method to redirect the users on login through code?

Subscribe to the UserLogin event like below:

in yourmodule/src/Event/UserLoginEvent:

<?php

namespace Drupal\yourmodule\Event;

use Drupal\user\UserInterface;
use Symfony\Component\EventDispatcher\Event;

/**
 * Event that is fired when a user logs in.
 */
class UserLoginEvent extends Event {

  const EVENT_NAME = 'yourmodule_user_login';

  /**
   * The user account.
   *
   * @var \Drupal\user\UserInterface
   */
  public $account;

  /**
   * Constructs the object.
   *
   * @param \Drupal\user\UserInterface $account
   *   The account of the user logged in.
   */
  public function __construct(UserInterface $account) {
    $this->account = $account;
  }

}

in yourmodule/src/UserLoginSubscriber.php:

<?php

namespace Drupal\yourmodule\EventSubscriber;

use Drupal\yourmodule\Event\UserLoginEvent;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;

/**
 * Class UserLoginSubscriber.
 *
 * @package Drupal\yourmodule\EventSubscriber
 */
class UserLoginSubscriber implements EventSubscriberInterface {

  /**
   * {@inheritdoc}
   */
  public static function getSubscribedEvents() {
    return [
      // Static class constant => method on this class.
      UserLoginEvent::EVENT_NAME => 'onUserLogin',
    ];
  }

  /**
   * React to the user login event dispatched.
   *
   * @param \Drupal\yourmodule\Event\UserLoginEvent $event
   *   Dat event object yo.
   */
  public function onUserLogin(UserLoginEvent $event) {
    $response = new RedirectResponse("yourpath");
    $response->send();
    return;
  }

}


a lot of template (.tpl.php) files, is it good or not? I have used about 110 template files (tpl.php) in my theme, will that slow my drupal site?

I mean:

  more template files == consume Server performance.

Say you override the default page.tpl.php with your own in your theme folder, and compare this to the case of using the default. In both cases, one page.tpl.php is being evaluated during the page render process - either the default template or yours. Even if you do not override the template, Drupal must search the theme folder to check if an override exists. Of course, if you have a lot of complex logic in your override the page will render more slowly, but that is not due to the overriding itself.

Creating custom templates with hook_theme might slow things down, though.

In general, caching will do more to speed up your site since it bypasses page rendering altogether.


Is it properly to include a third-party php library via composer without creating drupal module for it? I want to ask a theoretical question.

For example, there is a project on Drupal 8. Working on the project, developers find a php library on the GitHub, include it via Composer and use it in their modules.

They don't create drupal 8 module which would present the library and contain files of the library, copied from GitHub before. And to use the library it would be necessary to install the module.

Is it the correct way to attach an external php library via composer and afterwards use it without creating a module for Drupal 8 for this library ?

Sure, you can do that on a project.

But you're probably going to write code somewhere to actually integrate that into Drupal and expose it somehow, and that will be in a module (or theme). But especially if that's a custom module that is just used for that site, you kind of have to add it to the project composer.json as composer doesn't include composer.json of moules that aren't actually added themself with composer (excluding solutions like merge plugin)


The website encountered an unexpected error. Please try again later When creating a new user account, as a visitor or unregistered user, I get the following message:

The website encountered an unexpected error. Please try again later.

and the account is not fully created.

The log (admin/reports/dblog) gives the following description of the error:

  PDOException: SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry '' for key 'name': INSERT INTO {users} (uid, created,
  data) VALUES (:db_insert_placeholder_0, :db_insert_placeholder_1,
  :db_insert_placeholder_2); Array ( [:db_insert_placeholder_0] =>
  150752 [:db_insert_placeholder_1] => 1422513054
  [:db_insert_placeholder_2] =>
  a:6:{s:7:"contact";i:1;s:20:"l10n_client_disabled";b:0;s:17:"mimemail_textonly";i:0;s:34:"user_relationships_ui_auto_approve";a:0:{}s:34:"user_relationship_mailer_send_mail";b:1;s:40:"user_relationships_allow_private_message";s:12:"on
  all users";} ) in drupal_write_record() (line 7239 of
  /home3/zacteyc1/public_html/includes/common.inc).

The referer is: user/register

However, if I am the super user (user/1) I can create a complete new user account with no error.

I have disabled all the modules I could (including core ones) one by one to find the culprit but even with all modules disabled, the error persists.

I have also uploaded a fresh copy of the core files, but to no avail.

I have then uploaded, one by one, backups of my database going as far back as September 2014. It is with the September 14, 2014 (and prior) that the error disappears.

I need to fix the current database otherwise I will have lots of angry users who will have lost all the pictures they uploaded, all they have written in blogs, messages, etc. since September!

Does anyone know how to do this (like comparing a "good" database with a "bad" one to isolate the error?)

Any and all suggestions to fix the current database is greatly appreciated!

Thanks. :)

The issue was created by rules.

I had read somewhere on two or three occasions that the Rules module could generate such error but I thought disabling the module would be enough to show if rules were involved or not. It didn't. Apparently, the rules are still active when the module is disabled (a diehard, at least in my case!)

I also had to disable the rules one by one until I found the culprit. It was a rule automatically making the new authenticated user a member of a welcome group. Somehow, the data in the rule had shifted and it was no longer the account but the site:logged-in-user that was made a member of the group.

The lesson here is about Rules and that the rules need to be disabled. Disabling the module alone is not enough. I hope this helps someone.


How do I let non-admin user approve comments? I'm looking for a way to allow a non-admin user to approve comments. I thought a Flag/Rules combination might be a solution but I can't figure it out.

I added a content-moderator role, then I created a view listing comments awaiting moderation. After that, I set up a flag to approve comments and added the flag link within the view, bu there is no Rules action that approves comments once the flag is clicked.

Do you have any idea?

You need to give the "Administer comments and comment settings" permission to the role and then it will be able to approve the comment.


Why do Chinese auto path URLs become something else? I have a Drupal 7 site with i18n on it. There are lots of languages. The problem is that if you save a node that is in Chinese, and you select auto path, then the title that was, for example, /空氣清淨機 will be changed to /kong-qi-qing-jing-ji.

What exactly is this process called? Is it an "English alphabet" version of the Chinese text?

The process you are describing in your question is called transliteration.
The reason for what you see happening in your site, might be because you're using the Transliteration module. Here is a quote from its project page:

Provides one-way string transliteration (romanization) and cleans file names during upload by replacing unwanted characters.
Generally spoken, it takes Unicode text and tries to represent it in US-ASCII characters (universally displayable, unaccented characters) by attempting to transliterate the pronunciation expressed by the text in some other writing system to Roman letters.

Here is a sample of what this module does for "file names":

However, it can also be used to transforms an URL like mydomain.com/последние-новости-в-Украине-и-мире in something like mydomain/poslednie-novosti-v-Ukraine-i-mire. To do so, you also need to enable the Pathauto module. After that, go to the Pathauto setting page and check "Transliterate prior to creating alias". For more details on that, refer to "D7 Pathauto transliteration". Attention: this does not "fix" already created aliases (those need to be deleted and recreated).
Note: There is also a transliteration tag on drupal.SE (with only 4 questions using it though ...).


Programmatically adding fields to node submission form I need to add fields to a node creation/editing form programmatically. More specifically, I need to take already-generated form elements from another form and insert them into the node submission form.

That part isn't what's hanging me up though. My problem is that I can't figure out how to make the database hang onto the values submitted via the new field.

For example, the following code (copypasta'd directly from the API Quickstart page) creates a form element inside the existing node form just fine, but when I enter a value and submit the form, the value is not stored.

function [mymodule]_form_alter(&$form, &$form_state, $form_id) {
    $form['foo'] = array(
      '#type' => 'textfield',
      '#title' => t('bar'),
      '#default_value' => t('foo'),
      '#size' => 60,
      '#maxlength' => 64,
      '#description' => t('baz'),
    );
}

How do I alter an existing form in such a way that the submitted values 'take,' so to speak?

Add something like this to your hook_form_alter().

$form['#submit'] += array('mymodule_another_submit_handler');

Create that function and save your values from $form_state['values'].

function mymodule_another_submit_handler(&$form, &$form_state) {}

Where are they supposed to go? You might try to fire the submit handler of the other form so you wouldn't have to write so much code.


What parts of a view can't be changed? Looking at my views listing, I see each has a "Type". The type effects the choices I have when adding fields. I have to create a whole new view if I want something different. Why is this? Many things are editable in the view. What are all the 'base characteristics' about a view that can't be changed?

I'm thinking about 7.x-3, but comparisons welcome.

The 'Type' corresponds to the database table used for queries. This option creates the 'FROM' part of the SQL query. That is really the only part of a view that cannot be easily changed after the initial creation.

See https://www.drupal.org/node/2287909 for some more information about the basics of Views 3.


Change the submit function I am using VBO and I want to change the submit function on my form. I have tried the following code:

function a_views_bulk_operations_form_alter(&$form, &$form_state, $vbo) {
  if($form_state['step']=='views_bulk_operations_confirm_form'){
    $form['#submit'] = 'a_myfunc';
  }
}

function a_myfunc(&$form, &$form_state, $vbo) {
  dpm('Hit');
}

The a_myfunc is not hit. Instead I go to the normal VBO processing page. How can I change the submit function>

You're overriding wrong submit handler, normally VBO submit handlers are available under $form['select'] key in $form array. You can confirm this in your case by printing $form in hook_form_alter(). Make sure to use proper form ID as well before using, you can confirm form ID by printing $form_id variable available in hook_form_alter(). Below is example of altering VBO Form and overriding submit handler (In my case I've only one submit button).

/**
 * Implements hook_form_alter().
 */
function [MODULE_NAME]_form_alter(&$form, &$form_state, $form_id) {
  // Confirm $form_id before using.
  // echo "{$form_id}<br>";
  switch ($form_id) {
    case 'VBO_FORM_ID':
      // In VBO, normally submit handlers are available under 'select' key.
      $form['select']['submit']['#submit'] = array('MODULE_NAME_vbo_submit');
      break;
  }
}

/**
 * Submit handler for Views bulk operations.
 */
function MODULE_NAME_vbo_submit($form, &$form_state) {
  // Do your processing here.
}


Ability to create forms for each node in Drupal 7 I am creating articles in which I want to ask, on each article, that whether the it was helpful to read or not.

The user would have two option boxes:-

© Yes

© No

One of these will be selected and the form should be submitted through JQuery. It should be recorded with each node so that we would also know how many total users found this helpful too?

Any idea how would I achieve that?

I wish it could be achieved through Flags or Rating but I haven't been able to do so.

Thanks a lot

This is pretty much the use case of the Rate module. By using a custom widget, you can present arbitrary label/value options for the user to select (e.g. Yes = +1 / No = -1).

The only difference is that they're presented as hyperlinks instead of radio selects. With some front-end customization, you probably could change that as well.


Importing nodes from custom XML feed: how do I convert some XML fields into entity references? Here's the problem:

I'm migrating a Wordpress website to Drupal. It's a gaming portal with a highly customized Wordpress with custom fields, so we decided to generate some XML dumps from Wordpress, then use Feeds module to import that. There are two different "content types", games and articles about those games (strategy guides, tricks, so on). We have two content types, so we generate two XML files. All good so far.

The problem is that those two content types are related. To be precise, the "article" content type is always referred to a game. In Drupal terms, "article" contains an entity reference fields that points to a node of type "game".

Where's the problem?
Example: we have an article entitled: "8 tricks for Clash of Clans". This article refers to game "Clash of Clans". The problem is: in our XML we have "Clash of Clans", written in words. I want Feeds module to those words to Node IDs, then save those Node IDs as node references.

I want to do the same with some Taxonomy Terms.

Makes sense?

Maybe a bit late...

Do you know the feeds_tamper module?

But - I think you won't get around writing your own feeds_tamper plugin.
You have to parse your input field and search for node IDs, then replace it with the ID, as you wrote. This can not be done with feeds_tamper standard plugins, because even with REGEX-replace you don't have access the node IDs.


How to redirect user using Rules when user visits a link with view? I have a rule that redirects a user when visiting a view. But it does not work with the event "view page" or "Drupal is initializing".

Here is the rule:

{ "rules_uid_141" : {
"LABEL" : "uid=141",
"PLUGIN" : "reaction rule",
"OWNER" : "rules",
"TAGS" : [ "redirect manager" ],
"REQUIRES" : [ "rules", "pathrules" ],
"ON" : { "node_view--page" : { "bundle" : "page" } },
"IF" : [
  { "data_is" : { "data" : [ "site:current-user:uid" ], "value" : "38" } },
  { "pathrules_checkpath" : { "path" : "team", "operation" : "equals" } }
],
"DO" : [ { "redirect" : { "url" : "team?field_manager_uid=38" } } ]
  }
}

Any suggestions?

Use 'Drupal is initializing'

To get this to work, you should be able to use the "Drupal is initializing" event (which is NOT shown in the rule included in your question). That will ensure that the rule gets triggered BEFORE the actual content of your "link with view" is shown (otherwise you are too late, it "is" already shown).

Use a 'Regular Expression'

That link that you want to "intercept", should be formatted in some type of regular expression, which you then use as your Rules Condition. So that you have a rule that corresponds to "before showing the actual content of something that matches a specific path ...". After you get that part to work, your Rules Action is probably fine.

Sample rule

Refer to the "Option 1" part of my answer to the question about "How to restrict access to a node via node/12 and allow access via a path like content/sometitle?", which contains this Rule in export format:

{ "rules_check_url" : {
    "LABEL" : "Disallow node/* access",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "ON" : { "init" : [] },
    "IF" : [
      { "text_matches" : {
          "text" : [ "site:current-page:url" ],
          "match" : "node\/\\d+$",
          "operation" : "regex"
        }
      }
    ],
    "DO" : [
      { "drupal_message" : {
          "message" : "Sorry, URLs like [site:current-page:url] are not allowed around here ...",
          "type" : "error"
        }
      },
      { "redirect" : { "url" : "no_access" } }
    ]
  }
}

Here is some suggested tuning of the above sample to make it work for your case also:

machine name and label.
replace the node/* by your path of your view (in the "label", and the regular expression).
replace the action part of the rule by your action that you have already.

Note: the rule included in your question also shows that you tried to use the Path Rules module, which implements Rules Conditions for checking an URL against a given string for triggering Rules Actions. That module is another interesting add-on module the Rules, but if you just use a regular expression as shown in my answer, you don't need that module for getting your rule to work.


where to edit styles in a sub-theme? I created a foundation sub-theme and am now customizing my site.  I am confused as to where to edit styles sometimes.  For example there are these styles are generated somewhere which I can't find where.  If I wanted to change the padding and line-height, what is the correct way of going about this?

@media only screen and (min-width: 40.063em)
.top-bar-section li:not(.has-form) a:not(.button), #topbar-forms li:not(.has-form) a:not(.button) {
    padding: 0 0.5208333333rem;
    line-height: 1.5625rem;
    background: #FFFFFF;
}

I find it's generally easier to track down CSS selectors by disabling CSS aggregation and then using your browser's inspector feature. This will give you a file and line number to reference for tracking down the selector in question. Often times, you may be able to simply copy-and-paste the selector in question into your subtheme and edit it as needed.

You'll always want to make your CSS and template changes in the subtheme; don't touch the base theme just like you wouldn't touch Drupal core to make code changes. This ensures that if there is an update to the base theme, you can apply it without losing all of your customizations.

Many base themes already have a CSS file structure or directory in place to help you figure out where to put your selectors. If not, the architecture is very much up to your personal preferences. You could put everything in one file if there are only a couple of changes, but most people use some sort of systematic CSS architecture, such as SMACSS, to keep things organized on more complex projects. Alternately, it might make sense to you to mirror the file structure already found in the base theme. You normally don't need to copy all the CSS files from the base theme, just create files to hold any new or customized selectors as needed.

If you haven't yet, check your base theme for a README file, or look at their online documentation for more hints on properly customizing it using a subtheme.

Follow-up, more specific to SASS and Foundation theme:

If you're looking for the SASS file that a selector comes from, the easiest way to trace that down is by enabling SASS source map generation in the subtheme's Gruntfile.js. Add sourceMap: true, to the sass options in grunt.initConfig() similar to this:

grunt.initConfig({
  ...
  sass: {
    dist: {
      options: {
        outputStyle: 'compressed',
        sourceMap: true,
        includePaths: ['<%= global_vars.theme_scss %>', '<%= global_vars.base_theme_path %>/scss/'].concat(bourbon)
      },
  ...

You may also need to enable loading of CSS source maps in your browser's settings (See the "Enabling source maps in the browser" section from http://thesassway.com/intermediate/using-source-maps-with-sass.

Using source maps to trace back to the specific selector from your OP, it seems to be located in path/to/themes/zurb_foundation/scss/foundation/components/_top-bar.scss. Looking at the base theme's SASS, you can see it utilizes variables for determining the padding and line-height properties:

.top-bar-section {
  ...
  li {
    ...
    &:not(.has-form) {
      a:not(.button) {
        padding: 0 $topbar-link-padding;
        line-height: $topbar-height;
        background: $topbar-link-bg;
        ...
      }
    }
  ...

And those variables are defined elsewhere in the base theme (do a text search to find them) with the !default property:

$topbar-height: rem-calc(45) !default;
...
$topbar-link-padding: ($topbar-height / 3) !default;

This means they can be set to something else in your subtheme's SASS before they are used in the base theme's SASS in order to override the base theme's defaults. I can't tell from the OP, but I'm guessing changing the value for $topbar-height might accomplish both changes you are attempting to make. Doing things in this way (overriding !default variables from the base theme) is less likely to cause alignment issues elsewhere in the theme, so it's generally the preferred methodology (assuming the theme is doing a good job of utilizing SASS, which seems to be the case for the ZURB Foundation base theme)

In order to do this in your subtheme, I'd recommend either adding the variable overrides to your subtheme's scss/base/_init.scss file, or creating a new scss/base/_overrides.scss file and editing the main theme SASS file at scss/your_theme_name.scss to @import "base/overrides" it just below the existing @import "base/init".

For example, try adding this to the bottom of the subtheme's scss/base/_init.scss file to double the top bar's height:

$topbar-height: rem-calc(90);


How to write a CCK widget with more than one input element? What I am looking for is not CCK flexifield or CCK Multigroup.
I am trying to develop a CCK widget that allows me to enter two or more input fields per value, kind of what Doublefield does for Drupal 7.
How would I develop that?

I built something like that for drupal 7. Considering CCK moved into the drupal core in d7, I'm not really sure how much different the code would be for a cck module in d6, but maybe this module will help you

I wrote this module as I had to somehow capture phone numbers, but have them split into country code / area code and number and save them into seperate columns in the database. All other field modules I tried did not allow for this!

That way all numbers can be entered uniformly and thus presented in a uniform way - especially helpful if you use it to store and manage customer information and possibly need to export it to different applications.
In my case, some users would enter phone numbers with a dash, other with a slash and others again with nothing seperating values making managing them difficult and displaying them messy.

Rip the code apart and modify it to suit your needs (like only 2 fields):

It's in my sandbox: http://drupal.org/sandbox/tecjam/1320886

in Git: http://drupalcode.org/sandbox/tecjam/1320886.git/tree/e7c97511506ee6e92a44656aa02d31f4e8f69727

I like to comment my code to help myself (sometimes there are more comments than code lol). So figuring out what does what and where should not be a problem at all.

You can always ask if you have any special questions.


How would I make a search view display results in a new page instead of on the same page? I have view (a block) that searches my products for various fields such as sell price, title, ect. It works except all the search results appear right in that block instead of on a new page. Here is an example of what I want to do: http://www.themesdojo.com/drupads/

You can show your exposed views filter as a block, and place the block on your search page, then all submissions will show results on your view page.

Under the advanced field-set in the views UI, once you have created an exposed filter, an option will appear under the EXPOSED FORM heading that will allow you to create a block.

You can see an example of a front page search leading to a views results page here... http://www.myweddingfayre.com


Token replacement by its value before indexing in apachesolr I'm using solr 4-x (apachesolr) for search functionality in my Drupal 7 site. I'm using a token in some long text fields in some nodes of different content types across my site. Lets suppose the token is [token_name] and its value is "test". So, whenever I search "test", the nodes containing this token don't show in search results. But when I search [token_name], the concerned nodes show in the search results.

What is happening here is that instead of the original token value, the [token_name] is stored in database. So, for indexing, the [token_name] is getting indexed instead of its value. And hence, it is unable to show results related to "test" as search keyword. Is there anyway to do this? Please suggest as I need to fix this ASAP.

P.S. I can't replace [token_name] by its value while saving the node by hook_node_presave.

you can use hook_apachesolr_index_document_build() function to override node data index in apache solr


flexslider is failing on version recognition and perms Updated via drush, flexslider module v.7.x-2.0-alpha3 is installed.
Installed latest version of library 2.3.0, released 17 days ago as of the time of this writing.
Getting drupal pesky error about version not recognized, so decided to downgrade library to 2.2.2, same error.
Moreover I am getting following errors in status report:

Warning: fopen(sites/all/libraries/flexslider/jquery.flexslider-min.js): failed to open stream: Permission denied in _flexslider_requirements_library_installed() (line 212 of /var/www/asflorida.com/sites/all/modules/flexslider/flexslider.install).
Warning: fread() expects parameter 1 to be resource, boolean given in _flexslider_requirements_library_installed() (line 213 of /var/www/asflorida.com/sites/all/modules/flexslider/flexslider.install).

Before somebody tells me that this is a perm issue: I checked thoroughly and perms are 775 throughout and ownership is correct.
Either alpha 3 is not working with older library or viceversa.
Thanks in advance.

Basically this is a duplicate issue, workaround (cannot be called solution) is to downgrade from v.2.3.0 to 2.2.2.
I already posted in the module's issue queue.
The other issues were caused by ownership and perms issues, while I was testing both library versions, disregard that part.


db_query() is not returning results from a valid query In short:  db_query of a SELECT statement is returning no results.  However, running the SELECT statement in phpMyAdmin vs the database returns thousands of results.  I'm using Drupal 6.

What I'm trying to do:  The site I'm working on gets thousands of spammers hitting it each day and creating accounts.  The accounts are worthless to them, because if they do not pay, they don't get to do anything but log in.  I want to safely remove these accounts.  Therefore, I'm selecting the accounts based on certain criteria and then want to iterate through each and use the Drupal delete user function to remove the user from Drupal.  Right now, I'm just trying to print the info that returns so I can see if I get the correct results before moving on to the delete, which is a simple 1 line addition.

Here's the code:

include_once './includes/bootstrap.inc';
include_once './includes/database.mysql-common.inc';

drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);

$query = "SELECT u.uid as id, u.name as name, u.mail as email, ur.rid as role, FROM_UNIXTIME(u.created) AS created, FROM_UNIXTIME(unix_timestamp()-1209600) AS deadline FROM {users} as u LEFT JOIN {users_roles} as ur ON u.uid = ur.uid WHERE (ur.rid < 3 OR ur.rid IS NULL) AND u.uid > 350 AND u.created < (unix_timestamp()-2419200) ORDER BY u.uid";

$results = db_query($query);

print $query;
print "
";
print db_num_rows($results);

foreach ($results as $row) {
        print "
";
        print "ID: " & $row['id'];
        print "Name: " & $row['name'];
        print "E-Mail: " & $row['email'];
        print "Role: " & $row['role'];
        print "Created: " & $row['created'];
        print "Deadline: " & $row['deadline'];
}

For Posterity's (and other people finding this question) sake, here's the final code:

include_once './includes/bootstrap.inc';
include_once './includes/database.mysql-common.inc';

drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);

$query = "SELECT u.uid as id, u.name as name, u.mail as email, ur.rid as role, FROM_UNIXTIME(u.created) AS created, FROM_UNIXTIME(unix_timestamp()-1209600) AS deadline FROM {users} as u LEFT JOIN {users_roles} as ur ON u.uid = ur.uid WHERE (ur.rid < 3 OR ur.rid IS NULL) AND u.uid > 350 AND u.created < (unix_timestamp()-2419200) ORDER BY u.uid";

$results = db_query($query);

print "Users To Delete:  " . db_affected_rows($results);

while ($row = db_fetch_array($results)) {
    print "
";
    print "Deleting: ";
    print " ID: " . $row['id'];
    print " Name: " . $row['name'];
    print " E-Mail: " . $row['email'];
    print " Role: " . $row['role'];
    print " Created: " . $row['created'];
    print " Deadline: " . $row['deadline'];

//delete the spam user cleanly
user_delete(array(), $row['id']);

    print " Completed.";
}

I setup a CRON job to run this weekly to do the clean-up.  There's no reason it can't be run more or less often, though.

The SQL looks fine, but you're using the wrong versions of the DB API at the moment.

For Drupal 6 you want to use syntax similar to the following:

$results = db_query($query);
while ($row = db_fetch_array($results)) {
  print "ID: " . $row['id'];
}

There's some good documentation for the D6 API on this post, it's worth a read.

Forgot to mention...db_num_rows() is a Drupal 5 function which is why the script is failing. There's a discussion on the alternative methods for D6 here (most involving COUNT queries)


How can I embed the YouTube field module in a specific page? Shifting from Wordpress, I'm quite a newbie at Drupal. So I want to embed the YouTube field module in a specific page, not just on the landing page (as it is shown in the setup video https://www.youtube.com/watch?v=SzvEEMO0_Ug). But how can I do this? I somehow just can't figure out where I can select the page I want it to be on. Thanks a lot for any help

Fields are designed to be attached to pieces of content (entities), especially the main content entities (nodes). Using youtube field, would mean you can attach a different youtube video to every type of content. This likely results in a textfield on every node edit page (of that certain content type) where you enter a URL or something.

If that is what you want, proceed happily. If you go to the manage display section of your content type you can alter the teaser view mode (switch in the right top) and remove the field from display so it does not show on the front page.

If that is not what you want and you only want one block to appear in a sidebar or something, go to the blocks page, create a new block and just paste the embed code there. Make sure to set the content filter to full-HTML so it does not get sanitized. Each block allows you to specify the URL's on which it should be displayed. (There is no need for this module)


Change page title from Views preprocess function I want to be able to change the main page title based on some value that I get in a views preprocess function.

The View is displayed as a page.

function MYTHEME_preprocess_views_view(&$variables) {

  // Can I set the page title from here?
}

The title I am trying to override is the title printed by the /templates/content/page-title.html.twig below:

{#
/**
 * @file
 * Theme override for page titles.
 *
 * Available variables:
 * - title_attributes: HTML attributes for the page title element.
 * - title_prefix: Additional output populated by modules, intended to be
 *   displayed in front of the main title tag that appears in the template.
 * - title: The page title, for use in the actual content.
 * - title_suffix: Additional output populated by modules, intended to be
 *   displayed after the main title tag that appears in the template.
 */
#}
{{ title_prefix }}
{% if title %}
  <h1{{ title_attributes }}>{{ title }}</h1>
{% endif %}
{{ title_suffix }}

I don't think hook_preprocess_views_view() or hook_preprocess_page_title() is good ways in your case. You can use hook_views_pre_render

/**
 * Implements hook_views_pre_render().
 */
function MYMODULE_views_pre_render(ViewExecutable $view) {

  if ($view->id() == 'VIEW_ID') {
    $arg = $view->args; // Argument from view.
    $default_title = $view->getTitle(); // Get view title.
    $view->setTitle('New title'); // Set new title
  }
}

All variables you need in here.


Ordering results for form autocomplete fields I've done the cursory googling, but so far I haven't found anything close to an answer for this.
I'm using the Masquerade module with a custom module on top to extend it and make its searching algorithms a bit more "clever" (Soundexes, custom fields and such), and it returns the results in a certain order, passed through to drupal_json_output(). However, because JSON isn't exactly indexed, it means that when the autocomplete text field picks it up, it's in a slightly screwy order based on its keys (which are the users' usernames). I can forcibly send a array_values() to the JSON output, but it breaks Masquerade's functionality as it requires the username to be the key. I'd imagine this would be a problem with other autocompletion stuff in Drupal that uses JSON loads.
Can anyone suggest a way of doing this please? I'm not sure whether it's a matter of Masquerade or of D7's textfield autocompletion.
Thanks

I would think its the query that handles the ordering. You can alter the query that fetches the results for the autocomplete field. Find the query in the module code and it should have a tag associated with it. You can then alter the query by implementing hook_query_TAG_alter

https://api.drupal.org/api/drupal/modules%21system%21system.api.php/function/hook_query_TAG_alter/7

This will allow you to change the orderby for the query

EDIT: Looking at the masquerade module I don't think it adds tags to the queries which means you cant mess with the ordering.


Generate password hash I have an external application written in VB.NET that needs to add user accounts to a drupal database.

We tried posting to the /user/register but something is funky with that code and it is not working. I also considered using a RESTful API plugin but that has proven to be more work than we are capable of delivering on short notice.

Just when I figured we could:

Add a value to sequences table
Use that previous value as ID of next user

We now discover that we need some fancy smancy hashed password. I look into the code and see D7 uses sha512 but also some hashing salt -- which again is yet another drupal method which accepts the number or iterations to hash (or something to that effect).

If the VB app uses a sha512 on a password will this suffice with Drupal? Will uses be able to login?

Tips, comments, etc more than welcome :)

Alex

No - a simple sha512 wouldn't be the same because its lacking the "salt" added by Drupal that prevents the "ability to use pre-hashed lists of candidate passwords" against your database (among other things). Its a security improvement over D5/D6 where a simple md5 update query could reset a user's password.

You might get more mileage out of connecting to the password-hash.sh script (in the scripts folder of your Drupal installation) in your VB script using whatever the equivalent to PHP exec() is in VB..


add is null condtion in db_update I want to use db_update with condition that a specify field is null ,how can I do it?

something like

->condition('used_date',  'isnull','=')

is this correct ,if not,what is the correct condition ?

As per documentation, there is a method just for that: ->isNull()

$query->isNull('myfield');
// Results in (myfield IS NULL)
$query->isNotNull('myfield');
// Results in (myfield IS NOT NULL)


How can I make a node template that works on any url I specify? At the moment I can make a template for a specific node based on the node id.
However I want to make the same template work off of the url or title of the node so I can use it on multiple sites for the same node which doesn't have the same node id on each of the sites.

How can I do this?

Probably best to add a template suggestion rule to hook_preprocess_node, to control which templates are looked for.

e.g, in template.php

/**
 * Implements hook_preprocess_node
 */
function mytheme_preprocess_node(&$variables) {
  if ($variables['node']->type == 'article') {
    // Regex replace anything not alphanumeric with underscore _ in node title
    $title = preg_replace('/[^a-z0-9]/', '_', drupal_strtolower($variables['node']->title));
    $vars['theme_hook_suggestions'][] = 'node__'. $title; // Use title in template suggestion
  }

}

Then you could use a template like

node--my-node-title.tpl.php


When Num of Values is "Unlimited", create begins with two instances I've created a custom module for a field in drupal that has two fields, Position and Affiliation.  I add the field to my test content, and set Num of Values to "Unlimited".

The Problem:

When I go to create a new instance of test content, instead of seeing one instance of my field and the "Add another item" button, it starts with two (see image) and the "Add another item" button.

If I set the Num of Values to 1, I only get one.  If I click "add another item", it only adds one.  I'm looking at my code, and for the life of me cannot figure out where the problem can be.  I assume it's something in the widgit.

function pos_aff_select_field_widget_info() {
    return array(
        'pos_aff_select_widget_default' => array(
            'label' => t('Affiliation and Position default widget'),
            'description' => t('Drop Down Menu for Affiliation and Position'),
            'field types' => array('pos_aff_select'),
            'behaviors' => array(
                'multiple values' => FIELD_BEHAVIOR_DEFAULT,
                'default value' => FIELD_BEHAVIOR_DEFAULT,
            ),
        ),
    );
}

function pos_aff_select_field_widget_form(&$form, &$form_state, $field, $instance, $langcode, $items, $delta, $element){
    $base = $element;

    if($instance['widget']['type']  == 'pos_aff_select_widget_default') {
        $element['position'] = array(
            '#type' => 'select',
            '#title' => t('Position'),
            '#default_value' => isset($items[$delta]['position']) ? $items[$delta]['position'] : NULL,
            '#options' => pos_aff_select_query("ibs_position"),
        );

        $element['affiliation'] = array(
            '#type' => 'select',
            '#title' => t('Affiliation'),
            '#default_value' => isset($items[$delta]['affiliation']) ? $items[$delta]['affiliation'] : NULL,
            '#options' => pos_aff_select_query("ibs_affiliation"),
        );
    }
    return $element;
}

Does anyone have any clue what is going wrong?

I'll post my work around just in case anyone else has the same problem.  But after fiddling around with it, I found out that if you have default values set, then it will set the first instance of the field to the default values and the second instance of the field to blank (I tested this by switching my select to textfield and if defaults were blank then I got only one instance of the field, if I put any text into the default, then I got two).  Because my fields uses a select form then I, by default, had set my field values to something, thus, I had default values, thus, it showed the behavior I mentioned.

I set 'default value' => FIELD_BEHAVIOR_NONE, in the hook_field_widget_info and the field only produced one instance.  Ridiculous.


Drupal places a  after text automatically? I have the below code, however when I place it within Drupal 6, Drupal places a  after the text 'Coordinator', see second code insert for the firebug info. I am not sure where this  is coming from? but it would be useful to remove as it means I have a text description, and the selection boxis on the line below. While all my other input box are inline with their descriptions.

Coordinator:<?php
 //Drop Down Select
 $sql = "SELECT user_id, concat (user_firstname,' ', user_surname) as username  FROM   user_tbl WHERE coordinator='True'";
    $result = pg_query($sql);
         echo "<select name='user_id'>";
       while ($row = pg_fetch_array($result)) {
          echo  "<option value='" . $row['user_id'] . " '>" . $row['username'] ."</option>";
 }
         echo "</select>";
?>

Second Code

Coordinator:

<select name="user_id">

I didn't see this problem before but maybe try to rewrite code above as follows:

<?php
//Drop Down Select
$sql = "SELECT user_id, concat (user_firstname,' ', user_surname) as username                       FROM   user_tbl WHERE coordinator='True'";
    $result = pg_query($sql);
         echo "Coordinator:<select name='user_id'>";
       while ($row = pg_fetch_array($result)) {
          echo  "<option value='" . $row['user_id'] . " '>" . $row['username']     ."</option>";
 }
         echo "</select>";
?>


changing display depending on fields value I want to change how a field value can be displayed to the front-end user,

For example I have an Article content type which have a priority fields,
this priority can be either low or high as a value...

so I want when the priorty is high, my displayed view show me an image icon instead of the high value.

Another approach is to use MY_THEME_preprocess_node(&$variables) in template.php and build your logic according to $variables array elements (e.g. $variables['field_priority']). Example:

function MY_THEME_preprocess_node(&$variables) {
  if($variables['type'] == 'page') {
    $priority = $variables['field_priority'];

    if($priority > 0 && $priority < 2) {
      // do_first_logic()
    }
    elseif($priority > 2 && $priority < 4) {
      // do_second_logic()
    }
    // .... so on
  }
}


Overwrite Taxonomy Term page display settings with custom URL's I would like to define the display settings of my Taxonomy term page. As I understand, this is possible by configuring the Taxonomy view provided by the Taxonomy module.

However, I use custom URL's and by so, my taxonomy pages doesn't have the URL taxonomy/term but something like products/tents.
Is there a way to customize these pages with the provide view?

You can set the patterns used for Taxonomy URL aliases.

http://drupal.org/node/120631

Sounds like you want to use: [term:vocabulary]/[term:name]

If you have it enabled, you should be able to see the patterns here:
www.yoursite.com/admin/config/search/path/patterns


Select List value in an If statement - Computed Field I have created a select list field in my Entity Form.

Select List : none||none and AM||AM and PM||PM

In my computed field, I want to know what did the user chose by using IF STATEMENT

example:

if($halfday == 'AM')
{
//action
}

I tried to use array_pop (example code :

$halfday = array_pop(field_get_items($entity_type,$entity,'field_halfday'));)

but it does not work for me. What PHP code should I use? Any suggestions?

Write the following code under Computed Code (PHP) texarea in computed filed settings

$calc =  $entity-> field_sample['und'][0]['value'];

if($calc == 'AM')
{
 //action
$entity_field[0]['value'] = 'After Meridian';
}

elseif($calc == 'PM')
{
//action
$entity_field[0]['value'] = 'Prime Meridian';
}

This is a sample tested code which prints the selected item at output of computed field.

Note: replace filed_sample with your select list field machine name.


How to create a dynamic menu block system with 3-tier system? I want to create a complex menu system as described in the following image:

It looks complex but logically it is simple.

I want to create a block containing Menu items.
Brief description of image for better understanding: There is a Standard main-menu as with all sites, under that, block is there as scenario-1 and scenario-2, I have just make two copy for better understanding. That block I want to keep in first sidebar. Block has three tier, it is just like M-item(main-menu) -> Its sub-menu items -> Its sub-menu items -> Its sub-menu items (So, it is like Parent -> child -> child -> child)
Logic: Hence, when user clicks M-item-1(parent, from main-menu) -> The block's first tier should show that main-menu item and its sub menu under that. Now suppose user clicks M-item-1-B(tier-1 item) hence in the tier-2 that item should display its sub-menu and M-item-1-B should be as title of tier-2 and same way if from tier-2 if user clicks M-item-1-B-b, its sub-menu should display as in the Tier-3. In short I want to display - 3-tier of menu items in one block only. Hence my purpose is to make the entire block dynamic. By default each tier's first menu item should show its sub-menu (as shown in the Scenario-1)
All the menu items which are active should show themselves highlighted (like what comes with any standard menu, when we click that item gets highlighted).
Path dynamics: Instead of click tier by tier if, I paste the path upto 3rd tier, the block should dynamically detect and show accordingly in the block.
This block or its all three sections are not drop-down type, it is just normal menu block.
The menu items is divided into two column as shown in the image block.

What I tried: I tried to achieve by this using the panels module(mini). I choose layout of 3 column and several row. And add the menu in the as content manually and set the visibility as per the path. But this is not a feasible. As you can see for the second tier I have to make the 6X2 panes and for 3rd tied 6X6X2 panes (2 is for 2 columns). This is not at all feasible. I did not try entirely, but i tried to see it, it is working with panel visibility setting.

Part 1 - Rules is definitely your friend!

It seems that you should definitely have a look at how the
the Rules Block visibility module can help you in "reducing" the challenge contained in your question here.

Admitted, you'll probably need MORE then just that module (and appropriate custom rules) to make it work, but I would definitely recommend this module as part of the solution you're looking for.

Even though your question does say so (yet), I imagine the various scenarios / menu items each also correspond to some combination of paths (URLs). With that, and by using the Rules event "Drupal is initializing", you should even get closer to what you're looking for.

And to avoid you'd get too many (separated) custom rules to make it all work, I'd also try to keep your number of custom rules to a minimum, by also adding the Conditional Rules module to this mix.

Part 2 - BEAN might help too!

Because you have quite some blocks-related requirements, I'd definitely also have a look at the Bean module, to check if it can help also to answer this question. Here is a quote about its project page:

  Think of a Bean as a method to provide new types (compared to node this would be a content type) which then provides an add content interface to create as many blocks as you require (see screenshot below). The bean content can then be placed around the site just like any other block.

The video tutorial Drupal Bean module tutorial - using Bean Admin UI provides a great introduction to really understand the power of this module, and the kind of things you can do with it (by only using site building techniques, no custom coding involved). It also shows how the Bean module transforms Drupal blocks into fieldable entities.

So by adding appropriate fields to your blocks, you may be able to reduce the number of blocks you'd actually need. E.g: maybe your Scenario 1 could be implemented with just a single block.


How to give different permissions for different domains I am using the domain access module in Drupal 7.

I want one domain to be accessible by anonymous users and the other domain to be accessible only by authenticated users.

How can I give the "view published content" permission to anonymous users for only one domain.

Is seems that Domain Strict, a Domain Access submodule, may help you, as stated in this issue:

  DA is a node access module (which is designed to enhance what 'access
  content' means), and you should be able to do this now by using Domain
  Strict and configuring user behaviors.

  Domain Strict forces people to be members of a domain in order to view
  its content. You would enable the module, then you will note:

  1) Anonymous users cannot access any content. This is because they
  cannot be assigned to a domain (since thiey have no account).

  However, you can use the User Defaults setting page to assign
  anonymous users to the primary domain.

  2) Use the same User Defaults setting to assign all 'authenticated'
  users to the domain(s) you prefer.

  Under this setup, anonymous users would still have the 'access
  content' permission, but can only see nodes posted to the primary
  domain.

  See section 4.10 of README.txt and the README for Domain Strict.

Check also README.txt from Domain Strict.

  [Domain Strict] it changes the default Domain Access behavior.  This
  module makes the grants given to a user specific to the domains that
  the user is registered to see.

You'll have to deal with User Defaults setting to set permissions for anonynmous users since initially they don't have domain assigned.


Views Block Question I created a view that is a block.  I then wanted to create another block for that view but with different criteria.  When creating the second block, it was identical to the first block created and when I lets say change the fields, the first original block gets changed as well.  So it seems anything I do to the new block changes the first block as well.

What is the purpose of being able to create a second block but it is the exact same as the first?  I think the only difference it can have is a display name?  Can anyone explain this to me or give me an example of the purpose of this functionality?

Change the "For" setting in the header whenever changing almost anything.

If you want the setting to change on both displays choose "All displays":

If you want the setting to change on only one display choose "This block (override)"


Adding two contextual filters (Content : nid) I want to display two type of contents : News and Events.
So I added them in the filters criteria. This works great.
Now I want them to be further filtered on the basis of the category the News and Events lie in. For example, I only want to display News and Events having category "xyz".
So what I did is, I added a reverse relationship for News and a contextual filter of Content : nid having the relationship that I made. This works OK and shows the desired news.
BUT
when I try to add another relationship and contextual filter, all the data disappears.

Any help in this regard would be highly appreciated!
Thanks!

Here are the sceenshots :

When you add two contextual filters, views expects to receive two contextual filters. Currently in your preview area you are only supplying one (you need to add the second contextual filter (article filter: content nid) as well and separate them with a /). If you use the Provide nid from url filters it might work on the page, but in the preview you still need to provide both values.

However this is not the correct way to proceed, you should be doing something like this:

Since your block should only show on the industry page, you need to obtain the nid of the industry you are looking at. Use one contextual filter, and fill if with the default value: content id from url. This will load the industry nid you are looking at.

Then, since this industry has two different content types attached, you need to add relations to both of them. If the content relates to the industry (likely scenario) you should be using the reversed relationship as you currently do. If the industry links to the content, you should use the non-reversed relationship. I guess you did this step right.

The biggest problem here is that you do not use your relationships for the filters. So Your content > -365 days is not filtering the articles or news, but applies to the industry. The same happens with your content type. You want to display nodes of articles or news, but instead you filter the node you are looking at to be of those types (which fails as it an industry).

So edit your filters and set them to use the related content's fields.
You can only set one relation for each filter, so you'd have to create each filter twice (once for articles and once for news). Then use the drop down button above the Filters section to create an And / or group and drag the items in a way so the type is of article or news.


Looking for Acquia Dev Desktop database settings I am using Acquia Dev Desktop to create local Drupal installations. I am also using Bluehost as a service. Unfortunately, Bluehost uses table prefixes for Drupal tables.

So, if I import something locally from BlueHost, I need to set a table prefix in the settings.php:

array(
  'driver' => 'mysql',
  'database' => 'databasename',
  'username' => 'username',
  'password' => 'password',
  'host' => 'localhost',
  'port' => 3306,
  'prefix' => 'myprefix_',
  'collation' => 'utf8_general_ci',
);

Unfortunately, I can't find the proper database settings for the local Acquia MySql database. Acquia does not create a setting.php file on fresh systems too.

Does anyone know those settings? Thanks.

In the case of Windows 8, Acquia Dev Desktop 2 generates the settings file in this location:

C:\Users\\[user]\\.acquia\DevDesktop\DrupalSettings\loc_Testing_local.inc