What is a good module that allows maintainers of nodes? Im on D7. I have nodes on my site that represent businesses. I want the business owners to be able to edit info about their business even if they didn't create it and I want multiple people to be do so. It would be nice if I could assign a user to a business giving them per node permissions. Any suggestions? thanks.

I have used Node Access Node Reference for this. You will need to install Entity Reference and create a multi-value entity reference field linking to users you want to be able to maintain your node.


drush 6.2.0 reports no version control found for core updates, but DOES find and use svn for module updates (pm-update) for drush 6.2.0, when running:

drush pm-updatecode --version-control=svn --svnsync --svncommit

on a drupal 7 site that only needs module updates, drush will properly commit the changes to svn as expected:

Project committed to Subversion successfully

however, if the site has a core update, drush will report:

No valid version control or backup engine found (the --version-control option was set to "svn").

and fail. does anyone have any idea why this is occurring, or what i should do to fix it?

I haven't used --version-control=svn for a while, and never liked --svncommit.  In any event, it looks like you have found a bug in Drush.  This should be reported in the Drush issue queue; however, since the current maintainers have pretty much moved on to git, I am not sure this code will continue to be supported unless a volunteer stands up to fix and maintain it.

In the meantime, you might try downloading Drush 5, and install it as a secondary version, perhaps setting up an alias 'drush5' to point to the older install, and use it only for core upgrades.  If that does not work, you could even try going back to Drush 4.  Note that neither Drush 5 nor Drush 4 are supported, though.


Alter Drupal search URL I have a third-party vender that provides particular information for us when queried.

Basically, we need to change the URL of the search results page so that their supplied javascript can contact their site and return results from searching the same term.

So if I searched for polar bears the resulting path would normally look like this
http://foo.com/search/node/polar%20bears

I need to append to the path like this
http://foo.com/search/node/polar%20bears?scq=polar%20bears
or
http://foo.com/search/node/polar%20bears?scq=polar bears

How would I accomplish this?

When you want to alter the behavior of an existing form, hook_form_alter() is a useful tool here. Here you want to alter the existing form so that the redirected URL has an extra query parameter. By looking at the submission handler we can see that the search form uses drupal_redirect_form() to go to the /search/node/SEARCH_TERM path.

We can add an extra submission handler to this search form so that it modifies the redirect path with the extra query parameter.

Here's an example MYMODULE that would do as such for the search block form.

/**
 * Implements hook_form_alter().
 */
function MYMODULE_form_alter(&$form, &$form_state, $form_id) {
  // Add an extra submission handler the search block form.
  if ($form_id == 'search_block_form') {
    $form['#submit'][] = 'MYMODULE_search_box_form_submit';
  }
}

/**
 * search_block_form submission handler
 */
function MYMODULE_search_box_form_submit($form, &$form_state) {
  $form_state['redirect'] = array($form_state['redirect'], array(
    'query' => array(
      'scq' => $form_state['values']['search_block_form'],
    )
  ));
}


Should block titles be ? These <h2> heading tags, in the canonical sense, should be used as headings only, right?

In Drupal, it seems these block headings get <h2> tags, but they aren't semantic headings insofar as being legitimate paragraph headings on legitimate paragraphs.

Surely as a search spider would not readily distinguish these tags, they in fact not be <h2> but standard <div>s?

'heading' != 'paragraph heading' (in fact there's no such thing as an HTML paragraph heading). A heading tag is used to denote the heading of a section (a conceptual section, not necessarily a <section /> tag) - it doesn't have to be above, or any where near, a paragraph.

If you're interested in SEO, whatever you do don't convert them from an <h2> to a <div>. A <div> carries no semantic weighting whatsoever, while an <h2> does. If you're not happy with <h2>, obviously choose something else, but for the love of Matt Cutts not a <div> :)

Personally the only tags I'd recommend are <h2> (which is standard for adding a heading to a section in any website, not just a Drupal one) or <h3>, if you're already using <h2>'s to markup more semantically important sections elsewhere in the page.


Adjusting Ubercart package weight I've got an e-shop for which I'm getting pretty accurate shipping rates from Australia Post eDRC (uc_auspost_2).

The problem is that sometimes I get overcharged because of the weight of the packaging material, envelope and a bunch of business cards I chuck into each package. On the other hand, I want to avoid overcharging customers by raising product weights.

Is it possible to automatically add say 200 grams to the weight of each package before requesting shipping rates? There is the Shipping rate markup configuration, but that only adjusts the rate after it has been received for a particular package weight.

There doesn't seem to be an "elegant" way to do this. All that Ubercart provides for shipping modules is a hook to register callback functions. The hard work of dividing products into individual packages is left on the modules. Which kind of makes sense, but also makes the system absolutely "unhookable".

Thus, to add an initial weight to each package, you would have to hack every shipping quote module and initialize each new package's weight before the individual products' weights are added up.

This is what I ended up doing with my UC Auspost module:

--- uc_auspost.module.orig      2011-08-15 08:59:46.000000000 +1000
+++ uc_auspost.module   2011-08-15 09:04:04.000000000 +1000
@@ -562,6 +562,7 @@ function _uc_auspost_package_products($p
           $addresses[++$last_key] = $address;
           $key = $last_key;
           $packages[$key][0] = new stdClass();
+          $packages[$key][0]->weight = 200;
         }
       }
       $packages[$key][0]->weight += $product->weight * $product->qty * uc_weight_conversion($product->weight_units, 'g');


Logged out when hit home link in drupal 7.19? Noticed I am auto logged out or at least that is how it appears with the admin bar disappearing and login form visible when I hit the home link.

If I go from logged out home page to another page I appear logged back in.

I am on drupal 7.19 and it resides in a folder set up as a subdirectory.

drupal.mysite.com

the folder is at drupal.mysite.com/drupal

This only occurs when I am navigating about without www prefix and does NOT happen when navigating about with www prefix. My site can be accessed either way but currently advertising as without prefix. The www is more secure obviously but need both to work.

Answer is well stated here http://drupal.org/node/110478

Had I spent a little more time reading I would not have had to ask this question.
Also I can see now it is making it so no matter which prefix you use the cookie will stick.


How to restrict access to specific php file to only athenticated users I manually made a php file that has the ability to connect to the database and create table entries, it works fine, but now the problem is that if I leave it there, anyone will be able to access it to create entries.
So I want to restrict the access to that file to only authenticated users, I think this may be posible using the .htaccess file, but I don't know how just yet.

.htaccess won't help with this; Apache doesn't know what an authenticated Drupal user is, and there's no easy way to grant it that knowledge. Fortunately there's a much better option:
Create a route in a custom module, and execute your code in its controller. You can easily protect the route with permissions, or by role. Aside from the flexibility this gives you around access control, you can also refactor your custom DB code to use Drupal's database API, making your code more future-proof.
The other option, less desirable IMO for your requirements, is to bootstrap Drupal in your custom PHP file, and use the current_user service to determine whether the user has access to your script.


Theming views and overwriting the default file upload display Theming views in Drupal 7 can be very tedious to newbies. In the following example, a seemingly simple task has become an overwhelming research project into the innards of Drupal! Hoping an experienced drupalite can make quick sense of this.

In our example view we are outputing a product list to a page. One of the fields is a file type where the user uploads a PDF file. To gain maximum control of the layout, we were trying to utilize 'Rewrite the output of this field, and want to create a link to the PDF file with text inside of it that says Download PDF. Sounds simple!! However, so far it has not been.

Because this view is a list of a certain content type, node theming doesn't appear as one of the potential options for template theming. See bottom of the post for potential theming file name conventions that Drupal is offering up.

Also, this may be something easy to do with a hook in the theme's template file, but as of now, that is a little confusing as well and I'm not sure where to look for that solution.

So, for this post, we're hoping to get a clearer picture into the stock views management system. However, all suggestions are welcome!

Here is the code that resides in the rewrite section of the view for the Content-PDF field:

Here are the relevant Replacement Patterns:
[field_pdf_upload] == Content: PDF
[field_pdf_upload-fid] == Raw fid
[field_pdf_upload-display] == Raw display
[field_pdf_upload-description] == Raw description

The problem,
[field_pdf_upload] - gives you a PDF icon, a link to the PDF and it names the title of the file. If I could figure out how to replace the file name inside the href tag with "Download PDF", then this would be essentially solved. I've tried many options in the replacement patterns and what not, but nothing has worked yet. I tried stripping HTML and then adding the direct path to the file and that worked, but if the upload has spaces in it, the path breaks.

If I had access to php in this section, I could do something like this

$fid = [field_pdf_upload];
$file = file_load($fid);

Maybe there is a way to do this and I'm just not getting it?
I am going to start a separate jquery option thread for this in a second, bare w me and it will be written soon.

An alternate method would be to alter one of the theme suggestion templates listed under Advanced->Information - Below is the list of options.

Display output: views-view.tpl.php, views-view--product-landing.tpl.php, views-view--page.tpl.php, views-view--product-landing--page.tpl.php, views-view--default.tpl.php, views-view--default.tpl.php, views-view--page-1.tpl.php, views-view--product-landing--page-1.tpl.php

Style output: views-view-unformatted.tpl.php, views-view-unformatted--product-landing.tpl.php, views-view-unformatted--page.tpl.php, views-view-unformatted--product-landing--page.tpl.php, views-view-unformatted--default.tpl.php, views-view-unformatted--default.tpl.php, views-view-unformatted--page-1.tpl.php, views-view-unformatted--product-landing--page-1.tpl.php

Row style output: views-view-fields.tpl.php, views-view-fields--product-landing.tpl.php, views-view-fields--page.tpl.php, views-view-fields--product-landing--page.tpl.php, views-view-fields--default.tpl.php, views-view-fields--default.tpl.php, views-view-fields--page-1.tpl.php, views-view-fields--product-landing--page-1.tpl.php

Field Content: PDF (ID: field_pdf_upload): views-view-field.tpl.php, views-view-field--field-pdf-upload.tpl.php, views-view-field--product-landing.tpl.php, views-view-field--product-landing--field-pdf-upload.tpl.php, views-view-field--page.tpl.php, views-view-field--page--field-pdf-upload.tpl.php, views-view-field--product-landing--page.tpl.php, views-view-field--product-landing--page--field-pdf-upload.tpl.php, views-view-field--page-1.tpl.php, views-view-field--page-1--field-pdf-upload.tpl.php, views-view-field--product-landing--page-1.tpl.php, views-view-field--product-landing--page-1--field-pdf-upload.tpl.php

Can anyone recommend a method and sample code for accomplishing this task?

You don't need to use a template or get your hands dirty with code.

Just add the field to the view twice.  Hide the first field from display, but change the formatter to "URL to file".  Rewrite the output of the second field to "Download PDF".  On the second field, select output field as link and assuming your field is named 'pdf', make the path [field_pdf].


Set SameSite=strict for session cookies I'm trying to figure out how to set the SameSite cookie attribute for Drupal 8 session cookies, but I can't find a solution.

I thought SessionConfiguration might give me enough options, but it seems not.

Where can I perform such magic?

Check this issue https://www.drupal.org/project/drupal/issues/3150614
You could set next parameters in you services.yml
parameters:
  session.storage.options:
    cookie_samesite: 'NONE'


How to resend emails that Drupal already sent? I need to theme emails that happen when a user completes a booking on our site or modifies there booking after this. Is there a way I can resend emails that Drupal has already sent? This would greatly speed things up for me not having to make new or edit existing bookings.

Step 1: Create a view of all these bookings

First think of a way to create a view (using the Views module) of all those bookings for which you want to resend such eMails.

Step 2: Create a Rules component for sending an eMail

Create a Rules Component that will be used in Step 3 to actually send your eMail. Here is an example of such Rules Component to be created:

{ "rules_send_booking_email" : {
    "LABEL" : "Send Booking eMail",
    "PLUGIN" : "action set",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "USES VARIABLES" : { "user_to_notify" : { "label" : "User to be notified", "type" : "user" } },
    "ACTION SET" : [
      { "mail" : {
          "to" : [ "user-to-notify:mail" ],
          "subject" : "Some information about your booking",
          "message" : "This is an update about your booking with reference [user-to-notify:field_about_some_booking] ...",
          "from" : "[site:mail]",
          "language" : [ "" ]
        }
      }
    ]
  }
}

It uses (references) some field that was added to the "user" entity with machine name (say) field_about_some_booking. Feel free to adapt to any field name you have available. And/or use some other entity (eg a node about a booking?), instead of "user", to which this field might be related to. If you want, you can just import the above Rules Component (in Rules export format) in your own environment (via copy-paste), but make sure the machine name of the field matches with what you have available (otherwise the import will fail).

Obviously, the Subject and Content of the eMail may need review / tuning, while you might also want to use some other From eMail ID.

Step 3: Get VBO involved to actually trigger all the eMails

Transform the view from Step 1 into a Views Bulk Operations (=VBO) view. And have the actual VBO "operation" execute the Rules Component that you created in Step 2.

If you're not familiar with how to do so, have a look at the video about Using Rules components with VBO". If you want even more, then also watch the subsequent "Using Rules components with more than one parameter" video.

Attention: the size (volume) that needs to be processed might be another (extra) challenge (memory requirements, etc). Therefor you might want to also watch the video about "More details about VBO settings" ... Before you are tempted to use VBO for processing them all at once ...

Happy VBO-ing while Rules-ing!


Create version of site with no header/menu? So what I need is a copy my website without the header or navigation menu (it will be used in a frame for another site) but using the same database. I've considered theming the pages based on parameters in the url (e.g. www.example.com/?simpleview=true) but I can't think of how to append "?simpleview=true" to the end of all the links on the page so when they click, it stays.

If there is an elegant solution to this, it would be appreciated... otherwise I will have to make do with a messy one. :P

What I ended up doing was having a subdomain "simpleview.example.com". Since I was already using the built in multisite, it opens up the same structure as "www.example.com" by default and all the links still work as they are relative. I then added a CSS file that would only show up if it was the simpleview subdomain (using the $_SERVER variable to get the URL) and made the elements I didn't want hidden with {display:none}.

Not sure if this is the best way to do it, but it got the job done without too much trouble.


Module ldap_sso lost when updating module to the new version I am in a process of updating the drupal core and some of the modules (quite deactualized). One of them is ldap module, on this server I have no way to update through the drupal administration page, currently the installed version is ldap 7.x-1.0-beta12, the system will follow me to install the ldap version 7.x-1.0-beta15.

As I mentioned, the only way I have to update is manually, I have deleted the files from the server and I have placed the new ones with the version ldap 7.x-1.0-beta15, when I run the update (update.php) it appears that there is a missing module called ldap_sso, and effectively when I review the contents of the ldap module there is no internal module called ldap_sso, but in the ldap version 7.x-1.0-beta12 if it is.

How can I update the module in this case?

Thanks

I found the solution,
In the mentioned version of ldap, ldap_sso was removed to a separate project, I proceeded to compare the code in case there was any important difference and the result is that they are the same.

So I proceeded to download:

ldap_sso from https://www.drupal.org/project/ldap_sso/releases/7.x-1.0-beta15 and

ldap from: https://www.drupal.org/project/ldap/releases/7.x-1.0-beta15 (by suggestion of drupal)

Now these modules go separately and I ran the update and it did not give any problem.

regards


What is the best protocol for uploading images in batch via FTP? What is the best protocol for uploading images in batch via FTP?

Let's say my website has 3 images.

Original size is 1000x1000

I upload all images via backend as "image upload".

Later on, I want to substitute all 1000x1000 images with identical images with same name but at size 400x400.

Curious as to what is the best workflow for Drupal for this scenario.

I want to substitute all 1000x1000 images with identical images
  with same name but at size 400x400.

Since they are identical, simply use image styles. Create an image style of 400x400 and assign it to your content type's image field OR in your image field settings in a View.

Watch: How to apply image styles in Drupal


hook_menu and Access Denied Why do all of these menu items return "Access Denied" pages no matter how many times I drush cc all and clear cache from admin/config/performance?

/**
 * Implements hook_menu()
 */
function caplogin_menu() {
  $items = array();
  $items['join'] = array(
    'title' => 'Foo settings',
    'access arguments' => array('access content'),
    'type' => MENU_NORMAL_ITEM,
  );
  $items['join/signup'] = array(
    'page callback' => 'caplogin_unified_registration',
    'access arguments' => array('access content'),
    'title' => 'Request Member Online Credentials',
    'type' => MENU_DEFAULT_LOCAL_TASK,
  );
  $items['join/login'] = array(
    'page callback' => 'caplogin_unified_login',
    'access arguments' => array('access content'),
    'title' => 'Members Login',
    'type' => MENU_LOCAL_TASK,
  );
  return $items;
}

For the first menu item, you didn't provide any page callback, and MENU_DEFAULT_LOCAL_TASK menu items inherited it from the parent menu item. In this case, Drupal returns a 403 error.
For the last one, the reason can be one of the following:

The page callback function doesn't exist, or it is defined in a file that is not the module file
The user account doesn't have the permission 'access content'


Add number of items as a class to menus I would like to add a class to menu that shows how many items are in that particular level.  I.E.

1

2

3

4

5

What's the best way to do this?

I've looked at theme_menu_tree but the tree is already rendered html by that point so there is no easy way to count the number of items.

It really feels like there should be a better way to do this (but I can't find one at the moment, theme_menu_link() isn't context-aware of its parent menu); however this will work:

function MYMODULE_menu_tree(&$variables) {
  // Load the current HTML into a DOMDocument to count the links
  $doc = new DOMDocument;
  $doc->loadHTML('
' . $variables['tree'] . '
');

  // XPath query to find only top-level
s
  $xpath = new DOMXPath($doc);
  $lis = $xpath->query('//ul[@class="identifiable-string"]/li');

  // Get the count based on the number of elements returned
  $count = 0;
  if ($lis) {
    foreach ($lis as $li) {
      $count++;
    }
  }

  return '
' . $variables['tree'] . '
';
}

It seems like a huge amount of effort (not to mention processor power) for not much reward, but if you're struggling then this method will definitely work.


How to display records in table programmatically? I'm using Drupal 8.0.1. I'm starting to develop a new custom module for learning purpose. Just I have created one form. From the form, the values are stored in my custom table. Now I want to show the records in separate page.

In drupal 7, I have used

  $query = db_query('SELECT id,name,email,age,gender FROM {learning}');
  $rows = array();
  while ($data = $query->fetchAssoc()) {
      // Fill the table rows
    $data['operation'] = l(t('Delete'), 'admin/people/survey/' . $data['id'] . '/delete');
    $data['operation'] .= "|";
    $data['operation'] .= l(t('Edit'), 'admin/people/survey/' . $data['id'] . '/edit');
    $rows[] = array('data' => $data , 'style' => 'word-break:break-all;' , );
  }
  //Number of records shown in per page
  $per_page = 4;
  $current_page = pager_default_initialize(count($rows), $per_page);
  $chunks = array_chunk($rows, $per_page, TRUE);
  // Prepare table header
  $header = array(t('ID'), t('Name'), t('Email'), t('Age'), t('Gender'), t('Operations'));
  // Output of table with the paging
  $output = theme('table',
    array(
      "header" => $header,
      "rows" => $chunks[$current_page],
      "attributes" => array(),
      "sticky" => TRUE,
      "caption" => "",
      "colgroups" => array(),
      "empty" => t("No Survey Records has been found")
    )
  );
  //return pager with limited number of records.
  return $output .= theme('pager', array('quantity', count($rows)));;

And this was working fine in drupal 7. I just want to do same in the Drupal 8. When I put this code in drupal 8 it shows error theme() not found. How can I create the table to show the list of records from my custom table.

In order to achieve this you need to do the following

Inject the database service as db_query is not working in Drupal 8 anymore
Use of theme() was discouraged in Drupal 7 as well, instead you need to use render array #theme key
Use Drupal 8 Database API db_select and chaining stuff and extend a special class Drupal\Core\Database\Query\TableSortExtender for rendering the data in tabular form
Finally form a render array with #theme key, #header, #rows.

The following example from my custom module display the data in table along with pager

      // Prepare _sortable_ table header
      $header = array(
        array('data' => t('ID'), 'field' => 'id'),
        array('data' => t('Name'), 'field' => 'name'),
        array('data' => t('Email'), 'field' => 'field1'),
        array('data' => t('Age'), 'field' => 'field2', 'sort' => 'desc'),
        array('data' => t('Gender'), 'field' => 'field3'),
        array('data' => t('Operations'), 'field' => 'field4'),
      );

      $query = $this->database->select('location','loc');
      $query->fields('loc', array('id', 'name', 'field1','field2','field3','field4'));
      $query->addField('loc','name','name_alias');
      $table_sort = $query->extend('Drupal\Core\Database\Query\TableSortExtender')->orderByHeader($header);
      $pager = $table_sort->extend('Drupal\Core\Database\Query\PagerSelectExtender')->limit(10);
      $result = $pager->execute();

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

      $build = array(
          '#markup' => t('List of All locations')
      );

      $build['location_table'] = array(
        '#theme' => 'table', '#header' => $header,
          '#rows' => $rows
      );
     $build['pager'] = array(
       '#type' => 'pager'
     );


How to convert a timestamp field into a date field? Is there a way to convert the data of a timestamp field into a regular date field in Drupal 8? preferably without coding or making a new module.

Export/import with Feeds

Feeds module can help to export the existing Timestamp field data and import it into a new Date field.

Feeds Tamper to convert from timestamp to ISO date format

I'm not sure if you can export timestamp into the ISO format directly. If you can't, then you may convert the timestamp to ISO format externally once you have it in a CSV file for example, or you use Feeds Tamper module to convert it during import.

Unix timestamp to Date is on the Feeds Tamper plugin list.

Setting up Feeds can take patience and time, so arm yourself with those, backup everything before starting to meddle with it, and test everything on a local/dev instance. (This always applies, but I find it's good to remind when dealing with Feeds.)

After you have the Date field correctly filled with data, you'll want to delete the Timestamp field.

Delete old Timestamp field

To do that you need to delete the Timestamp data and then the field from your system. You won't be able to delete the field that has some data in it.

To delete the Timestamp data you can use another Feeds import to update the nodes and make that field empty.

You could also delete the data with the help of Views Bulk Operations (VBO) or work directly on the database through some other SQL tool but that is probably out of scope here.

When the Timestamp field is empty you can delete it from your content type through the usual Drupal interface.


Override Module for mobile users I'm using Manual Crop, which is not functional on a mobile phone (you can't drag the resize tool), so I'd like to prevent the init on a mobile device.

Any advice on how to override a module for smaller screen widths?

I could set the mobile user to not have access via Mobile Tools, but I'm not confident that module will work for D7, plus it may be overkill for my needs.

Thoughts? Is this even possible?

Kate H

I can think of two approaches.

The quick(er) dirty way:

Hide it with CSS!

Problems:

I assume you're using seven or some other admin theme that you can't edit so all this will need to go in a module with drupal_add_js() or some other method for inserting JS.
After we determine if the visitor is on a touch device, we can't hide the element with simple jQuery because the element is dynamically inserted.

First, we'll need a way for JS to add CSS to the page. This function will let us do that:

function addCss(cssCode) {
  var styleElement = document.createElement("style");
  styleElement.type = "text/css";
  if (styleElement.styleSheet) {
    styleElement.styleSheet.cssText = cssCode;
  } else {
    styleElement.appendChild(document.createTextNode(cssCode));
  }
  document.getElementsByTagName("head")[0].appendChild(styleElement);
}

Then determine if the current visitor is on a touch device:

var is_touch_device = 'ontouchstart' in document.documentElement;

If so, add some CSS to page that hides the "Crop" button.

if (is_touch_device) {
  addCss('.manualcrop-style-button-holder {display: none;}');
}

The harder way:
Somehow determine if the current visitor is on a touch device via PHP. I don't have a foolproof method for this, but you can look into something like php-mobile-detect.

If you can determine that the visitor is on a touch device in PHP, you can return the manualcrop_croptool_process() function early. (Line 151 of manualcrop.helpers.inc). Of course, that will require filing an issue with module maintainer and providing a patch of those changes.


Change drupal language from neutral to en i have a huge drupal website(nodes) and i have to implement a multi language system now it has only one language.

I have installed the i18n module, and set another language but o can`t update the existing nodes from neutral language to EN or RO.

How can i update all the existing nodes from neutral language to EN.

Thanks

You should use Language Assign to easily update all the languages of your nodes.


How to reference without tagging? My problem is a priori simple: I would like in a node to refer to the terms of taxonomy that concerns this node, but without "tag" this node, ie: without the node is referenced in the list corresponding to the terms of selected taxonomy.

Indeed, currently, I use an "entity reference" field for "taxonomy terms", and when I refer to a taxonomy term, the node is automatically tagged and appears in the list of nodes related to these terms of taxonomy.

Now, in other words, I would like to "quote", "link", but not "tag".

Example:

I have a node: "Ernest Hemingway", I would like to reference in this node the term taxonomy "The books of Ernest Hemingway", which allows to link / access to all the books of this writer, but for all that, I do not wish the node "Ernest Hemingway" appears in the list "The books of Ernest Hemingway", which is a list of books.

It sounds simple, but I do not find how!

Do you know how to do it?

The pages that list content related to specific Taxonomy terms are created through views called Taxonomy term (usually at /admin/structure/views/view/taxonomy_term).

You can control what those pages output by editing that Views. I usually disable that original View and Duplicate it to work on overrides, so I can always refer back to the original if something goes wrong.

Which exact steps to take to exclude depends on your particular needs.

If there aren't that many nodes that need to be excluded you can just add the filter for node ID, use the Is not equal to Operator and enter the ID of the node that is not supposed to be found on Taxonomy term pages.

This solution will exclude that node from all the terms pages. If that node is referencing more than one term, it will not display on any of the terms pages.

To exclude more than one node you can add as many ID filters as you need, or more conveniently use the Regular expression, see this answer for more info: How to exclude multiple nodes based on their ID in taxonomy term view?

If you need to exclude your list of nodes from terms from one Vocabulary, but not from all the other Vocabularies, you'd have to modify the Contextual filter settings in those Views and configure separate ones for that special vocabulary and then the other Contextual for all the rest. You'd have to use the OR instead of AND (there's a module for that). This requires a bit more experience with Views configuration.

Another way may be to create a new field on your content, it probably makes the most sense to make it of type Boolean, that only have true/false states, and set those special nodes to True for that field (hide that field on Manage display, this is just your internal mark). Then in Taxonomy Views exclude the nodes that have that field set to True.

The advantage of this approach is that you control that when creating/editing nodes, while in the above solution you have to go edit Views each time.

Anything more than that you'd have to think about your site structure and change filters in Views to match that logic.


Recommended modules for managing Content access? I am looking for an access module.

Probably, the most popular is the Content Access module. But what modules are exist for that as well?

Also, when it says I have to rebuild the links (or permission, I don't remember) right after installation, what exactly does it do?

Recommended modules

Here is what I consider as the "shortlist" for such modules (quotes are from their project pages):

Content Access.

  This module allows you to manage permissions for content types by role and author. It allows you to specifiy custom view, edit and delete permissions for each content type. Optionally you can enable per content access settings, so you can customize the access for each content node.

Taxonomy Access Control:

  Access control for user roles based on taxonomy categories (vocabulary, terms).

  Automatically controls access to nodes (based on their taxonomy terms).
  Configuration page for each user role.
  Three node access permission types: View, Update, Delete.
  Two term access types: View tag, Add tag.

Simple Access (RC4 version only for D7):

  This module allows administrators to make some nodes private and/or editable by certain user roles. It can manage viewability, editability, and/or deletability and provides an easy way to make nodes accessible by only a group (or groups) of users. It is perfectly suited for making private nodes that are only viewable to certain 'access groups'.

  Access groups are based on roles. So for example, my site has roles entitled "Coach Level 1", "Coach Level 2", and "Coach Level 3". I can create an access group called "Coaches" and assign all of these roles to it. Then when I assign a node to be viewable only by "Coaches", only users who are a member of these roles will be able to view.

  Nodes that are not assigned to any access groups will remain viewable by all users, so all nodes will remain viewable when activating this module. And nodes only become private when they are assigned to an access group. The end result is that this module can be enabled for a site with existing nodes without making them all invisible.

Special case: Organic Groups, which provides 'Groups' for Drupal users, and management of Access Control based on these groups. A great resource for learning about Organic Groups is the (free) video training about Learn Organic groups, a set of 14 videos.

My "recommended" module is Content Access ... Also because of al sorts of integrations with the Rules module.

For more details, refer to Access Control modules.

Rebuilding permissions

About "Rebuild permissions": any time the "Access" rules are changed (via admin settings), Drupal needs to ensure that these rules are applied to all impacted content (nodes). That's why Drupal then re-applies the updated access rules. A special case is the "installation" (actually "enable") of a module, when rebuilding permissions is also required. Makes sense? Clear enough?


How to change all iterations of a string to another word? I noticed that most of my Russian clients afraid "Таксономия" ("taxonomy") word, because the word sounds like something very complex and incomprehensible for them:)

I want to change all iterations of "Таксономия" to another word, for example to "Классификация", because this word is familiar to everyone in Russia.

So how can I change one word to another in ALL iterations of the word in translate system ON EXISTING site. In other words, how can I bulk update translation by some algorithm instead of edit each string manually?

Method 1: Edit settings.php file

Pros

Quick method for small number of strings.
Less accessible in cases where you want to retain some control even after granting administrator access.

Cons

English only.
No admin pages, requires access to files on server (FTP / SFTP / SSH).
Difficult to delegate changes to non-developers.

Procedure

Edit settings.php for the site in question.

You'll need to either download the file, edit it, and re-upload it, or edit it in place on the server. Of course, make a backup.
Either way, you'll probably need to temporarily change the permissions of the file and its containing folder to to give you "write access". Be sure to take note of the permissions and change them back to what they were afterwards.
The default settings file is in drupal_root_folder/sites/default/settings.php

Look for this code at the bottom

# $conf['locale_custom_strings_en'][''] = array(
#   'Old string 1'      => 'New string 1',
#   'Old string 2'      => 'New string 2',
# );

Remove the comment marks ('#') and add string replacement assignments:

Method 2: String Overrides module

Pros

Admin page for managing string replacements.
Uses access permissions. Easier to delegate management of replacements.

Cons

Yet another module to install, update, and administer.
Possible performance hit and more difficulty to deploy (stores replacements in the database).
Uses access permissions. Harder to restrict changes when you have to give administrator access to others.

Procedure

Install and enable the module.
Follow the instructions / documentation for adding string replacements.

Method 3: hook_boot()

Procedure

Implement the hook_boot()
Use the same array as in the settings.php.

/**
  * Implements hook_boot().
  */
 function mymodule_boot() {
   global $conf;
   $conf['locale_custom_strings_en'][''] = array(
     'Old string 1'      => 'New string 1',
     'Old string 2'      => 'New string 2',
   );
 }

Method 4: Replace all the strings in the database

Procedure

Dump the database to a text file.

mysqldump -u user -p databasename > ./db.sql

Run a sed command to find/replace target string

sed -i 's/oldString/newString/g' ./db.sql

Reload the database back into MySQL.

mysql -u user -p databasename < ./db.sql

Note: All commands are bash commands on Linux, but you can replace them with another method.

References:

https://www.drupal.org/node/522036
https://stackoverflow.com/q/11839060/3653989


"You are not authorized to access this page." immediately after logging in with any user I'm getting the seemingly famous You are not authorized to access this page. message whenever I log in to my local development environment from /user or from /user/login. I'm on Drupal 7.26, PHP 5.6.3, running under XAMPP 3.2.1.

I've tried clearing all browser history, truncating flood and session tables, making sure I'm not defining $cookie_domain. I'm sure I've tried other things, but nothing seems to work. What should I try next?

This is one of those "this worked yesterday" things that became one of those "I was sure I fixed this but I have no idea how" things.

edit: So I ran the following to disable most of the modules and then logging in worked again:

drush @alias pm-list --type=Module --no-core --status=enabled | sed 's/.*(//' | sed 's/).*//' | sed '/^ *$/d' | sed '/^.*views.*$/d' | sed '/^.*entity.*$/d' | sed '/^.*ctool.*$/d' | sed '/^.*ctool.*$/d' | sed '/^.*date.*$/d' | sed '/^field_collection$/d' | sed '/^link$/d' | sed '/^youtube$/d' | sed '/^block.*$/d' | tail -n+2 > modules.txt; cat modules.txt
drush @alias dis `cat modules.txt`
drush @alias cache-clear all

I did have some issues such as Fatal error: Call to undefined function entityreference_get_behavior_handlers() in entityreference_schema(), which is why that command is so ugly. (I'm sure there's a neater sed command.) Now I'm turning on the modules one at a time.

edit: Disabling all modules and then re-enabling all modules except for the libraries module and modules that depend on allows us to log in again. However, enabling that module breaks logging in. This problem is only in our local development environments, not our hosted environments.

Backup the database and rebuilt the permission of the user under "/admin/reports/status/rebuild"..


what action can trigger clearing of caches? I have a site that is cached for anonymous users. However it seems that something clears caches every now and then (many times daily.) And it is not result of admins activity. I found about it only by chance, when looking at page_cache table, refreshed it after a while and all records were gone.
Question: how to start debugging this? What can I do to track what user action or anything causes caches to be cleared? Thank you.

Have you checked whether Cron is configured on your site under Configuration options.

When trying to speed up my site, this article was very useful as Cron will clear cache.

http://www.metaltoad.com/blog/how-drupals-cron-killing-you-your-sleep-simple-cache-warmer


How to get $form_id based on $form_state for custom form rule? I'm building custom form rule which is having $form_state as rule input parameter, however I would like to use drupal_form_submit() which requires $form_id.

Is it possible to fetch/compute automatically $form_id based on its $form_state to make my rule generic?

Or maybe there is some documentation that explains what $form_state should consist exactly?

My rule is like:

/**
 * Implements hook_rules_action_info().
 */
function rules_forms_rules_action_info() {
  $actions['rules_forms_submit'] = array(
    'label' => t('Submit the form'),
    'group' => 'Rules Forms',
    'parameter' => array(
      'form_state' => array('type' => 'form_state', 'label' => t('Form state')),
    ),
    'base' => 'rules_forms_action_submit',
    'access callback' => 'rules_forms_integration_access',
  );
  return $actions;
}

/**
 * Action: Submit the form.
 */
function rules_forms_action_submit($form_state) {
  // $form_id = ?
  drupal_form_submit($form_id, $form_state);
}

I've checked $form_state and it's a huge (~0,5MB size-like) ArrayObject with the following main keys/properties:

build_info, temporary, programmed, programmed_bypass_access_check, cache, entityform, entityform_form_mode, field, storage, rebuild, rebuild_info, redirect, submitted, executed, method, groups, buttons, input, values, complete form, process_input, invalid_token, triggering_element, submit_handlers, clicked_button

I think the easiest way was to pass $form ArrayObject which has $form_id present. So:

'form' => array('type' => 'form', 'label' => t('Form')),

needed to be added next to $form_state parameter in hook_rules_action_info and the final function looks like:

/**
 * Action: Submit the form.
 *
 * @param ArrayObject $form
 *   A reference to the form array of the form for which the event
 *   was triggered.
 * @param ArrayObject $form_state
 *   A reference to the form state array of the form for which the
 *   event was triggered.
 */
function rules_forms_action_submit($form, $form_state) {
  $form_id = $form['form_id']['#value'];
  $form_state = (array)$form_state;
  drupal_form_submit($form_id, $form_state);
}

For submitting entity form, check: How to programatically submit an entityform?


Check for existing node titles Is there a way to Add autocomplete to Node Titles?

This way I could display duplicate content to users before they add a new post.

Any suggestions?

Used Finder module as separate input box for people to check for existing titles.


Form custom with method GET remove form_build_id and op from GET variables If I create a custom form with get method:

$form['#method'] = 'get';

When I click the submit button, many variables are populated with GET
Can I remove them cleanly according to the drupal logic?

You need to alter the form after it has been built, for example

$build = [];
$build['filter'] = $this->formBuilder->getForm(LibrarySearch::class);
$build['filter']['form_id']['#access'] = FALSE;
$build['filter']['form_build_id']['#access'] = FALSE;
$build['filter']['form_token']['#access'] = FALSE;

Once the form has been turned into a render array, you can set the access to FALSE for those items. This is also documented in the core Search module.


How to give edit permission only to specific fields in node edit in? I have content type with some cck fields:

- task time
- task status
- task executor
- task category

and of course title/body and other drupal node default fields.

each node of this content type will be assigned to a user selected from site users in task executor field.

I want the when the executor logins view all fields of assigned to task(node) but only can change (edit) the value of task status field. node edit doesn't do that.

I try to use 'Content Permissions' of cck module but it is not what I really need. it doesn't have control on title and body field and also the user can only see the fields he has edit permission on them in node edit page.

What can I do?

I hope I could explain my question clearly.

Thank you.

You can use the Field Permissions module. It allows you to set permission for each field for every user type. It works simply fine.

  The Field Permissions module allows site administrators to set field-level permissions to edit, view and create fields on any entity.

  Features

  Enable field permissions on any entity, not just nodes.
  Role-based field permissions allowing different viewing patterned based on what access the user has.
  Author-level permissions allow viewing and editing of fields based on who the entity owner is.
  Permissions for each field are not enabled by default. Instead, administrators can enable these permissions explicitly for the fields where this feature is needed.


Context Module Rehashing Blocks Slows Website on Development So I'm working on a big website that runs fine on live (A bit on the slow side, but not unbearable), but when it comes to development servers it runs like ass (30 seconds to load a page ass). I used xdebug to profile the code, and what I found was that about half of the time in execution is spent updating the database. More specifically, on every page load when the Context module would load the the block list, it would look for block info in the cache, find nothing and then go and call _block_rehash, which then does DB updates for what appears to be every block. I tracked it down to where the context module tries to get a cache with

$cache = get_cache('context', 'cache');

And it comes back empty. I have caching enabled, block caching enabled, and I'm not sure why this is happening. Can anybody shed some light on this issue? This is an installation of Drupal 7 and Context 7-3.1

It turns out that my settings.php file had some custom code to completely disable caching for localhost machines, so that developers wouldn't be forced to refresh the cache all the time. Commenting out that code produced the performance that I expected


setting content to display on a basic page I'm creating a classified section on my site, and I have a basic page created for the content. How do i set content to go to that specific page?

Thanks for the help

set up a block view with all your classifieds and then  via admin/structure/blocks find your classified block and configure it to show on your basic page.


Creating specific front pages for departments The Drupal 7 site I am working on has its own company front page, and there are a couple of branches of the company in different location. I want to add specific front pages with "about / contact us / other menus" for each of those departments/branches of the company that will be displayed when each of the branches is accessed.

How can I achieve this?

If you don't want to code, and you are familar with context module you can use this Context Reaction Menus.
Add new context with a URL as a condition, for example "department1/*" and as a reaction change the main menu, this will change in all pages that start with "deparmente1"


403 Forbidden Error in Ajax call Actually this is first time to implement Ajax in drupal.
I would like to implement a user name validation using Ajax in user register section. When a user enter his name and filling another field, then validation is  running and if the user name already existing in the system, then a error message  shows, the user name is already taken.  I used to call the Validation function on "blur" event of Jquery.  The Jquery cod is below

$("#edit-name").blur(function()
{
$.post(Drupal.settings.basePath + "username_checking",{user_name:$(this).val()} ,function(data)
    {
if(data=='no') //if username not avaiable
      {
        $("#msgbox").fadeTo(200,0.1,function() //start fading the messagebox
        {
          //add message and change the class of the box and start fading
           $(this).removeClass();
          $(this).addClass('messageboxerror');
          $(this).html('<img align="absmiddle" src="images/Error.png" /> Username Not Available...').show().fadeTo(1900,1);
          disable();
        });
      }
 }
    });
 }
});

and I implemented the function in a hook menu as below,

    $items['username_checking'] = array(
'title' => 'username_availability',
'page callback' => 'username_availability',
'access arguments' => array('access caubo_registration content'),
'type' => MENU_CALLBACK
);

and function is here

function username_availability() {
$user_name = $_POST['user_name'];
$select = "SELECT name FROM name WHERE user_name='%s' LIMIT '%d'";
$result = db_query($select,$user_name,1);
$node = db_fetch_object($result);
if($node->name = $user_name){
  return "yes";
}
else{
  return "no";
}
}

It shows the error in Firebud
POST http://localhost/WC/drupal_website/username_checking
403 Forbidden

I want to confirm is my method is right or not ? If right please solve the problem, or give the exact way to do.

if this is a registration function for anonymous users do they have the respective access caubo_registration content permission set in User Permissions?


How to create rule to change user role based on points (using User Points module)? I'm using the User Points module which allow me to grant points to user. So far so good.

I need to create a rule to fire this condition/action: When user points are granted, then check if the user has more than 10 points. If so then add the "Master" role to this user.

I try using the Rules Condition "Data comparison", but I can't find the value something like "total points of the user".

Can I do this in any way?

Have you tried the user points contrib module. I am specifically referring to

userpoints_role

Users join/leave roles as they earn/lose certain points threshold.


How to conditionally book an appointment on calendar module? I would like to offer the opportunity for users of the site to book a visit to the doctor, do not let book if the day is full of appointments and show the day in red on the calendar.

Is this possible?

I'm not aware of any way to use the Calendar module for this. However, there are some distributions and/or contributed modules for managing such bookings. More details below.

Option 1: Distributions

The Clinic Appointment distribution is a brand new distribution for D7. Some more details about it (from its project page):

  It is a doctor appointment management system. It manages patient profile, doctors profile, and appointments. It supports multiple offices. It creates all kinds of reports that help clinic's day to day operation and business growth. It is a great choice for doctors to have an excellent management system built on a free open source software.

  Appointment Management System is the quickest way to get up and to run with patient appointment management. It includes the latest version of Drupal core, FullCalendar, and the other modules it is depending on. It lets you create a fully functioning appointment book, managing system out of the box. It comes with comprehensive reports powered by views module.

  Who should use Clinic Appointment? Anyone who want to build an appointment booking system. Anyone who wish to use it to schedule an appointment with doctor and patient. Customize patient, doctor content type by adding and deleting fields to the need for your business.

According to Comment nr 2 in issue # 2646628 it "Can be used for appointments made by patients" also.

Option 2: Contributed modules

These modules have a stable release, and can be used  for either D6 or D7 (quotes are from their project pages):

Availability Calendars (D6 or D7).

  ... allows you to add an availability calendar to entities. Example use cases are tourist accommodation, e.g. bed and breakfast, holiday homes or self catered apartments, and car or motor bike rental.

  An availability calendar shows your customers at what dates your accommodation is still available and at what dates it is already booked.

Simple Reservation (D6 or D7).

  ... provides a simple and easy way to reserve items which can be created by the administrator. Examples for it's usage can be hotel rooms, boats, cars, airplanes, basically anything you can think of which can be reserved by one individual.

  The module provides the possibility to create reservations for other users (dependent on the permissions), and provides also restrictions in the maximum number of reservations a user can make and a maximum time a reservation can be made in advance.

  There is NO support for payment, booking and what ever one could imagine beyond the pure and simple reservation, and it is also NOT intended to create more than this simple functionality.

MERCI (D6 or D7).

  ... can extend any content type into a list of unique reservable items (like studios) or buckets of interchangeable items (like DV cameras). We followed the approach used by Organic Groups, Feed API, and Scheduler and added MERCI's configuration to the Edit tab of those content types.

Resource Conflict (D6 or D7).

  ... allows for users to book resources for use during events. For example, a student can book a microscope for use within their lab.

Booking Systems Comparison

Refer to Comparison of Booking System modules for a comparison of various modules related to bookings / reservations.

This comparison contains some other modules (not mentioned in my answer here) that might be worth considering also, e.g. in case of requirements that are slightly different (as compared to those in the question here).

Deciding which module to go for

When deciding between multiple modules, a typical consideration is often about the "maintenance status" of the various modules. To illustrate some of the criteria I often use for that, please checkout the community documentation about Maintenance Scorecards. Here is the intro about it (from that page):

  ... contains a list of 23 criteria (=28-5) that might help to evaluate
  the maintenance and support of contributed modules. Below is an
  attempt to apply those criteria to each of the native charting modules
  ...

Obvious, these scorecards are related to "charting modules", but the same criteria are applicable, IMHO, wheneven you need to decide between multiple modules.

Disclosure: I'm the author of that community documentation page (partially inspired by the 28 criteria in the issue linked near the beginning of the scorecards paragraph).


How do you recycle a css file from a different theme into your new theme? I really like the form.css from Corolla. I have built a new theme, but would like to reuse Corolla's form.css.

Downloaded form.css from Corolla theme
Saved it to sites/all/themes/my_theme/css

Now what? Do I need to add a reference to this css file in the main css file? New to site building / theming, so our of my element.

Thanks - keb

As @cilefen pointed out you need to do a couple of things.

Put the form.css on sites/all/themes/my_theme/css/.
Update your sites/all/themes/my_theme/my_theme.info file to have stylesheets[all][] = css/form.css.
Clear the cache.

Oh and make sure that my_theme is set to default or at least active in the page that your are working.


Formatting text in Drupal 7 not working I am new in Drupal 7 and I am trying to format my text using CKEditor. I started to create a basic page, I supplied the Title since it is a required field, then I put my text inside the body, there is a section in the Body that I want to use <h1> to make it look like the page title. So to do this, I clicked Heading 1 from the Format drop-down. On my editor the text now looks bigger, but when I tried to save it the <h1> tag was not implemented. I also tried to style my text using css but it didn't work.

How can I fix this?

You need to set the text format as Full HTML, text format select list will available below the body text area.

If the text format is specified as Plain text, then it will remove the html tags.

You can find out more information and best practices here - Specifying the allowed formats for user input


an image that is inside the content Good morning,
I use the Zen theme. I did override the node.tpl.php putting a copy in myzen / templates /, I saw that the content is printed with this statement:

print render ($ content);

my problem is that having made my own content type, content is an image and text, I would give a different width by css to my image and text. how do I make a reference with css at image and text placed separately?

The $content variable is an array (a 'render' array in Drupal parlance). You'll be able to render the parts of the content individually instead of all in one go if you want, and wrap them in specific HTML:

  <?php echo render($content['body']); ?>

  <?php echo render($content['field_some_image_field']); ?>

You can even provide a template file for just the content type you want to change, by calling it node--content-type-name.tpl.php, and just apply the changes to that particular content type.

For styling, each field will already be wrapped in HTML with many, many classes attached to it. Just fire up developer tools/firebug, inspect the elements, and you'll find the correct selectors to target with CSS. If that fails, you've can add the wrappers in yourself like in the code example above.


Organic groups, group content types and pathauto In pathauto module settings I have

  localhost/[node:group_group]

for all group types. I have few group types:
Ex Technology, Arts, Design etc and within each group type you can create as many groups as you want.

So when I create a group named google, the path looks like this :

  localhost/technologies/google

.

I want to have any article created within that group and to have a path like this

  localhost/[node:group_group]/[node:title]/[content-type]/[title]

Ex:

  localhost/technologies/google/article/some-article

How to achieve something like this?
I could not find any token replacement pattern for my use case in pathauto module. Is there some trick here?

Thanks

I tried:

[node:og-group-ref:url:relative]/[node:menu-link:parent]/[node:title]

Worked like a charm.

So, I guess that you should go with:

[node:og-group-ref:url:relative]/[node:content-type]/[node:title]

Note:
Posted the answer since this was the first result on Google (for me), and no answer was given... Perhaps it will put someone else in the right direction faster.


Menu token. Problem with [current-user: name] I saw this question, but how to make that anonymous user does not see this menu link "anonymous"?

check permissions and make sure anonymous users don't have access to that page (or set of pages, content type)


How to resolve the 403 error when creating a new node via RESTful module? I'm trying to create a new node through REST on Drupal 8 with no success and a 403 (Forbidden) error. I'm using REST UI module to enable permissions with the following config for Content resources:

  GET authentication: basic_auth formats: hal_json, json

  POST authentication: basic_auth formats: hal_json, json

After many failed tries I installed a fresh copy of Drupal 8.2.3 to discard it had to be with the recent core upgrade on my original site. The big surprise is on the fresh site there are no other RESTful module permissions than Administer REST resource configuration, no permissions to grant DELETE, GET, PATCH or POST to each role.

I'm using Postman for testing purposes as follows:

Request body:

{
    "_links": {
        "type": {
            "href": "http://fischer.dev:81/rest/type/node/article"
        }
    },
    "title": [
        {
            "value":"My article"
        }
    ],
    "type": [
        {
            "target_id":"article"
        }
    ]
}

User role is granted permissions to create Article nodes. I tried even with the admin credentials with no success. The GET method for retrieving an existing node is woking fine.

I don't know if there was any change on the latest Drupal release since the official documentation page for this module appears to be outdated. Am I missing something?

For headers you only need Content-Type and Authorization.

Your POST url needs to be http://fischer.dev:80/entity/node (this is only for POST).

If you are going to PATCH or DELETE, the url would then be the url of the node, Ex: http://fischer.dev:80/node/1 that you want to update (patch) or delete.

PS: Not really sure why you have port numbers in your url, and why you were using port 81 instead of 80, using http://fischer.dev/entity/node should be good enough.


How do I add a My Account Item to a New Menu? Hi I need to add a My Account link to a new menu. I know about me aliases module and others, but I would like to do it using my own code. Any ideas ?

Update: I am using Drupal 6. Is it possible to use the My Account provided by the user module in a differente menu than Navigation ?

/**
* Implementation of hook_menu().
*/
function mymenu_menu() {
$items['user/%user_uid_only_optional'] = array(
'title' => 'My account',
'title callback' => 'user_page_title',
'title arguments' => array(1),
'page callback' => 'user_view_page',
'page arguments' => array(1),
'access callback' => 'user_view_access',
'access arguments' => array(1),
'menu_name' => 'your-menu',
);
return $items;
}


See Which User Created/Edited Block? Is there any way in Drupal 7 to view which user last made edits to a particular block, or who created the block?

STEPS:
1. Start creating a new view by clicking "Add new view" link under Admin > Structure > Views.

2.
a) Type "Other Contents by Author" in "View name" text box.
b) [Optional step.] You can check "Description" checkbox and write a description for view. If you wish, check and write "A list which contains other content by author."

Select "Content" from the "Show" select list.
Uncheck "Create a page".
Check "Create a block". You can enter any block title you wish. To limit the items shown in block, type a number in the "Items per page" text box. (You can change it later.)
Click "Continue & edit". At this stage, it is a good idea to click the "Save" button after each alteration/change to save the View.

7.
a) Click the "Advanced" link in right side of the page (if the pane is not open).
b) Click the "add" link in CONTEXTUAL FILTERS row.
c) Check the "Content: Author uid" checkbox from the "Add contextual filters" popup.
d) Click "Apply..." button.
e) Check "Provide default value" option in the WHEN THE FILTER VALUE IS NOT AVAILABLE section.
f) Select "User ID from URL" from the "Type" select list.
g) Check "Also look for a node and use the node author" checkbox.
h) Click "Apply..." button.

8.
a) Click "add" link again in the CONTEXTUAL FILTERS row.
b) Check "Content: Nid" checkbox from the "Add contextual filters" popup.
c) Click the "Apply..." button.
d) Check "Provide default value" option in the WHEN THE FILTER VALUE IS NOT AVAILABLE section.
e) Select "Content ID from URL" from the "Type" select list.
f) Scroll down to the MORE section and check the "Exclude" checkbox.
g) Click the "Apply..." button.

Click the "Save" button and save the view.

You can add different fields and filters and make changes to create solutions for different needs.


Overwrite jquery.ui.slider.min.css generated by jQuery Update module The jQuery Update module generates a css file jquery.ui.slider.min.css for my website. I need to overwrite the jquery.ui.slider.min.css for this slider field. I don't want to loose my changes when we update the jQuery Update module.

What is the best way to add jquery.ui.slider.min.css into my theme?

The solution is to insert in your themes template.php the following:

function mytheme_css_alter(&$css) {
  if (isset($css['misc/ui/jquery.ui.theme.css'])) {
    $css['sites/default/modules/jquery_update/replace/ui/themes/base/jquery.ui.theme.css']['data'] = drupal_get_path('theme', 'mytheme') . '/mytheme_jquery_design/jquery.ui.theme.css';
  }
}


How do I override a fields output in a Views template? I have a field, foo, set to "Exclude from display", and output later in a "Global: Custom text".

I need to control the rendering of this field based on a different value on the same node.
I thought I could just implement a template file like:

function THEME_views_view_field__VIEWNAME__DISPLAYNAME__FIELDNAME($view, $field, $row) {
  $output = isset($bar) ? $foo : $baz;
  return $output;
}

But as soon as I add this function to my template.php file, I loose all output instead. No matter what I return, I get nothing. I tried trivial things like

return 'AAAAA';

to no avail. I'm probably doing something very simple wrong, but looking at my own previous attempts to do similar things in the same template file, I can't see what's wrong. Yes, I've cleared the cache numerous times.

I don't know if this is the answer you wanted, but I template the individual fields by templating the custom:global, and accessing the individual pieces through the $view object.


How to add link to my module in the Structure admin page I would like to add a link to my module in the Structure admin page.

I already use a hook_menu for turn in my module accessible but how can I add a link in the "structure" admin section ?

function tamtamimporter_modules_menu() {
$items['admin/config/tamtamimporter'] = array(
        'title' => 'Gestion du Tamtam importer',
        'description' => 'Gestion de l\'importation des flux par le biais du module Tamtam importer',
        'page callback' => 'tamtamimporter_modules_page',
        'page arguments' => array('tamtamimporter_modules_page'),
        'access arguments' => array('administer site configuration'),
        'file' => 'tamtamimporter_modules.admin_list.inc',
        'type' => MENU_NORMAL_ITEM,
);
}

Thank you very much for you help.

You would need to specify a url that beggins with /admin/structure for that matter (Drupal 7).


How to display "NEW" label in comments list How do I display the "(new)" label in comments listing page.
What is the logic of displaying the "(new)" label. How does it work?

There is a database table called history that records a users history to check against. There is an option in Views to add a 'new' marker to content that has not been viewed by the user and had been created within a certain time frame. If you are further interested in how the 'new' marker works, you can find the query that Views uses in views/modules/comment/views_handler_field_node_new_comments.inc to add the 'new' tag to a list of fields.

(edited for clarity)


Change TPL file based on taxonomy term I would like to change the tpl.php file used depending on the taxonomy term applied to a node.

There is a snippet on this page that explains how to do that. However, it is written for Drupal 6, and doesn't work for Drupal 7.

The snippet is as follows:

// Add this to your theme's template.php
// Replace "THEMENAME" with your theme's name
function THEMENAME_preprocess_node(&$vars) {
  foreach ($vars['node']->taxonomy as $term) {
    $vars['template_files'][] = 'node-term-'. $term->tid;
  }
}

I have tried to update it for Drupal 7 as follows:

function THEMENAME_preprocess_node(&$variables) {
  foreach ($variables['node']->taxonomy as $term) {
    $variables['template_files'][] = 'node-term-'. $term->tid;
  }
}

However, it still doesn't work. I just get the following error message:

  Notice: Undefined property: stdClass::$taxonomy in
  THEMENAME_preprocess_node()  Warning: Invalid argument supplied for
  foreach() in THEMENAME_preprocess_node()

Any help would be appreciated.

You could probably handle it with the following code:

function mytheme_preprocess_node(&$variables) {
  if (isset($variables['node']->field_myfield[$variables['node']->language][0]['tid'])) {
    $tid = $variables['node']->field_myfield[$variables['node']->language][0]['tid'];
    $variables['theme_hook_suggestions'][] = 'node__term_'. $tid;
  }
}

Now if a term with the id 6 would be referenced from a node's 'field_myfield' Drupal would look for a template named 'node--term_6.tpl.php' and use that if available.


How to achieve order fulfillment in drupal commerce like ubercart? I'm new to drupal commerce. I would like to know how to achieve Order fulfillment in drupal commerce like ubercart. I'm using UPS,FedEx & USPS for shipping. I had seen package options in each shipping methods configuration. I'm confused to handle shipment process for orders. Is there shipment requirements has send automatically to respective shipping service(UPS,FedEx & USPS) after creating an order?

Please help me to get clear about handle order shipment process in drupal commerce.

Have you tried https://drupal.org/project/commerce_delivery at all? That appears to be used in conjunction with https://drupal.org/project/commerce_physical_fields and its dependent Physical Fields module.


Theming a custom user field on register form I have added a checkbox list field on the register form and I want to change the template for that field.

I have used field--field-checkbox-list.tpl.php and MYTHEME_field__field_checkbox-list() function, but with no luck on user_register_form.

Two possibilities.  You could alter the form element with hook_field_widget_form_alter, or you could override theme_checkbox.

More info: http://drupal.org/node/173880


How do I get an argument of a path with Rules URL Argument? I am trying to get the first argument of a path in rules. That argument would be needed to fetch an Entity. I have no idea how to "tell" Rules URL Argument "get the first argument". Then I tried to get that part of the URL with regex...but I failed retrieveing just that part (it only checks whether it is "there").

I am not a coder....no idea of php...

Note: I tried for example to set the Argument path Name: site:current-page:path:1 - which is obviously not working.

To make the value of the URL argument available as new variable to Rules, you can use the Rules URL Argument module. Here is a quote about it (from its project page):

  ... provides two rules conditions based on URL arguments:

  check if a URL argument is present.
  compare the value of an URL argument.

  It also provides an action that makes the value of an URL argument available as new variable to Rules.

The newly provided Rules actions and conditions can be found under the "URL Argument" conditions and actions groups in the rule configuration interface.

For an example of how to use it, refer to Comment # 3 in issue # 1686360 which is about "Pass an amount to the url, ie; site/content/node-title?amount=10 or /node-title?=amount:10". Here is the relevant part of it:

  add a "Check if URL argument exist" condition to your rule and set the "ARGUMENT" value to "amount".
  add "Provide URL argument value" action to the rule and set "URL ARGUMENT NAME" value to "amount" and in the "Provided variables" section "ARGUMENT FROM URL - Variable name" to e.g. "amount_from_url".

  You will now be able to use the amount value as a variable "amount-from-url" for other actions in this rule.

For an example of a rule (in Rules export format) that uses this module, refer to (Step 4 of) my answer to "How to limit access of a view about Group Memberships to the Group's administrator?".

The above explains How to get AN argument (as in the question title) using this module. However, to my knowledge this module cannot be used to set the ARGUMENT value to "the first Argument" (as in your comment below this answer).


how to add next and previous link on content full display page on tpl file in drupal 7? I have a content type called flower and I have created a node--flower.tpl.php for displaying products.

I am also using category of flowers. I need to add next and previous links on this page for a specific category. For example if I'm on rose page then all roses are needed to show on next and previous link, not other category data.

You will have to write this logic yourself in a hook_preprocess_node(). This code should be added to the template.php file of your front end theme.

Here's an example:

function YOUR_THEME_preprocess_node(&$variables) {
  // Perform the logic for selecting prev/next terms here. Install and use
  // the Devel module to see what is available to you and to debug the code.

  // See what's available:
  dpm($variables);

  // Load a sample term. Note: this should be different if your website is
  // in multiple languages. Below is just an example.
  $term = taxonomy_term_load($variables['node']->field_term[LANGUAGE_NONE][0]['tid']);

  // Pass a variable to the node--flower.tpl.php file. Code below will make
  // the $previous_category and $next_category variables available in the
  // node--flower.tpl.php file.
  $variables['previous_category'] = 'Your link here';
  $variables['next_category'] = 'Your link here';
}


Put link/button in email to reply to sender on website I'm having a bit of trouble figuring out how this is meant to work. What I'm trying to achieve is as follows:

1) I've got Webform module installed and working. Just has generic fields for now.

2) What I want it to do is as follows:

User A wants fills in the form (webform) asking for a quote to clean their 3 bedroom house. This form gets submitted and cleaning companies get notified by email. - This bit I have figured out!

BUT - What I want to happen is that when the cleaning companies receive this email (name, number of bedrooms etc) I want there to be a link within the email that allows the cleaning company to click on that takes them to another form on the website where they can enter quote information (like price, imagery etc). When the cleaning company clicks submit the original user A gets notified a quote has come in.

Any ideas how I set this up? It doesn't appear to be included in the standard module.

I don't think you can do this from webform alone.  I would create a custom form (using Form API in a custom module) with a path that includes a parameter to identify the original webform submission.  Something like /quote-response/{webform-submission}.  The "response form" then queries the webform submission to get the email of the person who submitted the original quote request.  Keep in mind if this route doesn't require any authentication, you could be opening yourself up to bots / malicious users, so I recommend implementing some additional security / verification.


Drupal node update detection Can anyone suggest how I might detect when a node has been updated via jquery?

I know jquery is a client-side technology but I really need to utilize jquery(ajax) to alert my users when a node is updated.

In the classic HTTP model, the server is passive and can only return information to the client when it request it. So, in this model, to alert the users when a node is updated, you have to periodically poll the server the ask it if the node has been updated. If you have a lot of clients waiting for the update of a lot of nodes, this can quickly overload your web server with too much request to handle.

Today, the best solution for this kind of requirements is to use WebSockets or a similar full-duplex technologies. Drupal and PHP are not designed to serve a WebSockets. Technologies like node.js and Socket.IO,  or APE are more suited.

The Node.js integration module integrates node.js and Socket.IO in a easy to use solution. It provides an API to easily implements your need.


Multiple Registration forms (with unique roles)? I have a scenario where I want users to be able to register via the standard registration form and be assigned a role of "tenant". I also need the ability for site administrators to be able to create either "tenant" roles (with unique fields) or "landlord" roles (with their own unique fields and roles).

I've looked at profile2, user role field, and field permissions as possible modules, but I'm unable to see a way of getting this to work. How can I make certain fields required for one role, but hidden for another?

Sounds like profile2_regpath will help you.


How to programmatically apply a fee/promotion? I am trying to use the new commerce_fee module to programmatically apply a fee during admin payment flow. I did a simple form_alter to the commerce_payment_add form to have a list of my Fee entities show up as checkboxes. This allows staff to add the specific fee if they choose.
I also set:
$form['payment']['amount']['#default_value']['number'] = $form['payment']['amount']['#default_value']['number'] + $form_state->getValues()['fee_amount'];

so that the fee is added in to the next step as the amount which will be charged to the customer's CC.
But the Fee is not properly added to my Order. I have seen Commerce documentation and a post here re: this but they do not work. At the moment I have a #submit added to the payment_add_form which follows some of the code I have seen; but no luck:
function _sia_add_fee_to_order (&$form, $form_state) {
  // its crazy that i need to figure out the Order from the URL; why isn't it in the form??
  $url = $_SERVER['REQUEST_URI'];
  $bits = explode('/', $url);
  $order_id = $bits[4];

  $order = Order::load($order_id);
  $fee = current(Drupal\commerce_fee\Entity\Fee::loadMultiple());

  $price = $fee->getPlugin()->getConfiguration()['amount'];
  $splitter = \Drupal::getContainer()->get('commerce_order.price_splitter');
  $amounts = $splitter->split($order, new Price($price['number'], $price['currency_code']));

  foreach ($order->getItems() as $order_item) {
    $order_item->addAdjustment(new Adjustment([
      'type' => 'fee',
      'label' => $fee->getName(),
      'amount' => $amounts[$order_item->id()],
      'source_id' => $fee->id(),
    ]));
  }

  $fee->apply($order);
  $order->recalculateTotalPrice();
  $order->save();
}

The post I saw here left out all the commerce documentation steps of adding adjustments to each line item and simply had the $fee->apply() function. Neither of theses work.
ADDED:
More info about commerce_fee: https://www.drupal.org/project/commerce/issues/2903716, https://github.com/lisastreeter/commerce_fee
This is basically the commerce "promotion" module but redone to be more specific to fees. The question i have posted could be asked re: promotions as well; as should apply equally to either.

After a lot of trial and error I thought of moving the code out of the form submit function and into an event subscription; in particular, i moved it to the commerce_order.order.paid event.
So I ended up with this in an existing event subscriber call back I already had:
  public function placeOrder($event) {
    $order = $event->getOrder();

    $fee = current(\Drupal\commerce_fee\Entity\Fee::loadMultiple());
    $price = $fee->getPlugin()->getConfiguration()['amount'];
    $splitter = \Drupal::getContainer()->get('commerce_order.price_splitter');
    $amounts = $splitter->split($order, new Price($price['number'], $price['currency_code']));
    foreach ($order->getItems() as $order_item) {
      $adjustments = $order_item->getAdjustments();
      $adjustments[] = new Adjustment([
        'type' => 'fee',
        'label' => $fee->getName(),
        'amount' => $amounts[$order_item->id()],
        'source_id' => $fee->id(),
      ]);
      $order_item->setAdjustments($adjustments);
      $order_item->save();
    }
  }

This code includes code to split the fee up among all the items; which may or may not be what you want (although doesn't seem like it could ever be a bad idea).


How to replace the search submit button with a Font Awesome character? I would like to replace the search submit button with a Font Awesome character like the Magnifier (Search Icon) character, and put Search the site inside the search box.

How can I achieve something like this?

In order to add the new form button, I used hook_form_FORM_ID_alter in my template.theme file in my theme folder (Notice:replace ThemeName with the name of your theme in below code):

ThemeName.theme:

**
 * Replace the Search Submit Button with a Font Awesome Character.
 */
function ThemeName_form_search_block_form_alter(&$form, &$form_state) {
  $form['keys']['#attributes']['placeholder'][] = t('Search');
  $form['actions']['submit']['#value'] = html_entity_decode('&#xf002;');
  $form['actions']['submit']['#attributes']['class'][] = 'search-button';
}

Remeber use html_entity_decode() to parse the Unicode code.
and CSS:

.search-button input[type="submit"]{
    font-family: FontAwesome;
    color: #fff !important;
    display: inline;
    font-size: 18px;
}


How do you programmatically hide a field based on another field on a custom content type? I have built a custom content type that has a boolean field called 'Hide images'. There is also an images field that displays all images at the bottom of the node. I'd like to setup a way so that depending on the 'Hide images' field I can decide whether to display the images field. Is there a way to edit this via a template?

I saw in page--node--contenttype.tpl.php that I could render($page['content']); but I couldn't actually see how I could choose what content to display.

In your template, instead of rendering the entire content array, you can break it down to print each individual item separately.  Then, you could wrap the printing of the images in a statement that checks if the boolean value is true/false.

<?php if ($content['field_boolean_hide_images'] === FALSE): ?>
  <?php print render($content['field_image']); ?>
<?php endif; ?>

This is just an example and shouldn't be used verbatim.

Also, to create a template for your content type, it would be node--yourContentType.tpl.php rather than a page template override.


How to access a table I inserted manually into Drupal 7 db I just inserted a new table into the Drupal db called mini_table with my own custom data using only phpmysql. How do I access this table's data for use in my *.tpl.php files?

EDIT: No cause for alarm. All my code is in template.php and not in any *.tpl.php file. Just wanted to clarify that.

You shouldn't do  a query from a .tpl.php or include any php logic there. If you have to do it in the theme (this would be better in a small custom module), do it in the template.php in a preprocess function (node or page preprocess, depending on what template you want your variable available).

So you do your query in the template.php file and then through a preprocess function send the variable to your .tpl.php files.

I also don't recommend writing MySQL queries in Drupal, you should use the Drupal API for this. Drupal has a database abstraction layer that gives you lots of handy function you can use.


Can I add php code on title of a link? I have this problem: I created three content types. Actor, author and musician.
An user can modify own actor, author and musician profile, if his role is one of these.

A user can have more than one role, so, he can be actor, author and musician.
An actor can be a man or a woman, so his role canbe actor or actres.
In user menu I must have links on pages for these roles, so, an actor can have actor/[user:name] and an author can be author/[user:name].
Title of these links should be [user-name] actor or actres depending on the role.

Ok, I can use user-name token, but how can I retrieve the role?
Can I use php code on title of link?

Since you did not specify a version I am assuming Drupal 8, but the hooks are nearly the same for Drupal 7. (You can navigate to them from the linked documentation pages).

The problem is that a user can have multiple roles and they can be assigned in a random order. This way you can never be sure that the correct role is shown.

You could try to provide Drupal with some custom tokens for these roles. This means you'll have to create a small custom module, but that is really not that hard.

Create a folder with your module name.
Create a <modulename>.info.yml file within that folder. (<modulename>.info for Drupal 7)
Create a <modulename>.module file within that folder.

Then you'll have to implement 2 hooks in your .module file:

hook_token_info_alter(). This allows for the tokens to show up in the token browser.

hook_tokens_alter(). The code could look something like this:

function <modulename>_token_info_alter(&$data) {
  // Add description of user tokens.
  $data['tokens']['user']['actor-role'] = array(
    'name' => t("Actor role"),
    'description' => t("Role if the user is an actor."),
  );
  $data['tokens']['user']['author-role'] = array(
    'name' => t("Author role"),
    'description' => t("Role if the user is an actor"),
  );

  // Add as much as you like (need).

}

function <modulename>_tokens_alter(array &$replacements, array $context, \Drupal\Core\Render\BubbleableMetadata $bubbleable_metadata) {
  $options = $context['options'];

  if ($context['type'] == 'user' && !empty($context['data']['user'])) {
    $user = $context['data']['user'];

    if (isset($context['tokens']['actor-role'])) {
      // PHP logic to determine the role. Below is an assumption and might not work.
      // Set the value to the actor-role token to 'Actor' or nothing.
      $actor-role = $user->hasRole('actor_role_id') ? t('Actor') : '';
      $actress-role = $user->hasRole('actress_role_id') ? t('Actress') : '';

      // Combine them (one should be empty leaving the other)
      $actor-role-to-show = $actor-role . $actress-role

      $title = $node->field_title->view('default');
      $replacements[$context['tokens']['actor-role']] = $actor-role-to-show;
    }

    // Again add as many as you like.
  }
}

Now you should be able to use [user:author-role] and any other tokens you have defined.


trouble with a view template I created a block view and am having trouble controlling the out put. Theme developer tells me the candidate template file is views-view-fields.tpl.php that file doesn't look like any of the others I have worked on. I have found the only control I have over the output is through the view settings itself. Why can't I format the output like any other block or page?

I've experienced the same issues with my conversion from D5.x to D6.x and what I ended up doing was to install the Semantic-Views module.  It allows, at a row/field level the ability to add classes to each field.  Not only does this work well it is a heck of a lot easier than creating and maintaining a tpl.php file.  Try it, you'll like it.


Where can I find custom content type templates file? Sorry for ask this easy question, I know the net its full of tutorials, but the info is a bit confusing since they are always showing the diference between D7 and D8 (i didn't use a CMS before so it is not helpfull enough)

My "news" custom content displays itself without classes, with the title of every field in the content and I want to modify the creation template.
Am I allowed to do that? or its supposed to reach this goal through other way?.

Thanks in advance

It's all in here Twig Template naming conventions

Nodes
Pattern: node--[type|nodeid]--[viewmode].html.twig
Base template: node.html.twig (base location: core/modules/node/templates/node.html.twig)

Theme hook suggestions are made based on these factors, listed from the most specific template to the least. Drupal will use the most specific template it finds:

1. node--nodeid--viewmode.html.twig
2. node--nodeid.html.twig
3. node--type--viewmode.html.twig
4. node--type.html.twig
5. node--viewmode.html.twig
6. node.html.twig
Note that underscores in a content type's machine name are replaced by hyphens.

The higher the number the less specific, For example, the last one (6) it affects everything.

While (1) affects a specific node with a specific view mode, Ex: node--1--teaser.html.twig will only affect /node/1 with teaser view.

For your case, you want to use (4), so in your case, its node--news.html.twig


I need to store an array of integers for configuration of a custom module - which of these is right? This is a list that is permanently recorded that should be able to change at a later time, either adding or removing items from the array at a user's discretion.

First method:

variable_set('module_listOfIntegers', serialize($arrayOfInts));

Second method:

$serialized = serialize($arrayOfInts);

$num_updated = db_update('module_config')
->fields(array(
  'listOfIntegers' => $serialized,
))
->condition('config_name', 'config_name, '==')
->execute();

And the final method could be creating a 2nd table with a single column where each row just holds the integer.  That seems a bit excessive for a simple array, though.

For saving module config settings, I use variable_set() in conjunction with the system_settings_form() function. Just also note that it and its companion variable_get() do the serialize/unserialize for you, so, there is no need for you to be doing it.


Display delete confirmations in a modal window How do I display delete confirmation form in a modal window? I have a view which displays submissions of an entity form. Each one has a 'delete' link for the admin to remove a particular submission, but clicking it goes to a new delete confirmation page (entityform/[nid]/delete). How can I display this confirmation page in a modal overlay, like the edit forms?

I tried the overlay_path module but it tried to display a styled page in the overlay and it looked terrible with my current theme

You can use https://drupal.org/project/ctools_automodal and then use menu_alter to use following code and see if it helps.

function modulename_menu_alter(&$items) {
    $items['entityform/%entityform/delete']['modal'] = TRUE;
}

Be sure to clear cache.


how do I control order of promoted pages? I have a bunch of pages I have promoted to the front page and I'm wondering how I can control the order the items appear in? This is in Drupal 7.

There is a tutorial at Custom re-ordered front page teasers. It uses the pre-packaged view Front page that comes with Views, as well as the Nodequeue module to re-order the teasers.

  The Nodequeue module allows users to collect nodes in an arbitrarily
  ordered list. The order in the list can be used for a any purpose


How to get the customer name in Commerce order confirmation e-mail? How can I get the customer name from the billing information variable in the commerce-order-receipt.twig.html template of the Drupal 8 Commerce order confirmation e-mail?

First, you have to create function as @NoSSweat suggested (thanks for the hint) and from it get it like:
function hook_preprocess_commerce_order_receipt(&$variables)
{
  $givenName = $variables['billing_information']['#profile']->get('address')[0]->given_name;
  $variables['given_name'] = $givenName;
}

(was incredible hard to figure this out :) ) Field name for last name would be "family_name". Checkout the file:
/modules/contrib/address/src/Plugin/Field/FieldType/AddressItem.php
for other available fields.
I added this function to my module, but adding it to theme file should also work.
That way you are assigning variable which is now available in twig template so you can print it simple as:
{{ given_name }}

Don't forget to clear the cache.


Which hook will load after node page load and file download I need to run  db_insert and db_update once after a node is loaded. Its only for particular node content type. Which hook can i use for it?. Can i add that hook in template.php instead of adding it in a .module file?.

I need another hook which will run once after a file gets downloaded.

It's not really clear what you need re node hooks, since your title says "after node page load" and the body of your question says "after a node is loaded". Those are very much two different things. If you're looking for a hook that fires after the page has been displayed on the front end, there isn't one (though you could theoretically implement your own using AJAX).

Your best bet would be to consult the list of Node API Hooks and select the one that best suits your exact use case.

To get notified of file downloads through the private file system you can implement hook_file_download(). There's nothing similar for public file downloads, as Drupal's default behaviour is to pass straight through to existing files, without bootstrapping (hence no hook could ever be fired).


Problem on the comment form #validation and #submit I've tried to create a validation and submit functions on a custom comment form, using drupal 7.9,  but it's not working, and I don't know why.

In the following code, we can see the "dpm's" in the first function, but not the "dpm's" in the last ones.

function job_form_comment_node_job_form_alter(&$form, &$form_state) {
    $form['#validate'][] = 'job_comment_validate';
    $form['#submit'][] = 'job_comment_submit';
    dpm($form);
    dpm($form_state);
}

function job_comment_validate($form, &$form_state) {
    dpm($form);
    dpm($form_state);
}

function job_comment_submit($form, &$form_state) {
    dpm($form);
    dpm($form_state);
}

if I add a #validate or #submit it also doesn't call others drupal hook comments like presave, insert etc.

If I comment these lines, the hooks are called, but I can't use the validation or the submission functions in this case.

Do you have any idea on why this happens?

You're missing $form_id, the third parameter of the function.

See hook_form_alter() reference on drupal.org. The problem you're experiencing might be a (weird) way of PHP reacting to that.

In situations like this you may want to check for errors on the logs (Drupal, PHP, MySQL). Some times there are useful hints there to figure what's wrong.


How to detect Adblock on my Drupal website? I want to be able to detect if the user is using adblock plus or any blocking ad extension. How can I do this in Drupal ?

Why ? I'm building a website that is going to contain ads on a block (so far I do not think I would use the adsense module) that block would only be display it to anonymous users. If the user have adblock plus enable on their browser, I would like to show another block that said something similar to this "If you enjoy our content free to ads you should become a member of this site. Ads help us creating more content." I would set a link on that block to encourage user to buy a role to help that website.

So far I notice there is a very popular question at Stackoverflow "How to detect Adblock on my website?". But I was wondering if there is a module or better Drupal way to detect if the user is using adblock plus.

As of right now, there are no ad blocking modules on drupal.org, save for the dSero module, which is more of a proxy for the dSero service, thus, not really a solution for detecting adblock usage.

AdBlock detection is simple in practice; include markup regions (e.g. a div & image sized to a standard 728x90 leaderboard ad size) and/or execute JavaScript (e.g. running JS called ad.js) that triggers the AdBlocker to hide it, then having some other isolated code check if region was hidden or the JS code was executed.

With that known, any Drupal based solutions are going to involve either finding an existing front-end library (e.g. FuckAdBlock) or creating your own. Given that any popular solution is ultimately self-defeating (e.g. the AdBlock updating its code to check for common Anti-AdBlocking tactics/libraries), you're probably better off creating your own custom front-end solution that catches ad blocking.