Show data like tool tip when hovered over portion or regions on a custom map I have a map and i want to create some regions in the map. When hovered on that region i need to show some content from database may be preloaded also. so which module should i use to create this task. when i hover should be able to show some click-able links to the user.

What kind of map is it? An HTML imagemap (using  and  tags)? If so, you can use the EasyToolTip and MapHilight JavaScript libraries. They aren't connected to any Drupal modules, as far as I know.

EasyToolTip allows you to format the tooltips almost any way you want, and MapHilight allows you to highlight the section of a map that the mouse is hovering over.


No one can login and access denied message The site worked till yesterday and just now it's behaving strangely.

The site is not created with features, an archive dump including the code and database is copied to server, and the old installation is replaced with the new one manually (unfortunately). Now it is irrelavant  also happening on local server.
No caching module is installed. Session API is not also installed.
Theme is set to 'seven' (core admin theme, just in case).
The watchdog does not contain any error, warning or info except the usual "session opened for user xyz";
The settings file does not contain any special cookie directive. It never did.
The site is running on php 5.6, Apache 2.2, CentOS 6. PHP is running as fast-cgi. Same as always.
It's Drupal 7.

I go to example.com/user/login, enter username and password, the form is submitted successfully, the page is redirected to example.com/user/%uid (tried both uid 1 and other users). and boom! I get an access denied. And the user is not logged in.

If I truncate the sessions table with truncate table sessions I can log in once and once only, with any user. Then again no one can log-in not even uid 1.

Also with a password reset link (using the command drush uli I can log in with no problem).

I disabled all contrib modules and theme, but the same problem persists.

What is causing such problems with sessions? any ideas?

The problem was ip_geoloc module. It was messing up $_SESSION variable, a solution is given on the issue queue (for now!) and the module author agrees with it. It's highly probable that it is happening because of a mis-configuration by me. The user was successfully logged in but immediately their session was invalidated. Somehow disabling it was not enough and it's directory had to be moved out of Drupal root. I am 100% sure not any of it's functions or APIs are used anywhere else. Maybe some cache problem?
Lesson learned:
When having signing-in problem, try to check the $_SESSION variable on the server using devel and it's helper functions (e.g dpm, dsm, dd, ... or as a last resort var_export) and not with you google/firefox developers console.
This is the third time I'm facing this strange behavior and the first time I was able to fix. If you are having this problem, try to follow this checklist:
Ask yourself:

Does truncating the sessions table fix the problem?
Does forcing a change for user password fix the problem?
Have you added any particular configuration to your settings.php? e.g base_url, cookie_domain, ...
Does UID 0 exist in your database (i.e anonymous user)?
Is any redirection module installed? search404, redirect, global_redirect,...
Do you have a custom module enabled?
Is there any problems with your theme?
Do you have any path altering modules, e.g path_alias?
Do you have any module changing the log-in behavior? e.g logintoboggan
Have you enabled any caching module? e.g authcache, memcache, session_cache, boost, varnish, ...
Do you have any access control module enabled? e.g workbench, content_access, acl, og_access, ...
And finally, have you enabled any module which changes the user $_SESSION? e.g session_api, session_cache, ip_geoloc, ...

Places to look / Things to do

Look at drupals watchdog messages. If you can not log-in, use drush watchdog-show --tail to see what's happening.
If running apache and mod-php, look in apache's error log, usually at /var/log/apache/error_log for *nix systems.
If running php-fpm, see the php-fpm log, make sure there is no communication problem with php daemon, such as headers are not lost. if you see no error log try running your site with drush/php internal server. the command is drush rs or drush rs the.ip.goes.here:thePort
make a fullbackup, disable all modules with this command AFTER making a full backup (you can make a backup with drush ard or just database drush sql-dump > db.sql or use backup_migrate module)drush dis -y $(drush pml --nocore --status=enabled --pipe) -> this command only works in *nix systems I don't know the direct translation for windows.
Set your default theme to something... safe! such as seven or garland. If you can not log-in use this drush commands:drush en seven && drush vset theme_default seven;
Monitor $_SESSION variable with any debugging tool, see if it's content are correct, ok, healthy.
For all the processes and daemons involved in serving a request (nginx, php-fpm, apache, varnish...) make sure they all have write access to their tmp directory.

Good luck debugging!


Views Bulk Operation alternative? As VBO for Drupal 6 is outdated due to a security issue, is there an alternative to this module?

Trying to find an alternative / replacement for VBO is similar to trying to do so for a module like Views, or other (popular) modules.

To my knowledge there is no other "contributed" module that can do the same as VBO to replace it. Your only alternatives to consider, I think, is either of these options:

Carefully review the D6 security issue and check if you can find a way to prevent that issue from happening in your site (do not allow it to be used in any way that might cause the security issue to arise).
Spend time to create a fix to actually resolve the D6 security issue in VBO, and optionally consider contributing that back to the VBO module (so that others may help to continue to "maintain" that fix).
Similar to "2.", but "hire somebody" to do it for you.

PS: Writing your own "custom" module to replace VBO entirely is another option, but of course "the toughest one" also ...


Suppressing APC cache warning messages in watchdog log My Drupal-oriented shared webhost recently updated PHP and APC and turned on reporting APC warnings. Now my watchdog log has many, many entries of the form Warning: include() [function.include]: Unable to allocate memory for pool, indicating that sometimes the cache is overflowing.

I know what these warnings mean: that's not my question. The APC cache is 96MB, which is big enough most of the time. But I have 127 enabled modules and certain page loads or doing admin work will overflow the cache. This doesn't occur on every page load by any means, but the warnings are filling up the log, making it hard to find more interesting entries, and causing the log to wrap more often than I'd like. I'm trying to cut down my needed modules but nearly all are there for good reasons.

I cannot change most of the APC settings (I might wish to use apc.filters, for instance).

Is there any module or other method that you know of that will filter messages before they get put in the log? I could make the log bigger, but I still have the problem of finding the wheat in the chaff of warnings.

You can create a module to use the hook_watchdog function. This hook would kick in when there is an error so you can check the type of error decide not to write it to the table. But the variable seems to be passed not as a reference and hence I dont think you would be able to change the variable it self.

The logs are written to the table by the dblog module. using the hook implementation of the dblog module. Just make sure that your function gets called after this so that the entry is already in the db. this should be the case already if not you can set the priority in the systems table to make this effect.

Now within your hook function you can decide to delete the entry that is just written.

function dblog_watchdog(array $log_entry) {
  Database::getConnection('default', 'default')->insert('watchdog')
    ->fields(array(
    'uid' => $log_entry['uid'],
    'type' => substr($log_entry['type'], 0, 64),
    'message' => $log_entry['message'],
    'variables' => serialize($log_entry['variables']),
    'severity' => $log_entry['severity'],
    'link' => substr($log_entry['link'], 0, 255),
    'location' => $log_entry['request_uri'],
    'referer' => $log_entry['referer'],
    'hostname' => substr($log_entry['ip'], 0, 128),
    'timestamp' => $log_entry['timestamp'],
  ))
    ->execute();
}

Another option would to create a hook_cron in your module and delete the wantchdog entries you dont want during the cron run.


How to upload multiple images to Ubercart product pages via FTP? I have a few thousand products that I plan to upload to a D7/Ubercart website and each one will have two or three images associated with it. Is there a way I can just dump all of those images onto the server and have them somehow be associated with their correct products? Or am I stuck uploading each one individually via the node edit fields?

Thanks!

The way I did it in similar, but not exact circumstances, was to use Node export module. It has it's import option. On an import, it expects images to be already uploaded, so the steps are:

Create two products with couple of images manually
See where it's images went
Upload the rest of your images in the same place
Export your products to a file format you are comfortable with, like CSV / DSV
Add the rest of your products to that file, using your manually added ones as examples
Import products from file

My nodes weren't Ubercart products, but above procedure should work none the less.

Remember: Files uploaded will not be managed until and unless you import nodes to use them, so it's a good idea to turn off any "garbage cleaning" modules you may have to avoid their deletion.


Filter using two taxonomy vocabulary I'm running Drupal 8 with two taxonomy vocabularies, which are as follows:

Color

Red
Blue
Green

Containers

A
B
C
D
E
F

My content has 2 term reference fields

Color
Containers

The first term reference can have multiple tags. What I'm trying to do is use the first vocabulary (Color) as exposed-filter/menu and the second (Containers) as term reference list on my views. I want to be able to show the second vocabulary (Containers)reference list based on the first vocabulary (Color) tags. So if someone clicks Red it will only list the second vocabulary (Containers) which has the term tagged as red.

How can I achieve this?

If you have to use two taxonomy vocabulary instead one, you can do the following.

On the "color" vocabulary add entity reference to the "containers" vocabulary and for each color term set avaiable containers for it.
Using Drupal.settings you give information about relations between terms (as an assocated array, for example) to browser so that it would use information in JavaScript.
Add JQuery script, which intercepts a selection of a color term and delete redundant terms in the select box for containers. That is, for example, you have selected a color Green and JQuery script has immediately removed all elements from the select box for contaners, except "B" and "C".

You can add the JQuery script and send data to Drupal.setting using hook_form_alter for the node insert/edit form.

Of course, I'm not guarantee that this way is the rightest one, but if I were you I would try so at the beginning.


How do i change the button text "subscribe", from the "simplenews" module, in drupal 8? I'm very new to drupal and programming.

I simply want to change some text on the simplenews "subscribe"/"unsubscribe" buttons.

From past questions I understand the only solution is programmatically? I've seen the hook_page_alter() method mentioned but I am not experienced enough to get it to work.

This is my poor attempt at utilizing it:

 function MYTHEME_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'simplenews_subscriptions_block') {
       $form['New button text'] = array(
           '#markup' => '<p> New button text </p>',
       )
    }
}

I figured it out due to 4k4's comment

Basically you can translate it english-to-english under /admin/config/people/simplenews/settings/subscriber/fields/
It's a part of the configuration translation module.

If you get the error message "The configuration objects have different language codes so they cannot be translated:" look at this thread for the solution for that: How to change default language for configuration entities


How do I change the ajax loading behaviour in Views? I have a view with some exposed filters in a block; it uses AJAX and the auto-submit feature so the view is re-loaded as soon as a filter option is changed.

In the short delay between selecting an option and the view being re-loaded, the familiar blue AJAX throbber is shown somewhere at the bottom of the form (I think where the hidden submit button is currently located).

I know I can customise this image by overriding the CSS for the throbber element, but I'd prefer not to use it at all.

What I'd much rather do is temporarily fade out the exposed filter form (and ideally the main view as well), using a jQuery animation. They would then fade back in when the AJAX call is complete.

Failing that, I'd like to use the same method that the Views UI module uses when it's updating, namely placing this icon in the middle of the page:

As that is already built in I just assumed there would be a setting somewhere to change the style/location of this loading behaviour; no such luck though.

How do I implement either of these methods?

I'm using Drupal 7 with Views 7.x-3.3.

If you don't mind using a little jquery you could always do something like:

$('#view-id').ajaxStart(function(){
   $('#view-filters-id').fadeTo(300, 0.5);
});
$('#view-id').ajaxSuccess(function(){
   $('#view-filters-id').fadeTo(300, 1.0);
});


How can I stop Google Analytics from tracking a certain user? I have the Google Analytics module installed. How can I prohibit the code snippet appearing on pages served to a particular user. Say user #15, for example?

I would consider creating a separate user role for that purpose and disabling Google Analytics for that role. The setting can be found at the module config page (/admin/config/system/googleanalytics) under Tracking Scope -> Roles.


Using views in Drupal I want to create a view page with the city events /attractions ... I want to categorize them as family , kids , outdoors etc. So that when a user clicks on a particular category they see the events/attractions listed under it.

How do I do this using Drupal 7 and views?

In the Filter Criteria add a filter Content: Has taxonomy term .

Choose the Vocabulary with your category. In the next step check Expose this filter to visitors, to allow them to change it . Set the Label as you want and "Apply".

Anyway, try to be more specific in your question if you want a better answer.


Custom user registration email - Drupal 6 I want to add image icons for Facebook, Twitter etc with associated links and Join Us hyperlink like Join Us to the user registration email.

Can anyone give me idea?

you can create and send system html emails using mimemail module and a wysiwyg editor http://drupal.org/project/mimemail (or even http://drupal.org/project/htmlmail )


How to link migrated image file to the user profile picture field? I used the following migration file to migrate user pictures from a Drupal 7 site installation to Drupal 8:

  migrate_plus.migration.drupal7_image.yml

id: drupal7_image
label: Images
migration_group: dhm_migrate_taxonomy
migration_tags:
  - Drupal 7
source:
  plugin: d7_file
  constants:
    source_base_path: '/var/www/html/migrate_training_7/web/'
process:
  fid: fid
  filename: filename
  source_full_path:
    -
      plugin: concat
      delimiter: /
      source:
        - constants/source_base_path
        - filepath
    -
      plugin: urlencode
  uri:
    plugin: file_copy
    source:
      - '@source_full_path'
      - uri
  filemime: filemime
  status: status
  created: timestamp
  changed: timestamp
  uid: uid
destination:
  plugin: entity:file
migration_dependencies: {}

And I am using this next snippet to link the migrated image files to the user picture field (This is used in my user migration file):

  migrate_plus.migration.custom_user.yml

  user_picture: # Image field name in Drupal 8 site
    plugin: iterator
    source: user_picture # Image field name in Drupal 7 site
    process:
      target_id: fid
      alt: alt
      title: title
      width: width
      height: height

migration_dependencies:
  required:
    - drupal7_image

I can see that the files are being migrated and downloaded to my Drupal 8 installation but when I check the users I don't see any user pictures (fields are blank).

I really don't know what I am missing, I searched for examples on the Internet but I didn't find much.

Any help would be much appreciated. Thanks in advance. ;)

Thanks a lot @MrD I tested using the migration_lookup plugin and it works like a charm:

  user_picture:
    -
      plugin: default_value
      source: picture
      default_value: null
    -
      plugin: migration_lookup
      migration: drupal7_image


Programatically render field in specific language while leveraging core content language detection I'm working on a contrib module port to D8 and can't seem to find appropriate Entity API documentation to figure out how to get a rendered field in a specific language. I have a controller that needs to generate some custom XML based on field data, and I would like to be able to use core's language detection to get an appropriately translated field that can be used to generate this XML.

(As an aside -- I realize that core services could be leveraged to get field data in a RESTful way, but the XML schema needed here is quite custom and warrents its own REST endpoint and controller.)

Consider a route for a REST endpoint, that simply accepts the entity and field specifics needed, via the path like:

mymodule.xml_field:
  path: '/mymodule/xml/field/{entityType}/{entityId}/{fieldName}/{displayName}'
  defaults:
    _controller: '\Drupal\mymodule\Controller\MymoduleXmlControllerField::xmlController'
  requirements:
    _access: 'TRUE'

And a matching controller method like:

class MymoduleXmlControllerField implements ContainerInjectionInterface {

  // ... Entity manager and other services are injected ...

  public function xmlController($entityType, $entityId, $fieldName, $displayName) {
    $entity = $this->entityManager->getStorage($entityType)->load($entityId);
    $field = $entity->{$fieldName}->view($displayName);

    // ... Extract needed data from $field, generate XML and return it in new Response() object ...
  }
}

This works great until I try to leverage content translations. If I use default URL language detection and then request the XML via a language specific path (with a prefix, like: /es/mymodule/xml/field/...) the default lanaguage is always still used in the $field output instead of the spanish (es) translation (which I've confirmed is available on the entity).

My initial expectation was that the entity load call, or the field view call, would internally trigger language detection (as in D7), but I see that it's now up to my controller to manually specify and set a langcode somehow as the loaded entity object seems to be language neutral. I'm just wondering how I do this given that the high-level entity/field interfaces I'm using don't take a langcode paramater, and (at the time of writing) the entity API docs don't seem to address this.

I'm assuming that I need to use a setter method somewhere on the entity or fieldlist object to declare a langcode before calling the view method. It looks like I can get the detected language easily via an injected language manager:

$langcode = $this->languageManager->getCurrentLanguage(LanguageInterface::TYPE_CONTENT)->getId();

But I'm not sure where to go from there.

You need get Translation of entity. function entity load just load default language, not load current language. Try this:

public function xmlController($entityType, $entityId, $fieldName, $displayName) {
    $entity = $this->entityManager->getStorage($entityType)->load($entityId);

    $entity_es = $entity->getTranslation('es');

    $field = $entity->{$fieldName}->view($displayName);
    new Response() object ...
  }

and you need detect language to auto. Code above just example.


Let user join an organic group during site registration I would like my users to be able to select a preexisting Organic Group to join when they are registering to use my site. Is this possible? How should I do this?

I already have the groups set up, and the permissions are set so that so that non members can 'Subscribe to group (no approval required)'.

You must enable the module:

Organic groups register (Allow subscribing to groups during the user registration)


drupal_goto forcing redirects to https when external link is http Our server uses https, but when we want to redirect to an external site that uses http, the https still gets added on. We will often have mixed links where some links are http and some are https. Our current call goes as:

drupal_goto($link, array("external" => TRUE));//where $link is the link we want to redirect to

Is setting the https option to false the way to go, or will it kill the links that should be https? I would think for an external link that drupal would not be trying to change that.

We changed the code to this, but it did not fix the issue:

$parsed = parse_url($link);
if ($parsed["scheme"] === "http") {
  $https = FALSE;
}
else {
  $https = TRUE;
}
// Forward to requested URL.
drupal_goto($link, ["external" => TRUE, "https" => $https]);

drupal_goto() takes a $path and $options which in turn sends them to url().
As you can see in the docs  for url()

https://api.drupal.org/api/drupal/includes%21common.inc/function/url/7

  'https': Whether this URL should point to a secure location. If not
  defined, the current scheme is used, so the user stays on HTTP or
  HTTPS respectively. TRUE enforces HTTPS and FALSE enforces HTTP, but
  HTTPS can only be enforced when the variable 'https' is set to TRUE.

so in your case the redirects will be https by default, which means you will have to set the them individually each time to use only http e.g.

drupal_goto($path, array("external" => TRUE, "https" => FALSE));


Some of the pending updates cannot be applied because their dependencies were not met I have a Drupal 7 site that is giving me the above error.  I cannot for the life of me, figure out what dependency needs to be met.  And I can't not remember what I did, or if I did anything, to cause it.

Is there any way to get more info than that?

This may help: http://drupal.org/node/915216

Others that are more module specific may be:

http://drupal.org/node/1190294
http://drupal.org/node/1111524


Disable checkout button I am using drupal 7 with ubercart.  Since I do not currently have a method to accept credit cards, I am using paypal express.  The issue I am finding is that still in the cart view there is a checkout button and a paypal button.  If the user clicks the CHECKOUT button they are taken to the next page but can go no further since there are no Credit Card options currently enabled.

Is there a way to only show the PAYPAL button in the cart? If so where?  I am not sure which file I should be looking in for the cart form.

Go to admin/store/settings/checkout and disable checkout.


Translate links in Drupal menu page I have a maybe rather silly question. I have a test website and a live website (both Drupal 7)

In the test website I have setup translations for my main-menu using the module "Menu Translation" (it is a sub-module of i18n) and at mydomain.com/admin/structure/menu/manage/main-menu I see a third column with the option to "translate" the menu options in the first column.

At my live website I want to do the same, but can't figure out what setting I have to change in order to get these " translate" links appear in the same page?

The settings in the testwebsite are done more than half a year ago and  I cant remember how I did that. The Multilangual option -> Translate and Localize is set for the main-menu on both sites.

This is what my live website looks like [1]: http://i.stack.imgur.com/p0L2y.jpg
 This is what my test website looks like [2]: http://i.stack.imgur.com/1BvNz.jpg

I assume that this has nothing to do with the "reset" link? (no idea what the purpose of that link is)

In General Usage of Contributed Modules first steps to use any module is

Read Documentation of Project Page in D.O . You will find the link in the right side bar.

Readme or Install files inside Module Folder
Still if you are unable to figure out.. Visit .module file and focus on hook_menu implementation which lists menu paths as keys of $items array.. By visiting those pages you will get a chance to see configuration pages given by that particular module.

In your case

Enable i18n_menu module which has following module dependencies. I enabled using drush which automatically downloads and enabled below modules. In your case make sure below modules are present in your instance.

The following extensions will be enabled: i18n_menu, i18n_translation, i18n_string, variable, locale, i18n

Once you enable you can see "Translate" setting in any menu page. I just verified no other changes are required. Just clear cache once you enable module in case.


Views insert current page node id to image link url I want to create a block view of some content's image field. I am trying to insert current page node id to paths of image links. Because linked page is a entity form and I try to prepopulate node id in one of the field of the entity form.

How can write to current node id to URL with views rewrite results?
URL pattern like that. example.com/form?edit[field_whatisrefferaelid][und][0][value]=[currentpagenodeid]
Actually I am seraching for current node id token avaible in views block.

If you have a Contextual Filter in place for Content: Nid that is pulling in the nid from the currently viewed page, can

Add a field for your image
Choose Image for the formatter.  Configure the image style that you want.
Link image to Nothing
In Rewrite Results, check Output this field as a link
In the link path, use form?edit[field_whatisrefferaelid][und][0][value]=!1
Check Use absolute path

The !1 is the replacement pattern for the first contextual filter.  It should be listed in the list of replacement patterns in the popup you do the configuration from.

That shuld


Mobile number validation for webforms I am looking for a way to easily implement an Integer field with webforms that can do mobile number validation (US numbers only). I am aware of http://drupal.org/project/webform_validation that can do numeric validation but looking for a more direct solution. If its a hook, that works as well.

You can do a hook_form_alter of your form, and add your own validation to it.

function YOURMODULE_form_alter(&$form, &$form_state, $form_id) {
  if($form_id == 'NAME_OF_FORM') {
    $form['#validate'][] = 'YOURMODULE_VALIDATE_FUNCTION';
  }
}

function YOURMODULE_VALIDATE_FUNCTION( $form, &$form_state ) {
  $mobile = $form_state['input']['field_MOBILE']['und'][0]['value'];
  $is_valid_mobile = YOUR_AWESOME_MOBILE_VALIDATOR($mobile);
  if( !$is_valid_mobile ) {
    $error_msg = 'Mobile is invalid. Please enter a valid mobile number e.g xxx-yyy.';
    form_set_error('field_MOBILE', t($error_msg));
    return false;
  }
}


How to display Commerce Order Owner role in Views fields? Using Drupal 7.58 and Views 3.18

I am simply trying to display Commerce Order Owner role on a View. Using the Commerce Order:Owner relationship, I have access to a large set of user fields and properties... except the User role? Did I miss anything here?

EDIT : I am using Aggregation on my View (if you want to replicate this issue)

EDIT#2 : interesting workaround here, simply add the user role field before activate the aggregation... Still, I could not manage to build a chart and only a list of roles counted per user, using Table with aggregation options display

Related question : How to add the "user role field" in View showing users

No clue why it's not showing. The Views module defines a "User: Roles" field, and I see that just fine in my own development environment for a View joining to Users via the "Commerce Order: Owner" relationship.


Make a field state change depending on the moderation state field I am trying to use the states to change another field depending on the moderation state, I tried this, but didn't catch it.

$form['schedule_publish_date'] ['#states'] =  array(
 'invisible' => array(
  ':input[name="moderation_state"]' => array('value' =>"published"),
 ),

I'm not sure what the correct field name of the moderation state is, this is the source code

      Moderation state
        <select data-drupal-selector="edit-moderation-state-0" aria-describedby="edit-moderation-state-0--description" id="edit-moderation-state-0" name="moderation_state[0]" class="form-select"><option value="draft" selected="selected">Draft</option><option value="needs_review">Needs Review</option><option value="approved_to_be_published">Approved to be published</option><option value="published">Published</option></select>

      The moderation state of this piece of content.

Drupal API: function drupal_process_states

Example A where the source fieldtype is a textfield

$form['moderation_state'] = [
  '#type'  => 'textfield',
  '#title' => ('Some title'),
];

$form['schedule_publish_date'] = [
  '#type'   => 'textfield',
  '#title'  => ('Invisible if ...'),
  '#states' => ['invisible' => [':input[name="moderation_state"]' => ['value' => "published"],],],
];

Example B where the source fieldtype is a select-field

$form['moderation_state'] = array(
  '#type'          => 'select',
  '#title'         => t('Some title'),
  '#options'       => array('unpublished'=>'unpublished', 'published'=>'published'),
  '#default_value' => 0,
);

$form['schedule_publish_date'] = [
  '#type'   => 'textfield',
  '#title'  => ('Invisible if ...'),
  '#states' => ['invisible' => [':input[name="moderation_state"]' => ['value' => "published"],],],
];


English translation as drupal message I am trying to add the English title as a drupal_set_message on all node pages if available - (Ive done something similar on the CMS) and if the user has node edit permissions (this can be checked using the node_access function).

Code for cms example mentioned. Inside a hook form alter.

// Translation display on CMS page
$nid = (isset($form['nid']['#value'])) ? $form['nid']['#value'] : false;
if($nid) {
    $node = node_load($nid);

    if($node) {
        $lang = 'en';
        $translations = translation_node_get_translations($node->tnid);

        $translated_node = (isset($translations[$lang])) ? node_load($translations[$lang]->nid) : $node;
        $translated_title = '
English Translation: ' . $translated_node->title . '
';
    }
}

$form['#prefix'] = (isset($translated_title) && $translated_node->title != $node->title) ? $translated_title : '';

I am now wanting something similar but as a drupal_set_message on all node pages.

<?php
$node = menu_get_object();

if(node_access('update', $node)) :
    $lang = 'en';
    $translations = translation_node_get_translations($node->tnid);
    $translated_node = (isset($translations[$lang])) ? node_load($translations[$lang]->nid) : $node;
    if(is_object($translated_node)) :
?>

English title: <?php print $translated_node->title; ?>

<?php endif; ?>
<?php endif; ?>

Directly in tpl file.


Getting an email notification when a new Drush version is available With standard Drupal modules, you get an email notification when there's an updated version.

How can we have this option with Drush?

I searched the official http://drush.org website and unfortunately there's no mailing list or RSS feed so that we know when there's a new version of Drush out.

If you go to the Drush project page on Drupal.org then you can follow the "Releases" RSS feed found at the bottom of the page.

EDIT

You can also use the IFTTT.com service if you want the e-mails.  Just set up a rule on the site so that when the RSS feed gets updated, it sends you an e-mail.


how to just print the value of author in node template There are some variables like author_name in node.html.twig of Drupal 8. {{ author_name }} will print something like below:

Basic

I tried using codes like below:

{{ author_name.0 }} plan to print: Basic

or

{{ author_name|field_value }} plan to print: Basic

Above codes NOT work. How can I achieve above result?

For most cases How do I get the raw field value in a twig template? will do. But since here according to node.html.twig

  author_name: Themed author name field.

I believe you can get the unthemed author name by using {{ node.getOwner.getDisplayName }}


PHP - If a field has a certain text value then print something The following PHP in a node tpl file:

check_plain($node->field_room[$node->language][0]['value'])

Will print this in the page:
Value1

What I want however is if the field has a value of 'Value1' then I want to print something else on the page. Ive tried the following but I think I have a syntax error:

if ( check_plain($node->field_room[$node->language][0]['value']) == "Value1" ) {
                        echo "<p>Print something else </p>";
                    }

There's no syntax error in the second code sample, if you're getting a syntax error it's not coming from those lines.

The best way to get values from an entity is with field_get_items():

$items = field_get_items('node', $node, 'field_room');
if (count($items) && check_plain($items[0]['value']) == 'Value1') {
  // Do something
}

But unless you have some sort of multi-lingual issue the code you've got should do exactly the same thing as that, so the problem might be elsewhere.


Custom module hook entity presave not 'firing' I've seen other posts and did all the good things, I think... still not firing.

I use Commerce Kickstart 2 in Drupal 7

I want my module to be called for the hook_entity_presave event.

I followed the docs to create my custom module: call it 'Update Description'
I put my new mod in sites/all/modules/update_description

update_description.info
update_description.module

I named the files and added the appropriate info

name = Update Description
description = This module populates a description field based on the selected product attributes.
core = 7.x

I see, and enabled the module in the modules list, and I cleared cache

The module looks for a type of entity, and updates it:

function update_description_hook_entity_presave($entity, $type){
    $entity->changed = REQUEST_TIME;
    $vari_result = "";

    watchdog('update_description', 'type: ' . $entity->type, array(), WATCHDOG_DEBUG, NULL);

    if($entity->type == 'my_new_content_type' && $entity->product_id && $entity->revision_id) {
        // do stuff
        /// watchdog the results
    }
}

But I never see any log messages show up when I create or update an item of 'my_new_content_type', other than the default creation 'info' log message that happens anyway.

What do I need to do to get this my module to 'hook' into this call?

The hook_ part is for example only; it should be replaced completely by your module's name:

function update_description_entity_presave($entity, $type) {


Exposed view filtering on a related node's value I have a view with a list of nodes. Each node has a number of related nodes which I want to display below the parent node. This works fine.

However, when I go to filter the listing on values in one of the related nodes, then an empty set is returned.

I'm guessing it's trying to filter the parent nodes on this value, and not the related nodes. How can I remedy this?

When adding a new relationship, ensure that you select 'Require this relationship'. Also, when adding a filter, ensure that you select the relevant relationship from the list where necessary.


What is the difference between a page and a node? What is the actual difference between a node and a page in Drupal 7? Why there is separate page.tpl.php and node.tpl.php pages. How is the theming applied for the actual page.

Any link for understanding all this would be greatly appreciated.

node.tpl.php

  Default theme implementation to display a node.

page.tpl.php

  Default theme implementation to display a single Drupal page.

see image for more detail.


Add checkbox to Ubercart checkout It sounds quite easy, adding a checkbox to Ubercart's checkout form. The consultant I spoke to told be to use hooks, or try using the uc_extra_fields_pane module, which I also cannot get to work properly (it's config page is not showing up). I'm using Ubercart 2 and Drupal 7.22.

In your custom module use the hooks defined in the Ubercart terms and conditions module.


Any advantage to using Profile2 module vs. custom user account fields? I'm trying to decide if I should bother messing with the Profile2 module. I need my users to have information like a real name stored and made available for other uses, but I'm not sure if there is an advantage to using the Profile2 module, or if I should just create custom user account fields for whatever I need.

The Profile2 module is only good if you need more then 1 type of profiles.
For example:
         - a student profile, with certain fields.
         - a teacher profile, with different fields.

If you don't need different types, just stick with the custom user account fields.

Hope this helps!


Google Analytics stopped tracking The Google Analytics module on a brand new Drupal 7 build just stopped tracking after 7 days. When I went to investigate, I checked the settings, all appeared fine. Then I checked the source of the page, and the analytics code was nowhere to be seen.

For now I have just added in the javascript within html.tpl.php. But I am curious why it has just stopped working for no apparent reason? A bug with the module?

This site is using a custom theme. I checked the html.tpl.php and $header and $page_bottom variables were all there.

Any ideas why this may be?

I don't see any current bugs like this in the issue queue of the module. So let's check the following:

What's up with the theme you're using? Have you tried this with another theme?
What performance settings do you use? (Is Javascript aggregation enabled? Do you use page caching?)
Is the Analytics code missing from the output when you're logged in as user 1? (If it's there, what's happened with the permissions of the module?)


Setting a new users profile fields based on a form Users on my site all have a "home region" field. This profile field is saved for each user and used to customise various site features, so that the user gets shown local content.
These regions aren't states or cities - they're more like electorate / local council boundaries (I'm not really sure what the US analogy would be). Most users are going to be uncertain about which region they actually want to save to their user profile.
I have a form which allows users to either (A) explicitly select their region from a select dropdown or (B) enter their postcode, submit the form, and get back their region. This form works fine.
I want users to be able to pick a region at registration time using this form, and have that region saved to their profile. Ideally I'd like to integrate the "select region" form with the user_register form, so that they can submit the form, get told "you are part of X region" and then click "register" and create a new user account with that region.
What I'm doing is using hook_user() to insert my form elements, perform my extra validation and then try to save the region data to the user on submit.
EDIT: the below is roughly how I solved this
function mymodule_user($op, &$edit, &$account, $category = NULL) {
  /* add "select your region" functionality to the user edit form */
  $category = 'Regional information';
  switch ($op) {
    case 'register':
    case 'form':
        /* "register": The user account registration form is about to be displayed. The module should present the form elements it wishes to inject into the form. */
        /* "form": The user account edit form is about to be displayed. The module should present the form elements it wishes to inject into the form. */
        $form = array();
        $form['Regional information']['region'] = _region_select('', _region_select_options());
        $form['Regional information']['postcode'] = _postcode();
        return $form;
        break;
    case 'validate':
        /* "validate": The user account is about to be modified. The module should validate its custom additions to the user object, registering errors as necessary. */
        $region = $account['region'];
        $postcode = $account['postcode'];
        // form_set_error() if I need to
        break;
    case 'insert':
    case 'update':
        /* submit happens *before* the user account is saved - we want insert or update
           "insert": The user account is being added.
           "update": The user account is being changed.
           The module should save its custom additions to the user object into the database and set the saved fields to NULL in $edit. */
        $region_code = $edit['region'];
        $postcode = $edit['postcode'];
        if (!$region_code && $postcode) { // pull the region from the postcode
            ...
        }
        if ($region_code) {
            $region_term = taxonomy_get_term($region_code);
            $region_name = $region_term->name;
            /* the profile module wants the name of the region, not the id */
            $profile_edit = array( 'profile_region' => $region_name );
            profile_save_profile($profile_edit, $account, $category);
        }
        break;
  }
}

Do you think you could just make the select dropdown and postcode input box parts of the user_form? Looks like you've got the functionality working already, so it would be a matter of a simple module implementing the following hook:

hook_user(register) to alter the registration form and add your custom fields. You'll want to use a profile or profile_taxonomy functionality to insert the form element
hook_user(validate) to validate the user input (incorrect postcode etc.)
hook_user(submit) to convert the postcode to region and to save that information in the user profile


How to disable comments in node.tpl? I decided to programatically print comments un Views using PHP footer. The problem is that they now appears twice (my code + default). When I disable comments in content type settings, both ddisappear. How can I disable the default comments and keep my comments printed by php code? I tried to edit node.tpl file. but there is no section responsible for showing comments there (I use Garland). Any advice appreciated.

Have you tried looking into the comment.tpl.php file?

You should be able to hide the 'real' db driven comments there and only display your printed comments.


How can I get a taxonomy menu into the main menu AND a block? I've got a taxonomy menu of products in DCommerce which appears in the main menu, but I also need it to show up in the sidebar. I installed menu_blocks but that can only access the main menu that the product menu is within.. and if I make the product menu into it's own menu, I can't get it into the main menu. Can it show up twice??

Taxonomy menu block combines the idea of Taxonomy menu with the workings of Menu block:

This module does not make use of Drupal's menu system. Taxonomy menu first creates a menu which can then be displayed through a block, this module creates the block directly.

Make multiple menus per vocabulary.

"Split" the taxonomy into different menus.

Make a menu out of a specific branch of your vocabulary only.

Follow the active trail, also for nodes coupled to a term with a term reference field.


Redirect language-specific URL to correct path prefix Drupal 7. I have a multi-language website. Let's call it website.com.

At admin/config/regional/language/configure/url I have selected "Path prefix" as the "Part of the URL that determines language".

My host is using nginx. The hosting company has configured the site so that when I go to my Spanish language url (let's call it sitio-web-en-español.com) the browser ends up at website.com.

What I would like it to do is end up at website.com/es so that the users have Spanish language immediately without having to use the language switcher.

My question: Can I do this within Drupal or do I need to get my hosting company to change their configuration?

Thank you!

Here's the solution that worked for me.

In the end I came to the conclusion that it was easiest to do this at the domain hosting company end.

So in the account where my Spanish-language domain (sitio-web-en-español.com) is managed, I set up a redirect that goes to:

website.com/es

... and it seems to work fine.


node_presave doesn't work I'm trying to do something before my invoice saves. In my invoice module I have:

function invoice_node_presave($node) {
  var_dump($node); die;
  if ($node->type == 'invoice') {
    // If true we are creating a new invoice
    if (intval($node->invoice_number) == 0) {
      // Get new invoice number
      if (intval($node->user_defined_invoice_number) > 0) {
        $node->invoice_number = $node->user_defined_invoice_number;
      }
      else {
        $node->invoice_number = _invoice_get_new_invoice_number();
      }
    }
  }
  ......
}

As you see I have a var_dump($node) & a die; . This works perfect. But then when I want to add the following in my template.php :

function xmed_node_presave($node){
  dump($node); die;
  if (($node->type == 'invoice')) { //node has not been saved
      dpr($node); die;
  }

}

He doesn't die. He just runs... Also the rest of functions in my template.php like function xmed_preprocess_page(&$vars) work.

hook_node_presave() is only invoked for modules, so you can't implement it in a theme.

It'll need to go in a custom module instead.

From a best practice point of view, that sort of logic definitely shouldn't be at the theme layer, it should be in a module.


How to alter and debug views queries? I'm trying to find the hook/module which can modify a views query.

The view is from Workbench module which is displaying the draft's of the actual user.

If I Disable SQL rewriting in the Query settings the display is ok,
so something is interfering.

What would be the method to debug?

We can alter a views query using hook_views_query_alter. Try to search in your codebase for this string views_query_alter, you should get a function in one of the custom module which is implementing hook_views_query_alter.

If it doesn't help, try to enable query log using devel module, so you will know what query are being executed for that page. Views also gives the sql query that a particular display will run. See if these two sql queries don't match. You can see the diff and then try to figure out which module might be adding the additional conditions to that query.


User added to a specific group should be blocked I'm trying to accomplish the task -" If the User is added to a specific CiviCRM group manually by admin/'users with permissions to add to group', The added user should be blocked.I'm using Rules module with CiviCRM entities.

Here is my Rules export:

{ "rules_block_unblock_user" : {
    "LABEL" : "Block\/unblock user",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "civicrm_entity", "rules", "civicrm" ],
    "ON" : { "civicrm_group_edit" : [] },
    "IF" : [
      { "civicrm_entity_contact_is_in_group" : {
          "civicrm_contact" : [ "site:current-user:civicrm-contact" ],
          "group_id" : "2"
        }
      }
    ],
    "DO" : [ { "user_block" : { "account" : [ "site:current-user" ] } } ]
  }
}

I guess I'm not selecting the right data selectors. Any help?

Not sure which tokens you have available to select from, but the token site:current-user refers to the user performing the add to group, i.e. some "admin/'users with permissions to add to group". So your Rules Condition seems to be wrong. Due to which your Rules Action is not performed either of course.

And if the list of available tokens doesn't seem to have any relevant token, it may be because you're using the wrong Rules Event.


Using taxonomy terms alias in views contextual filters I hope you can help me out with this. I have created a simple view with an argument. I use that argument to filter (contextual filter) the content of the view. I already know I can use that argument as a taxonomy term ID and as a taxonomy term name, which means I can get my view loaded as:

www.myhost.com/myview/12

or

www.myhost.com/myview/termname

Both ways are ok and work fine but the problem I have is that I'd like to use an alias for the term, instead of the termname. Term names I already have on the site have some characters which are not really SEO friendly.

Is there a way to use the taxonomy term alias or any other workaround to get this?

Thanks in advance for your help.

Finally my work around this was as it follows:

I created a custom taxonomy vocabulary which has an extra field "human friendly tag".
I changed the name of all the taxonomy terms for being seo-friendly (not spanish accents, nor brackets and so forth).
I use term name for the internal stuff in my view (term names are part of the url). You can see how to get this here as @RobW pointed out.
I use the first field (the "human friendly tag") when content is rendered (in the view). I need to use "rewrite results" options when creating the view.

I hope it is clear enough. :-)


Multiple File Uploads fail when webform is placed in a block I'm in Internet Explorer support hell.

I have a webform which uses Multiple File Uploads. When the form is displayed as a regular node (e.g. www.example.com/node/4), file uploads work as expected.

When the node is shown as a block on another node, file uploads fail with the message:

  An unrecoverable error occurred. The uploaded file likely
  exceeded the maximum file size (20 MB) that this server supports.

Needless to say, all php.ini configuration options are in order, (post_max_size=128M, upload_max_size=20M, etc) and the temp folder is writable.

Uploads fail specifically on Internet Explorer 8 and 9. There is no indication in the log of anything going wrong, just the error message above.

Any ideas?

Turns out that I had, due to custom markup added to the webform, nested <form> tags. Per the spec, this is a big no-no. What happens in the older browsers appeared to have been that the form AJAX submission tried to use the form ID of the most recent <form> tag, which, in my case, was empty. It triggered this in file.module:

if (empty($_POST['form_build_id']) || $form_build_id != $_POST['form_build_id']) {
  // Invalid request.
  drupal_set_message(t('An unrecoverable error occurred. The uploaded file likely exceeded the maximum file size (@size) that this server supports.',
    array('@size' => format_size(file_upload_max_size()))), 'error');
  ...
  ...

Removing the unneeded <form> tags resolved the issue.


D7 - hide the ajax_command_html message I'm using the following code to display a (success) message, it's working quite nicely, however I want it to disappear after, lets say 3 seconds.

  $commands = array();
  $commands[] = ajax_command_html('.ajax_messages', ' message ');
  $page = array(
  '#type' => 'ajax',
  '#commands' => $commands,
  );

  ajax_deliver($page);

How can I achieve this?

Maybe something like this in a js file included on the page.

(function ($) {
  Drupal.behaviors.myModule = {
    attach: function (context, settings) {
      $('.ajax_messages').delay(3000).fadeOut();
    }
  };
})(jQuery);


Change style of custom view mode condionally I have a custom view mode created with ds module,
this view mode lists node articles, each article displays like this :

  title
  description
  url
  term reference field
  some other fields...

I want to add some style condionally depending on the term reference field
For example:
the first article has the term reference with the value "1", I change the backgroud of the this article to "red"
the second article has the term reference with value "2", I change the backgroud to "green"
...

EDIT :

this is an image how look like the manage display of some fields :

My interest is with the Flag field:
It's a taxonomy field reference having (title, color (hexadecimal value), description...)
This flag field as you see has the formatter 'editable' (done with editablefieds module), so editors can edit the value of this field.

Now I want to add another field next to Flag witch is the color field of the current Flag taxonomy term, and render for example a simple div with some width and height and with the backgroun-color, this color field

Hope it's more clear than the old post :)

Thanks in advance.

This is pretty similar to How to provide template for particular view mode? where as you can add custom php code to add further variables used in that viewmode or add simple if/ else/ in_array to the used template (this is not limited to a custom template - you can always override the default node.tpl.php in your theme.

UPDATE: add only a css class depending on the term reference field.

// can also be THEME_
function MYMODULE_preprocess_node(&$vars) {
  if ($vars['view_mode'] == 'myviewmode') {
    if(isset($vars['node']) && isset($vars['node']->field_my_term_reference)) {
      // class to add a general has-term-reference-class
      $vars['classes'][] = 'has-term-reference';
      // add a specific term-reference-class
      foreach($vars['node']->field_my_term_reference as $tid) {
        // class based on term id
        $vars['classes'][] = 'term-id-' . $tid;
        // class based on term name
        $term = taxonomy_term_load($tid);
        $vars['classes'][] = 'term-name-' . $term->name;
      }
    }
  }
}


How can I specify inner elements template in custom login page? I am new in Drupal 8. I want to create a new theme to according to my HTML. What is the best practice to integrating a custom build theme to drupal engine.

I have covered all sections in Drupal 8 theming tutorial. Now I need to integrate custom login page.

I have added the following hook inside mytheme.theme file

function wms_aupl_theme(&$existing, $type, $theme, $path) {
  $hooks = array();
  $hooks['user_login_form'] = array(
      'render element' => 'form',
      'template' => 'user-login-form',
  );
  return $hooks;
}

And Inserted my HTML in user-login-form.html.twig file as follows.

        <form{{ attributes.addClass('user-login') }}>

Auktionsplattform

                    Some dummy content

            {{ form.name['#title'] }}

                        {{ form.name. }}

                {{ form.pass }}
                Passwort vergessen

            {{ form.form_build_id }}
            {{ form.form_id }}

                    {{ form.actions }}

                    Noch kein Konto? Hier registrieren

        </form>

Now i need to specify inner element's template. How can I specify inner elements template?

Is there any better way to do this?

See How to manipulate forms in Drupal 8:

  To make changes to the fields in your form, you have to change the specific twig templates. First check which twig templates correspond with the base theme of your Drupal application. It is important that you give new twig templates the same name as the original ones, otherwise your new templates will not be recognized.


How do I redirect access denied to front page? I asked this a while back and got nowhere. Sorry for the repost but it needs to be resolved (somehow).

If a visitor types in a URL for which they are not authorized, I do -not- want them to see a 403 page. I just want them to be redirected to the site home page.

I entered...

<front>

...in the 403 field under admin/config/system/site-information but that apparently does nothing. We're using LoginToboggan which (I think) overrides this.

How can I do this?

TIA,

Instead of <front> try using node or 'home page path' if you have customized home page.

...in the 403 field under admin/config/system/site-information.

Ref: Redirect 404 errors to home page?


How to set a coming soon page on drupal? All request must be redirected to the coming soon page, is there any module can do it or a solution, I'm using the zen base theme.

Thank you for your help :)

You can put the site on maintaince mode and can use the message as coming soon.


How do I pass data between hooks that don't interact? How do I pass data between hooks that don't interact between them, or between a menu callback and a hook?

In the case the two hooks have a parameter in common, and that parameter is passed by reference, that is easy. What do I do when the hooks, or the menu callback and the hook, don't get a common parameter?

In Drupal 7, or higher, use a static variable handled with drupal_static().
drupal_static() is a function that handles a central storage for static variables. Differently from the variables declared using the static keyword, the static variables handled with drupal_static() are accessible from every function; this is possible because drupal_static() returns the variable's content by reference, allowing every function to alter it.

Suppose that you need to pass a value between a menu handler, and the implementation of hook_block_view(); you could use the following code.

function mymodule_menu() {
  return array('path/%' => array(
    'page callback' => 'mymodule_callback_function',
    'page arguments' => array(1),
  ));
}

function mymodule_callback_function($data) {
  $data_passer = &drupal_static('mymodule_block_data');

  $data_passer = $data;

  // Other logic specific to this page callback.
}

function mymodule_block_view($delta = '') {
  // $data_passer will now contain the value of $data, from above.
  $data_passer = &drupal_static('mymodule_block_data');

  // Change the block content basing on the content of $data_passer.
}

In the case that data need to be accessed more frequently, you should use a static local variable that would contain the value returned from drupal_static(). As static variables can only be initialized from literal value, and static variables cannot be assigned to references, the only working code is similar to the following one. (This code is taken from user_access().)

  // Use the advanced drupal_static() pattern, since this is called very often.
  static $drupal_static_fast;
  if (!isset($drupal_static_fast)) {
    $drupal_static_fast['perm'] = &drupal_static(__FUNCTION__);
  }
  $perm = &$drupal_static_fast['perm'];

The value returned from drupal_static() is reset every time Drupal bootstraps; if you need a value that is preserved between different pages, then you need to use a database table to store the value, or use variable_get()/variable_set().

Drupal 6 doesn't implement drupal_static(), but you could copy its code in a function defined in your own module.

function &mymodule_static($name, $default_value = NULL, $reset = FALSE) {
  static $data = array(), $default = array();

  // First check if dealing with a previously defined static variable.
  if (isset($data[$name]) || array_key_exists($name, $data)) {
    // Non-NULL $name and both $data[$name] and $default[$name] statics exist.
    if ($reset) {
      // Reset pre-existing static variable to its default value.
      $data[$name] = $default[$name];
    }
    return $data[$name];
  }

  // Neither $data[$name] nor $default[$name] static variables exist.
  if (isset($name)) {
    if ($reset) {
      // Reset was called before a default is set and yet a variable must be
      // returned.
      return $data;
    }
    // First call with new non-NULL $name. Initialize a new static variable.
    $default[$name] = $data[$name] = $default_value;
    return $data[$name];
  }

  // Reset all: ($name == NULL). This needs to be done one at a time so that
  // references returned by earlier invocations of drupal_static() also get
  // reset.
  foreach ($default as $name => $value) {
    $data[$name] = $value;
  }

  // As the function returns a reference, the return should always be a
  // variable.
  return $data;
}

Before using a static variable with drupal_static() (or the back ported function defined in your module), you should keep these considerations in mind:

The code works only when the code that sets the static variable runs before the code to get its value; if the execution order is not the thought one, the code doesn't work. When the order of execution is not clearly defined in Drupal documentation, there is the risk the order changes in future versions of Drupal; check the execution order doesn't change in the Drupal version for which you are implementing your code.
Drupal could have implemented a mechanism to share data between different hooks. For example, in the case of different implementations of hook_form_alter(), each implementation can share data with other hook_form_alter() implementations using $form_state; in the same way, form validation handlers, and form submission handlers, can share data using the $form_state parameter that is passed by reference. Before implementing your own code, verify it is possible to share data using a different mechanism already implemented by Drupal for the specific case.


Add product to cart programmatically I want to add a product to the cart programmatically on form submit

My code below works only for root, but in my site an anonymous user can access the cart and checkout, but when submitting form with non user=1 it returns Your shopping cart is empty.

In my submit function:

$uid = ($user->uid) ? $user->uid : 0;
    $order = commerce_order_new($uid, 'checkout_checkout');

// Save the order to get its ID.
    commerce_order_save($order);

// Load whatever product represents the item the customer will be
// paying for and create a line item for it.
    $product = commerce_product_load($product_id);

    $line_item = commerce_product_line_item_new($product, 1, $order->order_id);
// Save the line item to get its ID.
    commerce_line_item_save($line_item);
// Add the line item to the order using fago's rockin' wrapper.
    $order_wrapper = entity_metadata_wrapper('commerce_order', $order);
    $order_wrapper->commerce_line_items[] = $line_item;

// Save the order again to update its line item reference field.
    commerce_order_save($order);
    //commerce_cart_order_refresh($order);
//    ym(commerce_cart_order_id($uid));
    //commerce_cart_commerce_order_load($order);
    //ym(commerce_cart_order_is_cart($order));
    //commerce_cart_product_add($uid, $line_item);
    //commerce_cart_product_add_by_id($product_id);
    //$form_state['redirect'] = 'cart';
    drupal_goto('cart');

Why does it not work correctly with non root (uid=1)?

You don't need to change the order directly, commerce_cart_product_add do it for you.

Try this code:

Variables:

 $product : commerce product
 $quantity: number of elements

Code

 global $user;
 // Create new line item:
 $line_item = commerce_product_line_item_new($product, $quantity);

 // Add to current user's cart: if the user is not logged in ($user->uid: 0) Drupal Commerce manages the $_SESSION
 $line_item_added = commerce_cart_product_add($user->uid, $line_item);

 // If $line_item_added !== FALSE the line_item has been added OK!


Developing sites while using Aegir and Drush make I read this article from mig5.net about 'Drupal deployments & workflows with version control, drush_make, and Aegir'. I am impressed by the efficiency of the workflow described here, and I really want to implement this. I read it again and again, but one thing won't get clear to me.

How do you, while developing websites, get your changes into the next build? When you find out you need an extra module, how can you get this in the next build when the (for example contrib) module isn't controlled in git? Do you need to edit your .make file every time you want to add a module, library etc.?

Thanks in advance.

Yes. The short answer is you update your Drush make file to point to the new version of the module you want to be included in your new platform(build).

In your drush make file you would include the version of each module you are including in your platform build. So views for example would look like this.

projects[views][subdir] = "contrib"
projects[views][version] = "3.4"

Now if you want to update to the new version of Views module you would update your make file to something like this.

projects[views][subdir] = "contrib"
projects[views][version] = "3.5"

Then build a new platform in Aegir using this updated drush make file. Then you would migrate the site to the new platform and Aegir will do the update for you.

It's a pretty slick workflow. I keep all of my drush make files in a repo called builds so I can have a record of each build of a project. Hope that helps.


Problem with images on a slideshow of product displays (Views Slide, Flexslider) Kind of a strange problem with trying to make a slide show of my product displays. I am creating a slideshow from content of type product display (ordered by newest first). The issue I have is that adding the fields Content: Image, Content: Product Image, or Field: Product Image doesn't load an image. I get asked about image styling, so clearly drupal knows that it's an image. I wouldn't think that I would need to add a relationship, because I have almost an identical view elsewhere that readily brings in the images. So can someone set me straight here?

I added a relationship to "Content: Referenced Product" and this solved the issue.  For anyone who is new to Drupal, it isn't obvious that this is (field SKU), but this is how to link back to the content in the Product Nodes in commerce.


How to trim a rendered item before and after specific symbols I've created a field where I store the URL to an image. I need to display the filename of the image without the part before the slash and without the file extension.

  http://some.url.com/folder/this/and/that/361.jpg

should be displayed as 361

  http://some.url.com/url/folder/this/and/that/1021.jpg

should be displayed as 1021

I know that this can be handled field--field-name-of-url.tpl.php file but I wasn't able to apply the solutions I've found correctly.

I tried the regex and explode method but I don't know how to insert it into the code below.

Thanks for any help.

<?php foreach ($items as $delta => $item) : ?>
    <?php print render($item); ?>
<?php endforeach; ?>

A tip from a friend got it working. Here the solution.

<?php foreach ($items as $delta => $item) : ?>
    <?php
     $file_extension = substr(render($item) , strrpos(render($item) , '.') +1);
     print basename(render($item), '.'.$file_extension);
    ?>
     </p>
<?php endforeach; ?>


How to convert hook_filter and hook_filter_tips in Drupal 7? I have trouble converting my custom modules in D7. Found a how-to here http://drupal.org/node/224333 but not so clear to me. This how my code in D6.

/**
 * Implementation of hook_filter().
 */
function custom_inline_filter($op, $delta = 0, $format = -1, $text = '') {

  switch ($op) {
    case 'list':
      return array(0 => t('Custom Inline Filter'));

    case 'description':
      return t('Substitutes @inline tags with the uploaded inline images of the node.', array('@inline' => '<!-- INLINE -->'));

    case 'settings':
      break;

    case 'no cache':
      return FALSE;

    case 'prepare':
      return $text;

    case 'process':
      return custom_inline_substitute($text);
      break;

    default:
      return $text;
  }
}

/**
 * Substitute inline image placeholder comments with inline image divs.
 * This function is usually called by hook_filter.process but also by template.php (used for RSS).
 *
 * @param $content
 * @param $node_id
 * @param $rss
 */
function custom_inline_substitute($content, $node_id = NULL, $rss = FALSE) {

  // Get nid from argument

  if ($node_id) {
    $nid = $node_id;
  }
  // Get nid when a node is displayed

  elseif (arg(0) == 'node' && is_numeric(arg(1))) {
    $nid = arg(1);
  }
  else {
    return $content;
  }

  // Instantiate inline image class

  $inlineImg = new CustomInlineImage($nid, $rss);
  return $inlineImg->substitute($content);
}

/**
 * Implementation of hook_filter_tips().
 */
function custom_inline_filter_tips($delta, $format, $long = FALSE) {

  if ($long) {
    return t('You may link to uploaded images within the current node using the wysiwyg editor toolbar icons.
      The Custom Inline Filter is to replace added image placeholders with uploaded inline images.'
    );
  }
  else {
    return t('Use the wysiwyg editor toolbar icons to display uploaded images inline.');
  }
}

The code you should use in Drupal 7 is similar to the following one.

function custom_inline_filter_info() {
  $filters['custom_inline_filter'] = array(
    'title' => t('Custom Inline Filter'),
    'description' => t('Substitutes @inline tags with the uploaded inline images of the node.', array('@inline' => '<!-- INLINE -->')),
    'cache' => TRUE,
    'process callback' => 'custom_inline_substitute',
    'tips callback' => 'custom_inline_filter_tips',
  );

  return $filters;
}

function custom_inline_substitute($text, $filter, $format, $langcode, $cache, $cache_id) {
  // …
}

function custom_inline_filter_tips($filter, $format, $long) {
  if ($long) {
    return t('You may link to uploaded images within the current node using the wysiwyg editor toolbar icons.
      The Custom Inline Filter is to replace added image placeholders with uploaded inline images.'
    );
  }
  else {
    return t('Use the wysiwyg editor toolbar icons to display uploaded images inline.');
  }
}

The documentation for the input filter implementations is provided in more than one page:

hook_filter_info()
hook_filter_FILTER_settings()
hook_filter_FILTER_prepare()
hook_filter_FILTER_process()
hook_filter_FILTER_tips()

For the parameters passed to the callbacks defined from an input filter module, see hook_filter_FILTER_settings(), hook_filter_FILTER_prepare(), hook_filter_FILTER_process(), and hook_filter_FILTER_tips().
In particular, it is relevant to know that:

$filter is a filter object, not a string that identifies the input filter; it contains information about the input filter, but what an input filter implementation normally uses is $filter->settings, which is an array of settings defined from the input filter.
$format is a format object, described in filter_format_save(); it doesn't contain information that an input filter normally uses.

To notice that only the first one is actually a hook; the others are callbacks. The documentation shows them as hooks because a limit of the module used to add documentation pages on Drupal.org API: A documentation page is added only if the function is contained in a module (a Drupal core module, or a third-party module), or it is a hook described in a .api.php file.


How to set up a repeated “field set” with unlimited time and event? I am planning to set up a “patient visiting record” , the repeated “field set” is time and events, for instance, “2017-12-15, the first visit, patient has stomach pain”, “2017-12-30, the second visit, patient has vomiting, has a rash on the left leg[image upload]”....every time when I click on “add item” the “time and event set” will pop up as one field. And the series “daily like” records will show on the patient record page, of course every patient will have their own page. The records of course are only accessible for admin. Is that possible to realize?

This is possible using the "double field" module (https://www.drupal.org/project/double_field) and using the "field permissions" module (https://www.drupal.org/project/field_permissions).

In the users' account settings add a double field, set it up as date/text combination, allow unlimited values. Use the field permissions setting to permit access to specific roles only.

This does't allow to use images to be used, unfortunately.

An alternative idea is using a paragraphs field (https://www.drupal.org/project/paragraphs), where you can define a paragraphs item with any fields you need. Again, set to unlimited allowed values and setting field permissions.


500 Internal Server Error after logging in I have a D7 site. I start getting a 500 internal server error. I get the default Chrome (my browser) error page, instead of the one from my server.

This error occurs only after I log in and have navigated through a page or two. The apache error log shows nothing except for the following message :

[Sun Jul 15 21:53:27 2012] [debug] mod_deflate.c(615): [client 127.0.0.1] Zlib: Compressed 0 to 8 : URL /php5-fcgi/index.php, referer: http://new.whack.co.in/admin/modules

I can browse through the whole site anonymously without encountering any problems. I can even access the site temporarily by clearing my browser's cache.

The site uses a combination of Varnish+Apache 2+APC+php-fpm+memcache.
I have a D6 site installed on the same server and I can navigate through it without encountering any problems.

This site was installed by using Drush Site Upgrade. Contents and settings were migrated from a the previously mentioned D6 site. The D6 site is stored on /var/www/drupal (Accesible from default domain) while the D7 site on /var/www/seven - (accessible from a subdomain).

What can be the possible cause of the problem and how can I fix it? Please do let me know if any other information is required.

From my research there are basically four things that could cause the '500 internal server error' with drupal :

Misconfgured server (you will have to dig into your server configs)
Misconfigured .htaccess file (replace your existing .htaccess with the drupal default)
Misconfigured file permissions
Low php memory_limit setting

In my case, the culprit was the memory_limit setting. After doubling the same, my site is flying right now.


Can't add assets to my Bootstrap sub-theme I'm currently struggling to include *.css and *.js files to my Bootstrap sub-theme.

I use Drupal 8 and the Bootstrap 3 base theme. I followed the instructions of the official documentation and went to create a custom SASS sub-theme for my site.

I could quickly use my newly created sub-theme in the admin panel. Great.

However it seems none of the assets registered in my *.libraries.yml are included in any page.

My SUBTHEME.info.yml file:

core:       8.x
type:       theme
base theme: bootstrap

name:         'My custom sub-theme'
description:  'This is a sub-theme of Bootstrap, using the Sass starter kit.'
package:      'Bootstrap'
version:      'alpha'

regions:
  navigation:             'Navigation'
  navigation_collapsible: 'Navigation (Collapsible)'
  header:                 'Top Bar'
  highlighted:            'Highlighted'
  help:                   'Help'
  content:                'Content'
  sidebar_first:          'Primary'
  sidebar_second:         'Secondary'
  footer:                 'Footer'
  page_top:               'Page top'
  page_bottom:            'Page bottom'

libraries:
  - 'SUBTHEME/global-styling'
  - 'SUBTHEME/bootstrap-scripts'

My SUBTHEME.libraries.yml file (unchanged):

global-styling:
  css:
    theme:
      css/style.css: {}

bootstrap-scripts:
  js:
    bootstrap/assets/javascripts/bootstrap/affix.js: {}
    bootstrap/assets/javascripts/bootstrap/alert.js: {}
    bootstrap/assets/javascripts/bootstrap/button.js: {}
    bootstrap/assets/javascripts/bootstrap/carousel.js: {}
    bootstrap/assets/javascripts/bootstrap/collapse.js: {}
    bootstrap/assets/javascripts/bootstrap/dropdown.js: {}
    bootstrap/assets/javascripts/bootstrap/modal.js: {}
    bootstrap/assets/javascripts/bootstrap/tooltip.js: {}
    bootstrap/assets/javascripts/bootstrap/popover.js: {}
    bootstrap/assets/javascripts/bootstrap/scrollspy.js: {}
    bootstrap/assets/javascripts/bootstrap/tab.js: {}
    bootstrap/assets/javascripts/bootstrap/transition.js: {}

I strongly believe my folder hierarchy is right ; I use the base bootstrap themes/bootstrap/templates/system/html.html.twig which embarks the following header:

<head>
  <head-placeholder token="{{ placeholder_token|raw }}">
  <title>{{ head_title|safe_join(' | ') }}</title>
  <css-placeholder token="{{ placeholder_token|raw }}">
  <js-placeholder token="{{ placeholder_token|raw }}">
</head>

The CSS / JS aggregation option in the admin/config/development panel is disabled.

I compiled sass/style.scss and I do have a corresponding css/style.css file, however it never shows up on my pages. Even worse, it seems none of the libraries assets are included either.

No, I didn't forget to clear the cache. I also tried to solve my problem by reading other questions, like this one or this one ; however the questions are either not resolved or do not apply to my case.

I tried to add the following lines to my SUBTHEME.info.yml, unfortunately it doesn't work either:

stylesheets:
  - 'css/style.css'

I tried to use the Drupal/Twig tag attach_library with no success.

Interestingly, assets added from third-party modules are successfully added in a way almost identical to what I'm trying.

I'm quite sure I'm missing something simple here. Any help deeply appreciated.

I see that you don't include global-scripts in .info.yml file. You should have something like this at the beginning of your .info.yml file:

global-styling:
  css:
   theme:
    css/style.css: {}

global-scripts:
  js:
   js/URI.min.js: {}
    js/jquery.waypoints.min.js: {}
     js/global.js: {}

If this doesn't work, I would highly recommend you to get a fresh copy of SASS directory of starterkits(it is in themes/contrib/starterkits/sass) then check out all the THEMENAME and replace it with your custom theme name. Kind regards


Add ellipsis replacement to Pathauto To handle users who like to occasionally use the custom ellipsis character from MS Word in titles, I would like to add replacement options for the character in the Punctuation settings for Pathauto using hook_pathauto_punctuation_chars_alter(). The problem is determining what value to put in the value setting in the hook. I found the T_ELLIPSIS constant in tokenizer.php, and tried using it like so:

function my_module_pathauto_punctuation_chars_alter(array &$punctuation) {
  $punctuation['ellipsis'] = array(
    'value' => T_ELLIPSIS,
    'name' => t('')
  );
}

and the value shows as Ellipsis (389) for the field label in the settings. However, when the alias is generated with the ellipsis character in the node title, it doesn't get replaced.

Is there a better/easier way to handle this? Also, should I use something like the UTF-8 code instead of the constant?

My prefered solution to scrub out extraneous characters in Pathauto URLs is this option under Configuration » Search and metadata » URL aliases » Settings.

It will scrub out all the extraneous characters that can mess up browsers/crawlers. This is assuming you're on an English language website.


Can't add or update a taxonomy term Something has happened on my site where I am unable to add taxonomy terms or edit existing ones.

If I go to add a taxonomy term or edit an existing one the form comes up, I made an changes (i.e. add some text in the description field) and then click save and it goes back to the Taxonomy list  but nothing changed. When I go back into edit the taxonomy term the previous change is gone.

The same thing happens when I try to add a term through /admin/structure/taxonomy/name_of_vocabulary/add form- it saves, but then the new term doesn't show up.

Any ideas?

Solved by upgrading to the most recent version of Meta tags module.

Thank you to Patrick Kenney for pointing me in the right direction.


How could I create multiple private sites within one Drupal site? Can I create a Drupal site, where a user, let's call her Jane, can create an account and publish some content, like a few articles. Then create accounts for her friends who can login and view all the nodes she has created, and which they create. At the same time, Paul creates an account, creates some nodes, and invites his friends etc. However, Paul and his friends cannot see Jane's nodes or users - and vice versa. It feels to Jane and Paul that they have there own separate website.

What are the key Drupal concepts or methods for creating a site like this? Thanks.

This seems like a perfect use case for Organic Groups.

  Enable users to create and manage their own 'groups'. Each group can
  have subscribers, and maintains a group home page where subscribers
  communicate amongst themselves.

I'm not going to go in depth with setup or anything, as OG is a beast of a module, but the benefits are immense, and should allow you to do exactly what you need. It's the same module that provides the groups.drupal.org functionality :)

A quick Google search will provide a wealth or information, as will a browse of the organic-groups tag.

Also check these out for a brief overview of OG:

Organic Groups for Drupal 7 (Lullabot)
An Introduction to Organic Groups with Drupal 7 (YouTube/Lullabot/Drupalize.me)


How do I set up CORS? Drupal 8 has RESTful web service in-built in core and since 8.2 we don't need cors module.

Now to use services we just enable and configure default.service.yml file as specified in here

However, I was not able to configure this setup to allow web service access over another domain.

My current service.yml setup for cors is:

cors.config:
    enabled: true
    # Specify allowed headers, like 'x-allowed-header'.
    allowedHeaders: ['x-csrf-token,authorization,content-type,accept,origin,x-requested-with']
    # Specify allowed request methods, specify ['*'] to allow all possible ones.
    allowedMethods: ['POST, GET, OPTIONS, DELETE, PUT']
    # Configure requests allowed from specific origins.
    allowedOrigins: ['*']
    # Sets the Access-Control-Expose-Headers header.
    exposedHeaders: false
    # Sets the Access-Control-Max-Age header.
    maxAge: 1000
    # Sets the Access-Control-Allow-Credentials header.
    supportsCredentials: false

I googled to find further detailed configuration on this but could not find one.

I am creating this for test development across two different domains.

Using pantheon dev environment for web services and localhost custom .dev domain for consuming those services.

Service access working fine using chrome CORS extension.

I ran into this fairly recently on Pantheon, and hopefully this helps if you haven't already solved it.

cors.config:
    enabled: true
    # Specify allowed headers, like 'x-allowed-header'.
    allowedHeaders: ['x-csrf-token','authorization','content-type','accept','origin','x-requested-with', 'access-control-allow-origin','x-allowed-header','*']
    # Specify allowed request methods, specify ['*'] to allow all possible ones.
    allowedMethods: ['*']
    # Configure requests allowed from specific origins.
    allowedOrigins: ['http://localhost/','http://localhost:3000','http://localhost:3001','http://localhost:3002','*']
    # Sets the Access-Control-Expose-Headers header.
    exposedHeaders: false
    # Sets the Access-Control-Max-Age header.
    maxAge: false
    # Sets the Access-Control-Allow-Credentials header.
    supportsCredentials: true

A few things to note...

Regarding the location of the file on Pantheon, please make sure your service.yml file is in /sites/default vs just /sites. I was wrongly under the impression it would work from both places. It will only work if in the /sites/default directory.

Notice the comma separated list of allowedHeaders each in their own set of quotes. I originally had a single string like you do in your example above, and it failed countless times before I caught the subtle difference. I'm fairly certain allowedMethods works the same way if you specifically want to list out your methods.

Please also note that while my code snippet will work well for development against a Pantheon sandbox you will likely want to lock things down a bit more prior to going into production. With Pantheon offering HTTPS you will also want to make sure to use it if you are going to be passing information around through headers. Hope this helps either you if you are still having issues or someone else that stumbled upon it down the road.


set a id for a div class in drupal Anyone help me how to set the id for a div class dynamically in code. Let suppose class name by group_left

      <div class-"group_left article_left">

I have to add a id attribute for this class "group_left article left"

I have used the java script to set the id but I can't.This is my code.

   var thediv = document.getElementByClassName(".group-left ");
    thediv.setAttribute("id", "pad_id");

There is any way API to add attribute id for a class in drupal.please help me.

You would be better off using jQuery:

(function($) {
  $(function() {
    // Grab the element with both group_left and article_left class and set an ID attribute.
    $('.group_left.article_left').attr('id', 'pad_id');
  });
})(jQuery);

It's worth checking that the element with both of those classes is unique on the page, if the same ID is added to more than one element then the document will become invalid and you might have problems with other javascript.


how to render html link within dsm message? I would like to include a link to the reports page within a dsm message.  Here is what I tried:

  $loglink = l("logs", 'admin/reports/dblog');
  $msg= "See $loglink for watchdog messages";
  dsm ($msg);

However, this displays the raw html (a href=...) and does not render the link.

How do I render the html link within a dsm message?  (I am using Drupal 6.x)

You can't with dsm() I'm afraid, it's run through Krumo which encodes any special chars into HTML entities. Check out the dpm() documentation (which is called internally by dsm()) and follow the function trail through and it'll make more sense.

You'll have to resort to good ol' drupal_set_message():

$loglink = l("logs", 'admin/reports/dblog');
$msg= "See $loglink for watchdog messages";
drupal_set_message($msg);


How can I un-subtheme a theme? I've been developing a custom theme as a Zen subtheme, but I've made so many changes and new files that nothing from the original Zen theme is being used.

However, my new theme is still connected to the Zen theme and requires that it is installed on the server.

How can I detach the Zen parent theme and have my subtheme stand alone?

Remove “base theme” declaration from YOURTHEME.info


CiviCRM Email Record appearing in other members profile Information We have a Drupal module that allows users to sign up and create their own personal fundraising page. Every Drupal user is matched to their equivalent CiviCRM profile where the information is stored. The Drupal module then reads information from CiviCRM  to display custom reports such as how much they have raised and their contact info.

There is one email that is in the system and is getting overlaid somehow into other members profiles. The owner of the email has not created a page, I'm not sure how their email even got into the system. It has happened twice already. On a mailing the owner of the email account responded saying they were not the correct person.

Any ideas how this happened and how to correct it?

CiviCRM has a table civicrm_uf_match, which links CiviCRM contacts to Drupal (or Wordpress or Joomla) users. Here is its structure:

CREATE TABLE `civicrm_uf_match` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT COMMENT 'System generated ID.',
  `domain_id` int(10) unsigned NOT NULL COMMENT 'Which Domain is this match entry for',
  `uf_id` int(10) unsigned NOT NULL COMMENT 'UF ID',
  `uf_name` varchar(128) COLLATE utf8_unicode_ci DEFAULT NULL COMMENT 'UF Name',
  `contact_id` int(10) unsigned DEFAULT NULL COMMENT 'FK to Contact ID',
  `language` varchar(5) COLLATE utf8_unicode_ci DEFAULT NULL COMMENT 'UI language preferred by the given user/contact',
  PRIMARY KEY (`id`),
  UNIQUE KEY `UI_uf_name_domain_id` (`uf_name`,`domain_id`),
  UNIQUE KEY `UI_contact_domain_id` (`contact_id`,`domain_id`),
  KEY `FK_civicrm_uf_match_domain_id` (`domain_id`),
  KEY `I_civicrm_uf_match_uf_id` (`uf_id`),
  CONSTRAINT `FK_civicrm_uf_match_contact_id` FOREIGN KEY (`contact_id`) REFERENCES `civicrm_contact` (`id`) ON DELETE CASCADE,
  CONSTRAINT `FK_civicrm_uf_match_domain_id` FOREIGN KEY (`domain_id`) REFERENCES `civicrm_domain` (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=4997 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci

'UF' stands for Underlying Framework, i.e. the Drupal, Wordpress or Joomla installation to which CiviCRM is linked.

Sometimes entries in this table can get out of sync, e.g. if the Drupal database has been copied from a development server to a test server without also copying the CiviCRM database.

Perhaps that is what has happened in this case. You could check by examining the civicrm_uf_match records for the relevant email addresses, which are stored in the uf_name field.

It can also be useful to join civicrm_uf_match to the Drupal users table and check for any records where the email in civicrm_uf_match differs from the email in users. Also a left join from civicrm_uf_match to users can highlight orphan civicrm_uf_match entries.


Moving the a view Contextual Filter default value("PHP Code") to a module code I am really wondered to know how I can move my designed view's Contextual Filter default value which is being provided by my written code as PHP Code, to a module code or a hook.

Is there any possibilities?

Moreover, I am not really interested in exporting view and putting it inside some hooks and ... (as it's again using eval for that PHP Code).
I really like to move the Contextual Filter default value which is being provided by my written code as PHP Code, to a module code or a hook.

Even if you can provide me a way to access&manipulate the designed view inside the Drupal, by a module hook/code, it can be really helpful for me.

This tutorial shows goes through exactly what you're wanting to do http://www.undpaul.de/en/blog/2013/04/04/contextual-content-flag-module-and-custom-views-default-argument-handler

You're definitely going to want to look at the module code in its entirety on his github linked in the article because in the blog post he left out some crucial code (like how to define the views_argument_default_flag handler as class that extends from views_plugin_argument_default.

In my own experience, I needed a custom argument validator instead of a default argument handler, so I followed this tutorial http://www.joetsuihk.com/en/en/custom_views_argument_validator_views_plugin_argument_validate and came up with the following working result.

The need for this custom argument validator arose from needing nested or hierarchical taxonomy term names in the URL instead of the taxonomy term IDs, like /parent-category/child-category/grandchild-category.  I tried to use the contextual filter validation method of converting the term name in the URL into its corresponding term id and replace spaces with dashes, but my category names have special characters like /, &, +, and -, which meant decoding the URL didn't always match the original term name.

So, the following custom views contextual filter (argument) validator correctly parses the term name out of the URL and figures out the corresponding term id by querying the url_alias table.  After querying a particular path once, the result is cached for better performance.  To get these hierarchical paths stored in the url_alias table, I set up a pathauto pattern for my taxonomy vocabulary, like store/[term:parents:join-path]/[term:name]

The info file:

name = Example Module
package = "Example"
description = Example Module custom views argument validator
core = 7.x

files[] = plugins/example_module_plugin_argument_validate_url.inc

The module:

/**
 * @file example_module/example_module.module
 * Implement hook_views_api - load up the custom views include files
 */
function example_module_views_api() {
  return array(
    'api' => 3.0,
    'path' => drupal_get_path('module', 'example_module'),
  );
}

The views include file:

/**
 * @file example_module/example_module.views.inc
 * Defines a custom contextual filter validator
 */
function example_module_views_plugins() {
  return array(
    'argument validator' => array(
      'taxonomy_url_alias' => array(
        'title' => t('Taxonomy URL Alias'),
        'handler' => 'example_module_plugin_argument_validate_url',
        'path' => drupal_get_path('module', 'example_module') . '/plugins',
      ),
    ),
  );
}

The contextual filter handler:

/**
 * @file example_module/plugins/example_module_plugin_argument_validate_url.inc
 * Contains the taxonomy url alias contextual filter validation plugin.
 */

/**
 * Validate whether an argument (contextual filter) is a valid
 * @ingroup views_argument_validate_plugins
 */
class example_module_plugin_argument_validate_url extends views_plugin_argument_validate {

  private $intAddUnixTime = 604800;
  private $error = FALSE;

  function validate_argument($argument) {
    $view = &$this->view;
    $handler = &$this->argument;

    if (!empty($view->args)) {
      //reconstruct the url from the views argument array
      $strPath = implode("/", $view->args);

      //get the taxonomy term id based on the url, not the term name
      $objAlias = $this->getTermId($strPath);

      //split the url_alias's source column up into an array.
      //the source column contains the term id at the end of a path like 'taxonomy/term/123'.
      $arrTermData = explode("/", $objAlias->source);
      $tid = end($arrTermData);
      $term = taxonomy_term_load($tid);

      //manually assign the term id to be the view's argument
      $handler->argument = $term->tid;
      return true;
    }
    else {
      return false;
    }
  }

  /**
   * Get the taxonomy term id from either the url_alias table or from persistent cache
   * @param string $strPath like 'parent-category/child-category/grandchild-category'
   * @return object containing the result of the url_alias table or persistent cache lookup
   */
  private function getTermId($strPath) {
    $objReturn = NULL;
    //attempt to get the taxonomy term id from cached url_alias table result object
    $objReturn = $this->getCache($strPath);

    //if cache is not set, do a select query
    if ($objReturn == NULL) {
      try {
        if(!$this->error) {
          $objReturn = $this->_dbSelect($strPath);
          //cache the response
          $this->setCache($strPath, $objReturn);
        }
        else {
          //log some error because $this->error was true
        }
      }
      catch (Exception $ex) {
        $this->error = TRUE;
        //log an exception
      }
    }

    return $objReturn;
  }

  /**
   * Run a query to look up the taxonomy term id based on the url alias path
   * @param string $strPath url alias like 'parent-category/child-category/grandchild-category'
   * @return object results of the query
   */
  private function _dbSelect($strPath) {
    $result = NULL;
    try {
      //The alias stored in the url_alias table is going to be prepended with 'store/' because of my pathauto taxonomy pattern
      $result = db_select("url_alias", "ua")
        ->fields('ua', array('pid','source','alias'))
        ->condition('alias', 'store/'.$strPath, '=')
        ->condition('source', 'taxonomy/term%', 'LIKE')
        ->range(0,1)
        ->execute()
        ->fetchObject();
    }
    catch(Exception $ex) {
      //log an exception
    }

    //$result is an object like:
    //$result->pid //'12345'
    //$result->source //'taxonomy/term/123'
    //$result->alias //'store/parent-category/child-category/grandchild-category'
    //$result->uid //1
    return $result;
  }

   /**
   * Get an object from cache
   * @param  string $strPath used as part of the cache id
   * 'cache_taxonomy_url_alias' is a custom cache bin
   * @return object data from the persistent cache
   */
  private function getCache($strPath) {
    $objCache = cache_get('example_module_plugin_argument_validate_url' . '::' . 'store/'.$strPath, 'cache_taxonomy_url_alias');
    if (isset($objCache->data)) {
      return $objCache->data;
    }
    else {
      return NULL;
    }
  }

  /**
   * Store an object in cache
   * @param  string $strPath used as part of the cache id
   * @param  object $objData contains the url alias table results
   * @return void
   */
  private function setCache($strPath, $objData) {
    cache_set('example_module_plugin_argument_validate_url' . '::' . 'store/'.$strPath, $objData, 'cache_taxonomy_url_alias', time() + $this->intAddUnixTime);
  }
}

After that I selected my custom contextual filter validator:


How to remove suggestions for a input field? Many browsers use a sort of autocomplete function. So the moment you already entered data in a field it will be added to there remembering list.

I would like to have no suggestion for fields.

A solution for this is using autocomplete on/off for the input fields
http://www.w3schools.com/tags/att_input_autocomplete.asp
I do not understand the compliance for the different browser...

I use many fields in my system. I do not want this for all fields.

There are some solution with modules but not for all fields:
https://www.drupal.org/project/no_autocomplete = only working for login screens

What ways are there to implement this in a easy way in Drupal 7?
I guess to have a hook_form_alter but then?

I guess something like this:

  ' Setuplist with fields automcomplete should be off
    afields_setautomcompleteoff ("fieldname1", "fieldname2","fieldname3")

    ' Look if the current form contains a fields with should be edited
    if(count(array_intersect(?????, $afields_setautomcompleteoff)) == 1){
        'add att to input field but how?
    };

Any suggestions?

Take a look at hook_form_alter. Also refer to the drupal FAPI, there are many form controls are available which you can use in a form.

For your case, below example will be helpful.

function example_form_alter(&$form, &$form_state, $form_id) {
  if($form_id === 'your_form_id'){
     $form['your_field']['#attributes'] = array('autocomplete' => 'Off');
  }
}

Other option is with JS.

Drupal.behaviors.exampleModule = {
  attach: function (context, settings) {
    $('input[type="text"]').each(function (i, input) {
      $(input).attr('autocomplete', 'off);
    });
  }
};