Remove the extra headers from the e-mails sent My site is made of book(book pages) and any authenticated user is able to send the book page as an e-mail to anybody (other user in the site / external user using e-mail) he wishes. The mail system is working fine but when (lets say) User1(user1@example.com) is sending mail to anyone, the sent mail headers are as follows:

  site_admin@example.com on behalf of user1@example.com

I want that a user should be able to send the email directly by his e-mail id.

I am using Drupal 7, with Print and SMTP configured to send to book pages.

Apparently someone came up with code to put in a custom module that will remedy this issue:

http://drupal.org/node/461324

I've yet to try it though.

UPDATE:

I tried out an altered version and it worked for me. Here's what I had:

email_sender_override.info:

name = E-mail Sender Override
description = Overrides the 'Sender' of an e-mail message with the 'From' address.
core = 7.x
package = Webform

email_sender_override.module:

<?php
/**
  * @file
  *
  * Mail altering function to override the 'Sender' of a mail message with the address
  * in the 'From' field.
  *
  */

/**
  * email_sender_override_mail_alter
  *
  * Alters the sender of the e-mail message to be the same as the 'From' address.
  * Taken from: http://drupal.org/node/461324
  * See also:   http://api.drupal.org/api/drupal/includes!mail.inc/function/drupal_mail/6#comment-3243
  *             http://drupal.org/node/656472
  *
  * @param message
  *    the full e-mail message being sent -- this will be altered
  */
function email_sender_override_mail_alter(&$message)
{
    $message['headers']['Sender'] = $message['headers']['From'];
}
?>


Why is the apostrophe converted to ' in account activation e-mail? In admin/config/people/accounts, the body of Welcome e-mail is (my site in in French):

user:display-name],

Un administrateur sur [site:name] a créé un compte pour vous. Vous pouvez maintenant vous connecter en utilisant le lien ci-dessous ou en le copiant dans votre navigateur :

[user:one-time-login-url]

Ce lien ne peut être utilisé qu'une seule fois pour vous connecter et vous redirigera vers la page où vous pourrez choisir votre mot de passe.

Après avoir choisi votre mot de passe, vous pourrez vous connecter sur [site:login-url] en utilisant :

nom d'utilisateur : [user:name]
mot de passe : Votre mot de passe

--  L'équipe de [site:name]

And in the e-mail received by the recipent, every apostrophe is changed to &#039;  like in the signature:

--  L&#039;équipe de Le Jardin de Poissy

My version of Drupal is 8.7.8 and I use these modules: Mail System and Swift Mailer.

How can I let Drupal send properly formatted mails including apostrophes?

The easiest way to fix this is simply set the formatter to the Default PHP Mailer, if you want to stick to plain text mail.

This is a known bug in the SwiftMailer module where Html::escape is called, even for plain text. Bug report here: https://www.drupal.org/project/swiftmailer/issues/2937293 .

The Html::escape function declares:

  /*
   * This method escapes HTML for sanitization purposes by replacing the
   * following special characters with their HTML entity equivalents:
   * - & (ampersand) becomes &amp;
   * - " (double quote) becomes &quot;
   * - ' (single quote) becomes &#039;
   * - < (less than) becomes &lt;
   * - > (greater than) becomes &gt;
   */

And that's where your &#039; comes from.


Add custom field for menu I am having menu like this in drupal which i have used superfish to show

I want each main menu to have a sub-title or description like this in below image

I searched alot online. Also tried for modules. Was wondering if there is a way to achieve that.

You could use the 'not often used' description field already available on each link? Then just add it into the menu links yourself on the front end by overriding the menu_link theme function.

function theme_menu_link(array $variables) {
  $element = $variables['element'];
  $sub_menu = '';
  $description = '' . $element['#localized_options']['#original_link']['description'] . '';

  if ($element['#below']) {
    $sub_menu = drupal_render($element['#below']);
  }
  $output = l($element['#title'] . $description, $element['#href'], $element['#localized_options']);
  return '
' . $output . $sub_menu . "
\n";
}


Granting per-node-type permissions in hook_node_type_insert() I use the Override Node Options module to specify granular permissions for publishing, leaving Revision log entries, etc. for each node type.

I almost always grant the same set of permissions to a certain role for every node type, so I thought I'd have Drupal automatically assign them on node type creation:

function MYMODULE_node_type_insert($info) {
    if(module_exists('override_node_options')) {
        user_role_grant_permissions(4, array(
            'override ' . $info->type . ' published option',
            'enter ' . $info->type . ' revision log entry'
        ));
        $role = user_role_load(4);
        drupal_set_message(t('The @role role has been given permission to publish, unpublish, and enter revision logs on @nodetype nodes.', array('@role' => $role->name, '@nodetype' => $info->type)));
    }
}

But when I do so, I get errors:

  Notice: Undefined index: override NODETYPE published option in user_role_grant_permissions() (line 3152 of /htdocs/modules/user/user.module).

  PDOException: SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'module' cannot be null: UPDATE {role_permission} SET module=:db_update_placeholder_0 WHERE ( (rid = :db_condition_placeholder_0) AND (permission = :db_condition_placeholder_1) ); Array ( [:db_update_placeholder_0] => [:db_condition_placeholder_0] => 4 [:db_condition_placeholder_1] => override NODETYPE published option ) in user_role_grant_permissions() (line 3154 of /htdocs/modules/user/user.module).

As it happens, node_type_get_types() ( which is called by node_permissions_get_configured_types()) does not return the node type I'm in the middle of creating, even though the documentation says "This list can include types that are queued for addition or deletion."

So now I'm flummoxed. How can I set a per-node-type permission automatically when that node type is created?

So, my bet is that the new node type isn't getting added to the cached list of types that node_type_get_types() returns. At the very end of node_type_save(), it calls node_type_cache_reset(), but that's probably running too late for your code.

So try putting a call to node_type_cache_reset() at the top of your function, and hopefully that will do the trick.


Content Aware Caching for Commerce Related Views Views Content Cache Project Page reads

  This module implements a views cache plugin that is aware of content
  and can provide caching for views, until the content in those views
  changes.

Do we have an equivalent for Drupal Commerce. So that when I have a view listing of Commerce Orders or Products, I can provide caching until the content(orders or products) in those views changes.

The list of products uses Views, so in theory the module should work for views in admin/structure/views/view/commerce_products


show order payment option in order (admin/commerce/order) I am using commerce kickstart (In admin/commerce/orders) How to show payment options for (authenticate) user. As, i give all the permission for authenticate role.

admin page screenshot show quick edit option Edit, invoice, payment, and delete

authenticate role page screenshot show quick edit here it is not option for any of the above.

Enable permission "Use the administration pages and help" under the System section should do the trick.


Development with git branches/ gitflow and new modules I wonder if somebody found a solution for the following issue related to Drupal 8 development with Git branches:

You work on a new feature in a local feature branch
for that you activate a contributed module or you write a custom module. This maybe delivers an own entity type and therefore creates a table after installing
Meanwhile you need to fix a bug -> you change to a newly created bugfix branch which starts from the current dev branch
After checking out the bugfix branch you import the current configurations to have the current active configuration of the branch -> the module you installed in feature branch is not activated anymore, the files of this module do not exist in the current bugfix branch
You do your bugfixing and merge ths bugfix branch into develop branch.
you change to your feature branch. To bring your local Drupal project to the status of this branch again you will import the configurations again

And here it comes to an exception: the table already exists in your database. When doing a drush cim it stops every following processing and you need to restart drush cim to import any further configurations.

Who does work with different feature branches and found a solution during development process to deal with this kind of situation?

I always have a somewhat up-to-date DB dump from live/master available. When switching between feature branches I can drush sql-drop the DB, drush sql-cli < live.sql and drush cim the branch config. If needed. When switching back into the develop or master branch I do the same steps again.

This means you routinely have to commit your feature's configs into its branch. Or to write really cool install.yml in a custom module and enable that after you switched back into the feature branch.

I guess we will have something automating this in half a year. But for now, it's perfectly fine. At least for me.


Validation message on Login form not shown I am using Drupal 7. When ever I visit site.com/user/login I could see my Login form, thats fine. But when I miss to enter any fields say name and click the login button it does not shows the validation error message. Does any one what the actal problem might be?

Thanks

Look at the form id for login form. and then try hook_form_alter() in any custom module.

Add a submit callback or validation callback in which you can check for the empty fields yourself. According use drupal_set_message() to display the error message.


Drupal Multi Site Folder structure I have a simple question.

I am trying to create a folder inside the Drupal installation that will not be shared to all the multi-sites.

For example:

  www.mydomain.com/xxx

  www.anotherdomain.com/xxx

I need this two folders of xxx should go to different path.

How can I achieve that?

I tried to create a new folder in Drupal root folder, but like this all the domains familiar with the same contents.

Thanks for the help.

To extend @Pierre.Vriens answer , you could then add a rewrite rule to make the urls a bit nicer

assumptions

you've got public files set up
you've got a url 'normalisation' (either symlinks in files directory or 301s)

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ /sites/%{HTTP_HOST}/files/$1 [L]

in your host will take

http://www.example.com/filename.pdf

and rewrite it to

http://www.example.com/sites/www.example.com/files/filename.pdf

what do i mean by url normalisation ?
well, if you can get example.com - then you'll get a 404 - as the folder in the sites directory is www.example.com

an easy solution is to use symlinks in the sites directory, or to use 301 redirects

to use symlinks, assume you have

sites/www.example.com

you could then create a symlink to it as follows

ln -s www.example.com example.com

this would create a symbolic link from

sites/example.com

to the www.example.com folder. this means that both www.example.com, and example.com would be found when the rewrite rule runs


How to display the username in view I'm new to Drupal 7 and I have created a content revision view. For that I have added a column of author in which I have also specified the user author relationship in view.

Problem is i am creating the content type using mobile device using web services  for this created content i have content revision view in D7 here for all the content created user name displaying as admin i,e if I check the user name column in content revision column, then it shows the same admin name for all content created through multiple users, as shown in this screen print:

In advanced section add a relationship by author like this :

Then add a field, choose User:name (the user or the author name) :

make sure that you have the relationship "author" in the field setting :

Now you should see the correct author name.


Updating Drupal project using Composer fails I have site (which is originally installed also with composer) with drupal core version 8.7.2. I'm trying to update it to latest 8.7.8. When I do:

composer outdated "drupal/*"

I get the list of all outdate and for core I get row:

drupal/core                       8.7.2       8.7.8       Drupal is an open source content management platform powering millions of websites ..

But when I try:

composer update drupal/core --with-dependencies

I get:

Loading composer repositories with package information
Updating dependencies (including require-dev)
Nothing to install or update
Package phpunit/phpunit-mock-objects is abandoned, you should avoid using it. No replacement was suggested.
Writing lock file
Generating autoload files

In composer.json core is added under require as (I just followed install docs - didn't change anything by hand):

"drupal/core": "^8.7.0",

That was suspicious to me so I tried replacing it with:

"drupal/core": "8.*",

But result was the same - nothing to update.

That message about phpunit/phpunit-mock-objects dependency is in green so I doubt that it causes this update to fail, but I'm not sure.

Why composer says that there's nothing to update?

Update:

Tried also:

composer prohibits drupal/core:8.7.8

and it says:

webflo/drupal-core-require-dev  8.7.2  requires  drupal/core (8.7.2)

And I really have inside composer.json:

"require-dev": {
    "webflo/drupal-core-require-dev": "^8.7.0"
},

Also tried:

composer update drupal/core --with-dependencies --no-dev

which removed dev dependencies, but also didn't update drupal core.
How to solve this?

Solved it. I had to add that "webflo/drupal-core-require-dev" to update command to be updates as well, because without that core couldn't be updated:

composer update drupal/core "webflo/drupal-core-require-dev" --with-dependencies

Saw that in "known issues" section. :/
It's really strange - what's the purpose of --with-dependencies when I have to add dependencies manually after all...


Remove nodes individually from Solr Search index I know you can choose which content types to exclude. However, is there a way of removing specific nodes from the Solr index?

That's exactly what I wrote the module for. There's a release now and I moved the module to Apache Solr Node Exclude because I botched the project creation the first time.


How do I Print/Display Site information Form I'm trying to print the Site Information Form, and a series of other forms in the near future, inside a lightbox using a snippet of code I found similar to the following.

global $user;
module_load_include('inc', 'user', 'user.pages');
print user_edit($user);

This, along with some other code not mentioned, will display the user account form. But I'd like to know how do I print the Site Info Form, and any other form I may wish to display in the future? What process or methods can I use to find out what I need to do?

I hope I'm not being too vague. Any pseduo-code, suggestions or even a hint would be greatly appreciated.

Thanks.

<?php print drupal_get_form('system_site_information_settings'); ?>

You can output any form in Drupal using drupal_get_form once you know it's form_id (which is the function name that returns the form array)


How to make product attributes appear as checkbox on the add-to-cart form? In Drupal Commerce how to make product attributes appear as checkboxes on the add-to-cart form? I want to see the sum of the prices of all checked products and add them all to the cart, when the add-to-cart submit button is pressed.

I wonder if there is tutorial, or - even better a module - for that?

The closest thing to what you're asking for is Commerce Add to Cart Extras.


Module content type not removed after uninstall My module adds content types by implementing hook_node_info. After disabling and uninstalling the module, the content type is still in the database and is merely marked as disabled.

NOTE: I also add create and instantiate custom fields for the created content type.

Since according to this answer content types created in hook_node_info are deleted automatically, is my problem a sign if DB inconsistency or am I doing something else wrong.

Code:

function test_core_node_info() {
    // Name of the proper localization function
    $t = get_t ();
    // Adding author
    return array (
            'test' => array (
                    'name' => $t ( 'Test' ),
                    'base' => 'test_module',
                    'description' => $t ( 'Test' ),
                    'title_label' => $t ( 'Title' ),
                    'locked' => TRUE
            )
    );
}

-- EDIT --

I mentioned removing instead of uninstalling. This is corrected now.

You shall have to uninstall the module to get the type deleted automatically.  Just disabling it will not remove anything.  Deleting the module after disabling it - without uninstalling it first - is not a good idea.

After disabling the module, click on the “uninstall” tab at the top of the modules page and check the module you want to uninstall, then click the "Uninstall" button.


Is it possible to get last modified date for certain field? Is it perhaps possible to get date and time of last modification of certain field?

Just like in table "Node" you have "created" and "modified" dates, but what about fields of certain content type?

I would like to know when certain field was last modified.

thanks!

I took a quick look at the field_data_xxx and field_revision_xxx tables and there is no time stamp field, which means you wont be able to get the last modified dates for fields.

You can probably use Field Attach API to add time entries to a custom table which will contain field_key, entity id, bundle id and time-stamp columns.


How to take contents of a tab and insert them inside a node I guess this is a pretty basic Drupal thing, but I'm not experienced with coding. I am using the Petition node module which displays a petition form and the results of that petition inside a tab on the same page. I found the code for this on line 174 of the petition.module:

$items['node/%petition_menu/signatures'] = array(
'title' => 'Signatures',
'page callback' => 'petition_signature_page',
'page arguments' => array(1),
'access callback' => 'petition_signature_access',
'access arguments' => array(1),
'weight' => 1,
'type' => MENU_LOCAL_TASK,

I want to render the signatures right next to the petition form, on the petition node page. How can I do this? My guess is that I could use this code and insert it inside the node template, but I need some instructions for that.

You can create a block using the block module hooks and you can generate the content of the block by using the page callback function in the menu to get the signatures displayed inside the block. You can then configure the block in whichever region you want.

Another option would be to use the page callback function inside the template file (.tpl file) of the petition  node and print the content near to the petition form.


Getting entityreference field from user I created additional field for user profile, which is a reference to node (content type - Company).

How can i get values of this field for a current user?

 $user = \Drupal\user\Entity\User::load(\Drupal::currentUser()->id());

 $field_company= $user->get('field_company')->value; // result is empty

I know that second string is wrong, but i don't know what should I write.
Please, help.

Thanks a lot.

Seeing this change record, this should work:

$items = $user->getTranslation($langcode)->get('field_company');


How to edit a custom region from an Omega subtheme in Drupal 7 I created a new region in my Omega subtheme called MYTHEME-MENU. I want this region to do the same thing as the normal menu region, but with adding some markup. What is the proper way of doing this (I don't want to add the markup in Omega's region-menu.tpl.php file)?

I see I have a template, process and preprocess directories along with an empty template.php file, but I'm not sure how to use these.

Essentially my MYTHEME-MENU region needs to spit out the following:

<div<?php print $attributes; ?>>
   <div<?php print $content_attributes; ?>>

    <?php if ($main_menu || $secondary_menu): ?>

    <?php print theme('links__system_main_menu', array('links' => $main_menu,
       'attributes' => array('id' => 'main-menu', 'class' => array('links', 'inline',
       'clearfix',     'main-menu')), 'heading' => array('text' => t('Main
        menu'),'level' => 'h2','class' =>     array('element-invisible')))); ?>
    <?php print theme('links__system_secondary_menu', array('links' => $secondary_menu,
       'attributes' => array('id' => 'secondary-menu', 'class' => array('links',
       'inline', 'clearfix', 'secondary-menu')), 'heading' => array('text' =>
        t('Secondary menu'),'level' =>     'h2','class' => array('element-
        invisible')))); ?>

    <?php endif; ?>
    <?php print $content; ?>

You don't need to create another region for that.

You just have to copy the Omega file omega/templates/region--menu.tpl.php
to your subtheme's template folder: MYTHEME/templates/region--menu.tpl.php.

There you can make whatever changes you need.


How to fetch the completed goal as an entity with the Rules module? Followup question for the question about "How to access fields from a goal when creating a node with Rules?".

I'm trying to create a rule that finds and uses the fields of the goal that triggered the goal completed event. They can be fetched if you know the goal id (as shown in the answer to the previous question). But creating individual rules for each goal is not viable because there are quite a few of them and I'd like administrators to be able to easily add them without having to write new rules.

So how can I create a rule without specifying a Rules Condition to check the id of the goal that was completed?

You could use the Views Rules to get this to work. Read on for more details about how to do so ...

Step 1: Create an appropriate view

Create a view of all goals completed by the current user, sorted (descending) by the date the goal was completed, and a "Rules" display type, in which you use a pager to only show 1 result (i.e. the most recent one ...).

Here is a view (in export format) with (a) a page display (to list all goals completed by the current user) and (b) a Rules display (to only list the most recent completed goal):

$view = new view();
$view->name = 'goals_info_about_completed_goals';
$view->description = 'A list of goals completed by a user.';
$view->tag = 'Goals';
$view->base_table = 'goals';
$view->human_name = 'Goals completed by a user';
$view->core = 7;
$view->api_version = '3.0';
$view->disabled = FALSE; /* Edit this to true to make a default view disabled initially */

/* Display: Master */
$handler = $view->new_display('default', 'Master', 'default');
$handler->display->display_options['title'] = 'Goals completed by a user';
$handler->display->display_options['use_more_always'] = FALSE;
$handler->display->display_options['access']['type'] = 'none';
$handler->display->display_options['cache']['type'] = 'none';
$handler->display->display_options['query']['type'] = 'views_query';
$handler->display->display_options['exposed_form']['type'] = 'basic';
$handler->display->display_options['pager']['type'] = 'none';
$handler->display->display_options['pager']['options']['offset'] = '0';
$handler->display->display_options['style_plugin'] = 'table';
$handler->display->display_options['style_options']['columns'] = array(
  'goal_img' => 'goal_img',
);
$handler->display->display_options['style_options']['default'] = '-1';
$handler->display->display_options['style_options']['info'] = array(
  'goal_img' => array(
    'sortable' => 0,
    'default_sort_order' => 'asc',
    'align' => '',
    'separator' => '',
    'empty_column' => 0,
  ),
);
/* Relationship: Goal: Goal - completed by users */
$handler->display->display_options['relationships']['goals_completed_goals']['id'] = 'goals_completed_goals';
$handler->display->display_options['relationships']['goals_completed_goals']['table'] = 'goals';
$handler->display->display_options['relationships']['goals_completed_goals']['field'] = 'goals_completed_goals';
$handler->display->display_options['relationships']['goals_completed_goals']['label'] = 'Completed goal';
/* Field: Goal: Goal Image */
$handler->display->display_options['fields']['goal_img']['id'] = 'goal_img';
$handler->display->display_options['fields']['goal_img']['table'] = 'field_data_goal_img';
$handler->display->display_options['fields']['goal_img']['field'] = 'goal_img';
$handler->display->display_options['fields']['goal_img']['label'] = 'Goal image';
$handler->display->display_options['fields']['goal_img']['element_label_colon'] = FALSE;
$handler->display->display_options['fields']['goal_img']['click_sort_column'] = 'fid';
$handler->display->display_options['fields']['goal_img']['settings'] = array(
  'image_style' => 'goal_image',
  'image_link' => '',
);
/* Field: Goal: URL */
$handler->display->display_options['fields']['url']['id'] = 'url';
$handler->display->display_options['fields']['url']['table'] = 'views_entity_goal';
$handler->display->display_options['fields']['url']['field'] = 'url';
$handler->display->display_options['fields']['url']['exclude'] = TRUE;
$handler->display->display_options['fields']['url']['link_to_entity'] = 0;
/* Field: Goal: Title */
$handler->display->display_options['fields']['title_1']['id'] = 'title_1';
$handler->display->display_options['fields']['title_1']['table'] = 'goals';
$handler->display->display_options['fields']['title_1']['field'] = 'title';
$handler->display->display_options['fields']['title_1']['alter']['make_link'] = TRUE;
$handler->display->display_options['fields']['title_1']['alter']['path'] = '[url]';
/* Field: Goal: Goal ID */
$handler->display->display_options['fields']['goal_id']['id'] = 'goal_id';
$handler->display->display_options['fields']['goal_id']['table'] = 'goals';
$handler->display->display_options['fields']['goal_id']['field'] = 'goal_id';
/* Field: Goal: User Points */
$handler->display->display_options['fields']['goal_userpoints']['id'] = 'goal_userpoints';
$handler->display->display_options['fields']['goal_userpoints']['table'] = 'field_data_goal_userpoints';
$handler->display->display_options['fields']['goal_userpoints']['field'] = 'goal_userpoints';
$handler->display->display_options['fields']['goal_userpoints']['settings'] = array(
  'thousand_separator' => '',
  'prefix_suffix' => 1,
);
/* Field: Goal: Goal Category */
$handler->display->display_options['fields']['field_goal_category']['id'] = 'field_goal_category';
$handler->display->display_options['fields']['field_goal_category']['table'] = 'field_data_field_goal_category';
$handler->display->display_options['fields']['field_goal_category']['field'] = 'field_goal_category';
/* Field: Goal: Goal Level */
$handler->display->display_options['fields']['field_goal_level']['id'] = 'field_goal_level';
$handler->display->display_options['fields']['field_goal_level']['table'] = 'field_data_field_goal_level';
$handler->display->display_options['fields']['field_goal_level']['field'] = 'field_goal_level';
/* Field: Goal - completed by users: Created */
$handler->display->display_options['fields']['created']['id'] = 'created';
$handler->display->display_options['fields']['created']['table'] = 'goals_completed_goals';
$handler->display->display_options['fields']['created']['field'] = 'created';
$handler->display->display_options['fields']['created']['relationship'] = 'goals_completed_goals';
$handler->display->display_options['fields']['created']['label'] = 'Completion date';
$handler->display->display_options['fields']['created']['date_format'] = 'short';
$handler->display->display_options['fields']['created']['second_date_format'] = 'long';
/* Field: Goal - completed by users: User */
$handler->display->display_options['fields']['uid']['id'] = 'uid';
$handler->display->display_options['fields']['uid']['table'] = 'goals_completed_goals';
$handler->display->display_options['fields']['uid']['field'] = 'uid';
$handler->display->display_options['fields']['uid']['relationship'] = 'goals_completed_goals';
/* Field: Goal - completed by users: Goal */
$handler->display->display_options['fields']['goal_id_1']['id'] = 'goal_id_1';
$handler->display->display_options['fields']['goal_id_1']['table'] = 'goals_completed_goals';
$handler->display->display_options['fields']['goal_id_1']['field'] = 'goal_id';
$handler->display->display_options['fields']['goal_id_1']['relationship'] = 'goals_completed_goals';
/* Field: Goal - completed by users: Goal - completed by users ID */
$handler->display->display_options['fields']['id']['id'] = 'id';
$handler->display->display_options['fields']['id']['table'] = 'goals_completed_goals';
$handler->display->display_options['fields']['id']['field'] = 'id';
$handler->display->display_options['fields']['id']['relationship'] = 'goals_completed_goals';
$handler->display->display_options['fields']['id']['label'] = 'Completed Goal Seqnr';
/* Sort criterion: Goal - completed by users: Created */
$handler->display->display_options['sorts']['created']['id'] = 'created';
$handler->display->display_options['sorts']['created']['table'] = 'goals_completed_goals';
$handler->display->display_options['sorts']['created']['field'] = 'created';
$handler->display->display_options['sorts']['created']['relationship'] = 'goals_completed_goals';
$handler->display->display_options['sorts']['created']['order'] = 'DESC';
/* Contextual filter: Goal - completed by users: User */
$handler->display->display_options['arguments']['uid']['id'] = 'uid';
$handler->display->display_options['arguments']['uid']['table'] = 'goals_completed_goals';
$handler->display->display_options['arguments']['uid']['field'] = 'uid';
$handler->display->display_options['arguments']['uid']['relationship'] = 'goals_completed_goals';
$handler->display->display_options['arguments']['uid']['default_action'] = 'default';
$handler->display->display_options['arguments']['uid']['default_argument_type'] = 'current_user';
$handler->display->display_options['arguments']['uid']['summary']['number_of_records'] = '0';
$handler->display->display_options['arguments']['uid']['summary']['format'] = 'default_summary';
$handler->display->display_options['arguments']['uid']['summary_options']['items_per_page'] = '25';

/* Display: Page */
$handler = $view->new_display('page', 'Page', 'page_1');
$handler->display->display_options['path'] = 'user/%/completed-goals';

/* Display: RulesList */
$handler = $view->new_display('views_rules', 'RulesList', 'views_rules_1');
$handler->display->display_options['pager']['type'] = 'some';
$handler->display->display_options['pager']['options']['items_per_page'] = '1';
$handler->display->display_options['pager']['options']['offset'] = '0';
$handler->display->display_options['defaults']['fields'] = FALSE;
/* Field: Goal: URL */
$handler->display->display_options['fields']['url']['id'] = 'url';
$handler->display->display_options['fields']['url']['table'] = 'views_entity_goal';
$handler->display->display_options['fields']['url']['field'] = 'url';
$handler->display->display_options['fields']['url']['exclude'] = TRUE;
$handler->display->display_options['fields']['url']['link_to_entity'] = 0;
/* Field: Goal: Title */
$handler->display->display_options['fields']['title_1']['id'] = 'title_1';
$handler->display->display_options['fields']['title_1']['table'] = 'goals';
$handler->display->display_options['fields']['title_1']['field'] = 'title';
$handler->display->display_options['fields']['title_1']['alter']['make_link'] = TRUE;
$handler->display->display_options['fields']['title_1']['alter']['path'] = '[url]';
/* Field: Goal: Goal ID */
$handler->display->display_options['fields']['goal_id']['id'] = 'goal_id';
$handler->display->display_options['fields']['goal_id']['table'] = 'goals';
$handler->display->display_options['fields']['goal_id']['field'] = 'goal_id';
$handler->display->display_options['rules_parameter'] = array(
  'uid' => array(
    'enabled' => 1,
    'type' => 'integer',
    'label' => 'Goal completed by user with id',
    'name' => 'goal_completed_by_uid',
  ),
);
$handler->display->display_options['rules_variables'] = array(
  'url' => array(
    'enabled' => 0,
    'rendered' => 0,
    'type' => '',
    'label' => 'URL',
    'name' => 'url',
  ),
  'title_1' => array(
    'enabled' => 1,
    'rendered' => 0,
    'type' => 'text',
    'label' => 'Title',
    'name' => 'goal_title',
  ),
  'goal_id' => array(
    'enabled' => 1,
    'rendered' => 0,
    'type' => 'integer',
    'label' => 'Goal ID',
    'name' => 'goal_id',
  ),
  'field_goal_category' => array(
    'enabled' => 1,
    'rendered' => 0,
    'type' => 'text',
    'label' => 'Goal Category',
    'name' => 'goal_category',
  ),
  'field_goal_level' => array(
    'enabled' => 1,
    'rendered' => 0,
    'type' => 'text',
    'label' => 'Goal Level',
    'name' => 'goal_level',
  ),
  'goal_userpoints' => array(
    'enabled' => 0,
    'rendered' => 0,
    'type' => '',
    'label' => 'User Points',
    'name' => 'goal_userpoints',
  ),
  'uid' => array(
    'enabled' => 1,
    'rendered' => 0,
    'type' => 'integer',
    'label' => 'Id of User completing goal',
    'name' => 'goal_uid',
  ),
);

Before trying to import the above view in your own site, make sure to define these custom fields for the goals you configured (these fields are select lists with a single value allowed):

Goal Category (machine name field_goal_category), eg with values such as "Privilege, Contribution, Participation, Moderation, None".
Goal Level (machine name field_goal_level), eg with values such as "Bronze, Silver, Gold, None".

Step 2: Create a rule that contains a Views loop

Create a rule which contains a "Views loop" as a Rules Action, which is similar to a regular Rules loop, but allows looping over rows of view results. Use the Rules Display type of the view created in the previous step. Obviously, because of the number of results we configured in the Rules display of the view, this list consists of only 1 list item (i.e. related to the most recently completed goal).

Within that "Views loop", perform a 1st Rules Action to "Fetch an entity by id", and with these additional details:

Parameter: Entity type: Goal
Identifier: [goal-id]
Provides variables: Completed goal (goal_completed)

Then add a 2nd Rules Action, within that same "Views loop", something like "Show a message on the site", with a message that looks something like so (note the 2 custom fields included, with machine names field_goal_category and  field_goal_level):

  Details about completed goal:

  Goal ID: [goal-completed:goal-id]
  Goal Title: [goal-completed:title]
  Goal Category: [goal-completed:field_goal_category]
  Goal Level: [goal-completed:field_goal_level]

Here is an export of a rule you can use for this (if you have both custom fields defined, you should be able to import this rule in your own site):

{ "rules_show_details_about_completed_goal" : {
    "LABEL" : "Show details about completed goal",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "TAGS" : [ "goals" ],
    "REQUIRES" : [ "rules", "goals" ],
    "ON" : { "goal_awarded" : [] },
    "DO" : [
      { "VIEW LOOP" : {
          "VIEW" : "goals_info_about_completed_goals",
          "DISPLAY" : "views_rules_1",
          "USING" : { "goal_completed_by_uid" : [ "awarded-user:uid" ] },
          "ROW VARIABLES" : {
            "goal_title" : { "goal_title" : "Title" },
            "goal_id" : { "goal_id" : "Goal ID" }
          },
          "DO" : [
            { "entity_fetch" : {
                "USING" : { "type" : "goal", "id" : [ "goal-id" ] },
                "PROVIDE" : { "entity_fetched" : { "goal_completed" : "Completed goal" } }
              }
            },
            { "drupal_message" : { "message" : "Details about completed goal:\u003Cbr \/\u003E\u003Cbr \/\u003E\r\n- Goal ID: [goal-completed:goal-id]\u003Cbr \/\u003E\r\n- Goal Title: [goal-completed:title]\u003Cbr \/\u003E\r\n- Goal Category: [goal-completed:field_goal_category]\u003Cbr \/\u003E\r\n- Goal Level: [goal-completed:field_goal_level]\u003Cbr \/\u003E" } }
          ]
        }
      }
    ]
  }
}

Here are the "Replacement patterns for Completed goal" that are shown with the Rules Action to Show a message on the site:

[goal-completed:title]                  Title               Goal "title" property.
[goal-completed:created]                Created             The date the goal was created.
[goal-completed:changed]                Changed             The date the goal was changed.
[goal-completed:Goal ID]                Label               The human readable label.
[goal-completed:url]                    URL                 The URL of the entity.
[goal-completed:field-goal-description] Goal Description    Field "field_goal_description".
[goal-completed:goal-userpoints]        User Points         Field "goal_userpoints".
[goal-completed:goal-img]               Goal Image          Field "goal_img". The following properties may be appended to the token: file (The image file.)
[goal-completed:field-goal-category]    Goal Category       Field "field_goal_category".
[goal-completed:field-goal-level]       Goal Level          Field "field_goal_level".
[goal-completed:field_goal_description] Goal Description    Long text field.
[goal-completed:goal_userpoints]        User Points         Integer field.
[goal-completed:goal_img]               Goal Image          Image field.
[goal-completed:field_goal_category]    Goal Category       List (text) field.
[goal-completed:field_goal_level]       Goal Level          List (text) field.

Obviously, these Replacement patterns have been made available via the Rules Action "Fetch entity by Id" that precedes it. And with that, you have anything available to "find and use the fields of the goal that triggered the goal completed event" (as in your question).

Step 3: Demo

Here is an example of a message shown to a user, after the user completes some goal (if the above view and rule is enabled):

  Details about completed goal:

  Goal ID: 11
  Goal Title: Citizen Patrol
  Goal Category: Moderation
  Goal Level: Bronze

Note: For way more details on using Views Rules, refer to ("Option 2" of) my answer to "How to use Rules to send an E-mail after saving a new comment, to users who checked a boolean in their profile?".

PS: this answer applies to D7 ...


db_select group by of union I'm quite new to drupal ad I've some problem with parsing a query throught the API:

    SELECT t.pg,p.classe, sum(t.punti) AS punti, sum(t.vinte) AS vinte, sum(t.perse) AS perse, (sum(t.vinte)+sum(t.perse)) AS giocate
    FROM(
        SELECT sid, team_member_a_1 AS pg, punti_team_a AS punti, 1 AS vinte, 0 AS perse
        FROM `webform_views_unusual_arena__risultati_6` AS t1
        WHERE tipologia_risultato = 0
            AND vincente = 0
        UNION
        SELECT sid, team_member_a_2 AS pg, punti_team_a AS punti, 1 AS vinte, 0 AS perse
        FROM `webform_views_unusual_arena__risultati_6` AS t1
        WHERE tipologia_risultato = 0
            AND vincente = 0
    ) AS t
    JOIN webform_views_i_miei_pg_1 AS p ON t.pg = p.nome_pg
    GROUP BY pg

But I can't find any documentation about a subquery or how to add field like "1 AS vinte"

EDIT
Thank's to Tenken this is the code I used.

$subquery_1 = db_select('webform_views_unusual_arena__risultati_6', 't')
    ->condition('t.tipologia_risultato', 0, '=')
    ->condition('t.vincente', 0,'=')
    ->fields('t', array('sid'));
$subquery_1->addExpression('team_member_a_1', 'pg');
$subquery_1->addExpression('punti_team_a', 'punti');
$subquery_1->addExpression(1, 'vinte');
$subquery_1->addExpression(0, 'perse');
$subquery_2 = db_select('webform_views_unusual_arena__risultati_6', 't')
    ->condition('t.tipologia_risultato', 0, '=')
    ->condition('t.vincente', 0,'=')
    ->fields('t', array('sid'));
$subquery_2->addExpression('team_member_a_2', 'pg');
$subquery_2->addExpression('punti_team_a', 'punti');
$subquery_2->addExpression(1, 'vinte');
$subquery_2->addExpression(0, 'perse');
$query = $subquery_1->union($subquery_2);

$query->addExpression('sum(vinte)', 'vinte');
$query->addExpression('sum(perse)', 'perse');
$query->addExpression('sum(punti)', 'punti');
$query->groupBy('pg');
$query->orderBy('punti', 'DESC');

Hope it will help someone else

See this WEALTH OF DOCUMENTATION on Dynamic Queries in D7 ... it will answer EVERYTHING :) .... in all seriousness :).

To add SUM(blah) as foo you want to add an SQL Expression to your Select clause with addExpression().

To add Group by COLNAME you want to use groupBy() with your db_selection, see group by docs.


Flexslider broken links I have a very weird problem with flexslider.

Everything was working ok, but suddenly flexslider stopped to show the images im adding.

My observations are:

Flexslider rewrites urls to the path, where there is NO images
there is a access denied warning in drupal logs but my permissions are set to 775/755

Whole flexslider mechanism is working correct, its cycling and stuff, but there is no content inside.

I will appreciate any help, and thanks a lot in advance.

This feels like an issue with your files directory permissions. Specifically, the permissions on the directory that contains the image style derivatives for the flexslider. My guess is that they are not being created properly.


Custom pager "Showing X - Y of Z results" I have some entities queried from an external solr server using custom code and Search API, and I'm listing them 10 per page.

I have created a pager for the page using pager_default_initialize() and theme('pager').

I wanted to insert a text into the pager div that says "Showing X - Y of Z results". I can do this manually by overriding the theme_pager() function, but I was wondering is there a drupal native function or some setting which you can pass to theme_pager that does this?

I suppose in short I want the Views 3 equivalent of "Full pager", instead at the moment I'm only able to produce the "Mini" pager.

In views you can use the below php function and place it in header with php filter

<?php
global $pager_page_array, $pager_total_items, $pager_total;
$my_view = views_get_current_view();
$items_per_page = $my_view->pager['items_per_page'];
if ($pager_total[0] == 1) {
  echo t('Showing !pager_total_items results',
    array('!pager_total_items' => $pager_total_items[0])
  );
} else {
  $start = 1 + ($pager_page_array[0] * $items_per_page);
  $end = (1 + $pager_page_array[0]) * $items_per_page;
  if ($end > $pager_total_items[0]) $end = $pager_total_items[0];
  echo t('Showing !start-!end of !pager_total_items results',
    array('!start' => $start, '!end' => $end, '!pager_total_items' => $pager_total_items[0])
  );
}
?>

See the below is result


Migrate user password hash We are migrating our old site from plain PHP to Drupal 8. Passwords are hashed with MD5 in the old site; I need to migrate them in Drupal.

I tried the following code, but it takes the password as plain text and calculates its SHA hash.

public function prepareRow(Row $row) {
    $password = $row->getSourceProperty('user_password');
    $hash = \Drupal::service('password')->hash($password);
    $row->setSourceProperty('user_password', $hash);
  }

This is the configuration file.

id: users
label: User migration
migration_group: mymodule_general_migration_groups
source:
  plugin: mymodule_migration_users
process:
  pass: user_password
  mail: user_email
  init: user_email
  status:
    plugin: default_value
    default_value: 1
  name:
    plugin: dedupe_entity
    source: username
    entity_type: user
    field: name
    postfix: _
  created:
    plugin: callback
    source: created
    callable: strtotime
  changed: user_regdate
  access: user_regdate
  login: user_lastvisit
destination:
  plugin: entity:user
  md5_password: true
migration_dependencies: {}
dependencies:
  enforced:
    module:
      - mymodule_migration

Since you don't know the password, only the hash, you can't migrate it directly. (MD5 is weak, but not that weak.) The whole purpose of hashing is that the password should be unknown to anyone except the user. There are 2 solutions to this.

Reset all your users password and send a one-time-login password to them once they are migrated - as already suggested in the comments above.
Write custom code that rehashes the password at login: "If the password is hashed with MD5, rehash it and store the hash when the user (successfully) logs in." This works because at login you have the user's password because they just entered it. And you know which hashing algorithm is used from the stored hash.Initially, you migrate the users with the MD5 password hash.

It turns out that Drupal does rehashing automatically (see UserAuth::authenticate()), but not for MD5 unless you modify the  existing hash slightly by prefixing it with an "U". (Thanks, d70rr3s and  Souvik Das.) See also user_update_7000.


Theming comments in node.tpl.php How can i theming the comments like this in the node.tpl.php (with a new column after 3 comments)? I want to use this:

$cols = array();

$cols[] = '
' . t(`Kommentare`) . '
';

$comments = comment_render($node, $node->cid);
$comcolnum = 0;

foreach($node-cid as $comcol){
$comcolnum++;
$cols[] = '
' . $comcol['view'] . '
';
}

$cols[] = '
' . drupal_get_form('comment_form',array('nid' =>
$node->nid)) . '
';

print theme_table(array(), array($cols))

$node->comments, &comments or ... doesn`t work.
I think first i need to override the comment output in the template.php like this for Drupal 6:

function phptemplate_preprocess_node(&$vars) {
$vars['node']->comment = 0;
$vars['comments'] = $vars['comment_form'] = '';
if (module_exists('comment') && isset($vars['node'])) {
$vars['comments'] = comment_render($vars['node'], $vars['node']->cid);
$vars['comment_form'] = drupal_get_form('comment_form', array('nid' =>
$vars['node']->nid));
}
}

But! What i need to get every comment for the foreach function? I`m really new with PHP and Drupal API, but i want to learn it! Can someone show me the right way?

Greeting Bruno

Use MYTHEME_preprocess_node($vars) instead of MYTHEME_preprocess_page($vars) to get your declared variables in template.php to get in node.tpl.php.

I see you are already using template_preprocess_node(), so just put all those things which are intended for node.tpl.php in that function.


Search API - Search widget with Facet OR Exposed filters clean url I'm trying to create "Search API widget" using two exposed filters "search: Full text" + "taxonomy term: City"

The good example of what I want to achieve would be visible here:

http://olx.in/

Whenever you type in the city + full text search it generates the url such as:

http://olx.in/city-name/q-something/

However if I use exposed filters it doesnt seem to work in that way it creates links like this:

http://localhost/search?search_api_views_fulltext={something}&field_city={taxonomy-term-id}

When after I do the search I use facet filter with pretty paths it gives a bit better result:

 http://localhost/search/field_city/{name_of_region}/field_city/{name_of_region}/field_city/{name_of_sub_region}/field_city/{name_of_region}/field_city/{name_of_sub_region}/field_city/{name_of_city}search_api_views_fulltext=&field_city=1031

But I want the end result pretty much to look like this:

http://localhost/{name-of-city}/search-something

And after searching I want it to activate proper facets for the "field_city" so if after searching someone would want to add facet it would not create a {field_city}/{field_city}

And in order to do that, I was considering instead of using a "exposed taxonomy term filter" to use facet block for "Field_city" but no luck so far.

** Update 01.10.2015 **

I was doing research and I think that the "cities" and "categories" on OLX or any other decent portal are not actually facets or exposed filters, but they are Taxonomy pages with inherited search query.

So if someone types in "Exposed full text search api" a "Yorkshire terrier"
He is redirected to: http://localhost/search?search_api_views_fulltext={Yorkshire terrier}
And on left sidebar he have "Taxonomy menu block" with vocabularies of "small ads categories" with terms such as "animals"
He clicks on "animals" term and the search value follows him.
http://localhost/small-ads-categories/animals/search?search_api_views_fulltext={Yorkshire terrier}
Of course the taxonomy is a search api view
However I also would want to extend this by adding a second parameter which is "city" <- not sure how to do that

Another feature that I'm trying to figure out how to create a "select box" for a city that is not a exposed filter but a link parameter.

For example: if someone wants to search for: Yorkshire Terrier + he selects locations from select box to be: London

Normally it is done by creating exposed taxonomy filter - however it generates ugly url, the thing that I'm considering is using the value that is selected to redirect user to the proper search results page. so if he selects Yorkshire Terrier in london he is redirected to:

http://localhost/london/search?search_api_views_fulltext={Yorkshire terrier}

Where london is also a taxonomy search api url.

** update: few hours later **

After further thinking and trying to solve this issue, using taxonomy terms view block seems like a good idea, but it displays ALL possible terms not only the terms that are related to current search query and that I'm not sure how could I limit ?

This module should help you getting rid of ugly URLs when using exposed filters:
https://www.drupal.org/project/query_parameters_to_url

  ...

  An example of a dirty URL like that could be:
  example.com/events?field_category_id[0]=100&field_category_id1=101&field_author_name[0]=John

  Using this module you can transform the URL into:
  example.com/events/p/field_category_id/0__100--1__101/field_author_name/John

  Or an even shorter URL if you use the provided alter hooks:
  example.com/events/p/cat_id/0__100--1__101/name/John

  Isn't that a joy to look at?

  ...

Please refer also to this question to achieve the same thing writing your own module.


Can Nivo Slider change slides without any effects? I am trying to make the Nivo Slider module slide in between pictures without any effects. Is this possible from the Drupal admin section? Do I need to dive into code to do this?

Thanks!

If you select fade and make the fade occur in 1ms, then it will appear to change slides without any effects.


How to use fields of a flag instead of only toggling the flag? I have created a flag (using the Flag module) called status and a field to it and named it remarks. Now, how do I let users to flag other users and fill in the remarks field for that particular flag.

All I am able to do is toggle the flag.

I couldn't find any documentation on it and the complimentary module of flag called flagging form is obsolete.

When a user flags another user, I want a pop-up to appear asking them for remarks before flagging the user.

When configuring flag(s) (using the Flag module), you can indeed attach fields to them. However when doing so, make sure to also be aware about (and do) what is described in Attaching fields to flags, i.e.:

By default, Flags use the "JavaScript toggle" link-type. While this allows entities to be flagged without reloading the page, users cannot set any field values with the Flag. In order for users to set a Flag's field values, you must use the "Form" link type.
Navigate to Administration > Structure > Flags page. Click the Edit link for the Flag. Scroll down to the Display Options box and select the Confirmation Form radio button.


Render date field in custom format in tpl file In a content type tpl file I can print my date field with the following:

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

However I need a custom date format. So instead of something like this:
Sunday, June 9, 2013 - 16:50

I need to print:
June 9th Sunday

I cant change the default date formats site wide or the node's field, I need to just modify how its printed in this instance.

Ive solved it a different way. Ive created a custom date format and I can chose that as the display option for the field for a specific view mode.

/admin/config/regional/date-time/formats


How do I move a https site to localhost? I am moving a site from the live server where it has an SSL certificate and is accessed by HTTPS to my localhost. After moving the site over, I get an ERR_SSL_PROTOCOL_ERROR.

I am uncertain of how to fix the issue. I tried turning off Clean URLs before the move. And I also tried changing the .htaccess file.

As Kevin suggested in the comments, I did not have a local certificate installed. Using MAMP, I ended up following the instructions here to solve the issue.


How to change path that username points to I have basically disabled user accounts from being accessed, because I am using Profile2 module for user profiles. So there is no need to view the users account page. But in posts and forums in my site the username shows up by default and links to the user's account, not their profile. Is there a hook somewhere that I can use to have the user account path /user/uid, always point the the profile /main-profile/uid?

I know I can change the link in views, but I was looking for a site-wide solution. That will always make the username link to the profile. I'm thinking there has to be some hook I can use to redefine $user_path, but I can't figure it out.

You can use hook_menu_alter, it's not even too much work to do, just

anymodule_menu_alter( &$items)
{
    $items['user/uid'] = $items['main-profile/uid'];
}

clear cache and it will turns user/uid into nothing more than an alias of main-profile/uid.


My hooks are not invoked by Drupal I am developing a module, but the hooks I am adding are not invoked from Drupal. It happens with more than one hook.

I read the documentation for the hooks, and I cannot find anything that would explain why this happens. I verified I am using the correct parameters, and returning the correct value.

What am I doing wrong? Is there anything I am missing?

When developing a module, you should keep in mind the following notes.

The implementation of a hook done from a module is a function whose name is prefixed with the module short name (also called the machine name); from the hook name, take off the hook part, and replace it with the module machine name. For example, the implementation of hook_menu() done from example.module is example_menu(). If the module is example_menu.module, and the function is example_menu(), that is not considered the hook_menu() implementation for example_menu.module.
This also means, for example, that the hook_form_alter() implementation in example_form.module is not example_form_alter(), but example_form_form_alter(). As another example, the implementation of hook_form_FORM_ID_alter() done for altering the form returned from user_register_form() from example.module is not example_form_user_register_alter(), but example_form_user_register_form_alter(). (The form ID is user_register_form.)
Generally speaking, using uppercase characters in the module machine name doesn't create problems: PHP doesn't make differences between myModule_get_value(), and mymodule_get_value(), and $value = myModule_get_value() would call either myModule_get_value(), or mymodule_get_value().
Although, there is a case where using upper case characters in a module machine name would cause problems: when defining the update hooks for a module. drupal_get_schema_versions(), the function that returns a list of available updates, contains the following code.

// Prepare regular expression to match all possible defined hook_update_N().
$regexp = '/^(?P<module>.+)_update_(?P<version>\d+)$/';
$functions = get_defined_functions();
// Narrow this down to functions ending with an integer, since all
// hook_update_N() functions end this way, and there are other
// possible functions which match '_update_'. We use preg_grep() here
// instead of foreaching through all defined functions, since the loop
// through all PHP functions can take significant page execution time
// and this function is called on every administrative page via
// system_requirements().
foreach (preg_grep('/_\d+$/', $functions['user']) as $function) {
  // If this function is a module update function, add it to the list of
  // module updates.
  if (preg_match($regexp, $function, $matches)) {
    $updates[$matches['module']][] = $matches['version'];
  }
}

The last line executed from drupal_get_schema_versions() is the following one.

return empty($updates[$module]) ? FALSE : $updates[$module];

If the module name is myModule.module, drupal_get_schema_versions('myModule') will return just the functions with a name that starts with myModule_update, and ends with a number; functions like mymodule_update_7120() will not be included because the regular expression used from drupal_get_schema_versions() is case sensitive. This still applies to Drupal 8, as the regular expression is still the same used in Drupal 7.
Some hooks are called in specific moments. For example, hook_menu(), and hook_menu_alter() are called from Drupal 7 after a module has been enabled/disabled, or when the cache for the router information is cleared; hook_init() is not invoked for cached pages.
Once the hooks are invoked because a specific event happened, they will not called again until a similar event doesn't happen. They are not called in two successive page requests.
Drupal caches the list of hooks implemented from a module. If you are editing the code of an enabled module to add new hooks, you first need to disable and  re-enable the module, or Drupal will not notice there are new hooks.
Ensure that a return statement didn't sneak its way into one of your hook functions during a refactoring. It has the potential to break not only the hook that it appears in, but to cause a chain reaction that breaks other hooks as well, making the problem difficult to locate.


What does "Entity API" add to the Drupal API, and why would a module depend on it? The Entity API module extends the entity API defined in Drupal. In which cases should a module use the API provided from that module? Are modules that implement new entities easier to be written if they depend on the Entity API module?

By "easier to be written" I mean that modules using Entity API would require less code to be written compared to a module that doesn't use Entity API.

I read the project page, but I still don't completely understand the reason to prefer creating a module that depends on the Entity API module, rather than a module depending only from Drupal core code. I understand that a module extending rules and implementing an entity should use the Entity API module; in the first case, the reason is also that the Rules module depends on the Entity API module.

Not complete, but here are some advantages that I know of:

Drupal core only provides an EntityController for loading entities. For save, update and delete, you either need to write it yourself or use Entity API.
You you can expose the base properties of your entities wit hook_entity_property_info(), see privatemsg_entity_property_info() for an example. The advantage of this is that rules.module knows your entity properties and you read and write them with rules. And you also get token integration for free.
It can also automatically provide you with an administrative UI for your entities


$form_state['redirect'] vs drupal_goto() in Drupal 6 What is different between $form_state['redirect'] and drupal_goto() to redirect user to a step in multi step forms in Drupal 6 ? I used $form_state['redirect'] but no redirection happend so I use drupal_goto() .

$form_state['redirect'] is not well documented in 6, but my understanding is that when it's populated it will not always work (see the part about exceptions), so although that's documentation for 7, check that other elements of your $form_state are not interfering. If you are working with a multi-step form, it might be that you need to unset $form_state['storage'] first.

drupal_goto() is simply a function will take the user away from the current page to whatever path you specify, and has a bunch of extra features for doing extra things (see the documentation). It is actually called anyway when your form redirects.

When a Drupal form is submitted,$form_state['redirect'] overrides the default form redirect (which will take you to the form you've just submitted) and thus is calling drupal_goto() on your behalf. By putting it in a variable, you can ensure that Drupal handles, in the background, when to do the redirect, rather than you having to specify drupal_goto() directly and getting it wrong.


How do I replace part of a webform component label with a variable token? I have webform component labels like this:

Did [your pet] have any illnesses?

and I want to replace [your pet] with a variable token?

Do I need to write a custom module or can I do this by editing one of the theme .tpl files?

Tried this code as suggested:

<?php

/*
 * Implementation of hook_form_alter()
 */

drupal_set_message(t('Outwith the hook'), 'warning'); // display outwith the hook

function wit_bootstrap_form_alter(&$form, &$form_state, $form_id) {

drupal_set_message(t('Inside the hook'), 'warning'); // display within the hook

 // target my form / my field
  if ($form_id == "webform_client_form_1") {
    // target my form / my field

    if ($form['neutered']['#title']) {
        $title = $form['neutered']['#title'];
        $token_val = 'freelo';//get_tokenised_value(); // Which ever way you handle that...
        $title = str_replace('[your pet]', $token_val, $title);
        $form['neutered']['#title'] = $title;
    }
  }
}

hook_form_alter() should allow you to so.

Within your theme you should be able to do something like :

/*
 * Implementation of hook_form_alter()
 */
function my_theme_form_alter(&$form, &$form_state, $form_id){
  // target my form / my field
  if ($form_id == "my_form") {
    if ( $form['my_field']['#title'] ) {
      $title =  $form['my_field']['#title'];
      $token_val = get_tokenised_value(); // Which ever way you handle that...
      $title = str_replace('[your pet]', $token_val, $title);
      $form['my_field']['#title'] = $title;
    }
  }
}

Also check the forms api reference to see what things you can set / alter on forms.


How do I show a field value of a referenced field separately? I can not write english correctly and very well,I am sorry about this issue.please help me for solving my problem.

How do I show a field value of a referenced field separately with the Views or the Rules module?

I want to show only the referenced field value to visitors.for example :

I have a field (field_describtion) with label about you , So I want to reference to this field_describtion and when see the content field_describtion only show to visitors.
I add referenced field_describtion from a content type and after search on that field and select a field_describtion value when click on referenced field value linked to referenced node.BUT I want to after click on referenced field (referenced field_describtion) link to a page that show only field_describtion (with label about you) to visitors.

I any way to work with this idea ?

My drupal version is 7 and I used entityreference module.

I Think found the solution.

I Create a views and add a relation to entityrefence field , So in field of the view I can add another field of referenced content.

for example if we added reference field to users,in a view can add relation to that reference field (go to relations part of views settings) and add another user fields like email or user picture in our views (from fields part of the views settings).picture and email of referenced user show to ours.

Sorry for bad english typing.I hope solve problem of somebody.


CSV column with multiple values I'm trying to use the feeds module to import structured data from a CSV file and map the values to node. I'm having an issue with a CSV field that contains multiple values.

e.g.
ingredients['peanut butter', 'jelly',]

Is there a good way accomplish this with feeds, or would I be better off writing my own custom mapping engine module? I'd prefer to find a way to get the Feeds module to work to avoid having to spend excess time on something that is already done.

I spent a couple hours working on this, and it seems as soon as I posted the question I found an answer. The Feeds Tamper module will do the trick. It provides a lot of preprocessing functionality before the data is mapped to the entity fields. When configuring the data mapping, select the feeds tamper link. The explode plugin will explode the values into an array. Fields can have multiple values within an array map to a single field.

I hope that anyone else that has this problem finds this to save them some time.


Problem with Drupal Beauty tips module I am using Beauty tips module to show AJAX content on hover, But When first time it loads I am getting unexpected look. From second time onward I get correct look.

I have attached an image of the problem.

The code that I am using for this is :

$options['bt_drupal_help_page'.$nodeid[$i]] = array(
  'cssSelect' => '#rating_'.$nodeid[$i],
  'ajaxPath' => $base_url.'/average_rating',
  'ajaxData' => array('rating'=>$nodeid[$i]),
 //'ajaxLoading' => '<blink>Wait Until It Loads...</blink>',
  'ajaxType' => 'GET',
  'width' => 'auto',
  'height' => '1000px',
  'ajaxCache' => false,
  //'windowMargin' => 5,
   'cornerRadius' => 15,
  //'cssClass' => 'tooltip-box',
 //'cssStyles' => "padding: 2px",
 //'overlay' => true,
 'shrinkToFit' => false,
 'killTitle' => true,
 //'hoverIntentOpts' => '{interval:300,timeout:500}',
);

beautytips_add_beautytips($options);

Please let me know, whether I am doing something wrong?

Thanks in advance for the help.

It doesn't look like a problem with beautytips module, but instead a lack of styling that's causing the problem. You should be able to fix this with normal CSS.


How to reference existing term if it exists or create new one if not exist via Inline Entity Form module? I have a content type book and it has a taxonomy term reference field: author.

I want to enter name and surname separately for each author on node add/edit page. Name and surname together will be the taxonomy term.

If I enter John for the name and Smith for the surname the taxonomy term will be John Smith.

I'm doing this by using the Inline Entity Form module with the Automatic Entity Label module.

The problem here is: the Inline Entity Form has two options while entering the term:

Add new term
Add existing term.

If you don't know if the term exists or not it become useless.

What I need is only one option and if the entered [name + surname] exist then select it as author automatically and if that not exist create a new term.

How can I do this?

(Similar structure can be created with some different methods such as References Dialog module, Entity Connect module etc but the main problem exist there too.)

Note: This question is not a duplicate of "How to create a name-surname structure for taxonomy terms?" ... even though they use the same image. In this question the main point is "how to combine creating new term and choosing existing one options", in the other question "how to create a name-surname structure on node form" is asked.

This solution is a bit "out there" so I'll just describe the logic.

Three taxonomy fields. One for first name, one for last name (so there's autocomplete), one for full name generated by rules.
On node save, join the first+last as tokens and fetch term by property name. This will give a list containing one or no terms.
Two rules components that receive the list.
No. 1: condition, list is empty. Actions. Create term and send it back to the rule.
No. 2: condition, list is not empty. Actions. Send back the fetched term.
In the main rule, set data value on node, returned terms.

It's "out there" but that's because there are two fields for one term.


How to filter a view relating node and user data? I created a content type called Vouchers. This content type has a field called: Points.

In the other hand I enabled the http://drupal.org/project/Userpoints module which allows users to get points.

I created 2 Vouchers nodes. One of them has the value 10 for the Points field and the other one 15

After, I created a view to show the content type: Vouchers. Now I need to add a filter to show the vouchers node only if its Points field value is lower than the User points value (the current logged user)

Please, look my capture to make this understandable:

You can add the same filter programmatically to your view.

/**
 * Implements hook_views_pre_view().
 */
function YOURMODULE_views_pre_view(&$view, &$display_id, &$args) {
  if ($view->name == 'your_view_machine_name') {
    $info = array(
      'table' => 'field_data_field_points', // name of your “Points” field table.
      'field' => 'field_points_value', // name of value field in that table.
      'value' => array('value' => userpoints_get_current_points()), // dynamic part.
      'operator' => '<',
      'id' => 'field_data_field_points_YOURMODULE', // unique id.
      'group' => 100, // new group.
    );
    $handler = views_get_handler($info['table'], $info['field'], 'filter');

    $handler->init($view, $info);
    $view->display_handler->handlers['filter'][$info['id']] = &$handler;

    unset($handler);
  }
}

It will automatically join the table and add condition to query.


routing.yml for a custom form not working I have a form I'd like to use as a standalone page, which I'm defining in a module I've called "SREvent". I have created modules/srevent/src/Form/SREventListForm.php:

<?php
/**
 * @file
 * Contains Drupal\srevent\Form\SREventListForm.
 */
namespace Drupal\srevent\Form;

use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\srevent\Entity\SREvent;
use Drupal\field_collection\Entity\FieldCollectionItem;
use Drupal\field_collection\Entity\FieldCollection;

class SREventListForm extends FormBase {
    public function getFormId() {
        return 'srevent_list_form';
    }

    //used in getEvents()
    public $inactive = [];
    public $active = [];

    //function to get all appropriate entities
    function getEvents() {
        //....
    }

    /**
     * {@inheritdoc}
     */
    public function buildForm(array $form, FormStateInterface $form_state) {

        getEvents();

        //form builder logic

        return $form;
    }

    /**
     * {@inheritdoc}
     */
    public function validateForm(array &$form, FormStateInterface $form_state) {
        return;
    }

    /**
     * {@inheritdoc}
     */
    public function submitForm(array &$form, FormStateInterface $form_state) {
        return;
    }
}

In routing.yml, the route is as follows:

srevent.list_form:
  path: '/srevent/listform'
  defaults:
    _form: '\Drupal\srevent\Form\SREventListForm'
    _title: 'SREvent List'
  requirements:
    _access: 'TRUE'

There are other routing entries in this file as well, but none of those are giving me errors. I double checked for typos in the routing file as well as to make sure all indents are spaces and not tabs.

After flushing the cache repeatedly, /srevent/listform is still a 404.

This is how I set up all of my forms and have never seen this issue before, and every post I see on the topic tells me to set up exactly like this.

Is there something I'm missing? This is driving me crazy...

Try these steps one by one.

Keep calm.

1) Check you are in the correct domain in your browser

Ugh, I hate when this happens, wrong domain, lol.

2) Check you're uploading or committing to the correct environment

Download the file from the server to see if it indeed changed and make sure you're in the correct environment.

3) Check that your form (SREventListForm.php) is indeed inside the /Form folder.

Simplify your process

4) Back up your current module. Delete all the other routes except for the one that you're trying to dbug.

5) Simplify your form's code. Put some basic code in there.

6) Change your routes path


How to scale uploaded image in ckeditor I am using CKEditor, and am having a problem with the scaling of the images during edit.  When I upload and insert them into my editor, if the image is very large, it displays that way in the editor, making it very hard on the user.

I have formats defined for these image styles, which set the class attribute to a CSS class.

Is there a way to get images in the editor to adhere to the CSS of their format, so the page layout during edit resembles what it will look like after being saved?

In the latest version of the ckeditor library there is the new Enhanced Image plugin.
This plugin allows you to resize the inline image by dragging the image corner.
Go to ckeditor building website ( http://ckeditor.com/builder) and select the Enhanced Image plugin (image2) and also deselect the standard Image plugin from the build.


Access fields in views-view Twig template I'm trying to loop through rows in a views-view template, but I can't seem to kint or dump anything out to help me in doing so.

I've tried following various other answers, such as:

In Drupal 8 view.html.twig file how do I access the view content such as individual field title and/or field content?
How to get each field value in views-views-unformatted--view-machine-name.html.twig?

Again, without any success.

Usually I'd create a views-view-fields template, and access my fields via fields.title.content for example. I need to loop through them via the views-view template, as I'm needing to do some checks, taking into account values of some of the previous row's fields.

How can I access a rows fields when looping through rows in my views-view template?

In your case you should be using views-view-fields.html.twig instead of views-view-unformatted.html.twig file.

Views fields template will iterate on all rows of result. Your views-view-fields.html.twig should contain below code -

{{ fields.title.content

You can check the fields array by using kint function like - {{ kint(fields) }}

Check for image path and anchor path variable from output of kint function.

If you want to do this in views-view-unformatted.html.twig, then you can access the field values like below -

{% for row in rows %}
  {% set photo = file_url(row['content']['#row']._entity.field_page_photo.entity.fileuri) %}

{% endfor %}


How to display block to the nodes of specific content type? I have created a content type "test". I also created a block "Search". I like to display the block only to nodes of the content type.

I configure the block and under Show block on specific pages >  Only the listed pages > Entered

  test/*

. It did not work. How can I display the block only to the nodes of the "test" content type?

Thanks,
D

In the block configuration page, select the content type like this picture:


How to bring facebook connect button in login form? For one of my projects I installed the Facebook O Auth module in my site. Now I would like to display the Connect with facebook in my login form.

You have to alter both form using hook_form_alter and add a markup field with value fboauth_action_display('connect')

$form[fb_connect] = array(
   '#markup' => fboauth_action_display('connect'),
);


How do I create a route to a raw text file I'm working on a Drupal 8 module, and I would like to include a couple of text files, each of simulated json data, as examples. How would I include these files in my module and create a route in the module.routing.yml file that would tell Drupal that when a visitor comes to mysite.com/examples/json1 to just print the text file (json data) as-is?

There might be a clever solution for this, but a simple straight forward solution would be to:

Make a Controller and use that in your routes.
In the method on the controller, load the contents of the file (or just hardcopy it into your controller method)
Return a JSON response in your controller.

I haven't gone into details on how to code this, there are plenty of code examples and documentation on this on drupal.org


different drop down list for different nodes I am using drupal 7.10.I have a content type bank details which is for entering bank details like bank name,address,contact details etc.,Now for each bank i need a drop down list which shows a list of agents of that particular bank.Note this is for each individual bank node.need help on this.Thanks.

Views + Node Reference. Create new Views, that handle arguments of current node and filter agents by required bank.


How to programmatically set a Views display to override style options I am working on the Charts module and have a stubborn issue that I'm trying to resolve.

Charts provides a Views style plugin and a Views display plugin called Chart Attachment. The display plugin extends the Attachment display plugin and sets the View's format to Charts. However, I run into an issue where I really need the Chart Attachment's formatting settings to apply to its display only ("This chart_extension (override)"). If it applies to all displays, it ends up breaking the Chart because the whole idea behind the Chart Attachment is for it to be different than its parent.

Here is what the Format settings should look like immediately after clicking "Add" -> "Chart attachment" in the View displays section:

Note the italic font on Chart and Settings within the Format section.

When you click on Chart from that attachment, this is what you should see without clicking anything else:

So how can one code the Display plugin to enforce style format options to "This chart_extension (override)"?

Or, if there is another approach that accomplishes the same thing, I would be open to that.

This is how you can achieve that:

diff --git a/src/Plugin/views/display/ChartsPluginDisplayChart.php b/src/Plugin/views/display/ChartsPluginDisplayChart.php
index 3dbad31..68048ce 100644
--- a/src/Plugin/views/display/ChartsPluginDisplayChart.php
+++ b/src/Plugin/views/display/ChartsPluginDisplayChart.php
@@ -29,6 +29,10 @@ class ChartsPluginDisplayChart extends Attachment {
     $options['style_plugin']['default'] = 'chart';
     $options['inherit_yaxis'] = ['default' => '1'];

+    // Set the default style plugin to 'chart'.
+    $options['style']['contains']['type']['default'] = 'chart';
+    $options['defaults']['default']['style'] = FALSE;
+
     return $options;
   }

API docs:
https://api.drupal.org/api/drupal/core%21modules%21views%21src%21Plugin%21views%21display%21DisplayPluginBase.php/function/DisplayPluginBase%3A%3AdefineOptions/8.2.x


How to get available view modes per content type? I am looking for an function that returns all view modes per content type. I already tried to use mobile_theme_entity_view_mode_alter but this function will return all available view modes for a node entity. What I need are the available view modes per node type...

any suggestions?

You can use following function to get this information

$view_mode_settings = field_view_mode_settings($entity_type, $bundle);

example:

$view_mode_settings = field_view_mode_settings('node', 'article');


iPaper like module recommendation I am looking for a module that will enable me to upload and preview pdf files, word docs etc on the site. Something along the lines of http://drupal.org/files/images/screenshot_2.jpg. I would like it to be indexable and searchable on the site.

Any recommendations for the module that will allow me to achieve this would be greatly appreciated.

You can try Embedded Google Docs Viewer and check whether your requirements are fulfilled or not. Here is the demo of the module.

The Embedded Google Docs Viewer module adds a new formatter to the File field using the Field API. This formatter displays PDFs, Microsft Word documents, Powerpoint presentations, or Excel spreadsheets directly within a Drupal node.


External javascript that contains jQuery I have been asked to include an external js file into a site where I don't have direct access to modify it and the generated script has jQuery it that references $.

Is it possible to include this without modifying the source js file?

I've added it as below

drupal_add_js("www.domain.com/my.js", array(
      'type' => 'external',
      'scope' => 'header',
      'group' => JS_LIBRARY,
      'every_page' => TRUE,
      'weight' => -1,
    ));

But I get undefined errors due to the use of $

Cheers

One way to circumvent this would be by installing the jQuery Dollar module.

This would allow you to avoid $ conflicts.


JPG user photos not displaying in Drupal 7 In D7, when I upload a photo to a user profile page, the image displays if the original extension was a *.png file, but not if it was a *.jpg file. Uploading the files places them in sites/example.org/files/pictures, which indicates that the permissions are correct. But jpg files don't diplay on users' profile or forum posts. Instead the words "username picture" is displayed.

In admin/config/people/accounts, enable user pictures is enabled. However, I did not add a existing image field in admin/config/people/accounts/fields.

Basic page, articles and forum has an image field (field_image), with allowed extensions png, gif, jpg, jpeg.

"username picture" is likely the alt text applied to the image. So it's trying to render an image, but failing because the web server can't find it. If you check the page source, is it trying to show the image with a .png extension instead of .jpg? If not, is the path correct?

If either the extension or the path are wrong, this could be a problem with the template. Perhaps it was hard coded in the past and settings have changed since?


Why is my validate function not receiving the value of my form element? function mymodule_email_reviewers_action_form($context) {
  $form = array();
    $form['email_text'] = array(
        '#type' => 'textarea',
        '#name' => 'message'
    );
    $form['submit'] = array(
        '#name' => '',
        '#type' => 'submit',
        '#value' => 'Apply'
    );
  return $form;
}

function mymodule_email_reviewers_action_validate($form, $form_state) {
    $text = $form_state['values']['email_text'];
    dsm($form_state);
    dsm($text);
    dsm($form);
    if ($text == 'Email body' || empty($text)) {
        form_set_error('email_text', t('Please enter a message'));
    }
}

I'm not sure what might be wrong here. Neither the $form nor $form_state contain the text I enter into my textarea.

In the description for the "#name" attribute is reported the following text:

  INTERNAL, except for buttons. All button and submit elements on a form should have the same name, which is set to 'op' by default in Drupal. This does not apply to image buttons. For non-button elements, Drupal sets the name by using 'foo' in $form['foo'] as well as any parents of the element.

You should not set that attribute, which is considered internal.


Batch deleting nodes breaks database On my Drupal site, I have about 100 nodes that need deleting. I have deleted them via Views Bulk Operations.

When I do this, if I make a backup of my site MySQL database and then try to restore it via PHP My Admin, I get the following error:

INSERT INTO `cache_form` (`cid`, `data`, `expire`, `created`, `serialized`) VALUES
('form_state_form-0ry4vXadnLIroZBOuRNpM4WJWgNm0HNVumQ1bNHLEu4', 0x613a363a7b733a31303a226275696c645f696e666f223b613a333a7b733a343a2261726773223b613a323a7b693a303b4f3a343a2276696577223a35363a7b733a383a2264625f7461626c65223b733a31303a2276696577735f76696577223b733a31303a22626173655f7461626c65223b733a343a226e6f6465223b733a31303a22626173655f6669656c64223b733a333a226e6964223b733a343a226e616d65223b733a31313a2262756c6b5f64656c657465223b733a333a22766964223b733a313a2236223b733a31313a226465736372697074696f6e223b733a303a22223b733a333a22746167223b733a373a2264656661756c74223b733a31303a2268756d616e5f6e616d65223b733a31313a2242756c6b2044656c657465223b733a343a22636f7265223b733a313a2237223b733a31313a226170695f76657273696f6e223b4e3b733a383a2264697361626c6564223b4e3b733a373a2265646974696e67223b623a303b733a343a2261726773223b613a303a7b7d733a383a227573655f616a6178223b623a303b733a363a22726573756c74223b613a3130303a7b693a303b4f3a3[...]
MySQL said: Documentation

#1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '' at line 2

The error has been caused by deleting the nodes. If I go to an earlier back-up before the nodes were deleted, it works fine. However, everytime I delete the nodes, this error comes back.

How can I delete the nodes without the database becoming corrupt. I clear the cache after deletion and before backing up, but the problem still occurs.

Interestingly after deleting nodes, the size of the databse jumps from 16MB to 80MB. So I am not sure if the deletion is putting some bad data in the database.

You need to increase max_allowed_packets in my.cnf file. to insert big data from cache tables. The best practice to avoid this is, never export cache prefixed tables data.


upload picture and make it my css background-image I want to upload picture and make it my CSS background-image in Drupal? Is it possible?

Please reply if you know how thank you!

You can do something like this:

hook_node_view($node, $viewmode, $langcode)
{
  if(count($node->field_background_image) && isset($node->field_backround_image[LANGUAGE_NONE][0]['uri']))
  {
    $node->content['#attached']['css'][] = array
    (
      'type' => 'inline',
      'data' => '#some_div{background-image:url(' . file_create_url($node->field_background_image[LANGUAGE_NONE][0]['uri']) . ');}',
    );
  }
}


Which is the preferred way to change field content before rendered? I'm working on an existing Drupal 7 module in order to make it work with Drupal 8. And for a peculiar aspect of its operation I'm currently a bit lost.

Th problem is that I must be able to make some changes in content of any text field, everywhere throughout all contents, before they're rendered.

In Drupal 7 I solved it behaving as a formatter, which I "grafted" before any existing formatter.
You can look at this SO post (I didn't know Drupal Answers at this time) to see more precisely how it worked.

After reading a lot of Drupal 8 documentation (which is currently quite messy) I can't yet realize which is the preferred way to achieve what I want.
I noticed some candidates such as the hook_entity_view_alter(), but also services and/or plugins, but keep totally undecided.

So I look for some advices pointing me to the right way.

hook_entity_view_alter() is for altering the render array of an entity, that is coming out of a view mode. It is not for a single field and changes in this hook would have no effect, when using the field alone, for example in a view. Using this hook would be the answer to the question Which is the preferred way to change the display (view mode) of an entity, before it is rendered?

(When using this hook, don't digg to deep, you can only change the render elements in the top level. Not the referenced objects, they are only to get information, not to change the rendering)

But the question is to change the rendering of a field, you asked "everywhere throughout all contents" For this the right solution is a field formatter, this can be used everywhere in drupal, whenever a field is rendered, no matter if you define a display mode (aka view mode) of an entity or use the field in Views.

To make the picture complete, you can change a field twice while displaying content, first in a field formatter and the second time, when the whole content is build and this build array can be altered in hook_entity_view_alter()

In drupal 8 field formatters are no longer hooks, they are now plugins.

https://api.drupal.org/api/drupal/core!modules!field!field.api.php/group/field_formatter/8

The documentation does not help to setup this plugin. I would copy an example from core and put my own code in it, for example:

core\modules\datetime\src\Plugin\Field\FieldFormatter


How can I determine if a form exists in my Drupal installation? I have a form with a simple textfield where the user enters a string. I want to check if this string is a valid form_id in the website. I thought about using the drupal_get_form but even if it would work, it would be kind of an overkill to retrieve the whole form array just to check if it exists.

Any ideas are more than welcome.

Since the 'ID' you pass to drupal_get_form() is actually the name of a PHP function, the simplest way to see if it exists is using plain old PHP:

if (function_exists('form_id')) {
  // ...
}

If you need to check that the return from the function is a suitable Drupal form array, you'll need to use one of the methods described by MPD.

This will only work for forms for which the name is explicitly defined as the string you're passing in; i.e. forms whose root function is provided by a hook_forms() implementation will not match using this method.

It's worth bearing in mind that with whichever method you use, any form you're trying to identify will have to exist in a file that's included in the current page request. With that in mind it might be wise to keep all the form functions in question in the .module file of an enabled module, which will always be included.


Hook not getting called (image_title module) I'm attempting to use the image_title module to replace a node's title by an uploaded image.  I thought it was working, but I've since discovered that it was only showing for me, not for anyone else on the site. =(

In debugging, I inserted the following into the image_title_preprocess_page() function:

$fh = fopen('/tmp/myfile', 'w');
fwrite($fh,date('r') . " starting page\n");

and I've found that this hook isn't getting called for anonymous users.  I can't think of why that would happen.  I also don't know much about the process by which hooks are run, though.

Perhaps page caching is causing the hook not to be called?

EDIT: If I just bypass the web server & call php index.php directly, image_title_preprocess_page() does get called, but then it does a SELECT image FROM {image_title_menu} and it finds nothing relevant.  I have to wonder why it's using the 'page' hook instead of the 'node' hook in the first place though.  Maybe this module just plain doesn't work.

I'm using Drupal 6.22, and while I'm investigating this (and maybe after, too) I've got a github fork here: https://github.com/kenahoo/drupal-image_title .

Thanks.

Figured it out.  There was this crazy code in image_title_nodeapi():

function image_title_nodeapi(&$node, $op, $teaser, $page) {
  if ( !user_access('create image titles') ||
       (variable_get('image_title_'. $node->type, 1) == 0) ) {
     return; // do nothing ...
   }

Which meant people could only see the images if they could also create images.  Not real bloody useful!  Fixed here:  https://github.com/kenahoo/drupal-image_title/commit/a4458676e7a6d1e00839a3d0e02a9d6c4f01fe2c

Update: on Paul's advice I created a fork in the Drupal Sandbox area: http://drupal.org/sandbox/kenahoo/1411716 .  I'm probably going to delete the github.com project now.


Can't moderate content from "View Draft" page using Workbench Moderation I am using Panels Everywhere, and Workbench Access & Moderation.
I have gotten everything to work, but I haven't been able to figure out how to get the block above the content created, that allows the moderator to go from Draft > Needs Review (or another transition).

9:24 in at http://nodeone.se/node/1024

I can moderate the content from root/node/#/moderation, but can't on the webpage.

Seeing if someone has run into this before and can help me out.

Figured this out.  Was so easy it was hard...

Had to configure the "Workbench information" block and set it to "Content" region.  It then would show up above the content.  I also had to add the tags in the "Page elements" panel settings.

Hopefully this will help someone else out.


Adding an image upload table How is it possible to add an image upload table in the code of a custom module in Drupal 7?

In other words, I want to add the "Images Table" (the one with drag-able rows) to a custom form I'm creating in my custom module. And I need all it's options too, like thumbnail, title and description fields for each uploaded image row plus the remove button, with the ability to limit the number of uploaded images of course.

What is the code to be used to achieve that?

Thanks for your time and help in advance.

Image upload fields and drag & drop tables are two separate elements that you can combine in your module by using a form callback function to declare your fields and a theme function to theme the upload fields in a drag & drop table.

D7 Form API provides an upload field named 'managed_file'. The documentation provides a clear example:

<?php
// Use the #managed_file FAPI element to upload an image file.
$form['image_example_image_fid'] = array(
  '#title' => t('Image'),
  '#type' => 'managed_file',
  '#description' => t('The uploaded image will be displayed on this page using the image style choosen below.'),
  '#default_value' => variable_get('image_example_image_fid', ''),
  '#upload_location' => 'public://image_example_images/',
);
?>

Then you can have a look at the documentation to setup the field with your desired settings. This element does not have a #multiple setting. So you can either generate many fields, either add new fields using ajax as in cck in D6.

Finally you can check this documentation on how to use drupal_add_tabledrag();


How to setup the recipient email in the webform mail template file? I have overridden the webform mail(webform-mail-19.tpl.php) template in my theme.
The problem is I want to set the recipient in this template file so I used this code.
$email['email'] = 'example@example.com'
but it did not send email to this address instead it sends email to the email address which i setup in the email settings of the webform.

I print the $email array and I could see "example@example.com" email there but did not know why it sends the email to the default email address which is setup at the email settings of the webform.

Any Idea about this?

You cannot set the recipient in a template file, these files are only used for the theme layer. The templates only control the display of information.

The recipient email must be set on the settings page of the webform.


multilingual while adding content I have enabled the i18n module and created a taxonomy vocabulary with translated terms. In addition I have created a CT (content type) in which I've added a term reference field of this taxonomy vocabulary.

Is there a way while I'm authoring a new content of this CT to have to choose only among the user's current language terms? At this point I'm seeing a list of 10x3 (30) terms 'cause I got 3 languages, and that's a bit of chaos for the authors.

Thanks in advanced, I hope I've been clear

You can create a node reference view. Check this answer for more information:
Display language in entity reference field

You can either limit your entries in the reference field or show the language in every entry.


Getting all revisions of an entity with EntityFieldQuery I'm trying to get all revisions of an entity with EntityFieldQuery.

Here's my code:

function entity_hash_queue($entity_restrict = NULL) {
  if ($entity_restrict) {
    $entity_info = entity_get_info($entity_restrict);
    if ($entity_info['entity keys']['revision'] != NULL) {
      $query = new EntityFieldQuery;
      $query->entityCondition('entity_type', $entity_restrict);
      $results = $query->execute();
    }
  }
}

I'm trying to figure out what property of the EntityFieldQuery object I can use to ensure that it gets every revision of an entity (if that entity supports revisions).

I'm getting a list of all entity objects, but not each revision for each object. How do I go about getting that information? I can't find anything.

In this case, use db_select instead EntityFieldQuery to get all revisions from the revision table:

$result = db_select('your_entity_revision_table', 'yert')
    ->fields('yert')
    ->condition('entity_id', {your Entity ID})
    ->execute()
    ->fetchAllAssoc('revision_id');

kpr($result);


How can I create a view to display a secondary tab on a node? Using views I can create a page with the nid as context and place a primary tab alongside the "View" and "Edit" tab on a node. How can I move it to the seconday tab on the "View" page?

e.g. What I can get

What I need

Try adding a View page with path

node/%/view/secondary-task

Make it a "Default task" or "Default menu tab" in the View menu settings.


How to change sender email Id using hook_mail_alter How to change the sender email id for some emails, using hook_mail_alter. The default SMTP configured email ID is 'test@myfirstdomain.com'
The subject gets altered correctly using the hook_mail_alter, however, the email which I receive is still from the default configured email 'test@myfirstdomain.com'.
function test_mail_alter(&$message) {
 switch ($message['key']) {
  case 'activation':

    $from = "test@myseconddomain.com" ;
    $message['from'] = $from;
    $message['headers']['From'] = $from;
    $message['headers']['Sender'] = $from;
    $message['headers']['Return-Path'] = $from;
    $message['subject'] = 123;
    break;
}

}

According to the documentation:
/**
 * Alter an email message created with MailManagerInterface->mail().
 *
 * Hook hook_mail_alter() allows modification of email messages created and sent
 * with MailManagerInterface->mail(). Usage examples include adding and/or
 * changing message text, message fields, and message headers.
 *
 * Email messages sent using functions other than MailManagerInterface->mail()
 * will not invoke hook_mail_alter(). For example, a contributed module directly
 * calling the MailInterface->mail() or PHP mail() function will not invoke
 * this hook. All core modules use MailManagerInterface->mail() for messaging,
 * it is best practice but not mandatory in contributed modules.
...

Can we check if the mail is sent MailManagerInterface->mail() like this and not any other way.