How do I get a field value in a template? I want to change the default HTML for a custom field called field_product_image and I created the field--field_product_image.html.twig template. Now I need to fill in the following information in the HTML, but for some reason I cannot get the content of the fields.

<img src="{{ TWIG }}" alt="{{ TWIG }}" />

I tried different suggestions like {{ content }}, {{ field.field_product_image }}, {{ field.field_product_image.value }}, {{ content.field_product_image }}, {{ content.uri.value  }} but they don't output the image link.

A simpler way to do this is to use mytheme_preprocess_image().

Here is an example:

/**
 * Implements hook_preprocess_image().
 */
function MYTHEME_preprocess_image(&$variables) {
  if ($variables['style_name'] == 'content_embed') {
    $variables['attributes']['class'][] = 'custom_class';
  }

  $variables['attributes']['data-custom-attr'] = 'value';
}

Variables can be used to construct new values that get injected before rendered. The above would add custom_class to a rendered images class attribute if a specific image style is being used in this instance, and all images would receive the second attribute. Rendering the image will already give you the src and alt attributes for you, so which attributes are you really trying to add?

Reaching into render arrays in the template just leads to a ton of cruft and hard to maintain code because it's really not the place for that.

If you don't want any divs or wrapping HTML in your field, you can just add this to the field twig template:

{% for item in items %}
  {{ item.content }}
{% endfor %}

This would only render the field item (in this case image), which should leave you with only the image tag on the page and no containers.


Unlimited values field in Drupal 7 - how to show extra field in page.tpl.php I know how can I retrieve the first file name

$fileupload = $node->field_fileupload[$node->language][0]['filename'];

but how can I retrieve the other unlimited file names

The best solution would be to run a foreach:

foreach($node->field_fileupload[$node->language] as $fileupload) {
  echo $fileupload['filename'];
}


D7 Webform tokens for user fields In D6 we could configure a webform field to pull profile data by using  a token like %profile[key] and assigning the user field to the form (Details here).
How can we to something similar in D7 using the user fields instead of the profile fields?

It appears that this can't be done using the standard webform module. It defines a limited list of tokens that hasn't been updated for the new user fields. They are included as tokens (if you use field_nnn) but they will be an empty value.

After initially looking at building a custom module, it seems that the Tokens module does make user fields available in the form [user:field_nnn].


Only Admin allowed to alter order in 'Review' state How can I make an Order with status of Review read-only to the creator user? And once the Admin updates to state to 'Payment', the creator user can continue as normal?

The best way to achieve this might be with a custom module. You could use hook_form_alter() to alter the order edit form and add a validation function that checks the order status and the logged in user ID - and throw a form validation error before saving if you want to prevent them.

You might be able to accomplish this point-and-click-style with the Rules Forms module (https://www.drupal.org/project/rules_forms) which adds the ability to trigger Rules events during form validation. I haven't tried that module myself, so I can't say for sure.


How to alter node links I have few existing node nodes which contains link Click here. Now I want to update all links to . Is there any way to do this in Drupal8 via code.

You can load all those nodes by nid with

node_load_multiple(array $nids = NULL, $reset = FALSE);

Loop over all nodes and then find and replace by using

str_replace('original link', 'new link', $node->field_you_want_to_change);

And then saving the node using

$node->save()


How to make weights continous with db_update? With pure MySQL, I can do something like:

SET @weight:=0;
UPDATE mymodule_table
  SET mymodule_weight=@weight:=@weight+1
  ORDER BY mymodule_weight, mymodule_id;

Is there a Drupal way to achieve similar result? Can I avoid calls to db_query and push it with db_update or db_merge?

MySQL solution adapted from this answer.

Adding the expression is no problem, but neither UpdateQuery nor MergeQuery implement an orderBy() method. Neither will support setting a local variable first either, as far as I can tell (I'm not even sure a standard query will let you do that actually).

So I think it's safe to say that the answer is no, unless you subclass either UpdateQuery or MergeQuery, and add the sorting and variable declaration functionality yourself.


How to rearrange fields in user/%/edit page I have tried rearranging fields in user/edit page and I succeeded in arranging only few fields.

I cannot move user image field and timezone field. I have used hook_form_alter and $form['#after_bulid'] to rearrange field but not working.

This is the code

function MY_MODULE_form_alter(&$form, &$form_state, $form_id){
  $form['#after_build'][] = 'MY_MODULE_user_profile_form_after_build';
}
function MY_MODULE_user_profile_form_after_build($element, &$form_state) {
  $element['field_user_image']['#weight'] = '';
  $element['timezone']['#weight'] = '';
}

I have tried all weight from -10 to 10 but not working. Fileds should be arranged in the order as I specified in the screenshot. Can any one help me?

use nod template as page--user--edit.tpl.php and you can able too rearrange the fields by its machine name like as we did for content types...

just try this..


How to bulk resize images imported with feeds importer module? I have a Drupal 7 site on a test machine (Windows 7/Apache/PHP 5.3), with the Commerce and Feeds modules installed, and succeded in importing a CSV of more than 400 products (images included!), which made me really happy.

Now I've got a problem: in the Commerce product settings, the maximum width & height are set to 700px and 400px, respectively. The feed importer didn't resize the product photos, so now I'm stuck with product images that are the original hi-resolution photos (all above 2000x1000 pixels)!

Is there a way to make Drupal automatically re-process all the Commerce product images (call it a bulk resize, or a batch resize...)? Or have I got to reprocess them through Photoshop or something like that, and then re-import the CSV?

I know that probably not many people have faced a similar situation... any hint is appreciated!

Edit

I'm using Views Slideshow with jQuery Galleria, which loads the original images and resizes them via img tag attributes width and height.

That is a reasonable part of the problem, because even if I use Image styles (Configuration>Media>Image styles), Galleria keeps using the original image, which slows down the browser and consumes a lot of RAM.

If you have access to a command line and ImageMagick, you can run convert from find.
In Unix et al
From Drupal root:
find sites/default/files/products -name '*.jpg' -execdir convert {} -resize 700x400 {}\;
(Note: this assumes all product images are in the "products" directory in sites/default/files. You DO want to make a copy of this directory with cp -r sites/default/files/products sites/default/files/products_backup before running the above in case it does something you don't want it to!)
In Windows:

Download and install findutils.
Download and install ImageMagick
Make sure both are working on the commandline. Type "find" and hit enter. Same with "convert". If neither gives you a "command not found" error, they're installed and working.
Backup your product images directory.
Instead of the above command, try:

find sites\default\files\products -name '*.jpg' -execdir convert '{}' -resize 700x400 '{}' ';'
If find chokes on that path, try using backslashes. Also, make sure it's using the GNU version of find and not some other version (The lender Windows machine I'm working on right now has a find command, don't know if that's standard or something somebody else installed).


How to implement pager in custom page template? in my theme I need a custom front page which displays a filtered set of news and paginated. The news are nodes with content type=news, and every one has a field "is topnews", so that only the freshest topnews is displayed at the top and all other news are displayed (with another layout) below the topnews.

So I created a page--node--9.tpl.php (which corresponds to the "empty" frontpage I created in the drupal backend), and used this code to get the topnews:

$query = new EntityFieldQuery();
$query->entityCondition('entity_type', 'node');
$query->propertyCondition("type","news");
$query->fieldCondition("field_news_typ","value","Topnews","=");
$query->propertyOrderBy("created","DESC");
$query->range(0,1);
$result = $query->execute();

Then I output the topnews with its special HTML and use this code to get all other news:

$query = new EntityFieldQuery();
$query->entityCondition('entity_type', 'node');
$query->propertyCondition("type","news");
$query->propertyOrderBy("created","DESC");
$result = $query->execute();

In the iterator loop I check the node-id against the topnews-node-id and output regular HTML for the news if they don't match. Now I want to add a pager to the mess so I can paginate the "normal news", but adding a ->pager(3) to the second query before the execute() call does not work and a var_dump(theme("pager")) returns NULL.

So there are two questions:

a) how do I make a pager (bonus points: the end result should be an AJAX pager which loads the HTML for ordinary news!) and

b) how do I move all that logic out of the .tpl.php and instead follow the "proper" drupal way? I imagine that having the "ordinary" and "topnews" HTML in separate .tpl.php files would be helpful in implementing said AJAX paging.

This can and should almost certainly be done entirely with the Views module (which is/will be in Drupal 8 core!). The filtering of your content by type and the value of the "top news" field can all be done with Views, along with the ajax pager. You can then use the Views attachment display type to attach those news items which do not have the "top news" box checked. You may also want to look into the Nodequeue module for ordering content in more ambiguous ways than just the most recent or whatnot, but you can also use Drupal's "sticky" setting on nodes that you want to keep at the top of the list and highlight, format them differently, etc. Views also allows you to rewrite the output of every item in the results in the UI or using tpl files. Views, my friend. Views.


Does caching has to be manually disabled for ajaxified forms? I switched on caching on my dev environment and it looks like ajaxified forms won't work* unless I specifically set max-age to them to 0. Is this normal? Or is this the case only when a form is displayed via lazy builder?

*they will work but submitting them will result in normal behavior where the form is submitted and the page is reloaded.

Not sure what you mean by "ajaxified". That sounds like a regular form is automatically "ajaxified".

Potentially this form is violating the principle that GET forms should not manipulate state. i.e. GET forms must be stateless. HTTP dictates this, but in Drupal 7 it was not respected. In Drupal 8 it is.

See https://www.drupal.org/node/2502785.


Creating multiple blocks programmatically I am writing a custom module for Drupal 7. I need to create 5 different blocks with the module. Drupal has the hook_block_info and hook_block_view hooks which create blocks. How can I add multiple blocks since these hooks allow only one block per module?

The following code should help.  You'll obviously need to add your 5 blocks as appropriate, but it's just to show how you can add multiple blocks in one module:

function MYMODULE_block_info() {
 $blocks = array();
 $blocks['myfirstblock'] = array(
   'info' => t('My block admin info'),
   'status' => 1,
 );
 $blocks['mysecondblock'] = array(
   'info' => t('My second block admin info'),
   'status' => 1,
 );

 return $blocks;
}

function MYMODULE_block_view($delta = '') {
  $block = array();

  switch ($delta) {
    case 'myfirstblock':
      $block = array(
        'subject' => t('My first block title'),
        'content' => t('My first block content'),
      );
      break;
    case 'mysecondblock':
      $block = array(
        'subject' => t('My second block title'),
        'content' => t('My second block content'),
      );
      break;
  }

  return $block;
}

Reason for status => 1 from hook_block_info() API docs:

  status: (optional) Initial value for block enabled status. (1 =
  enabled, 0 = disabled). Most modules do not provide an initial value,
  and any value provided can be modified by a user on the block
  configuration screen.

I'm not sure where you got the one block per module idea from.  You can create as many blocks as you'd like in a module.


Is there any management utility for multi-site deployment? I'm creating a multi-site instance for a client that makes heavy use of Webform. It's going to be a survey tool of sorts with a single base domain (no sub-domains) and a single SSL certificate.

I've set up the /sites/default the base of what we'd like all other sites to be like. I've gone so far as to attempt this using bash. (This is not my best code and it lives on a throw away VM*):

# Create temporary password
PASS=`tr -dc a-z1-4 </dev/urandom  | head -c 10`

# File structure and empty settings file
mkdir /var/www/html/sites/$1
mkdir /var/www/html/sites/$1/files
cp /var/www/html/sites/default/default.settings.php /var/www/html/sites/$1/settings.php

mysql -u root -p -e "create database $1"
mysql -u root -p -e "GRANT ALL PRIVILEGES ON $1.* TO '$1'@'%' IDENTIFIED AS PASSWORD('$PASS');"

# And here is where things fall apart
drush si ???

My question is, is there a module or utility that could help create a new site inside this multi-site installation? That is, I'd like to clone the model database, create a /sites/new-site/settings.php, and enable a chosen set of modules.

My dream would be to have a drush clone-site command.

Take a look at Aegir:

http://drupal.org/project/hostmaster
http://www.aegirproject.org/

It's probably a bit more than what you are looking for, since it manages your web server vhosts (apache or nginx), which means that it kind of takes over part of the system configuration. It also works much better on Debian (with Debian packages, installation/upgrades are pretty easy.. kind of annoying otherwise).

Once it's installed, you can create your base site and clone it using the Aegir user interface (which is a Drupal site, called the "hostmaster", which is completely autonomous from the other sites you are hosting - it's just that as Drupal developers, they used Drupal for the front-end to their tool). Under the hood, Aegir uses Drush, so it's not re-inventing the wheel.

Anyway, fair disclaimer: there is a learning curve, but it has a pretty good community and it's well worth it when managing farms of small sites. It also has commercial training/support available from a few companies (listed on the project page).


Is there a module that allows users to post content in steps? sometimes posting a blog post can seem daunting to some of my users. They see a large page with so many entry points that I think I'm missing out on some good content. So what I would like to do is give users the ability to add entries in steps. without seeing the entire form.

Title
body
tags
video

Try Multistep Nodeform

  Multistep Nodeform" is a module to split the node creation and node
  editing form into several steps. This may be usefull for you if you
  have lots of fields in your content type and would like to provide a
  wizard-like UI for content creation/editing.


Tracking down pesky PHP 5.3 errors We have a site that is throwing errors when uploading files to a simple "Page" node. I've done a lot of work trying to track down the actual source of the error, and I posted a half dozen messages to various likely threads at drupal.org.

The errors we get on file attach/upload:

  warning: Parameter 2 to wysiwyg_form_alter() expected to be a
  reference, value given  in /var/www/drupal/includes/common.inc on line
  2892.

  warning: Parameter 2 to simple_access_form_alter() expected to be a
  reference, value given in /var/www/drupal/includes/common.inc on line
  2892.

I understand about passing by reference versus value. I understand about fixing the problem in the offending module by using the two calls to drupal_alter(), as described on
http://drupal.org/node/930992#comment-4066840, but so far I have not been able to find what module is making the call incorrectly.

I tried installing and enabling the same set of modules on a test site but cannot reproduce these errors.

It's hard to post a bug report when you don't know the offending module.

See also http://drupal.org/node/1200970#comment-5463436.

Assuming you do not have a debugger going (getting XDebug to run for your local development environment is probably the single most useful thing you can do the entire year), you could use debug_backtrace() at the place of the error (i.e. in the two form alter functions) to find out what is calling them. If you shoot its output into watchdog(), hopefully you can cross reference the time of the error with a particular invocation of these functions. Do be aware that these are form alter hooks, which get called for each and every form Drupal is building (and you might be surprised there can actually be several forms on a single page; just think of search and login forms). I.e. not every call will be the offending one.


Is there a hook after user confirmation? I want to add a content type after a user registers to the site.

I tried hook_user_save() but it saves the content type before the user confirms his e-mail.

Is there a hook after e-mail confirmation?

Although this approach uses modules, I add nodes after users confirm their e-mails using Logintoboggan and Rules.  The Logintoboggan rules integration adds a new event, When the user account is validated, which will allow you to perform actions upon e-mail confirmation.


html.tpl.php for a View (machine_name)? how can I assign my own html.tpl.php to a view (machine_name) via a preprocess-function (template.php) or a hook?

If my view is called "foo_view_machine_name_bla", which contains 50 views-pages with path, I would like to have a "html--foo_view_machine_name_bla.tpl.php".

I do not know songs how to do that.

Can someone help me please.

If I understand you correctly you are wanting to create a specific 'view' template file, your initial question is not clear. You also don't mention which Drupal version you are using. I will assume it's Drupal 7.
Go to your specific view and click Advanced then select Theme. There is a list of file names used for the view. The highlighted templates are current. After is a list of suggested templates that can be used. It's quite safe to use the first example. Copy the highlighted file from core and save it to your themes/templates folder rename it to the suggested file name.
Clear cache and revisit the same view > Advanced > themes section. Your new template file should now be highlighted.
That's it! You are now control of the output. Edit the file as you wish.


What's the accepted way to add different prices to commerce products? The standard model for an e-commerce system is to have an RRP price and sale price (and when relevant a cost price).

I know there are product pricing rules to apply discounts, but this is a pretty un-intuitive solution as it requires the adding of a new rule for every single product that needs a discount.

Plus 'discount' isn't the right way to look at this particular situation conceptually in my opinion. I don't want the users to have to work out what the discount should be when all they want is to set a static 'special offer' price. It also doesn't make sense to refer to the cost price as a discount of any kind.

What I'd like to have is 2/3 (or as many as I want to be honest) different price fields on the product to represent the different prices. The system would then obviously display the correct price at the correct time based on some sort of rule.

I know I can just add new fields to the product bundle but their relationship to the overall price of the product will obviously not exist until "something" happens.

This seems like a pretty standard use case...has anyone come up with a good solution? Code and UI solutions both welcome.

As mentioned you can add new field to your product type:

Next enable commerce_product_pricing_ui module or just add new Rule on event “Calculating the sell price of a product”. Rule looks like this (full size):

You can control the order of Product Pricing rules by Rules weight.

But I prefer to create field “Old price” (or “Common price”) and to add simple description:

  If you want to create special offer for this product, please, place new price in the Price field and move crossed out price to “Old price” field.

So, “Old price” is only for theming. It works for small commerce sites and I don't need any crazy Rules.


permisssions set to 755 - image upload is not possible - in drupal-commons 6x 24. hello and good day hope  you are all well!

newest update:
Now i have created a second installation with partly other conditions:(haviing permissions 755 with user vhost: www on /home/vhost/WWW/campus-24.com/sites/default The selected file xxxxx could not be uploaded. Only JPEG, PNG and GIF images are allowed. Well this is a new error - i had not this error before - what can i do. Guess that i have a made a big step... what do you think!?

Here the original-thread-start: just installed a drupal -commons version 6x 24:

when i try to upload images i get errors - and after doing some search in the system and the adminstration-controll i fould out: the reported error

image upload is not possible - in drupal-commons version 6x 24 {released on jan 18th ):  i have done some research and found out that i have: 755 -  in directory sites/default/files

Allthough i have the permisssions set to 755 -

what can i do here - just lemme know!

The directory sites/default/files is not writable
see the path where i i have recogniczed the error

http://schulcenter.org/?q=admin/build/themes/settings

The directory sites/default/files is not writable

Well what can i do here?!

update: thx alexandru and Mpd - thx for the answers; well everytime i touch the permissions i get  lost.- (i have troubles n issues with permissions and file users. see here https://superuser.com/questions/382792/setgid-bit-always-unset-when-changing-file-permissions  hmmm - well MPD guess that you are right and i am pretty lost -here . what can i do now??

You have to set files directory permissions to 777 to make it writable by "others". As I understand you set it to 755 and expect to be writable? 755 means all for the owner, read and exec by group and read and exec by others.

EDIT: As MPD said, if the owner of the files is same user as the one apache runs as than files directory doesn't have to be 777. 755 is enough and it is also recommended.


Translation of fields By mistake I deleted a translation item instead o editing it in admin/config/regional/translate/translate, and now it seems to be gone. Is there any way to get it back to the list of translatable fields?

Cheers
/bo

View the page this item is supposed to appear on, Drupal will encounter the item and add it to the translation interface again.


Views: How can I show a list of users who have a taxonomy term attached via a term reference field? I'm using the views module's built-in "Taxonomy term" view which overrides the way Drupal displays taxonomy by default and makes it accessible to views.  However, this only works for content, not users.

I tried creating a new view that lists users but there is no contextual filter like "User: has taxonomy term", just "Content: has taxonomy term."  In my case, however, some of the fields I want to display are term references stored on the user profile; they don't exist on any content.

Ideally, this is what I want: if a user visits the page taxonomy/term/oranges, it will show all users who have "oranges" in a taxonomy reference field.  How can I do this?

I ended up implementing this by overriding the taxonomy page with panels instead of views.  I then made the old view taxonomy term override into a content pane.  Then, to get the "User: has taxonomy term" effect, I made a view (content pane) for each vocabulary with a "Term ID" contextual filter (supplied as a panel argument) and a relationship of "Taxonomy term: User using MY TERM".  I then added these views as content panes to the taxonomy override in panels.

I had to do this for each vocabulary, but it works.


Controlling/selling node access by node reference? I have been using Drupal for many years now (starting with Drupal 6) and only recently - in the context of a big project - made the switch to D8. So far, working with D8 has been a very pleasant experience, to say the least. I was prepared, however, that there would be a few rocks on the road. And I would like to ask for help removing a big one (for me)...
In a nutshell, the situation is this: I am creating a kind of learning management system (LMS), with lessons, courses and classes. Each lesson belongs to exactly one course, but each courses may or may not belong to zero, one or more classes. I was thinking of using simple node references to structure this:

a field in the content type lesson that references the course that this lesson belongs to
and an entity reference field in the content type class that references all courses in this class (so, this is referenced the other way round)

Now, I'd like to sell access to each of these content types and my problem is this: If a user buys access to one of the classes, she should also be able to access all of the courses (and lessons) that are referenced by this class. So, when checking the access permissions for a single course, the system will not only have to check, if the user has bought this course, but also, if the user has access to a class that contains this course.
I was first thinking of solving this with the module Node access node reference, but this seems to work the other way round (and doesn't have a D8 version). Same for Access by Reference. (In general, most of the access control modules I looked at, don't seem to be ready for D8 yet.) But what about rule-based access control? Or groups?
Can anybody suggest a way forword?
Any help would be much appreciated.
Thanks in advance.

Why not go custom access the main thing is relating your "Class" or Item to the product the person buys aka on the product you could create a entity reference to the node or class or whatever  ...

you can do some thing like the following

use Drupal\Core\Access\AccessResult;
/**
* Implements hook_node_access().
*/
function mymodule_node_access(\Drupal\node\NodeInterface $node, $op, \Drupal\Core\Session\AccountInterface $account){
// Note thes checks do not work on admin (user 1). and clear cache each time.
$type = $node->bundle();
if ($type === 'your_content_type') {
  if ($account->id() !== 0) {
    $user = $account->getAccount();
    $uid = $user->id();
    // Ok we know is trying to access and the node type.
    $storage = \Drupal::entityTypeManager()->getStorage('commerce_order');
    $orders = $storage->loadByProperties(['uid' => $uid]);
    if (count($orders) != 0) {
      $has_bought = FALSE;

      // CUSTOM FIND Your Corse .
      $corse_type = $node->field_corse_type->value;
      foreach ($orders as $order) {
        $order_items = $order->order_items->referencedEntities();
        foreach ($order_items as $item) {
          // Do better than this lol ...
          // dump($item);
          if ($item->title->value == 'SOME Course' && $corse_type == 'SOMETHING RELATED TO PRODUCT') {
            $has_bought = TRUE;
        }
      }
    }
    // final check.
    if ($has_bought === TRUE) {
      return AccessResult::isAllowed();
    }
    else{
      // Kick them. as not bought.
      return AccessResult::forbidden();
    }
  }
  else {
    // Kick them. as not paid.
    return AccessResult::forbidden();
  }

  }
  else {
  // kick them.
  return AccessResult::forbidden();
  }
 }
 else {
  return AccessResult::neutral();
  }
}


Views grouping rows case-sensitive, I need to ignore case I have a view which groups rows in a table according to the first letter of the title. Some of the letters are uppercase and some are lowercase. View treats the upper and lower case as separate groupings (see image attached) but I want them to be grouped case-insensitively.

I've checked my db tables are ci and I've tried to alter the query using hook_views_query_alter but haven't managed to find a solution yet.

Thanks

In Drupal 8, this can be done pretty effortless thanks to Twig.
Just override the output of the grouping field with its value plus Twig's built-in uppercase filter (|upper or |capitalize), see screenshot:


For each row in a view, show a list of entities with entity reference field pointing to that row's content? For instance, say I have an Author node and multiple Books with entity-reference to that Author. How can I make a view showing each author with a list of their books?

To create a list of referencing content for each row in a view, use views_field_view to pull a secondary view into the row.

Add a secondary view with the fields to list and a contextual filter to receive the nid of the content being referenced from each primary view row.

Add a "Global: View" field to the primary view and use [!nid] for the contextual filter in View Settings to pass each row's nid to the secondary view.


How to create a view of all the nodes sorted by date width header per each year I need to create a view like this:

2012

node/1, node/2

2011

node/3, node/4

2010

node/5, node/6

The nodes have to be grouped by date and add the header with the year.

I don't want to create one view per each year but just one view. Shall i do it using taxonomy?

I'VE FOUND THE SOLUTION:

I created a view with fields, i added the field date, under "format -> setting" i used the option Grouping by and I selected the date field and here we go!


Creating a template file for one specific page created by a custom module How do I call a custom theme file (stored in the theme folder) that displays on a specific page that is created by a module.

It's a module for viewing mortgages in a full-page view. The template file is called page--single_view.tpl.php

The module is named single_view and has these functions:

<?php
/**
 * @file
 * Single Mortgage Views module file
 */

 /**
 * hook_menu() add to menu
 */
 function mortgage_single_view_menu() {

  $items = array();

  $items['mortgage/%/view'] = array(
    'page callback' => 'single_view_theme', //This isn't correct but just set this way for now
    'page argument' => array(3), //pass 3rd argument of url -- 1. drupal 2. mortgage 3. %
    'access callback' => TRUE,
  );

  return $items;
 }

 /*
 * Implementation of hook_theme().
 */

function single_view_theme($existing, $type, $theme, $path){
  return array (
    'page__single_view' => array (
      'variables' => array(),
      'template' => 'page--single_view' ,
      'base hook' => 'page',
      'path' => drupal_get_path('module', 'single_view'),
    ),
  );
}

I'm guessing my implementation of hook_theme isn't correct. The page that comes up is just blank?

I think you can't pass the single_view_theme as a page callback.

create a new function with something like this:

function single_view_callback($something) {
  return theme('page__single_view', $variables);
}

And in your page callback replace 'single_view_theme' with 'single_view_callback'.


What is the best way to submit form values and output on an unthemed page? I am writing a custom module that will be used to print consignment labels for a shipping provider.

The labels print 4 to a page. The module provides a form that allows the user to specify the number of packages, the dimensions etc then prints a label for each package. I will want to format them with CSS so that they print correctly to the label peel off sections etc

One way I had worked out to do this was to have a second form on the page which submits to a PHP file in my module directory. I place the code in this PHP page to process the labels and output which I can then print from.

This solution works, however it is outside of Drupal in that the form posts to a standalone PHP script. Is there a way to do this within Drupal? I have looked at the Print, PDF module but I dont know if I can configure it in this way.

If you want to break out of the theming system and display your own markup for a page you can do so.

Simply print whatever you want in your callback and rather than returning the content do an exit;

It isn't very elegant but it will do the job.


How to create a rule to combine the terms of 2 fields to create a new term stored it in a 3rd field? I have a content type that has 3 term reference fields:

Field A, required, is a term reference using a vocabulary with machine name vocabulary_a.
Field B, required, is a term reference using a vocabulary with machine name vocabulary_b.
Field C, is a term reference using a vocabulary with machine name vocabulary_c and is generated automatically.

When creating or updating a node, values are entered for field A and B. I want to have a rule (using the Rules module) with some Rules Action to set a data value for field C, equal to the concatenation of the value entered for field A and B. Here is a picture of what I'm trying to achieve:

When I use a Rules Action of "Set a data value" (for field C), I can only refer to one value (eg the token from Field A), and not to the tokens from both Fields (A and B).

So how can I get this to work somehow?

Note that this is a followup to these prior questions (which are not duplicates ...):

How to create a rule to combine the terms of 2 fields to create a new term and store it in a 3rd field? : that question assumes the taxonomies for the 3 fields are the same (as per the "The tags from those 3 fields all relate to the same taxonomy." in it). While this question here is about "Each of these 3 fields have their own taxonomy (they are different)".
How to correct my rule to prevent duplicate taxonomy terms to be created? : that question is about preventing the creation of duplicate terms for the "Field C" (when using the rule in the linked question). And inherently (since it is a followup question) also is about the same taxonomy for the 3 fields.

So this question here is about (a) those 3 fields which each have their own taxonomy and (b) at the same time avoiding the duplicate terms to be created.

My previous answer is based on using Rules Event "View a node of content type Article".
However (as confirmed by OPer after I posted a comment about that, in a comment deleted by a moderator), I think it should be (1) When a node of that content type is created and also (2) When a node of that content type is updated. But (3) when a rules event like "View a node of that content type" happens, I think that should NOT trigger any Rules Action (because viewing should not change any of those values).
Here is a variation of the previous rule, which takes the above into account:
{ "rules_combine_taxonomy_terms_in_a_3rd_taxonomy_for_create_and_up" : {
    "LABEL" : "Combine taxonomy terms in a 3rd taxonomy for create and update",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules", "rules_conditional" ],
    "ON" : { "node_presave--article" : { "bundle" : "article" } },
    "DO" : [
      { "drupal_message" : { "message" : "Value of term for Field C has to be set to \u003Cstrong\u003E[node:field-a][node:field-b]\u003C\/strong\u003E, i.e. the combination of the value of Field A (= \u003Cstrong\u003E[node:field-a]\u003C\/strong\u003E) and the value of Field B (= \u003Cstrong\u003E[node:field-b]\u003C\/strong\u003E)." } },
      { "variable_add" : {
          "USING" : { "type" : "text", "value" : "[node:field-a][node:field-b]" },
          "PROVIDE" : { "variable_added" : { "combined_term" : "Combined Term" } }
        }
      },
      { "entity_query" : {
          "USING" : {
            "type" : "taxonomy_term",
            "property" : "vocabulary",
            "value" : "vocabulary_c"
          },
          "PROVIDE" : { "entity_fetched" : { "existing_terms" : "Existing Terms" } }
        }
      },
      { "variable_add" : {
          "USING" : { "type" : "boolean", "value" : "0" },
          "PROVIDE" : { "variable_added" : { "new_term_exist" : "New term exists" } }
        }
      },
      { "LOOP" : {
          "USING" : { "list" : [ "existing-terms" ] },
          "ITEM" : { "current_term" : "Current term" },
          "DO" : [
            { "CONDITIONAL" : [
                {
                  "IF" : { "text_matches" : { "text" : [ "current-term:name" ], "match" : "[combined-term:value]" } },
                  "DO" : [
                    { "data_set" : { "data" : [ "new-term-exist" ], "value" : "1" } },
                    { "data_set" : { "data" : [ "node:field-c" ], "value" : [ "current-term" ] } },
                    { "drupal_message" : { "message" : "Term \u003Cstrong\u003E[node:field-a][node:field-b]\u003C\/strong\u003E already existed and will be used to automatically set the value for Field C to this term also." } }
                  ]
                }
              ]
            }
          ]
        }
      },
      { "CONDITIONAL" : [
          {
            "IF" : { "data_is" : { "data" : [ "new-term-exist" ], "value" : "0" } },
            "DO" : [
              { "entity_create" : {
                  "USING" : {
                    "type" : "taxonomy_term",
                    "param_name" : "[combined-term:value]",
                    "param_vocabulary" : "vocabulary_c"
                  },
                  "PROVIDE" : { "entity_created" : { "term_created" : "Created term" } }
                }
              },
              { "entity_save" : { "data" : [ "term-created" ], "immediate" : "1" } },
              { "data_set" : { "data" : [ "node:field-c" ], "value" : [ "term-created" ] } },
              { "drupal_message" : { "message" : "Term \u003Cstrong\u003E[node:field-a][node:field-b]\u003C\/strong\u003E did not yet exist and was created just now. It will be used to automatically set the value for Field C to this term also." } }
            ]
          }
        ]
      }
    ]
  }
}

To import it in your own site (using the Rules UI), use the same trick as in my prior answer.
The difference with my previous answer is (a) another Rules Event and (b) the messages that are simplified now.
Probably most important is that there is no more page refresh needed (you see the result right away).
Demo
Some messages that will be shown, depending on the scenario used:

Update an existing node, or create a new node, with a term for field C that already existed:

Value of term for Field C has to be set to Term A6Term B1, i.e. the combination of the value of Field A (= Term A6) and the value of Field B (= Term B1).
Term Term A6Term B1 already existed and will be used to automatically set the value for Field C to this term also.

Update an existing node, or create a new node, with a term for field C that did not yet exist:

Value of term for Field C has to be set to Term A3Term B1, i.e. the combination of the value of Field A (= Term A3) and the value of Field B (= Term B1).
Term Term A3Term B1 did not yet exist and was created just now. It will be used to automatically set the value for Field C to this term also.

Done ...


banner image showing on all pages except forum and views result pages My image is showing on all pages except the forum and classifieds result pages.

How can I make sure it shows on all the pages?

In the block I have selected all pages and not checked any of diff types so that it should show site wide.

A quick inspection of your html shows that the block is showing up.  However, the issue is you have a relative path in your img src, eg, you have this:

and that works fine when you are in the top level of your site.  But, when you go "down a level" it fails.  Changing it to:

should fix the problem.


Failed attempt at moving Drupal 8 to a clean installation of my OS. Okay, so ive reinstalled my ubuntu OS,  reinstalled the LAMP stack, ive restored the database and connected to it just fine. Ive checked which php modules drupal 8 requires and installed them, my version of php is above the 5.6 lower limit - i have not installed ALL of the php5-* modules in apt-cache though but i dont think thats an issue(?), ive set the chmod 777 . But now my /user/login kind of routes dont work, it just gives a 404. Have anyone experience anything like this, and how to solve?

I have looked at the clean_urls in my .htaccess, but drupal 8 clean urls should just work out of the box.

Okay so i went inside of /etc/apache2.conf and changed

<Directory /var/www/>
    Options Indexes FollowSymLinks
    AllowOverride none
    Require all granted
</Directory>

to

<Directory /var/www/>
        Options Indexes FollowSymLinks
        AllowOverride all
        Require all granted
    </Directory>

that worked :)


Removing all unapproved comments from database dump file I got thousends of spam comments on my drupal 7 site. The mysql database file is grown to 1.9GB and the site is broken. How can i delete all comments (or even better: all unapproved comments) from the database dump file?

From your dump file,  I would cut the part that insert the data to the comment table. Note: Leave the part that create the table.

In another file paste the part that you cut from the original dump file, using a text editor that can handle to search using regular expressions (as Sublime Text 2).
Create the regular expression that would give you as a result the complete row insert if that row has the status column value set to one.
Once that the regular expression is working, now use the search an replace.
Search all the matches and replace them with ''

When the search and replace is done, you can copy and paste to the sql tab if you are using phpMyAdmin, or even save the resulting file as .sql and import it.

Pretty much the laborious part would be to find the regular expression to use.

Hope this help!


How can I change a file field description? How can I change the file field description without altering a module file?
The function I would like to modify is theme_file_upload_help().

I have accomplished similar by using a hook_form_alter() in a custom module and altering the field's #description property.


Openlayers3 - Tiles not Loading - Failed to load resource: net::ERR_NAME_NOT_RESOLVED I setup a Drupal Website with Openlayers3.

Openlayers Module: 7.x-3.1         -  2016-Jan-03
Openlayers Library: 3.11.2
Drupal Version: 7.56

The settings are the default. I'm just trying to show a Geofield through a widget Openlayers with a setup like this:

Openlayers map: Openlayers Geofield: Formatter Map
Openlayers layer: openlayers_geofield_layer_formatter
Data options: Use full geometry

The map is there, controls and marker are ok, but either on the preview and on the field display I see no tiles, they are being loaded from the wrong place. This is the screenshot of the error I get:

Errors are like this:

GET https://otile1-s.mqcdn.com/tiles/1.0.0/osm/3/3/3.jpg:1 GET https://otile1-s.mqcdn.com/tiles/1.0.0/osm/3/3/3.jpg net::ERR_NAME_NOT_RESOLVED
Image (async)
Mz @ ol.js?ov6n8a:756
l.load @ ol.js?ov6n8a:688
Lk @ ol.js?ov6n8a:190
l.Qk @ ol.js?ov6n8a:439
c.port1.onmessage @ ol.js?ov6n8a:139
[...]

JQuery Update is Installed and I tried many jquery versions combination (default, 1.7, 1.10...)

I can't get it work... I just want to show a geofield as a map. Any other workiaround in order to achieve that?

You can find the solution with the patch, HERE.

MapQuest, which is the default map of Openlayers, doesn't work.
You need to switch to another map, e.g., Openstreetmap.


How to use drop tables on target when via drush sql-sync? I'm using the following command::

drush sql-sync @prod @dev

As I experienced, it does not drop tables on target (@dev) machine.

Is there a way, while syncing this way, to drop tables on target, so databases match completely? Or I must manually first drop tables on target?

Drush sql-sync will not drop tables on the target unless you specify --create-db.  Note that the later drops and recreates the entire database; if you do not have permissions to do this, you could run drush sql-drop on the target first.

There has been a feature request to add this functionality (drop before sync) in the Drush issue queue for years: http://drupal.org/node/716412.  Patches welcome.

Important update:  On Drupal 7, if you drop tables on the target prior to sql-sync, you could run into trouble unless you have http://drupal.org/node/1996004#comment-7419764. This is fixed in 8.x-6.x-dev, but is not part of 5.9, 7.x-5.x-dev or 8.x-6.x-beta1.

Update 2: This fix has now also been committed to 7.x-5.x-dev.


Drush update: How to keep file permissions? Following scenario happens to be in place. There is a server administrator (root) who doesn't know a thing about Drupal. Then, there two (or more) web developers (userA, userB), who do not have root access but are all in the group "web".

The server has several Drupal instances which have to be updated on a regular basis. Each Drupal instance is set with permissions 2775 (dirs) or 2664 (files) and belongs to either userA or userB, group in all cases is web.

When using drush to update an instance, all files that are overwritten (due to updates) now belong to the user running drush and get the permissions 644 (instead of 664). Thus, when userA updates e.g. a module, this module can't be changed or updated by userB afterwards. userA always has to chmod the files after an update.

How can this be rendered unnecessary, or how can the file permissions be kept when using Drush?

Write a script that correct permissions, you can find an example in this article:

Securing file permissions and ownership

Execute this script manually every time a drush update is made.

Or you can write a simple drush command that executes this script when a drush commands that cnahges files executes. Check the drush_hook_post_COMMAND:
http://drupalcontrib.org/api/drupal/contributions%21drush%21docs%21drush.api.php/function/drush_hook_post_COMMAND/7


How to change facebook og:image to post image link? For the facebook comments/share/etc I get the wrong thumbnail and as far as I've googled, it's due to the og:image meta tag. I'm using Drupal for Facebook module, is there a way to alter it? I found that I have to place 'rel="image_src"' somewhere, but where? At the image tag? And how can I do that using views?

The Metatags module supports OpenGraph meta data with token support, patterns, overrides for individual nodes and so on. It's a really handy module for this kind of stuff.

http://drupal.org/project/metatag

If you're getting the wrong image show up in Facebook you could point it to the correct image using this module's token support.


Attach #ajax to submit button created in hook_form_alter with #markup I created a custom submit button for the user-login form using #markup because I couldn't alter submit button html to resemble what I needed. The second custom submit button with the needed html is added with:

$form['submit2'] = array(
  '#markup' => '
<button type="submit" name="submit"></button>
');

I then added a "hideme" class to the orginal button with $form['actions']['submit'] ['#attributes'] (deleting it stopped the other submit from working).

So far so good. But now I would like to validate the login form using AJAX. Only if I add the #ajax key to $form['submit2'], the callback is never called. This only seems to work with regular form items.

Is it possible to trigger an Ajax callback on a #markup element (in hook_form_alter)? I'm using Drupal 7.

You cannot, since the #ajax attribute is not used for the markup item. You can use an image_button form element.

If the image_button form element doesn't render as you want and it is not possible to alter it the way you want, you need to implement a new form element with hook_element_info(), using the definition of the image_button form element as guide.

  $types['image_button'] = array(
    '#input' => TRUE,
    '#button_type' => 'submit',
    '#executes_submit_callback' => TRUE,
    '#limit_validation_errors' => FALSE,
    '#process' => array('ajax_process_form'),
    '#return_value' => TRUE,
    '#has_garbage_value' => TRUE,
    '#src' => NULL,
    '#theme_wrappers' => array('image_button'),
  );

The theme function that renders that form element is theme_image_button(). Changing the value of #theme_wrappers, you can alter the way your form element is rendered.
Keep in mind that theme wrappers, as any other theme functions, need to be declared with hook_theme().


Notice: Undefined property: stdClass::$field imce drupal I'm in trouble so maybe someone can figure it out: I'm trying to have singular folder for every user in imce (drupal7) and I want that the folder is a code that I can insert with a field in user profile. (like 78M4589)

well, this code generate the folder in the right place:

return 'users/'.$user->field_code['und'][0]['value'];

but in imce on the page i have this notice:

  Notice: Undefined property: stdClass::$field_code in eval() (linea 1 di () : eval()'d code).

I really can't figure it out.

The global $user object is not guaranteed to have all the fields loaded onto it.

Try specifically loading the user like this:

global $user;
// Load the full user object.
$account = user_load($user->uid);
// Get the user code.
$code = '';
if ($items = field_get_items('user', $account, 'field_code')) {
  $code = $items[0]['value'];
}
return $code;


Module to create a custom field in all the content types I am building a module to insert a custom field in all bundles of the node. I have encountered many difficulties, any help they can give me, I would appreciate it very much.

The custom field I am creating is used to save a tocken automatically or manually. - field_custom_tocken -

If a new bundle is created, the field_custom_tocken field must be added automatically to the new bundle. To generate the token it is necessary the id of the entity (nid), or that the tockent is inserted by the user.

I have used Drupal Console, create the field type, the widget and the formatter. This does not generate the field, the drawback is that you have to manually add the field to the bundle.
drupal generate: plugin: field

In this documentation the field is created and added to a specific bundle, I use part of this documentation. field.storage.node.field_brand_information.yml

I have this:

this creates the field.
modules/custom/custom_tocken/config/install/field.storage.node.field_custom_tocken.yml

# field.storage.node.field_custom_tocken.yml
langcode: en
status: true
dependencies:
  enforced:
    module:
    - custom_tocken
  module:
    - node
    - text
id: node.field_custom_tocken
field_name: field_custom_tocken
entity_type: node
type: string
settings: {  }
module: core
locked: true
cardinality: 1
translatable: true
indexes: {  }
persist_with_no_fields: false
custom_storage: false

This should create the custom field in the existing bundles, when the module is installed, but it does not work :(

/**
 * Implements hook_install().
 */
function ide_d8_url_shortener_install() {
  $entity_type         = 'node';
  $bundle              = '';
  $field['field_name'] = 'field_custom_tocken';
  $field['label']      = 'Tocken';
  $field['entity_type']= 'node';
  $field['type']       = 'string';
  $field['settings']   = array();

  $bundles = \Drupal::service('entity_type.bundle.info')->getBundleInfo($entity_type);
  $arr_bundles = [];

  foreach($bundles as $key => $value) {
    $bundle = $key;
    $fields       = \Drupal::entityManager()->getFieldDefinitions($entity_type, $bundle);

    if ( !isset($fields['field_short_url']) ) {
      entity_get_form_display($entity_type, $bundle, 'default')
        ->setComponent($field['field_name'], $field )
        ->save();

      entity_get_display($entity_type, $bundle, 'default')
        ->setComponent($field['field_name'], $field)
        ->save();
    }
  }
}

Any help you can give me I would appreciate it.

Instead of installing the field in your install hook (which will be triggered when installing the module only), you should implement hook_entity_base_field_info() to add the field to all nodes and all bundles.

An example below:

use Drupal\Core\Entity\EntityTypeInterface;
use Drupal\Core\Field\BaseFieldDefinition;

/**
 * Implements hook_entity_base_field_info().
 *
 * Attaches a custom field 'field_custom_tocken' to all nodes.
 */
function mymodule_entity_base_field_info(EntityTypeInterface $entity_type) {
  // Whether the entity type is 'node'.
  if ($entity_type->id() == 'node') {
    return [
      'field_custom_tocken' => BaseFieldDefinition::create('string')
        ->setName('field_custom_tocken')
        ->setLabel(t('Tocken'))
        ->setDescription(t('My tocken, which might be named token instead.'))
        ->setSettings([
          'max_length' => 150,
          'text_processing' => 0,
        ])
        ->setDefaultValue('')
        ->setDisplayOptions('view', [
          'label' => 'above',
          'type' => 'string',
          'settings' => [
            'link_to_entity' => FALSE,
          ],
          'weight' => 0,
        ])
        ->setDisplayOptions('form', [
          'type' => 'string_textfield',
          'weight' => 0,
        ])
        ->setDisplayConfigurable('form', TRUE)
        ->setDisplayConfigurable('view', TRUE),
    ];
  }
}


How to use service renderer with context theme? I have snippet code:

//Load block view (have override template)
$block = Block::load('views_block_1480647185');

// get render array
$render = \Drupal::entityTypeManager()
  ->getViewBuilder('block')
  ->view($block);

// get markup string
$markup = \Drupal::service('renderer')
  ->render($render);

kint($markup);

when i visit different url admin (example.com/admin/content), non-admin (example.com). Value markup is different.

In example.com/admin/content

In example.com (use override template view)

I think because url use different theme (bartik and seven).

So how can set markup value same value in url non-admin? How can do that with drupal service renderer?

Use the theme.manager service to set the active theme to what you desire, render the block and set the original active theme back.

/** @var \Drupal\Core\Theme\ThemeInitialization $theme_initialization */
$theme_initialization = \Drupal::service('theme.initialization');
$active_theme = \Drupal::theme()->getActiveTheme();
\Drupal::theme()->setActiveTheme($theme_initialization->getActiveThemeByName($theme));
// Render your block...
\Drupal::theme()->setActiveTheme($active_theme);


Webform submitted data field names I am beginning a module which implements the hook_webform_submission_insert. I am successfully getting the following data from my implementation of that hook:

stdClass Object
(
    [nid] => 3401
    [uid] => 1
    [submitted] => 1425491295
    [remote_addr] => http://myserver.com
    [is_draft] => 0
    [data] => Array
        (
            [2] => Array
                (
                    [value] => Array
                        (
                            [0] => Chandler Mann
                        )

                )

            [3] => Array
                (
                    [value] => Array
                        (
                            [0] => tecutij@yahoo.com
                        )

                )
.
.
.

I need to write code to programmatically map each value index to node fields in a process of creating nodes from custom code.

However, as the output above does not have field names, it's difficult to map correctly to the necessary node fields.

Can anyone advice how I might discover what name webform assigns to the field#id 2, 3 etc as in my code sample above?

The $node argument to hook_webform_submission_insert() contains the info you're looking for. For a Webform node, you'll find an array $node->webform->components where, for example, $node->webform->components[2] would correspond to the item whose value is "Chandler Mann" in your data.


Block content returns no results for anonymus user only I've setup View Block that renders a custom content type. The issue is that block content shows up for logged users only. I ensured that anonymus user has "view published content" permission. No permission restrictions are set for that specific block.

any ideas what is wrong here? Could I use a Devel to inspect that somehow? thx!

There are multiple layers of permissions which might responsible for this,trying to cover some of them if that helps you.

Check right in the views configuration page and check "access" should be set to "view publish content".
Ensure you are not having contrib module like block_access or custom code which is putting a check the block view on user role basis.
Ensure if you are using contentaccess module or nodeaccess module and they are not letting the block visible to anonymous user.


Automatically import data from Google spreadsheet using feeds module I have data in a Google docs spreadsheet. To import that data I currently have to download the spreadsheet as a csv file and then import using the Feeds module.

What I am trying to work out is if there is someway to automate the process? Is there some way to have feeds access the spreadsheet directly from Google docs?

Would appreciate some step by step instructions on how to set this up. Note that I already have feeds setup to manually import a csv file, so the issue at hand is how can I set it up so that feeds can retrieve the data directly from Google docs at regular intervals?

Note that the data is stored as regular Google doc spreadsheet, so solution needs to make sure that the document retrieved is in CSV format (is that possible by using a certain URLs structure?)

Sorry, bit late to the party. How I solved this was:

Publish the file to the web using the option in Google Sheets' file menu. This gets you a special link to an always up-to-date version with the format of your choice. I used CSV.
Select HTTP fetcher as fetcher.
Select appropriate parser (CSV in my case) and set up mapping
Set up periodical imports.
Enter the URL you got from Google Sheets as source when importing.

Your updates to the Google Sheets file will be imported with the periodical imports.


XML Sitemap stopped working I don`t know exactly when but it seems to me after upgrade of some modules and core, sitemap stopped working. Using latest Drupal 7.17 and XML Sitemap 7.x-2.0-rc1

You can see it with some kind of error here http://www.testtest.detect.by/sitemap.xml (Use Firefox to get it displayed)

How could i know what`s the problem?

Thanks in advance!

Your sitemap seems to work. When viewing the source of your sitemap, the XML needed for crawlers is displayed.

If you're talking about the blank page you get to see when viewing it in your browser: see if you've enabled the "include stylesheet for humans" option in the configuration of the module.


Title used for pages I have installed Drupal 6.19 and 6.20; in Drupal 6.19, I can see the page title like "site title|page title", but in Drupal 6.20 the page title "site title".

How can I add the node title to the page title in Drupal 6.19?
I didn't use Page Title in Drupal 6.19, nor did I in Drupal 6.20.

In the template.php of the theme add the following code.

function phptemplate_preprocess_page(&$vars) {
  $title = $vars['title'];
  $site_name = $vars['site_name'];

  $vars['head_title'] = implode(' - ', array($site_name, $title));
}

Verify the $head_title variable is present in page.tpl.php.


extra 'field_' prepended to fieldnames in views $rows (Drupal 7) I created a field "myfield".  I then created a Drupal 7 view and selected the field 'field_myfield'.  (As expected the system prepended 'field_' to my fieldname.)  When I call dsm ($rows) to look at the row data that gets passed to my custom template, I see that the field is now called 'field_field_myfield'.  Why is a second 'field_' prepended to the fieldname?  Should I assume all fieldnames in $rows will have 'field_field_' prepended?

The drupal field api enters fields in the database with the field_ prefix (to avoid conflicts with other existing tables). If you use field in your name as well, it will become field_field_... in the database.

And since views loads the fields directly from the database, the prefix is there as well.


Service event_subscribe before path_processor_inbound I have ha service with tag: event_subscribe (KernelEvents::REQUEST) with priority 30 and in the same module a service path_processor_inbound with priority 29

The problem is: in event_subscribe Service creo a Constant but the service path_processor_inbound is called before.
I tried all the variants of priority, but it is not the problem.

Both priorities are for different queues. If you set a priority for an event subscriber this is only for the specific event you subscribe to. In this example you subscribe to KernelEvents::REQUEST. Then you can only move up and down in the list of all other subscribers to this event.

You can find more information and a list of the D8 events here:

https://api.drupal.org/api/drupal/core!core.api.php/group/events/8.2.x

Path inbound/outbound processors are not even events. These are handled by the PathProcessor Manager and the priority set here is again only for the list of all other path processors.


Drupal 7 Block View include File I have a rather newbie question, I am following a Drupal 7 module examples, specifically an ajax wizard form. All form creation / manipulation is included in ajax_example_graceful_degradation.inc which when is called in file attribute:

// A classic multi-step wizard, but with no page reloads.
  // See ajax_example_graceful_degradation.inc.
  $items['examples/ajax_example/wizard'] = array(
    'title' => 'Wizard (with graceful degradation)',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('ajax_example_wizard'),
    'access callback' => TRUE,
    **'file' => 'ajax_example_graceful_degradation.inc',**
    'weight' => 7,
  );

Next i would like to create a block which will be included in my template. It seems that i cant include a file attribute in block_view function. How can I do that?
Note: If I include all fuctions of ajax_example_graceful_degradation.inc in .module file then my block works ok.

There is no such an attribute in block_view function, but you can always use something like that (assuming that you have already implemented hook_block_info() and you have defined your own MYBLOCKDELTA):

function MYMODULENAME_block_view($delta = '') {
  switch ($delta) {
    case 'MYBLOCKDELTA':
      $block['subject'] = t('This is my block');
      module_load_include('inc', 'MYMODULENAME', 'my_inc_file');
      $block['content'] = myblock_contents($delta);
      break;
  }
  return $block;
}

Then define function myblock_contents($delta) in your my_inc_file.inc in MYMODULENAME module folder.


How to prevent behavior-attached functions from being attached twice? I have a behavior that adds on to some checkboxes.

(function($) {
  Drupal.behaviors.mymodule = {
    attach: function (context, settings) {

      $('.skip-line', context).on('change', function(){
        // some code
        if ( confirm(Drupal.t('Apply to all languages?')) ) {
          // applying...
        }
      });
    }
  };
})(jQuery);

It works very well, but checkboxes are in AJAX-loaded part. If I reload that part of the form, clicking on them makes confirmation popup twice. Now, I know I can test inside function if it's the first time in a row it's called, but I would prefer to make sure it is added to my element only once, and thus called only once. How can I do that?

The once() function will help with that,e.g.

(function($) {
   Drupal.behaviors.mymodule = {
    attach: function (context, settings) {

      $('.skip-line', context).once('mymodule').on('change', function(){
        // some code
        if ( confirm(Drupal.t('Apply to all languages?')) ) {
          // applying...
        }
      });
    }
  };
})(jQuery);

One of the many references


Periodically invoking modules So I have the module import_html and I'm trying to figure out if there is a way to periodically invoke it so that it imports new html files. Is there a way to periodically invoke modules with a script? I'm hoping someone can direct me to a good starting source as I am really new to Drupal.

The answer is yes. The import_html module has a few tools available for this. You can:

Build a custom module that makes use of hook_cron() to trigger importing import functions in import_html. This would be good for standard periodic import based on certain times of the day.
Utilize the module's Drush integration and use the drush import-html command inside a shell script that's executed with crontab. This would be good for periodic import as well as one time imports that you can do with the command line.

The module also has an API to take action upon various parts of its import process too if you need it (e.g. alerting site admins of new imported site content).

As a starting point, you should review the documentation on the project page. It has a help document that walks you through the usage of the module. If #1 is your preferred goal, you'll want to get familiar with the Drupal API, so you can understand how to create modules and understand the code of import_html module. For #2, you'll need to install Drush, learn how to use the drush import-html, and write out a shell script.


Copy data of Email in registration to the username not showing in the registration page I want to copy the value of email to the username, which is not showing in the registration page, but it is showing in the /user/edit page as Display Name, which is randomly generated such that my username is my email, giving more flexibility to the user.

The Email Registration module will allow for using the email address as the username.

The LoginToboggan module will allow the user to create a username, and allow them to login with either the username OR email address.

Email Registration also provides a hook which will allow a custom module to set the account name to whatever you want it to be.  That does require writing a module, however, it doesn't have to be very complicated.

The only thing you would need to include in your module file is the hook.
Example adapted from http://www.grasmash.com/article/using-your-email-address-your-drupal-username#sthash.uZkOo6j6.dpuf

<?php
/*
* Implements hook_email_registration_name().
*/
function grasmash_email_registration_name($edit, $account) {
  return $account->mail;
}


How to add a user/login Link to the Maintenance Mode page? I have my site in Maintenance Mode. I know I can get to my login page by going to http://example.com/login .

My client wants a login link on the Maintenance Mode page (when in this mode). Before I say "no this is not possible", I am wondering if this is possible. I could add this to the Maintenance template page right? I already have a custom Maintenance Mode page.

EDIT: Where the http://adaptivethemes.com/how-to-theme-the-user-login-page-in-maintenance-mode
solution works, its not what I want. All I want is a link to the user login page displayed on the Maintenance Page.

I did try this: I added html to the maintenance php template:
Login

HOWEVER this only show a link that was NOT clickable. Also how would I get to the User login page if I am testing this on a test server, but the domain will be different than on the test server. Change the domain once on the production server?

Yes, you should be able to. You can create a maintenance page template similar to any other in Drupal, "maintenance-page.tpl.php". However, to get that to work you probably have to make some changes to your template.php file.

More info can be found here: http://adaptivethemes.com/how-to-theme-the-user-login-page-in-maintenance-mode although I believe that example is from Drupal 6, but the idea should be fairly similar for Drupal 7 as well.


How to trim trailing spaces from labels of radio buttons/select list elements Every label of every element of every list has trailing space, and it is annoying and makes styling sometimes hard or in certain ways impossible. I was trying to add :before pseudo element to label with content: "\0020";, to make trailing spaces symmetrical at least, but it doesn't work. How to get rid of them?

Yeah, this is a known issue.  The form.inc file from /includes/form.inc which themes form labels outputs the following for labels:

$t('!title !required', array('!title' => $title, '!required' => $required))

The offending space is the space between '!title' and '!required', where !title will contain the actual label text and !required will contain a '*' for fields that are required to be filled in the form...

In any case, this is all in core, and there is an initiative to fix it for Drupal 8: https://drupal.org/node/1623574.  Definitely follow that or add your voice to the mix! Any fix will not be back-ported to Drupal 7, however, because lots of themes rely on that extra space and will be messed up if it is removed.

What you can do in your own case, though, is override the core hook_form_element_label theme function.

So, in your custom theme, just create the necessary function in your template.php file:

function YOURTHEMENAME_form_element_label($variables)
{
}

Now just copy the entire function from /includes/form.inc and just change the very last return statement to not include the space unless there is a required star ('*') to go after the label.  Your new and improved return should be:

return ' <label' . drupal_attributes($attributes) . '>' . $t('!title!required', array('!title' => $title, '!required' => $required ? ' ' . $required : '')) . "</label>\n";

That should do it!!  However, make sure you click around your site and check whether this messes anything else up before going in production.  You may see some labels mashed into other stuff without the space, again because some themes have relied on it!  And make sure to clear cache so the new function is picked up.

Let us know if it works...


Alter existing route's output formats? I want to alter the entity.node.canonical route so that when it is accessed using ?_format=json it will return the rendered node in JSON.

So far I have created a RouteSubscriber that alters the route like this:

use Drupal\Core\Routing\RouteSubscriberBase;
use Symfony\Component\Routing\RouteCollection;

class RouteSubscriber extends RouteSubscriberBase {

  /**
   * {@inheritdoc}
   */
  protected function alterRoutes(RouteCollection $collection) {
    if ($route = $collection->get('entity.node.canonical')) {
      $route->setRequirement('_format', 'json|html');
    }
  }

}

Ideally I want to have a seperate controller that is called when the format is JSON and otherwise use the default controller from core.

Is this possible, and how would I have to code it?

If that's not possible how can I override the default controller then?

I found the solution myself.

I just created a new route with the requirement _format: json and the path /node/{node} just like entity.node.canonical. Then I could set a controller that is only called when the node is being output in JSON format.

My route definition looks like this:

entity.node.canonical.json:
  path: '/node/{node}'
  defaults:
    _controller: '\Drupal\my_module\Controller\NodeViewController::json'
    _title_callback: '\Drupal\node\Controller\NodeViewController::title'
  requirements:
    _entity_access: 'node.view'
    _format: 'json'


Drupal 7 template_preprocess_block I am trying to alter content of the system main block but only on the front page. I have added template_preprocess_block() in the template.php file, but is_front is FALSE even though I am on the front page of the site?

I use the Context module to control blocks, but the main block is the only one I have added using /admin/structure/block not Context.

Update
I have also tested hook_block_view_MODULE_DELTA_alter() but is_front is not passed to this function.

Update
Even though I disable the Main page content block front the Content region, I still see a node on the front page, publishing options set to published, promoted to front.
Doing this on a fresh install locally.

Enabling the Main page content block and setting "All pages except those listed" to  doesn't change anything - still looking at my node.


How can I create a Link to an URL containing a fragment identifier? Is it possible to create a Link to a node with a hash in url (for opening a special Tab).
I use:
Link::createFromRoute('Title', 'entity.node.canonical', ['node' => 77]);

And I want to link to: "/node/77#example"

Please see public static function Link::createFromRoute

array $options: The options parameter takes exactly the same structure. See \Drupal\Core\Url::fromUri() for details.

You can pass a 4th argument as an array with a fragment key value:
Link::createFromRoute($this->t('Title'), 'entity.node.canonical', ['node' => 77], ['fragment' => 'example']);


Webform email with list of senders I am build a webform to send emails.
I have some user local accounts.
I would like to login with personal user account and send an email, choosing from a list of possible senders.
It is possible in that webform to choose from which email I want to send?
For e.g. I have 2 emails

email for advertise
email for internal communication

I would like to go to webform, choose from which this 2 emails I want to sent, is this possible?

Go to your Webform and in Build tab add field of type Select (Select / Entity Select) and define all options (email addresses from which it is possible to send emails) in your field's detail form.
Then go to Webform settings and under tab Email handlers add new Email. Fill basic fields (subject, body) and as your sender (address from which email should be send) select name of the Select field you've created earlier. As receiver (address which should receive email) set whatever email you need.


hook_module_implements_alter() not working for me. What am I doing wrong? I use D7 and need 2 different modules to parse article text on save. For simplicity's sake let's say module_one changes all f's to z's and module_two changes all foos to bars. So basically "F foo fo foo" is to become "Z bar zo bar". To accomplish that I need module_two node_presave event to fire before module1. Otherwise the result will be something like "Z zoo zo zoo". But hook_module_implements_alter() doesn't seem to do the thing. I write it like this:

function module_one_module_implements_alter(&$implementations, $hook) {
  if ($hook == 'node_presave') {
    // Move module_one_node_presave() to the end of the list. module_implements()
    // iterates through $implementations with a foreach loop which PHP iterates
    // in the order that the items were added, so to move an item to the end of
    // the array, we remove it and then add it.
    $group = $implementations['module_one'];
    unset($implementations['module_one']);
    $implementations['module_one'] = $group;
  }
}

This hook executes but I still get module_one's node_presave hook executed before module_two's. So what am I doing wrong?

Double check the weight in the system table on your d7 database. You can try giving module one a higher weight therefore making it run second.


Is there a html5 video player for Drupal 6 that run well on ios device? I need to play videos on my drupal 6 site that would run well on IOS device (HTML5?).
Is such solution available?

My site currently serving flv files using jwplayer 6.x-1.1.

Yes; try jPlayer: http://drupal.org/project/jplayer

Note that you might be better off implementing this directly (as I did recently) than using the module since the module supports the older version. You will also need m4v files to play video on iOS devices.

I implemented it by following their Quick Start Guide and placing the HTML and JS into my theme, tailored of course to be Drupal-friendly (i.e. using Drupal.behaviors for the JS and using preprocess functions to set file paths properly).

It works well, and my iOS-using client was able to listen to audio (I implemented it for audio) from their iOS device without issues.


Add a display by copying settings from another display in Views I may be missing the obvious, but how can I add a display in a view (content pane for instance) and have it copy all the settings (fields-relationships-headers-etc) from another display in that view? (in my case a page).

If you want an exact copy of the page, you can clone the display.  In Views 3 on Drupal 7, you do this by opening the view to edit it and clicking the downward-pointing triangle next to view page above Advanced and choosing clone page.

EDIT: Sorry, missed that.  By default, Views will use all applicable settings data from the Master display (hidden by default in Drupal 7).  So your content pane should inherit whatever the settings are in the Master display, which will be the same as those for the first display you created (the view in the first row) in that view, assuming you didn't override anything.  (note that some things may not apply to content panes when moving from a page but your fields, relationships, etc. Should definitely be pulled in by default under normal circumstances.)

To make the Master display visible so you can see if there's something going wrong with it, you can visit admin/structure/views/settings and check Always show the master display.

It sounds like you have multiple displays and the one you want is not the master display.  I don't think there's an easy way to copy settings back to the master display so your best bet is probably to make the master display visible and reset it to what you want before making more displays.


EntityFieldQuery fieldCondition Date not working as expected No matter what i try i cant get EntityFieldQuery to work i have a date and i need to check if it is between the start date and end date of a date field that is set to unlimited values.. it should be at least between any one.. here is what i got.. can anybody help me?

UPDATE 10/26/2016:
So from what I found doing some more googling to do what I want I need to use delta_group so I added it to the code below but it doesn't seem to be working. Anybody have any idea what I'm doing wrong?

    $myDate = date('Y-m-d H:i:s');
    $query = new EntityFieldQuery;
    $query->entityCondition('entity_type', 'node')
          ->entityCondition('bundle', 'caregiver_db')
          ->propertyCondition('status', 1)
          ->fieldCondition('field_available_dates', 'value', $myDate, '>=', 0)
          ->fieldCondition('field_available_dates', 'value2', $myDate, '<=', 0);

    $results = $query->execute();

So it looks like the final issue I was having was the operators I was using. Had to go <= on value and >= value2. I had it the other way around before. Here is the code that worked.

$myDate = date('Y-m-d H:i:s');
$query = new EntityFieldQuery;
$query->entityCondition('entity_type', 'node')
      ->entityCondition('bundle', 'caregiver_db')
      ->propertyCondition('status', 1)
      ->fieldCondition('field_available_dates', 'value', $myDate, '<=', 0)
      ->fieldCondition('field_available_dates', 'value2', $myDate, '>=', 0);

$results = $query->execute();


Using an authentication provider to keep a user permanently logged in eventually causes session problems Because I got fed up of having to log in to my local development sites every however long, I tried making a simple custom module that just has an Authentication Provider service that always returns user 1, like this:
  /**
   * {@inheritdoc}
   */
  public function applies(Request $request) {
    return TRUE;
  }

  /**
   * {@inheritdoc}
   */
  public function authenticate(Request $request) {
    return $this->entityTypeManager->getStorage('user')->load(1);
  }

The idea being that with this module enabled, every page load considers the authenticated user to be user 1. In theory, I'd be logged in for ever!
However, after a few weeks of this working fine, all my form submissions broke! Every form submission fails with:

The form has become outdated. Press the back button, copy any unsaved work in the form, and then reload the page

This turns out to be because CsrfTokenGenerator::validate() fails. Specifically, the $seed in this bit is just NULL:
  public function validate($token, $value = '') {
    $seed = $this->sessionMetadata->getCsrfTokenSeed();
    if (empty($seed)) {
      return FALSE;
    }

I presume it's because the session has expired in some way? The time this has taken to stop working is roughly the amount of time it would have taken the site to log me out automatically.
How can I fix this?

I presume it's because the session has expired in some way?

First you need to understand how this happens.

Configuring Garbage Collection
When a session opens, PHP will call the gc handler randomly
according to the probability set by session.gc_probability /
session.gc_divisor. For example if these were set to 5/100
respectively, it would mean a probability of 5%. Similarly, 3/4 would
mean a 3 in 4 chance of being called, i.e. 75%.
If the garbage collection handler is invoked, PHP will pass the value
stored in the php.ini directive session.gc_maxlifetime. The
meaning in this context is that any stored session that was saved more
than gc_maxlifetime ago should be deleted. This allows one to expire
records based on idle time.
However, some operating systems (e.g. Debian) do their own session
handling and set the session.gc_probability variable to 0 to stop
PHP doing garbage collection. That's why Symfony now overwrites this
value to 1.
If you wish to use the original value set in your php.ini, add the
following configuration:
# config/packages/framework.yaml
framework:
    session:
        gc_probability: null

Source: Symphony's official docs on Configuring Sessions and Save Handlers

In Drupal 8 & 9 you can see these gc settings in default.services.yml
Possible Solutions on how to stay logged in longer.
In /sites/default/settings.php uncomment
 if (file_exists($app_root . '/' . $site_path . '/settings.local.php')) {
   include $app_root . '/' . $site_path . '/settings.local.php';
 }

then copy /sites/example.settings.local.php and rename to /sites/default/settings.local.php
Now you can use /sites/development.services.yml to override those settings, for example
(I used these numbers for testing so it logs me out after 2 seconds):
parameters:
  session.storage.options:
    gc_probability: 1
    gc_divisor: 1
    gc_maxlifetime: 2
    cookie_lifetime: 2

I tried setting gc_probability to 0 or null, which should stop it, but the gc() function still fired. Perhaps it's reading the value from php.ini
So alternatively you could set the gc_maxlifetime and cookie_lifetime to not expire decades from now. See set a cookie to never expire.


Which hooks should I implement in Drupal 7 that are the equivalent of hook_comment() and hook_nodeapi()? This is the code I am using for Drupal 6:

/**
 * @Implement of hook_nodeapi()
 */
function mycaptcha_nodeapi(&$node, $op, $teaser, $page) {
  global $user;
  switch ($op) {
    case 'insert':
      if (isset($_SESSION['mycaptcha_ask_key'])) {
        unset($_SESSION['mycaptcha_ask_key']);
      }
    break;
    case 'validate':
      if ($node->mycaptcha_ask) {

        mycaptcha_ask_form_validate($node->mycaptcha_ask);
      }
    break;
  }
}

/**
 * @Implement of hook_comment()
 */
function mycaptcha_comment(&$comment, $op) {
  global $user;
  switch ($op) {
    case 'insert':
      if (isset($_SESSION['mycaptcha_ask_key'])) {
        unset($_SESSION['mycaptcha_ask_key']);
      }
    break;
    case 'validate':
      if ($comment['mycaptcha_ask']) {
        mycaptcha_ask_form_validate($comment['mycaptcha_ask']);
      }
    break;
  }
}

What are the equivalent hooks that I should implement for Drupal 7, to obtain code equivalent to the one I am actually using for Drupal 6?

from kiamlaluno's help. i changed the code to the following. but the validation still doesn't work. but the above code(hook_comment) works ok under drupal 6.

what's wrong with my code in drupal 7.

function mycaptcha_comment_insert($comment) {
  global $user;
      if (isset($_SESSION['mycaptcha_ask_key'])) {
        unset($_SESSION['mycaptcha_ask_key']);
      }
   }

function mycaptcha_form_comment_form_alter(&$form, &$form_state, $form_id) {
    global $user;
  $form['#validate'][] = 'mycaptcha_comment_validate';
}

function mycaptcha_comment_validate($form, &$form_state) {
    global $user;
      if ($comment['mycaptcha_ask']) {
        mycaptcha_ask_form_validate($comment['mycaptcha_ask']);
      }

  }

I will reply to your question basing on the value for $op shown in your code snippet.
hook_nodeapi(), "insert"
The equivalent for Drupal 7 is hook_node_insert(), which receives just one parameter: $node.
hook_nodeapi(), "validate"
The equivalent for Drupal 7 is hook_node_validate(), which receives three parameters: $node, $form, &$form_state.
The implementations of hook_node_validate() don't usually use the last parameter, but they check the values of the properties for the $node object.
hook_comment(), "insert"
The equivalent of that hook, in Drupal 7, is hook_comment_insert(), which receives the comment object as unique parameter.
hook_comment(), "validate"
Unfortunately, in Drupal 7 there isn't hook_comment_validate(); you need to add a validation handler for the comment form.
function mymodule_form_comment_form_alter(&$form, &$form_state, $form_id) {
  $form['#validate'][] = 'mymodule_comment_validate';
}

function mymodule_comment_validate($form, &$form_state) {
  /**
   * Validate the comment.
   * $form_state['values']['name'] is the name of the user who wrote the comment;
   * $form_state['values']['is_anonymous'] is TRUE if the user is anonymous (not logged in);
   * $form_state['values']['mail'] is the email address of who wrote the comment;
   * $form_state['values']['homepage'] is the URL of the website of who wrote the comment;
   * $form_state['values']['subject'] is the title of the comment;
   * $form_state['values']['comment'] is the text of the comment;
   * $form_state['values']['language'] is the language associated with the comment;
   * $form_state['values']['uid'] is the user ID of who wrote the comment.
   * $form_state['comment'] is the comment object.
   */
}

Notice that mymodule_comment_validate() doesn't get any $comment parameter, and $form_state['comment'] is an object, not an array. You are using a $comment variable that is not defined, nor is one of the parameters.
The code I wrote works independently from the content type of the node where the comment appears. In Drupal 7, the hooks called to alter a form build from another module are hook_form_alter(), hook_form_BASE_FORM_ID_alter(), hook_form_FORM_ID_alter(). The base form ID for the comment form is "comment_form."
If you just need to alter the comment form for a specific content type (e.g. the "Article" content type), then you replace mymodule_form_comment_form_alter() with mymodule_form_comment_node_article_form_alter().


How to allow multiple parents (menu items) for a single node How can I enable a single node to have multiple parents (D7)?

Is it possible to show the hierarchical structure in the menu, therefore breadcrumb?

Can I set a structure like the following?

Home > Section 1 > SubSection A > 'my node'
Home > Section 2 > SubSection B > 'my node'
Home > Section 2 > SubSection B > 'my node'

Before you ask/suggest:

I used nodehierarchy on a previous project, and the subfeature 'Allow multiple parents" seems a little buggy at the moment
Duplicate content is not a problem here, since it's an intranet

Do you have any suggestion?

The meny system can't do that

The Drupal menu system does not support what you want to do. Each entry has exactly one parent (which is id -1 if at the top).

The taxonomy module however, can

One could map the menu structure onto a vocabulary tree. The complex part here will be the node <=> term mapping, as I'm not aware of a module for that.

However, it's also worth noting that given that nodes and terms are very similar in D7, it's entirely possible to just migrate to using Terms for your main content, if the multiple parents hierachy generally makes sense for you. This could avoid a lot complexity.

Other options

One also make something completely custom or build the hierachy directly onto the entities with entity references, or separately as relations.

Node hierachy

If there is a module that solves your problem, you should probably be using it. Since Node hierachy is apparently one such option, it's worth your attention. If it really is buggy, you may want to consider helping out with that, if it helps to avoid a large custom effort.


Which table contains all of the module permission data? I'm coming into an existing project and the previous developer totally messed up the site. There was a custom module made for a custom field and it shows up in the People > Permissions page. I cannot set this new entity type to Viewable by anonymous users via the gui interface. I would need to go into the database to make this change. Which tables do I need to look at to find this setting?

To modify the permission data via drush command line. I first had to find the permission name by right click the checkbox on the module page and inspect element, in my case it was 3[view any office office]

The table responsible for permissions is: role_permission

I then goto the terminal and insert the following query:

drush sqlq 'insert into role_permission values(3,"view any office office", "office")'

3 is the role number then the name of the permission (view any office office) and then the module name (office).


How to add a image in your drupal.org bio? Some www.drupal.org profiles like https://www.drupal.org/u/artofeclipse have a image in the Bio section like this:

So, I trying to achieve the same in my profile (https://www.drupal.org/u/adriancid) but with another image. The problem is that the site always says this:

But if you go to see the image it exists in drupal.org, but the site always says Only local images are allowed.

How can I add a picture in my drupal.org profile?

I just did a similar experiment (followed by an undo ...), and tried adding this HTML code in the same "Bio" file:

Drupaler driven by Views/Flag/Rules/Message/Group.

And guess what, it worked!

The bio you can currently see in my drupal.org profile is created using this HTML code:

Drupaler driven by Views/Flag/Rules/Message/Group.

So I think you should use an existing image that you know already exists on drupal.org (such as within /files/ for both of my sample images).

Ps: note the special image I used from that pictures directory ... looks familiar?


Update programmatically value of field collection item I want to update a field collection

I have the following:

function pdf_app_node_presave($node) {
    if (!$node->is_new) {
        global $base_url;
        if($node->type == 'article') {
            $node_wrapper = entity_metadata_wrapper('node', $node);

            foreach ($node_wrapper->field_chapitres->value() as $library) {
                $library_wrapper = entity_metadata_wrapper('field_collection_item', $library);

                  $books = $library_wrapper->field_subchapters->value();
                  foreach($books as $book){
                    $book_wrapper = entity_metadata_wrapper('field_collection_item', $book);
                    $title ='sfsdfsd';
                    $book_wrapper->field_pdf_title2->set($title);
                    $book_wrapper->save();

                  }
            }

            field_attach_update('node', $node);

        }

    }

}

But i get an error i think i should use something like

    $values[0]['field_title'][LANGUAGE_NONE][0] = $title;

but it is also not working.

If you want to Update value of field collection item use Set Something like:

$book_wrapper->field_title->set($title);

For more info See Entity metadata wrappers Docs Example using field collections Section.


is there any way to load commerce_products into a collection in rules configuration I need to load all commerce products that their status is "active" into a collection in rules configuration.

I searched in internet and also I tried rules bonus pack but the didn't help me.

Is there any way to load commerce products into a collection and iterate collection via loop ?

I found that VBO (Views bulk operation) give me ability to load views result into a collection in rules.

Just install VBO and make a view and use it.


Form is not calling custom submit function From my understanding, and as I've seen it in other examples of code, all I need to do to call a custom submit function is include the "#submit" => array("myModule_submit");.

I use a drupal_set_message to post a message on the site so I can know if the myModule_Submit is being called from the form submit button:

function myModule_submit($form, &$form_state) {
  drupal_set_message($form_state['values']['name']);
}

When I click on the "Send" button nothing happens, and it seems the page just refreshes.

function myModule_form_builder($form, $form_state){
  $form['myModule_message'] = array(
    '#type' => 'textfield',
    '#title' => t("Outgoing Message"),
    '#size' => 150,
    '#maxlength' => 150,
    '#required' => TRUE,
    '#description' => t("Type your message"),
  );

  $form['buttons'] = array(
    '#type' => 'button',
    '#value' => t("Send"),
    '#submit' => array('myModule_submit'),
  );

  return $form;
}

function myModule_submit($form, &$form_state) {
  drupal_set_message($form_state['values']['name']);
}

To my understanding drupal_set_message() will display a message to the user on the current page somewhere given the parameters. When I put information in the fields and press submit though there are no messages. I have seen other examples on the web that use this method and they say it works.

Try next:

function myModule_simple_form($form, &$form_state){
  $form['firstname'] = array(
    '#title' => t('First name'),
    '#type'  => 'textfield',
  );
  $form['lastname'] = array(
    '#title' => t('Last name'),
    '#type'  => 'textfield',
  );

  $form['submit'] = array(
    '#value' => t('Search'),
    '#type'  => 'submit',
  );
  return $form;
}
function myModule_simple_form_submit($form, &$form_state) {
  drupal_set_message($form_state['values']['firstname']);
}

Any rendered drupal form already have a submit function. Also try: drupal_set_message($form); in your hook_from_alter when $form_id = 'myModule_simple_form' too see where is default submit function. You can also add a custom submit funtion in array but it is necesary only if you need more than 1 submit function for your form. In all othre cases use just form_id_submit.


Translation showing up in backend but not on display or user registration I translated some fields, everything looks fine in the back end. String are successfully translated to French.

However they don't show up for user registration/profile modification, they don't show up on exposed filters or views.

Everything looks fine and translated, but not working...must be a setting? I have tried the language detection, views setting for user language, refreshed strings, updated, cleared cache...

do you also use the i18n module ?

tmgmt is not enough !! this module is meant to help the translators and to use external translations servives.

probably you need to enable more translation modules from i18n like field translations, entity translation (seperate module) etc.


How to display legal link on registration page in colorbox node? I have installed the module Legal and choose to have a checkbox on registration. On registration of a new user is then displayed:

Accept Terms & Conditions of Use *

The Terms & Conditions are link to page /legal in the same window.

I want to show this link in colorbox node so a style should be appended. Probably I have to modify the code (which I do not prefer) or can implement a hook for this? If so, how?

Any other suggestion?

You will have to add the class colorbox to the Terms and Conditions link generated by the Legal module.

This is easily setup through a theme_ function override.
Use the following code in your theme's template.php file:

    function YOUR_THEME_legal_accept_label($variables) {
      if ($variables['link']) {
        return t('Accept Terms & Conditions of Use', array('@terms' => url('legal')));
      }
      else {
        return t('Accept Terms & Conditions of Use');
      }
    }

Note: you might have to tweak the output in the popup, but that's outside of the scope I guess.


An error occured while attempting to process /ajax/ajax_facets/refresh:$.blockUI is not a function Ajax facets work but I get an error "An error occured while attempting to process /ajax/ajax_facets/refresh:$.blockUI is not a function" when I click on ajax links with checkboxes for the facets for the first time.

I am using search api views as per mentioned in the project description
You can check the error in the screenshot attached

The above issue was occuring due to conflict with other module Ajax Screen Lock
Disabling it solves the problem.


Complex view based off of Node Reference Drupal 7

Is it possible to get the current pages Node name and dynamically use it for a view using node reference? I have a content type called product and I am going to add a view to this content type that will show a list of image content types that have a node reference field set to the product content type.

For example:

"Furniture" page - content type "Product"
"Clothing" page - content type "Product"

"Image" content type - "Image 1" w/ a node reference field of "Furniture"
"Image" content type - "Image 2" w/ a node reference field of "Clothing"
"Image" content type - "Image 3" w/ a node reference field of "Clothing"
"Image" content type - "Image 4" w/ a node reference field of "Furniture"

So when I go to the Furniture product page my view will have Image 1 and Image 4 in the list
and if I got to Clothing product page it will show Image 2 and Image 3.

If this needs more explanation please let me know.

First add the node reference field as a relationship. That will enable the node reference field to be added as a contextual filter.

You can use EVA module to attach the view to your node page, which will automatically pass the node ID to the view (which your contextual filter should pick up and show only images referencing that node).

You can checkout Is there a good tutorial for "Entity Views Attach Module"? for more info on EVA