Add HTML5 required attribute to webform fields set as required Could someone advise me how to use a hook to add the HTML 5 required attribute to all inputs that have been selected as 'required' within webforms.

Webforms already adds class 'required' but the HTML 5 required attribute provides great instant validation in Opera, Firefox and Chrome browsers.

You will need to create a module for this.
Note that, this answer assumes you need to set required attribute on all form elements which are required in web form settings.
you will need to implement a different hook and/or add conditions to make this strict.

Create a file named webform_formalters.info and put following to it.

name = webform form alters
description = a collection of custom form alters for webforms.
core = 7.x
package = Custom
dependencies[] = webform

Create another file named 'webform_formalters.module' and put following in it.

<?php
/*
 * implements hook_form_BASE_FORM_ID_alter.
 */
function webform_formalters_form_webform_client_form_alter(&$form){
  //dsm($form);
  foreach ($form['submitted'] as &$field){
   if (is_array($field) && isset($field[#required]) && $field['#required'] == 1){
     //dsm($field);
     $field['#attributes']['required'] = 'required';
   }
  }
}

Put both files to a folder named webform_formalters and upload to your site's module folder and enable the module. See if it works.

Unlike other forms, web forms' fields are stored in $form['submitted'] array. So we go through each item (which should be an array of form definitions) and check if the element has marked as required.
if so, we add or merge required attribute. We are altering an existing form, so we are not going to pop out existing attributes.

Good luck!


Having problems with OpenLayers in Drupal 7 I had some issues with a site I'm building so I decided to start over with a fresh Drupal install... but when I install/enable OpenLayers I get this ugliness http://pastebin.com/XJYy76n1

I have absolutely no idea what can this be and it's been driving me a little crazy for the past couple of days.

Any ideas?

Edit: for some additional incomprehensible info, I just enabled the test suite and ran it against the openlayers module and got the following: http://pastebin.com/MHdtHxNm

The errors you are seeing, are mostly harmless. PHP on your server is configured to be very strict, which is a good thing, and the Openlayers have previously not been very strict about the coding standards.

I haven't looked specifically at the errors you are seeing, but when I've seen similar issues, I've almost always found the problem fixed in the dev version.

As no-one is actively maintaining the module, there is not likely going to be  a new release any time soon. You're best option is probably to try dev, and report the issue if that doesn't help.

The ugly workaround is to turn down strictness on the error reporting on your php install.

You can also give the less feature rich but newer Leaflet module a try.


can we use one argument for two contextual filters can we use one argument for two contextual filters OR
can we create and pass dynamic argument from one filter to another by using validation php code in first one?

drupal7.com/location-map/region-or-type-field-here

i want to use contextual filter for region and type fields for same argument.

You should be able to set "WHEN THE FILTER VALUE IS NOT AVAILABLE" on the contextual filter to "Provide Default Value" and set "Type" to "Raw value from URL" and set the Path component, in case of example provided in your question, Path component 0 is location-map and Path component 1 is region-or-type-field-here


set default timezone, date first day and date format medium via drush Is there is away to set :

default timezone
date first day
date format medium

via drush instead of doing it via drupal web interface ?

There is no specific command to set default value. You need to set those variables using drushcommands.

For Drupal 7 version you can use below commands.

To set default timezone you can use

drush vset date_default_timezone 'Europe/London' -y

To set date first day you can use

drush vset date_first_day 1 -y

I hope this helps..  :)


How to merge two forms (with separate purposes) and have one submit? Problem

I'm trying to combine two forms. A custom form and the user register form. I want the user to be able to fill in both and submit them together. How would I do this?

CONTEXT: The custom form creates a node, but you have to be logged in to do it. To lower the barrier I want users to be able to create the node and register on the same screen.

(Ideally the user register form won't appear if they're logged in.)

So Far

I tried calling two forms on the page but they have different submit buttons.

function postajob_page_callback() {
    $build = array();

    $build['form_one'] = drupal_get_form('postajob_form');
    $build['form_two'] = drupal_get_form('user_register_form');
  return $build;
}

So I called the user register validate and submit handlers in the custom form validate and submit calls.

function postajob_form_validate($form, &$form_state) {
     user_register_validate($form, $form_state);
     ...
 }

function postajob_form_submitform, &$form_state) {
     user_register_submit($form, $form_state);
     ...
 }

This calls the function but because the form doesn't contain any of the fields (i.e. username, email, password etc.) it  throws a horrible error:

Notice: Undefined index: administer_users in user_register_submit() (line 3824 of C:\XAMPP\htdocs\drupal5\modules\user\user.module).
Notice: Undefined index: pass in user_register_submit() (line 3827 of C:\XAMPP\htdocs\drupal5\modules\user\user.module).
Notice: Undefined index: mail in user_register_submit() (line 3838 of C:\XAMPP\htdocs\drupal5\modules\user\user.module).
Notice: Undefined index: #user in user_register_submit() (line 3840 of C:\XAMPP\htdocs\drupal5\modules\user\user.module).
Warning: Creating default object from empty value in entity_form_submit_build_entity() (line 8009 of C:\XAMPP\htdocs\drupal5\includes\common.inc).
PDOException: SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry '' for key 'name': INSERT INTO {users} (uid, created, data) VALUES (:db_insert_placeholder_0, :db_insert_placeholder_1, :db_insert_placeholder_2); Array ( [:db_insert_placeholder_0] => 165 [:db_insert_placeholder_1] => 1379868880 [:db_insert_placeholder_2] => a:6:{s:16:"ckeditor_default";s:1:"t";s:20:"ckeditor_show_toggle";s:1:"t";s:14:"ckeditor_width";s:4:"100%";s:13:"ckeditor_lang";s:2:"en";s:18:"ckeditor_auto_lang";s:1:"t";s:17:"mimemail_textonly";i:0;} ) in drupal_write_record() (line 7166 of C:\XAMPP\htdocs\drupal5\includes\common.inc).

So I tried to merge the forms using info from here and I added the following two lines of code just before the submit button in the form.

function postajob_form($form, &$form_state) {
      ....

     $extra = user_register_form($form, $form_state);
     $form = array_merge($form, $extra);

     $form['submit'] = array(
       '#type' => 'submit',
       '#value' => t('Submit'),
      );

    return $form;
}

This adds the form but seems to break the submit button and both submit buttons call the user_register submit not the custom form submit. Any ideas?

Instead of using custom form you can add fields.
Go to
Administration » Configuration » People » Account settings

And In the manage fields tab u can add  fields you want.

You can check the commerce_auto_product_display module tar files which has used similar functionality of adding nodes to the already built form


How to easily create a landing page for contents with specific tag I'm building an intranet portal for a non-profit organization I work in, and currently figuring out how to make it easier for my colleagues to build a landing page that displays all contents tagged with x. For example, if they create a landing page called Jobs, all contents tagged with jobs will be updated on the Jobs page.

Think of it similar to OpenAtrium where you could create a section, then upon creating a content you could choose which section it will get automatically posted to.

Currently this is doable by:

1) Users creating a tag (i.e 'jobs'), then creating a view to pull all contents tagged with jobs. But this means I will have to give them permission to taxonomy, views, and page manager. Plus, the steps and interface are too daunting.

2) Using Panopoly module, I can easily add a 'content list' pane that can choose between different content type. Unfortunately it doesn't have an option to filter by tags. Is there any way to include this?

Is there a better way to do this?

You can still do this easily with view panes. They play very nicely together with panels.

First step is to create the vocabulary you want to use / filter on. Then create a view pane with this vocab as an (exposed) filter.  By exposing this filter when a user adds this view pane to a panel, that exposed filter becomes a pane configuration option.  You can even expose content type as a filter and the user can choose what content types and terms they want to filter on when they add the pane.


Omega theme is not adding livereload.js I'm setting up Omega 4 using SASS / Compass for the first time, I have:

Linux VM running apache and guard
Windows machine for code editing and browser

Whatever I do I cannot find livereload.js in the page source.

Guard is running fine
I have cleared the cache several times
I can view the script at ip.ad.dr.ess:35729/livereload.js and at my_site.com:35729/livereload.js in my browser
I've tried changing the settings at admin/appearance/settings/my_theme to various different things but I don't think that makes a difference if the script is not included in page source

Any gems of wisdom would be greatly appreciated.

Livereload will only be added to the page if the Drupal instance can reach out to the livereload.js specified.  Note that loading it in your browser (remotely from the server) is different than Drupal loading it from the machine.  Drupal is running under Apache as a process on the machine.  What it sounds like is Drupal/Apache/PHP cannot access the settings you have in Omega.

If you are familiar with Linux command line.  Log into the machine and attempt to load the livereload.js file using wget from the machine using the exact URL you are using in Omega. If you do not get a return, you have found the problem.


Show only nodes that are connected via entity reference with views I am trying to create a simpler version of Organic Groups as I don't need most of it's functionality. What I am trying to do is use entity reference, nodeaccess_userreference and nodeaccess_nodereference to duplicate the bulk of what OG does.

At the moment I am trying to create the view to show all content types content that is linked to a "group" content type.

Content types:

Group

Link

Text Post

(basically reddit.com!)

Fields:

field_group - entityreference to group content type attached to link and text post.

field_shortname - textfield with a shorter name for group (no spaces, alphanumerical, etc..)

Views:

Format: Unformatted List

Page: /g/% <---so I can use group name or shortened name to access group page

Relationships:

Entity Reference: Referenced Entity to field_group (required)

Contextual Filters:

Content: Title

Content: Field_shortname

Content: NID

(all requiring relationships to Entity Reference)

This way if some one goes to /g/Long-Group-Name-Blah-Blah /g/Shortername or /g/3 they will all point to the correct group page and show the link and text post content type content.

I can sort of get it to work if I just use Content: NID as the contextual filter. But I would like to be able to use the group name or shorter version in the URL as well. It also stops working as soon as I add 2 contextual filters.

Any help on getting this to work.

Thanks

Contextual filters work combined (AND), so if you define two or more contextual filters, all of them have to pass.

Here's what I would do.

Use Pathauto to create a pattern for your group content, e.g. g/[node:nid].
Create additional aliases for long name and short name.
Make your view work with just the NID contextual filter and use the block display type.
Configure your block to only show up on group node type and place it in main content.

Alternatively, you can also use Panels to create a similar node page for group nodes. To create the additional URL aliases for each group, you might want to try NodeSymLinks module.


How to modify account page adding possibility for a user to chose one of 2 roles I have Drupal 7 installed on my WAMP localhost.
I need to add a widget to the account page to allow users to chose 1 of 2 roles (recruiter or applicant). Having chosen one role the user cannot switch back to the other again.
For particular reasons I do not consider possibility to chose role DURING registration.

I have read and searched a lot on this subject recently but have not yet found the solution.
I understand it can be done with the help of hook_form_alter() in a module? Then I need to update the users_roles table

Could you please guide me a bit through the code  or tell me where I can find some examples.

Thank you.

Meanwhile I moved on -  I have created the module with hook_form_alter().
The 2 radiobattons show up on non admin user's page (see attached screenshot).

The code is missing saving to the database and probably validation is also required - I dont know where to go yet.
Looking forward to your comments/corrections of the below code which is far from being professional.

<?php
/*
 * Implements hook_form_alter().
 */
global $user;
if($user->uid !== 1) {
function testpwd_form_alter(&$form, &$form_state, $form_id) {
#   krumo($form_id);

    switch ($form_id) {
        case 'user_profile_form' :

// Adding radiobuttons
            $form['account']['roles']['#type'] = 'radios';
            $form['account']['roles']['#title'] = 'Role';
            $form['account']['roles']['#weight'] = -20;
            $form['account']['roles']['#access'] = true;
            $form['account']['roles']['#default_value'] = '';
            $form['account']['#access'] = true; /*without this Roles do not show up on autheticated
            user's profile page. I think after setting it to TRUE access for the nested elements has also
            changed to TRUE. I need to check what changed and set access to False for some nested elements.  */

            $form['account']['current_pass']['#access'] = false; /*see comment 1 line above.
            Not needed on this page as for changing passwords users are directed to Master site
            (2 sites joined with Bakery sso module).*/

            $form['account']['roles']['#options'][115362423] = 'applicant';
            $form['account']['roles']['#options'][100482362] = 'recruiter';

//To hide Roles options appeared. Where hide() does not work I used unset()
            unset($form['account']['roles']['#options'][30037204]); // admin
            hide($form['account']['roles'][2]); //auth users
            unset($form['account']['roles']['#options'][139881272]);
            unset($form['account']['roles']['#options'][29617163]); //content admin

            krumo($form);

//nice print of arrays
            echo '<pre>', print_r($form, true), '</pre>';
        break;

    }
  }
}

The drupal module Auto Assign Role allows you to do this (users can select during registration, not afterwards).

The module name is a little misleading because although one of its features is allowing for automatically assigning roles to users, another of its features is to allow users to select a role for themselves.


Is it possible to return a form element AND an ajax response from the same ajax callback function? I have an ajax callback function that needs to return a form element and also an ajax response. Is it possible to do both?
In my callback I need to set and return something like:
$form['fid'] = array(
  '#type' => 'textfield',
  '#value' => 1,
);
return $form['fid'];

And also something like:
   $response = parent::uploadAjaxCallback($form, $form_state, $request);
   return $response;

Is there a way that I can achieve return both a form element and an ajax response?
EDIT: Latest attempt is returning the form element for display but when I examine the $form from the form build function the value is still empty.
class MyManagedFile extends ManagedFile {

  /**
   * {@inheritdoc}
   */
  public static function uploadAjaxCallback(&$form, FormStateInterface &$form_state, Request $request) {

    $response = parent::uploadAjaxCallback($form, $form_state, $request);

    $form['fid'] = array(
      '#type' => 'textfield',
      '#prefix' => '
',
      '#suffix' => '
',
      '#value' => '1',
    );

    $response->addCommand(new ReplaceCommand('#fid', $form['fid']));
    return $response;

  }

}

Examining the $form from the form builder (dpm($form)) results in:
[fid] => Array
(
[#type] => textfield
[#prefix] =>
        [#suffix] =>

    )

If you want to do more than simply return new markup, then your response should be an instance of Drupal\Core\Ajax\AjaxResponse, to which you can append one or more AJAX commands via the addCommand() method.
A simplified version of this would be:
use Drupal\Core\Ajax\AjaxResponse;
$response = new AjaxResponse();
$response->addCommand(new ReplaceCommand('#my-wrapper-id', $form['fid']));
return $response;

I recommend checking out a tutorial, such as one of those below, for more information on using AJAX with FAPI:

https://www.sitepoint.com/using-ajax-forms-drupal-8/
https://www.drupal.org/docs/drupal-apis/ajax-api/core-ajax-callback-commands


Redirect from route when the controller has been changed I'm trying to redirect to an external URL in a custom controller whenever I land on the 404 page.

Right now I alter the controller destination in a route subscriber like this:

public function alterRoutes(RouteCollection $collection) {
  if ($route = $collection->get('system.404')) {
    $route->setDefaults([
      '_controller' => '\Drupal\test\Controller\TestController::test',
    ]);
  }
}

This is my controller:

public function test() {
  return new TrustedRedirectResponse('https://google.com', 307);
}

Right now my controller redirects to the frontpage when I try to redirect.

I could fix this problem by calling $response->send() but that is not a good idea since I'm bypassing the http-kernel call stack that way.

How can I redirect from the 404 page?

With the help from @4k4 I found a solution.

I created an event subscriber that extends the HttpExceptionSubscriberBase class. There I created the redirect like this:

public function on404(GetResponseForExceptionEvent $event) {
  $response = new TrustedRedirectResponse('https://google.com', 307);
  $event->setResponse($response);
}


How to add fields to menu items I need to build a main menu that is a subset of the regular menu. The design team thinks it would be better for user to have only the most important links in the main menu and not have everything. Some links are top level menu and some are sub menus. For this I was hoping to be able to add a field to the menu link item form as a drop down. When creating a link the user could use this dropdown to "promoteToMainMenuAsBigLink" or "promoteToMainMenuAsSmallLink" or leave none to not show the item on the main menu.

I'm looking for a similar solution as this Drupal 7 solution but for Drupal 8.

I was hoping to be able to add a column in the table menu_link_content_data beside 'expanded'. I was hoping not to have to record this information in an other table like shown in the d7 solution.

I was able to add a field to the link form in a custom module I build, just for test purpose I only added a text field to start with:

custom_menu.module:

function custom_menu_form_alter(&$form, FormStateInterface $form_state, $form_id) {
  if($form_id == 'menu_link_content_menu_link_content_form') {
    $form['promoteToMainMenu'] = array(
      '#type' => 'textfield',
      '#title' => t('Promote to main menu'),
      '#description' => t('Promote link menu to main menu.'),
      '#default_value' => '',
      '#weight' => -9
    );
  }
}

The field is indeed shown in the link form but it is never recorded.

Can someone help me with this?


Reorder Content Types in ("/node/add")? In drupal 7 it can be do like this. 7 - Reorder Content Types in ("/node/add") - Drupal Answers

How can I reorder Content Types with Drupal 8?

Drupal 8 doesn't respect the menu structure anymore when displaying the node types. Node types have no weight concept, so there is no direct way to control this.

What you could do is to implement a template/preprocess for node_add_list/node-add-list.html.twig and then reorder the types in code.


Multistep information collection with reference to price addition or substraction As I have posted previously, I was trying to built product kit with customization option. But there is no easy solution for that and diving into the coding using drupal commerce or ubercart need understanding of those module first.

So I reviewed the requirement again and saw, checkout is not required. I just have to declare the product kit & gather the information...

Have a look here on this link - Customize Your Laptop

I have to declare package like this. Where there would be default price for kit which will be sum of all default product. Every kind of product, there would some other option either in radio or checkbox and at time of going through step by step user can give their input and total price would change accordingly.

I will tell you the options which I have till now -

Webform (But the reference price change would be an issue)
Quiz (Same problem)
Form API (Client can't create package from them-self that is the main criteria behind this application)

Can I have some suggestion from someone, like what can be my roadmap or which module can help me with it by some tweaking or their API?

If you dont want the shopping aspect of the site then I would do the following.

Create the content types called the product.
Add a field with a drop down with the different steps (Processor, RAM etc)
Add a field to add the price.

Create a custom module with formAPI to call these values and do the needful.

Multistep forms would be the way to go. With Ajax to give it some flare.

You can download the example module to see how the form APIs work. The examples you would want to check would be the form example and ajax example


Changing the key/value pair of a field list in Drupal 7 once content has been added to the site I have a field list on my content type that I need to edit. Specifically I just need to change one of the key/value pairs. Unfortunately there's already content in the site so I can't just change it in the admin interface (it gives me an error that there are already records that use this).

I'm looking through my database (mysql) and I can't even find where the key/value pairings are stored. I can see the keys being attached to my nodes and can manually change them there, but that doesn't solve my underlying problem.

So my question is two-fold:

1) where is the table to edit field lists for a content type?

and

2) what's the preferred way to change a field list key/value pairing once content has been added to the site (too much to delete and start from scratch)?

Thanks!

In future use taxonomy for the list. That way you can add/edit to the list without any problems. Lists should be used for things that are constant, like the seasons of the year etc.

Use MySQL Workbench (assuming you are using MySQL). Open the table 'field_config' and do a select on it.

Look for your field in question. It's data is a blob. Right click on the blob and select 'Open Value in editor'. Select text.

You will see something like this:

  a:7:{s:12:"translatable";s:1:"0";s:12:"entity_types";a:0:{}s:8:"settings";a:2:{s:14:"allowed_values";a:2:{i:1;s:3:"one";i:2;s:3:"two";}s:23:"allowed_values_function";s:0:"";}s:7:"storage";a:5:{s:4:"type";s:17:"field_sql_storage";s:8:"settings";a:0:{}s:6:"module";s:17:"field_sql_storage";s:6:"active";s:1:"1";s:7:"details";a:1:{s:3:"sql";a:2:{s:18:"FIELD_LOAD_CURRENT";a:1:{s:21:"field_data_field_list";a:1:{s:5:"value";s:16:"field_list_value";}}s:19:"FIELD_LOAD_REVISION";a:1:{s:25:"field_revision_field_list";a:1:{s:5:"value";s:16:"field_list_value";}}}}}s:12:"foreign
  keys";a:0:{}s:7:"indexes";a:1:{s:5:"value";a:1:{i:0;s:5:"value";}}s:2:"id";s:1:"6";}

You can see under allowed values I have two list entries:

1 => one

2 => two

To add 3 => three I change this bit:

"allowed_values";a:2:{i:1;s:3:"one";i:2;s:3:"two";}

To this:

"allowed_values";a:3:{i:1;s:3:"one";i:2;s:3:"two";i:3;s:5:"three";}

a:2 changed to a:3 as it is the count of values in the list

i:3 indicates the new key

s:5 is the string length of the word three

Then hit apply in the edit box, and hit apply in the SQL window and you are done.

So you don't want to add a new value, but edit an existing one. Use same process as above, but just edit the allowed_values, then run an SQL update on your two tables for the field : 'field_data_XXX', 'field_revision_XX' to update old key to new key.


Get IP of the Author only I use this solution for now which works great: It's with Computed fields, and I use this line: $entity_field[0]['value'] = ip_address();

So basically what it does, it's when a user submits a new node, it also attach his IP address to the node, which is great.

The problem is that if another user decides to edit the node, the IP field is being updated with the editors IP. Which is bad.

The IP should be printed only of the author of the node. And no matter how many other IPs edits the node, those should be ignored.

So, I was thinking maybe there was possible to do this by editing the PHP line or am I looking in wrong direction?

Another option is to use Rules on new content creation then run the php code.

  The Rules module allows site administrators to define conditionally
  executed actions based on occurring events (known as reactive or ECA
  rules). It's a replacement with more features for the trigger module
  in core and the successor of the Drupal 5 workflow-ng module.

EDIT:

Enable the module 'PHP Filter'
In Rules, use the 'After Saving New Content' React on Type - this will trigger each time content is published for the first time
Optionally, add a condition Restrict by Type, choose the content type in which you want this to appear
Add a new action 'PHP: Execute custom php code' with your own code


Anyone knows a good tutorial to learn how to create install profile? I just want to create an 'install profile'.

Anyone knows a good step-by-step tutorial to learn how to create install profile starting from a production site?

Thanks

Developing installation profiles covers the majority of install profiles, well worth a look at to get started.

There is a how to guide here as well.


How to implement Page not found (404) for unpublished content? On my site, some nodes are unpublished forever instead of being deleted. I'd like to return Page not found (404) for anonymous trying to access unpublished node pages instead of Access denied (403). It's not about displaying a different message to the user, but rather about returning the 404 error code (important for bots).

So I've added the following to my module:

function mymodule_init() {
global $user;

  $normal_path = current_path();
  $parts=explode('/', $normal_path);
  $nid_part = $parts[1];
  $node = node_load($nid_part);
  if (!isset($node)) {
    return;
  }
  if (($node->status == 0) &&
    ($node->nid == $nid_part) &&
    ($user->uid == 0)) {
    drupal_not_found();
  }
}

But I still get Access denied as anonymous user on unpublished pages. How to implement it?

You should be able to do it with Rules:

  The Rules module allows site administrators to define conditionally
  executed actions based on occurring events (known as reactive or ECA
  rules). It's a replacement with more features for the trigger module
  in core and the successor of the Drupal 5 workflow-ng module.

Using Rules...

Event: Content is being Viewed (by content type if you desire)

Condition: Content is Published, Negate

Event: Redirect to custom 404 page

This requires that you set up a custom 404 page, but most people do that anyways, and core takes care of everything else.

Specify 403 and 404 error pages for more info on setting up a custom 403 and 404 page


Is it possible to do a Drush make custom installation profile? Is is possible to make a selective Drush Make file?

For example:

The site has 3 modules, with 3 library files.

A normal drush make will give me all modules and files.

But it is possible to selectively, fetch some modules and files?

For example: fetch module 1 and file 1 but not 2 and 3?

You can use the OPTIONAL ATTRIBUTES

root_element[first_key][next_key] = value

  The 'projects' attribute is where you define the modules/themes that
  are to be packaged with the profile. The first key is the short name
  of the project (as seen in the drupal.org/project/{projectshortname}
  URI).

  These projects are defined using the short form definition. You can
  use this form if you only want to declare the version of the
  project. The version is the value to the right of the core Drupal
  version in a full version string. For example, if you wanted to
  specify Views 7.x-3.1, you would use:

projects[views] = 3.1

  For pre-releases, like CTools 7.x-1.0-rc1, use this format:

projects[ctools] = 1.0-rc1

  You can also specify -dev releases of projects; however, this is
  generally NOT recommended, since it results in end users getting
  different sets of files at different times that distribution is
  built, which can cause confusing bug reports. If you really must use
  a -dev release, it's better to specify a Git revision (see below).

projects[media] = 2.x-dev

Reference

Full example drupal-org.make file.
Managing Drush make files for an installation profile.


Make Wysiwyg Use CKEditor CDN Is it possible to make the Wysiwyg module use the CKEditor's CDN for delivering the editor to the browser client?

If all you're using the wysiwyg editor is for ckeditor, you can use the ckeditor module instead.

  This module will allow Drupal to replace textarea fields with the
  CKEditor - a visual HTML editor, usually called a WYSIWYG editor. This
  HTML text editor brings many of the powerful WYSIWYG editing functions
  of known desktop editors like Word to the web. It's very fast and
  doesn't require any kind of installation on the client computer.

you can tell ckeditor to use the CDN in the Advanced settings of the Global Profile:


Adding Fivestar rating each item in a view containing most recent stories? I'm using the Fivestar module (drupal.org/project/fivestar) and was just wondering if it is possible to add it to a view of my most recent stories. Basically, I want it to appear below each item in the view so users can both view it and use it.

Adding the Fivestar widget to your views is pretty simple:

Add the relationship Node: Vote Results
Add the field Vote Results: Value
Choose how you wish to display the widget by changing Appearance: to either Fivestar Stars (clickable, with text) or Fivestar Stars (clickable, no text)
Click "Update" and save your view


How to send HTML email I am creating a simple module which will be sending HTML emails to users for deals in our website.

I have searched a lot, but I can't find a solution proper solution for Drupal. Now I can send mails but plain text.

What is a step-by-step procedure to send HTML emails in Drupal 7?

function example_form_submit( $form,&$form_state) {
    $friend_email=$form_state['values']['friend_email'];
    $mailto =$friend_email;  //gift to a friend
    $mailfrom ='no-reply@example.com';
    $subject = "another message for  HTML email from example.com";
    $body="
Hello EMAIL, i here i want to be bolded
";
    if (drupal_mail('example', 'send_gift', $mailto, language_default(),$params,$mailfrom,TRUE)) {
        drupal_set_message(t('Your gift was sent successfully!!!'));
    }
    else {
        drupal_set_message(t('Error occured while sending your mail!!!'));
    }

/****hook_mail*/
function example_mail($key,&$message,$params) {
    $language = $message['language'];
    switch ($key) {
        case 'send_gift':
            $message['subject']=t($params['subject'], $var, $language->language);
            $message['body'][]=$params['body'];
            $message['headers']['Content-Type'] = 'text/html; charset=UTF-8; format=flowed';
        break;
    }
}

Like geoff mentioned one option would be to use the Mime Mail module, but you can also enable your custom module to send HTML e-mails with some extra code. In short you'd need to alter the mail_system variable and write your own implementation of MailSystemInterface. An example of that is the following code.

Inside 'mymodule.install':

function mymodule_enable() {
  $current = variable_get('mail_system', array('default-system' => 'DefaultMailSystem'));
  $addition = array('mymodule' => 'MymoduleMailSystem');
  variable_set('mail_system', array_merge($current, $addition));
}

function mymodule_disable() {
  $mail_system = variable_get('mail_system', array('default-system' => 'DefaultMailSystem'));
  unset($mail_system['mymodule']);
  variable_set('mail_system', $mail_system);
}

Inside 'mymodule.module':

class MymoduleMailSystem extends DefaultMailSystem {
  public function format(array $message) {
    $message['body'] = implode("\n\n", $message['body']);
    $message['body'] = drupal_wrap_mail($message['body']);
    return $message;
  }
}

You'd have to replace mymodule instances with your actual module's name then disable and re-enable your module to get the variable changed after which things should be working. For a complete example you can check out my answer here. Additionally this page on drupal.org is from where I originally got all the information from.


Country based city list selection I can use hierarchical select module but it contains lot of manual work in entering data. I want for all countries their city list. How to do it ?

Is there any module which helps to show city list based on a country selection? Is there a custom way to do it? thanks in advance

You can use the Address Field module.  To do just the country and city, you will have to define a plugin.  Look in the addressfield/plugins/format directory for examples.

To add the cities, you will have to define a list of cities for each country in the plugin.  You can then format the list and add it to your plugin and you should be good to go.

One advantage of using the Address Field module is that if you do not define a list of cities for a country, users will still be able to input the city themselves.


Taxonomy term custom menus I have a site with different sections for separate projects.  Some of the sections are just a single page with a project summary, but others are more involved with several pages.  All the pages are created via a content type "projects."  I have a term reference field in the content type in order to categorize which pages belong to which project.

What I'm trying to do is have a menu automatically generate for all the pages that belong to a specific project.  I've found ways to create menus of terms, but I can't find a way to make a menu of nodes using the term.

Any ideas?
-JB

you should create a view which display only the nodes related to the current term. You'll have to play a bit with contextual arguments but it works. The simple way is to add a contextual argument to the term field.


Rewriting a field in organic group member view I am not sure if this is possible..

My organic group 'member view' filters all the members of a particular group.
I have created the view so that the first member gets listed in a sidebar to become a link  'members' pointing to the complete member list for the current group.

The same view is used for a different grouptype.
So the first member gets listed as a link as well.
However with this grouptype i want my 'first member link' to be 'rewritten' as 'friends' instead of 'members'

Can this be done with one view?

I have tried using two fields to display rewriting one as 'members' and the other as 'friends'. Without succes i tried finding a proper relationship for them....

Help appreciated.

did you try https://www.drupal.org/project/views_conditional?

it allows to conditionally format/rewrite the output of certain views fields depending on the value of other fields that you have added in your view.


How to programmatically link commerce products to taxonomy terms I'm trying to link existing commerce products to an existing taxonomy term in Drupal 7:

$products = commerce_product_load_multiple($pids);
foreach($products as $product){
    $product->field_some_option[LANGUAGE_NONE][0]=$tid; //the taxonomy term id
    commerce_product_save($product);
}

This doesn't work.

Typically when I assign the taxonomy term to the product via the admin pages it adds an entry to a database table called field_data_field_some_option, which contains the product and term id. When I use the above code, a new entry is again made in the table, but the term id is set as NULL.

Note that I'm trying to link commerce products, not product displays, which as far as I understand means I can't use the typical node-taxonomy linking approach.

Anyone know how to get this working, short of bypassing Drupal APIs and editing the database directly?

You're close, but need to tweak setting the field value to:

$product->field_some_option[LANGUAGE_NONE][0]['tid'] = $tid;

For the taxonomy term reference field uses the 'tid' key there.

You could also do it with a metadata wrapper like:

$wrapper = entity_metadata_wrapper('commerce_product', $product);
// Append to existing field value
$values = $wrapper->field_some_option->raw();
$values[] = $tid;
// Set field values
$wrapper->field_some_option->set($values);
$wrapper->save();


Add 2 filters for a single field in views I am writing a view code for my module, stuck with writing 2 filters for a single field.

 $data['taguser']['tag_uid'] = array(
    'title' => t('Tagged user'),
    'field' => array(
      'handler' => 'taguser_views_handler_field_user_name',
      'help' => t('Display the user name the Item has been assigned to.'),
      'click sortable' => TRUE,
    ),
    'filter' => array(
      'handler' => 'taguser_views_handler_filter_user_options',
      'help' => t('Filter Action Items by the assigned user.'),
    ),
    'argument' => array(
      'handler' => 'views_handler_argument_user_uid',
      'help' => t('Filter Acton Item by the assigned user.'),
    ),
    'relationship' => array(
      'help' => t('Relate a case to the user who have been assigned to the case.'),
      'handler' => 'views_handler_relationship',
      'base' => 'users',
      'base field' => 'uid',
      'label' => t('Assigned to'),
    ),
  );

i want another filter for this field like

'filter' => array(
  'handler' => 'taguser_views_handler_filter_user_options_list',
  'help' => t('Only limited user.'),
),

how can i add to it ??

It depends on your version of views, best way is to create the view in views and then export it, you can then tweak the code as needed.

Here is an example if you had a Node Type Filter and a Date Filter

/* Filter: Node: Type */
$handler->display->display_options['filters']['type']['id'] = 'type';
$handler->display->display_options['filters']['type']['table'] = 'node';
$handler->display->display_options['filters']['type']['field'] = 'type';
$handler->display->display_options['filters']['type']['value'] = array(
  'rfp' => 'rfp',
);
/* Filter: Date: Date (node) */
$handler->display->display_options['filters']['date_filter']['id'] = 'date_filter';
$handler->display->display_options['filters']['date_filter']['table'] = 'node';
$handler->display->display_options['filters']['date_filter']['field'] = 'date_filter';
$handler->display->display_options['filters']['date_filter']['operator'] = '>=';
$handler->display->display_options['filters']['date_filter']['value']['min'] = '2012-01-01 00:00:00';
$handler->display->display_options['filters']['date_filter']['value']['max'] = '2012-01-01 00:00:00';
$handler->display->display_options['filters']['date_filter']['exposed'] = TRUE;
$handler->display->display_options['filters']['date_filter']['expose']['operator'] = 'date_filter_op';
$handler->display->display_options['filters']['date_filter']['expose']['label'] = 'Date: Date (node)';
$handler->display->display_options['filters']['date_filter']['expose']['identifier'] = 'date_filter';
$handler->display->display_options['filters']['date_filter']['expose']['single'] = TRUE;
$handler->display->display_options['filters']['date_filter']['date_fields'] = array(
  'node.changed' => 'node.changed',
);


Parsing form submitted values - D7 Could anyone please point out where I might be doing something wrong? I can't seem to capture the form values to manipulate them when this form is submitted.

   function admin_score_table_block_view($delta = '') {
      //The $delta parameter tells us which block is being requested.
        switch ($delta) {
            case 'admin_score_table':

                $block['subject'] = t('Admin Editable Score Table');
                $block['content'] = '';
                global $user;

            $form = drupal_get_form('admin_scores');

            $block['content'] = $form;

        break;
    }
    return $block;
}

function admin_scores($form) {
  if ($node = menu_get_object()) {
        $node = node_load($nid = $node->nid);

        $programmetmp = $node->field_sportevent_cd;
        $programme = $programmetmp['und'][0];
    }

    $form['#tree'] = 1;

    $result = db_query("SELECT cdt.entity_id AS nid FROM field_data_field_team_corpdec AS cdt WHERE cdt.field_team_corpdec_nid = " . $programme['nid']);
    foreach($result as $row){
        $team = node_load($row->nid);

        $form[$team->nid]['nid'] = array(
            '#type' => 'hidden',
            '#value' => $team->nid,
        );
        $form[$team->nid]['team'] = array(
            '#type' => 'textfield',
            '#value' => $team->title,
            '#title' => 'Team',
            '#attributes' => array('class' => 'field-team'),
            '#name' => 'team[' . $team->nid . ']'
        );
        $form[$team->nid]['score'] = array(
            '#type' => 'textfield',
            '#value' => '',
            '#title' => 'Score',
            '#attributes' => array('class' => 'field-score'),
            '#name' => 'score[' . $team->nid . ']'
        );
    }

    $form['submit'] = array(
        '#type' => 'submit',
        '#value' => 'Save scores',
    );

    return $form;
}

function admin_scores_form_submit($form, &$form_state){
    var_dump($form_id);

}

Your form is called admin_scores() but your submit function is called admin_scores_form_submit()...this isn't Drupal's naming convention so your submit handler will never be executed.

Either change the name of your submit handler:

function admin_scores_submit($form, &$form_state) {

}

Or add your non-standard submit handler in the form itself:

$form['#submit'][] = 'admin_scores_form_submit';

Also the signature you're using for your form function is slightly wrong, in Drupal 7 it's like this:

function admin_scores($form, &$form_state) {


Subscribing to events calendar updates I've implemented an events calendar to my drupal 7 site. How would I offer the option for users to subscribe for event calendar updates?

A couple of options, for example:

Provide an RSS feed of the calendar events.
Provide email notifications with something like http://drupal.org/project/subscriptions


Drush rsync and drupal composer wrong destination dir I'm trying to sync two D8 sites. Both set up with drupal composer which means that the directory structure is a bit different than usual. Composer puts drupal files inside web sub directory like this:

/var/www/drupal8
|-- composer.json
|-- composer.lock
|-- drush
|-- scripts
|-- vendor
`-- web
    |-- autoload.php
    |-- core
    |-- index.php
    |-- modules
    |-- profiles
    |-- robots.txt
    |-- sites
    |-- themes
    |-- update.php
    `-- web.config

My aliases file looks like this:

<?php

$aliases["local"] = array (
  'root' => '/var/www/drupal8/web/',
  'uri' => 'http://local.site',
);

$aliases["remote"] = array (
  'root' => '/var/www/drupal8/web/',
  'uri' => 'http://site.example.com',
  'remote-user' => 'dev',
  'remote-host' => 'site.example.com',
);

When I do drush rsync @remote @local I end up with all files from @remote/web inside @local/web/web like this:

/var/www/drupal8
|-- composer.json
|-- composer.lock
|-- drush
|-- scripts
|-- vendor
`-- web
    |-- autoload.php
    |-- core
    |-- index.php
    |-- modules
    |-- profiles
    |-- robots.txt
    |-- sites
    |-- themes
    |-- update.php
    |-- web
        |-- autoload.php
        |-- core
        |-- index.php
        |-- modules
        |-- profiles
        |-- robots.txt
        |-- sites
        |-- themes
        |-- update.php
        `-- web.config
    `-- web.config

I can't edit aliases to remove web sub dir from root path because then drush will not work as it will complain that it needs a higher bootstrap level to run (because it won't know where is drupal root folder).

How can I instruct drush to use proper destination path for synchronisation?

I had the same problem took me ages to find out what was wrong.
Turned out to be the slash (/) behind the root folder that was missing.

self.site.yml

remote:
  host: domain.com
  user: user
  root: /home/user/public_html/
  uri: http://domain.com

@see https://unix.stackexchange.com/questions/402555/why-add-a-trailing-slash-after-an-rsync-destination

Turned out to be a bug in drush
https://github.com/drush-ops/drush/pull/3405


Show Related Terms Block Not Nodes Hello i have been trying for many a moon to create this View and i cant go on any longer its destrying my life (honest)

I want to show Related Terms (not content) on my taxonomy/term/* page. Example.

White Setter and Black Setter are both in a dogs vocabulary. I have 'related' them via the
taxonomy/term/*/edit-term page.

I want to create a block view that will show Black Setter on the White Setter page and vica versa. I have tried every relationship and every argument with no success at all. Does anyone know if this is possible to make?

Relationships
Taxonomy: Related terms
Arguments
Taxonomy: Term ID

Thanks

Before i post i see that i have asked ths on other peoples posts (and one of mine) they where never resolved. People keep talking about adding nodes in the view but i was wanting to use a term View.

As your requirement is to create a block that will show Black Setter on the White Setter page and vica versa, there is another simple way to achieve this.  The function taxonomy_get_related() will do this.

Create a block with input format as php and use above function to print related terms by passing current page term id. Then assign the block to particular region. The following snippet will works,

for eg:

 <?php
    $termid = arg(2);
    $terms = taxonomy_get_related($termid, $key = 'tid');
    //print_r($terms);
    foreach($terms as $term){

       $link = url('taxonomy/term/'.$term->tid);
       echo ''.$term->name.'';
     }
  ?>


Recurring Payment Reminder email I am selling some monthly basis services like website hosting. And I like to get prepaid payment for every month. So, how do I send email to my clients for notification by email to give payment for coming recurring date?

For example - A client purchase a digital service from our website in 5th of Jan. Next recurring payment date should be 5th Feb. So, I like to send recurring payment reminder before 15 days, then before 10 days (if not paid), then before 5 days (if not paid), then in the recurring date i.e. in 5th Feb.

I have install drupal 7, commerce recurring framework module, rules, rules scheduler. Currently I am stuck with how to send periodic email to my client for recurring date, after they have initially pay for the services?

Is this module is perfect for this - https://www.drupal.org/project/datereminder. I think this module - https://www.drupal.org/project/uc_recurring is not sending email reminders. Specially I am looking for email reminders which will work with commerce recurring framework.

So, how can I do this?

You can do this by using Rules module.

  The Rules module allows site administrators to define conditionally
  executed actions based on occurring events (known as reactive or ECA
  rules). It's a replacement with more features for the trigger module
  in core and the successor of the Drupal 5 workflow-ng module.

How to Send Follow-Up Emails Using Rules Scheduler in Drupal 7 ?


Have Google Analytics code still run on force download When you click on a download link (my_download/download/agent/%/week/%) that I have set up dynamically for each user it runs some logic and downloads a file.

I was thinking that I could just check Google Analytics to see how many people downloaded the file but the data is not there.  Does anyone have any idea to have it force download like I have set up and run Google Analtyics?

/**
 * Implements hook_menu().
 */
function my_module_menu() {
  $items['my_download/download/agent/%/week/%'] = array(
    'title' => 'Download',
    'description' => 'Download File.',
    'page arguments' => array(3, 5),
    'page callback' => 'my_module_file_download',
  );

  return $items;
}

/**
 * Download file.
 *
 * @param string $agent_id
 *   Agent number.
 * @param string $date
 *   Date string.
 *
 * @return string
 *   Force file to download or give error.
 */
function ea_email_requote_agent_file_download($agent_id, $date) {
  $file_name = my_module_agent_file_name($agent_id, $date);
  $file = "/mypath/$date/$file_name";

  if (file_exists($file)) {
    // Transfer to browser download.
    drupal_add_http_header('Pragma', 'public');
    drupal_add_http_header('Expires', '0');
    drupal_add_http_header('Cache-Control', 'must-revalidate, post-check=0, pre-check=0');
    drupal_add_http_header('Cache-Control', 'private');
    drupal_add_http_header('Content-Type', 'text/csv');
    drupal_add_http_header('Content-Disposition', 'attachment; filename="' . $file_name . '";');

    readfile($file);
    drupal_exit();
  }
  else {
    drupal_set_message('File has not been loaded yet.', 'error');
    return '';
  }
}

For that kind of thing, you can use the GA "event tracking" to track the click event for the file download.

  Events are user interactions with content that can be tracked independently from a web page or a screen load. Downloads, mobile ad clicks, gadgets, Flash elements, AJAX embedded elements, and video plays are all examples of actions you might want to track as Events.

The GA module provides some click event tracking for files by default in the config, else you can check here for more info on adding such a feature:

https://developers.google.com/analytics/devguides/collection/analyticsjs/events


How do I get rid of  tag in manually created block? I'm trying to remove a <p> tag from a manually created block. This block only contains an image and nothing else. I have kpr() function outputting block variables but am not seeing where, or how the unnecessary <p> tag is being generated.

Would the modification occur in theme_preprocess_block function? It seems it's not possible to get rid of within the block template file.

Another thing is that my tried was getting turning on themes info, clicking the element in hopes of finding some override function, but themer_info only shows me block info instead of some function info.

Any help would be greatly appreciated, thank you.

It's in fact because of the text input format. Going to admin/config/content/formats and removing the checkbox for

Convert line breaks into HTML (i.e. <br> and <p>)

for the input format you're using should do the trick (re-save the block, of course). Also, if you use WYSIWYG editor, it could do some formatting for you and put the image in <p> tag.


Drupal Time field for hour:minute:second.tenth of a second Is there a drupal field type to represent time for athletics sports events. e.g. for 100m sprint: 10.42 seconds but for 800m 1:40.89 (1 minute, 40.89 seconds)
In the format : hour:minute:second.tenth of a second

No time field will give you what you are looking for. They all work with Unix time, which is defined as 'the number of seconds since midnight, January 1, 1970'. The maximum granularity you will see is one second.

If you wish to record this information to one one-hundredth of a second, you will need to define the field and its formatting yourself.


Drupal 7 "Page not found. The requested page "/" could not be found" after enabling module While enabling a module (Imagecache External), Drupal showed an error related to memory limit, then the site crashed. I'm unable to login anymore, since any page shows now:

  Page not found. The requested page "/" could not be found.

I get the same result when I try to go http://www.example.com/index.php?q=user.

phpinfo() says mod_rewrite is enabled.

After extensive research I managed to solve this issue. The following info was helpful:
https://www.drupal.org/node/262892

What I did:

Disabled the problem module in the system table in SQL, by setting
the status field of the suspect module to 0 in the {system} table.
Rebuilded Database menu system to get access again, by running update.php. The update.php by default don't allow to access, so I need to edit settings.php (located in /sites/default/) and change
$update_free_access = FALSE; to TRUE. After rebuilding menu remember
to change this back to FALSE.


selecting hierarchical select values during migration I want to select the values of a taxonomy which is being shown by heirachical select. These values are to be selected while importing the data through csv by  using migration module.
right now i am passing the values but it not picking up the hierarchical select list.
Any help would be useful..
thanks

Dunno why my last message has been deleted but well I founded the answer alone :
In order To make it work, you have to pass an array of values containing the terms tid values and their parent's tid.
You might have to use a callback that retrieve the parent tid from the children one.

I am migrating contents from drupal 6 to 7, not from a csv, but I've declared a static function containing the mapping between the old tids and the new ones like so :

public static $hierarchicalThemesToTheme1TidsMap = array(
  '1'     => array('tid' => '13', 'parent' => '0'),
  '1797'  => array('tid' => '14', 'parent' => '13'),
  '14993' => array('tid' => '15', 'parent' => '13'),
  '1801'  => array('tid' => '16', 'parent' => '13'),
  '59'    => array('tid' => '17', 'parent' => '13'),
  '1795'  => array('tid' => '18', 'parent' => '13'),
  '1796'  => array('tid' => '19', 'parent' => '13'),
  '1798'  => array('tid' => '24', 'parent' => '13'),
  '1799'  => array('tid' => '23', 'parent' => '13'),
  '1811'  => array('tid' => '42', 'parent' => '0'),
  '1812'  => array('tid' => '42', 'parent' => '0'),
  '1813'  => array('tid' => '42', 'parent' => '0'),
  '1800'  => array('tid' => '20', 'parent' => '42'),
  '1802'  => array('tid' => '21', 'parent' => '42'),
  '1803'  => array('tid' => '22', 'parent' => '42'),
  '1804'  => array('tid' => '18', 'parent' => '13'),
  '1805'  => array('tid' => '18', 'parent' => '13'),
  '62'    => array('tid' => '25', 'parent' => '0'),
  '1806'  => array('tid' => '26', 'parent' => '25'),
  '1807'  => array('tid' => '27', 'parent' => '25'),
  '64'    => array('tid' => '28', 'parent' => '25'),
  '1808'  => array('tid' => '29', 'parent' => '25'),
  '1809'  => array('tid' => '30', 'parent' => '25'),
  '61'    => array('tid' => '32', 'parent' => '0'),
  '1723'  => array('tid' => '33', 'parent' => '32'),
  '1724'  => array('tid' => '34', 'parent' => '32'),
  '1725'  => array('tid' => '35', 'parent' => '32'),
  '1726'  => array('tid' => '36', 'parent' => '32'),
  '1727'  => array('tid' => '37', 'parent' => '32'),
  '1728'  => array('tid' => '38', 'parent' => '32'),
  '1729'  => array('tid' => '39', 'parent' => '32'),
  '1730'  => array('tid' => '40', 'parent' => '32'),
  '1731'  => array('tid' => '41', 'parent' => '32'),
  '1810'  => array('tid' => '43', 'parent' => '13'),
  '4401'  => array('tid' => '44', 'parent' => '13'),
);

I had to do that because we didn't use migrate for the taxonomies. I guess there's a better way if you had use migrate to import your taxonomies.

Then I've declared a callback which use that static array to retrieve the tids and their parent tid :

public function getHierarchicalThemeByTids($tids) {
  $mapped_tids = array();

  foreach($tids as $tid) {
    $mapped_tid = FOMigration::getMappedId(self::$hierarchicalThemesToTheme1TidsMap, $tid, NULL);
    if($mapped_tid !== NULL) {
      $mapped_tids[] = $mapped_tid['tid'];
      if (!in_array($mapped_tid['parent'], $mapped_tids)) {
        $mapped_tids[] = $mapped_tid['parent'];
      }
    }
  }
  return $mapped_tids;
}

Finally I just tell migrate he has to use that callback to get the values :

$this->addFieldMapping('field_types', 'field_theme')->callbacks(array($this, 'getHierarchicalThemeByTids'));
$this->addFieldMapping('field_types:source_type')->defaultValue('tid');


Custom block created with GUI stripping some  tags, not all of them I am creating a custom block in D8; the block includes the following HTML:

  Donate Now
  Connect With Us
  Menu

I have saved the block using the Full HTML format and placed it into the header region, here is a screenshot of what is added to the page:

I have disabled JS and re-loaded the page to make sure nothing else was happening.  Here is a screenshot of the edit screen:

There was a similar question recently and the problem was CKEditor, could be the same here.

If you want to be sure that your markup is not altered in any way, create a text format without ckeditor and use that.


How to programmatically load a rendered view exposed filter block I'm in Drupal 8 trying to load a Views Exposed Filter block based on its ID, similarly to how I would load a content block.

$bid = 'exposedformview_nameview_display_name'; // Found on mysite.test/admin/structure/block/manage/exposedformview_nameview_display_name/
$block = \Drupal\block_content\Entity\BlockContent::load($bid);
$render = \Drupal::entityManager()
        ->getViewBuilder('block_content')
        ->view($block);
return $render;

Nothing ends up printing out, and in the error log I see this message:

  Recoverable fatal error: Argument 1 passed to Drupal\block_content\BlockContentViewBuilder::view() must implement interface Drupal\Core\Entity\EntityInterface, null given

Sure enough, when I debug($block), it shows NULL.

I know this works for other blocks created in the content placement area, not sure why it wouldn't also work for views exposed filter blocks.  They are both available for placement in the manage blocks page.

EDIT: It seems as though it will not be possible to load the block like this.  This method depends on revisions being available for blocks.  There is no revision for a views exposed filter block so there must be another way to accomplish this.  Perhaps by loading the form directly.

The block content entity is not the block entity that is required there.

The actual block entity is a configuration entity. Use the \Drupal\block\Entity\Block::load method to load it.

Try the following:

$bid = 'exposedformview_nameview_display_name';
$block = \Drupal\block\Entity\Block::load($bid);
$render = \Drupal::entityTypeManager()
        ->getViewBuilder('block')
        ->view($block);
return $render;


Best option to upgrade Drupal 6 Video field to Drupal 7 I'm trying to update a Drupal 6 site to Drupal 7.

I'm trying to move a video CCK field to Drupal 7. If I try to move to a video field, I get a message telling me there is not way to migrate.

How can I upgrade Video from 6.5.2 to Drupal 7.2.7?

For the video module there is no any direct migrate path even though it is CCK field, so what you have to do is use Migrate module. Just create a Views that output all the videos as XML in D6 site and use that XML input in D7 site to create new video nodes. This may need some additional effort but ultimately this will be really smooth approach.


How do I display a field that's set to "Hidden" by the content type in the template? I have an existing site where a bunch of the fields are set to Hidden in the Display fields for the content type. I don't want to change that because I'm not 100% sure how that will affect other aspects of displaying the page.

When I do a var_export($node, TRUE) I can see the field values are present in the node, they just aren't being rendered in $content.

Can I use hook_nodeapi() to change the field display to "Default" or "Trimmed", etc?

$node->content will be a string containing the generated HTML output of the node's fields that will be displayed.

In hook_nodeapi() the $node->content is already generated, but you can append the hidden field's value to it if needed, with something like this:

function mymodule_nodeapi(&$node, $op, $a3 = NULL, $a4 = NULL) {
    switch($op) {
        case 'view':
            if($node->type == "mytype") {
                $node->content .= "<div>".$node->field_myfield[0]['value']."</div>";
            }
        break;
    }
}


Excerpt of Search API index is cached I'm using the search_api extension (V 8.x-1.14) with the Database search (no solr, etc.)

I use the search block which is created by the search view (/search path)

I want to show the highlighted excerpts which are setup in the Manage processors for search index  (/admin/config/search/search-api/<x>/content/processors)

In the view I select Rendered Entity as show format and chose search result hightlighing input in the settings.

Everything works fine now, but ...

Consifer I have a page About us with this sentence written somewhere on the page.

  'We will deliver your quality product on time and safely at the location of your choice.'

When the user searches for time, this page will be hit and the correct highlight will be shown

  We will deliver your quality product on time and safely at the location of your choice.

Now this excerpt is cached and when I search for quality the excerpt stays the same with the wrong word highlighted.

  We will deliver your quality product on time and safely at the location of your choice.

I deactivated the cache of the view, but it didn't change anything

Thanks to berramou!

I ended up using this in my theme:

/**
 * Implements hook_preprocess_HOOK().
 */
function MYTHEME_preprocess_node(array &$variables) {
  if ($variables['view_mode'] == 'search_result') {
    $variables['#cache']['max-age'] = 0;
  }
}


I can't get the og_group_ref set in a node form rendered via a custom block My block code is as follows:

mymodule_block_info() {
  $blocks = array();
  $blocks['my_contenttype_form_block'] = array(
    'info' => t('My CustomContentType Add Form'),
    'cache' => DRUPAL_CACHE_PER_PAGE,
  );
  return $blocks;
}

function mymodule_ui_block_view($block_name = '') {
  global $user;
  switch ($block_name) {
    case 'my_contenttype_form_block':
  module_load_include('inc', 'node', 'node.pages');
  // Create a node for the content type.
  $node = new stdClass();
  $node->uid = $user->uid;
  $node->name = (isset($user->name) ? $user->name : '');
  $node->type = 'my_contenttype';
  $node->language = LANGUAGE_NONE;

  $block = array(
    'subject' => t('Create New CustomContentType record'),
    'title' => t('Create New CustomContentType record'),
    'content' => drupal_get_form('my_contenttype_node_form', $node),
  );
    break;
  }

  return $block;
}

The "Groups audience" field is missing. It shows up in the standard add page (mysite.com/node/add/my_contenttype).

I've tried setting this programmatically via hook_form_alter, and also by setting the $form_state['values']['og_group_ref'][0], but nothing seems to work (although it makes sense that these approaches are failing when the field isn't even in the form.

Thanks in advance for the assist!
Any thoughts as to why it's missing?

For the benefit of others, I realized the user was not a member of the child group they were trying to add content to. They were members of the parent, but that didn't allow them to add content to the child group in question, so permissions didn't propagate as expected. There is an OG subgroups module (https://drupal.org/project/og_subgroups) which is supposed to help with this, but I wasn't able to configure it correctly for some reason before realizing that this particular application required the user to be a member of the subgroup in order for them to actually post.


URL redirects within drupal 7 site breaking image display in blocks I am developing a drupal 7 site where 4 pages have url redirects from a parent page within the site. I have a block in the footer that is shown on all pages but the 4 pages mentioned above do not display the image within that block. I'm thinking that it must have something to do with the redirects as it is only these 4 pages that don't display the image. All other pages with that block show the image up just fine.

Well, this image will play nice only if you are in your homepage or something and then the relative path is as: http://site.com/sites/default/files/footer-get-in-touch.png

Off course this won't play for other paths as this is invalid

http://site.com/<PATH>/sites/default/files/footer-get-in-touch.png

Quick Solution:

Enable php filter module, to be able to write php inside the blocks contents and provide correct image path for all cases

<?php
    global $base_path;
?>

    <img src="<?php echo $base_path; ?>sites/default/files/footer-get-in-touch.png" alt="" width="250" height="291" />


Leverage browser caching issue I added some lines in my .htaccess file, following Is it possible to leverage browser caching?, but Page speed tool still throws "Leverage browser caching error." for only images.

Read this article about Leverage Browser Caching for Images, CSS and JS.

Add these lines to your .htacess file.

## EXPIRES CACHING ##
<IfModule mod_expires.c>
ExpiresActive On
ExpiresByType image/jpg "access 1 year"
ExpiresByType image/jpeg "access 1 year"
ExpiresByType image/gif "access 1 year"
ExpiresByType image/png "access 1 year"
ExpiresByType text/css "access 1 month"
ExpiresByType application/pdf "access 1 month"
ExpiresByType application/javascript "access 1 month"
ExpiresByType application/x-javascript "access 1 month"
ExpiresByType application/x-shockwave-flash "access 1 month"
ExpiresByType image/x-icon "access 1 year"
ExpiresDefault "access 2 days"
</IfModule>
## EXPIRES CACHING ##

Also you can try

<FilesMatch "\.(jpg|jpeg|png|gif|swf)$"> Header set Cache-Control "max-age=604800, public" </FilesMatch>


How can I merge or combine facets? I have a search page with a faceted filter on 'Content Type' field.

I basically need to merge some of the content types into one single facet.

Example:

Content Type A
Content Type B
Content Type C

Should be turned into:

Content Type AB
Content Type C

How can I achieve this?

My Drupal setup for this scenario is the following:

Search API + Search API Solr + Facetapi + Views

I fact all you need is

hook_facet_items_alter(&$build, &$settings);

There you can change the queries and hide/show other facets like

      $build['A']['#markup'] = 'NewA';
      $build['A']['#count']  = $build['A']['#count'] + $build['B']['#count'];
      $size = count($build);
      $build['A']['#query']['f'][$size] = 'field_filter:B';


Load JS only on specific content_type node creation Drupal 6. What is the proper way to execute drupal_add_js only when specific content_type is being created?

I have some jQuery code that needs to execute only to control some form elements in a specific content_type creation.

you need to write a simple module where you hook into the page you need and add drupal_add_js()

e.g. when you create a content type the form node_type_form is being called. so you have to hook into the form with

/**
 * implimentation of hook_form_alter()
 */
yourmodulename_form_node_type_form_alter(&$form, &$form_state, $form_id) {
  drupal_add_js('jQuery(document).ready(function () { alert("Hello!"); });','inline');
}

I asume you need to add a JS to a content_type being viewed. in this case you will need to use hook_view() :

/**
 * implimentation of hook_view()
 */
yourmodulename_view($node) {
    if ($node->type == "your_type") {
        drupal_add_js('jQuery(document).ready(function () { alert("Hello!"); });','inline');
    }
}

Update:

of course you can modify your template.php in the theme directory as well. remember that the theme for administration is different than the site theme by default. be aware which template.php file you are changing.


How to see the filenames imported by the Feeds module? Is there any way to see the past filenames that have been imported by the Feeds module (using Drupal 7)?

I am trying to warn people if they try to import a file that has already been uploaded by Feeds.

Imported files are stored in default/files/feeds by default I think so you could test on that first.

Feeds does create a watchdog event but it doesn't persist.

If you attach feeds to a node then you have several advantages. You can re run the import. And more interestingly you can access the node via Views and probably Rules. With those two you could build something with a Rules trigger event on the node save or Feeds import that would check for an existing node with a matching file.

If you can't get that working then post back and I'll try to make an example.


Custom template files for multiple blocks provided by a custom module? The custom module is called, "epic_module". It defines several blocks, say "awesome_block" and "epic_block".

function epic_module_block_info() {
  $blocks['awesome_block'] = array(
    'info' => t('Awesome block'),
    'cache' => DRUPAL_NO_CACHE,
  );

  $blocks['epic_block'] = array(
    'info' => t('Epic Block'),
    'cache' => DRUPAL_NO_CACHE,
  );

  return $blocks;
}

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

  switch ($delta) {
    case 'awesome_block':
      // TO-DO: Set $block['content'], etc...
      break;
    case 'epic_block':
      // TO-DO: Set $block['content'], etc...
      break;
  }
  return $block;
}

I have also created a templates directory under my module's directory.

I'm confused by the naming conventions. I want to link the template files for the specified blocks.

If you want to use a different template file for your blocks, by default Drupal uses the following template files.

block--epic-module.tpl.php for all the blocks implemented by the module you are showing
block--epic-module--awesome-block.tpl.php and block--epic-module--epic-block.tpl.php for the blocks implemented by that code

Keep in mind that each underscore in the module name or in the block name (i.e. what the documentation calls delta) is replaced with a hyphen.

Reference

template_preprocess_block()


URL paths in optimized CSS sometimes are https instead of http The expanded URLs inside my optimized CSS files are sometimes getting generated with https instead of http.  This appears to happen randomly. Doing a cache clear, recreates the optimized CSS and usually the URLS are correctly expanded using http.

The source CSS files have relative paths in them, for example:

@font-face {
  font-family: "my-custom";
  src: url("../fonts/my-custom/my-custom_47f454dc1e054575ab6c2a63cbc17e46.eot");

In the optimized CSS this gets expanded to a full URL:

@font-face
{ font-family: "my-custom"; font-style: normal; font-weight: normal; src: url("http://i.cdn.my.com/drp/.../assets/fonts/my-custom/my-custom_47f454dc1e054575ab6c2a63cbc17e46.eot?#iefix") format("embedded-opentype"),

Then, seemly randonly it will be:

@font-face
{ font-family: "my-custom"; font-style: normal; font-weight: normal; src: url("https://i.cdn.my.com/drp/.../assets/fonts/my-custom/my-custom_47f454dc1e054575ab6c2a63cbc17e46.eot?#iefix") format("embedded-opentype"),

I have CDN enabled on the site, so that might be a factor.  But again why is the behavior seemingly random?

Any suggestions on where to start looking in settings, hooks that affect CSS optimization behavior, known bugs with CSS optimization, etc. would be appreciated.

I don't think the behaviour is random.

These files are regenerated periodically, and the regeneration is mainly going to be triggered by visits to pages. I would guess that the urls in the CSS files get http when the page that triggered the regeneration has http, and https when the page that triggered the regeneration has https.

Prepending the URLs in CSS with the full protocol and domain is not a stock Drupal behaviour, so something in your setup is doing it–probably whatever module you're using to set up the CDN. You don't mention which module you're using for this, so it's difficult to say. I would begin by looking in the module settings.

It's also possible that your CDN service itself rewrites the urls in CSS files. Cloudflare, for example doesn't do this, but does have configurable options that rewrite certain files (such as, e.g., minifying css, js, or html).


Adding Taxonomy terms programmatically with specific tid? I would like to add a term to a vocabulary specifing the tid, already tried with Taxonomy CSV import/export and Taxonomy import/export via XML modules but both create terms with a new tid.

I even tried programmatically with taxonomy_term_save() but if i set the tid it just looks for a term with that ID.

I need to do this because then i'll import a lot of nodes, and all of them already have a relation with a term.

Any other way to do this?

tid will be assigned to the terms automatically by drupal. My suggestion is first create the terms then you can use taxonomy_get_term_by_name function to find the term and then map it to the respective node while importing.


Deploy block and block configuration to production instance My clients create content and blocks in a staging environment (this is mandated by client) and then we use Deploy with Auto Deployment Plans to send the content over to the production server. They create a lot of blocks for different purposes and on the fly.

With Deploy (and UUID), while we are able to get the block copied over from staging->prod, the configuration of the block does not get transferred over. The client must login to the production environment and configure the block settings as an extra step. Is there a known way to copy over block configuration using Deploy (that is reasonable for a client with minimal Drupal knowledge)?

You should look at the Bean module as a possible alternative to answer this question. Here is a quote about its project page:

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

This module also works great in combination with the UUID and UUID Features Integration modules. And after you become familiar with the Bean module, you might find other cases in your site where you also want to use this module (which somehow compensates the fact that you need to add another module).

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

This module only started as of D7 (because of the "entities" of course that were only introduced in D7). Those who don't use it yet should definitely start looking at it in preparation of some day upgrading to D8. Because this is what is currently shown on its project page (I added the bold markup here):

  This module has been included with Drupal 8 core. Refer to this issue for more information.


How do I add classes to read-more link and add-comment link on node for bootstrap 3 Witch preprocess function let me add btn classes from bootstrap 3 to the two links at the bottom of every teaser in Drupal 7?

I tried the following.

function meetu_preprocess_node(&$variables) {
   $variables['content'] ['links']['node']['#links']['node-readmore']['attributes']['class']
 [] = 'btn btn-primary'.
   $variables['content'] ['links']['node']['#links']['comment-add']['attributes']['class'][]
  = 'btn btn-primary';
  }

The result is that my "add comment" link is gone and the "read more" link has its new classes.

What's wrong here?

Is this the right way to add bootstraps btn calsses to the two links named above?

You were very close except at the end of your first line you had a "." instead of a ";".

function meetu_preprocess_node(&$variables) {
  $variables['content']['links']['node']['#links']['node-readmore']['attributes']['class'][] = 'btn btn-primary';
  $variables['content']['links']['node']['#links']['comment-add']['attributes']['class'][] = 'btn btn-primary';
}


Mail form results (no webform) I've built a form within a module using form api.
Simply liek this:

function input_menu() {
  $items['request'] = array(
    'title' => 'Request',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('input_request'),
    'access callback' => TRUE,
  );
}
function input_request($form, &$form_state) {

    $form['make'] = array(
    '#title' => t('Car make'),
    '#type' => 'textfield',
    '#required' => TRUE,
    );
}

I have some specific fields that didn't allow me to use webform module.
Now how can I send the results of this form to my mailbox?

Thank you!

function input_request($form, &$form_state) {

    $form['make'] = array(
    '#title' => t('Car make'),
    '#type' => 'textfield',
    '#required' => TRUE,
    );

return $form; //you need this here
}

On order to send it to your mailbox, you will also need a submit button and a submit handler for your form.

Read this, it has good info on how to create, validate, submit, theme drupal forms. http://drupal.org/node/751826

FOr sending email you can use the drupal_mail_send() API or drupal_mail() depending on your Drupal core

http://api.drupal.org/api/drupal/includes--mail.inc/function/drupal_mail/7. http://api.drupal.org/api/drupal/includes--mail.inc/function/drupal_mail_send/6


Forcing Flag To Be Unique In Drupal 7 In Drupal 7, using Flags (and possibly Rules or another contrib module) how can I force a flag to be unique for a specific content type.  I do not want to force users to manually 'unflag' content before 'flagging' a new node.  I would like reviously flagged nodes to be automatically unflagged once a new flag has been set.

The goal is to allow users to select a 'default node' by use of flags.  Only one default node should be allowed.

How can I force and automate flag uniqueness?

Drupal Rules has a Trim-A-Flag action that lets you set a 'queue' size, or a 'max' number of flags allowed.  If you set the queue to 1, you can force a flag to be unique, and have it automatically update when a new entity is flagged.

Screenshot below.


Default language wrong on front page I've got two langagues enabled on a Drupal 7 test site, English (set to default in admin/config/regional/language) and Finnish. Under 'Detection and Selection' URL and Default are checked, and URL is set to look for a path prefix.

I've 'translated' (i.e. run through Google Translate) one content item and can switch between the two versions by adding or omitting 'fi' to the path. However, on the front page list of content items the Finnish version is displaying, when I'm expecting to see the English one.

Does anyone know what I'm likely to have messed up or overlooked?

Toby

You say this happens with "the default Drupal front page" (that content feed). Realizing it now. The below is for those who have this problem with the front page set to display a specific node instead (at /admin/config/system/site-information).

Possible cause: using a multilingual variable for setting the front page content, and forgetting to update it. In that case, when visiting example.com/en, the Finnish version of the front page's node is displaying. However, when accessing that same node via (say) example.com/en/node/1, the English version would show.

Explanation. Normally, one URL is configured as alias for the frontpage at /admin/config/system/site-information. If this points to a content item with translations, they are shown as selected by the path prefix. With the multilingual variables however, one URL is configured per language version of the front page, completely overriding Drupal's normal language negotiation mechanism. The path prefix then selects the node given in the corresponding language version of the configuration option, even if that node is in a language not matching the path prefix. (Which leads to the funny effect that in the code rendering that front page node, $language is "wrong": it is that node's language, here and only here potentially different from the language selected by the path prefix.)

Fix. To fix this condition and preventing it from recurring:

Go through all translations of your frontpage node and set them to the same alias, let's say, home [source]. This should work, as each has a different language path prefix.
Go through the language versions of /admin/config/system/site-information and update all "Default front page" fields to contain home.
You probably have to repeat the last step for a new language after adding it. But I did not confirm this.

This whole multilingual variable thing is only to allow the front page being shown in different languages even when language is not selected by path prefix.

Or disable the multilingual versions of this variable altogether, by following this process in reverse.


Permission restrictions deny you access to this broken link In Reports -> Broken links page for some records it is showing

  permission restrictions deny you access to this broken link

Site have only one language also, some of the broken links are showing with https link also. So I don't think the problem with protocol or language.

What is the part of link-checker cron. It was not running and i tried running it manually? But still the broken link is not showing (which I intentionally put some broken link).

What else could be the problem? How to resolve this issue?

Please suggest other than "Re-Analyze link data", that removes all old records also not showing the new one.

I was able to view what the links were by modifying linkchecker.pages.inc line 158 to be the following:

if (empty($nids) && empty($cids) && empty($bids) && !user_access('bypass node access')) {

With this change, assuming that you have bypass node access, you will be able to see the links instead of the annoying message. Unfortunately, the "Edit Link Settings" option will not work for these rows still, because the link data may be out of date.

In order to fix the result list for real, I ran the following drush commands, one after the other. They are defined in linkchecker.drush.inc:

drush linkchecker-analyze

Reanalyzes content for links. Recommended after module has been upgraded. This can also be done from the settings page: /admin/config/content/linkchecker

drush linkchecker-check

Check link status. (Note that this doesn't check them all, only the batch number set in your linkchecker settings.)

If necessary, you may also try running this first:

drush linkchecker-clear

Clears all link data and analyze content for links. WARNING: Custom link check settings are deleted. This can also be done from the settings page: /admin/config/content/linkchecker


Get role label instead of "database value" I want to know how to show role label in twig view.

I have this

{% set roles = user.getroles(TRUE) %}
{{ dump(roles) }}

It's giving me my role, but instead of showing "Directeur (CR)" this is showing "directeur_cr_".

How can I display "Directeur (CR)" ?

You can try like below:

function MYMODULE_field_template_preprocess_default_variables_alter(&$variables) {
  $variables['user_roles'] = user_role_names();
}

and in .twig file you can use as {{user_roles['ROLE_NAME']}}


Implement variable in node confirmation popup I want to add a confirmation popup for node form.
The message should be changed dynamically.
The code below worked fine in form_alter.
$form['actions']['submit']['#attributes']['onclick'] = 'if(!confirm("Really Save?")){return false;}';

But the popup didn't show up if I include a variable in the code like this:
$text = "Really save?";
$form['actions']['submit']['#attributes']['onclick'] = 'if(!confirm({$text})){return false;}';

Is there any way to change the text dynamically?

It worked!
$text = "Really save?";
$form['actions']['submit']['#attributes']['onclick'] = 'if(!confirm("' . $text .'")){return false;}';


Entity Translation: Translate breadcrumb I'm having issues translating breadcrumb.
Everything works, menu items, strings etc... a part from breadcrumb.

I've tried hook_menu_breadcrumb_alter to reset the title with no success.

How can I translate breadcrumb?

You need to add that string(those are not getting translated) into backend, using translate interface- http://example.com/admin/config/regional/translate/translate


How to consistently redirect after saving on Add/Edit node form? When creating a new node doing a $form['redirect'] seems to work consistently, but doing the same redirect when editing an existing node doesn't. The problem only occurs when the admin overlay is shown.

Is there any way around this?

This does the trick ;)

The code below was added in hook_form_alter().

/* Set the desired redirect */
$form_state['redirect'] = 'node/add/lesson';

/* Then clear the "destination" value */
unset($_GET['destination']);
drupal_static_reset('drupal_get_destination');


How do I redirect from /index.php/event/* to /event? I have old links, for example the following ones.

index.php/event/nr1
index.php/event/nr2

If users are coming on index.php/event/*, they should be redirected to
/event.

How can I achieve this?

You can use Match Redirect module.
How to use:
1) Enable module as usual
2) Go to configuration page /admin/config/search/match_redirect
3) Add redirect settings there


feed import on node reference doesn't add language in database I got a XML import witch imports new nodes, in this nodes there is a node reference field. When I run the import I get the message "does not match an existing node" when I look at the nodes they got the node reference, but when you edit the field is empty.

If you look in the database I see that language stays on UND when I change this and update the database it works but when the import runs again its ruined again.

Any solution?

The issue you have run into looks like it may be identified here: https://www.drupal.org/node/1183440.  I walked through this issue queue and was able to get my feed processor to specify the language it was importing.  The comment #193 was particularly useful.  I'll elaborate on his directions a little bit.

For the record, this patch applies only to the feeds module, but you will need to have Feeds Entity Translation installed as well (which you probably already do).

drush dis feeds -y
rm -rf feeds - remove feeds directory entirely
git-pull the feeds repo and checkout older commit:

git clone --branch 7.x-2.x http://git.drupal.org/project/feeds.git

cd feeds

git checkout 006234fc3cc859e4fec0cb261675577efcf389b8
enable all feeds modules that were disabled from step 1:

drush en feeds, feeds_ui, feeds_tamper, feeds_tamper_ui, feeds_et, feeds_ex -y
patch feeds:

wget https://www.drupal.org/files/issues/feeds-field_translations-1183440-191.patch

git apply < feeds-field_translations-1183440-191.patch
confirm patch by building new feed. you should see a language option under the processor settings.

There is a little bit of work to do on this patch before it can be incorporated in the Feeds trunk, but I'm hopeful it will be in place within a few months.


Where can I download old releases of Drupal? I'm trying to find a copy of 6.20 to run a diff on a client's Drupal install. I believe there's been changes to core.

How can I get version 6.20? Additionally, how can I download any older Drupal versions?

You can get Drupal 6.20 from the Drupal 6.20 released page.

You can also view a list of all current and previous releases on the Releases for Drupal core page, complete with download links. It goes all the way back to Drupal 4.2.0, which I'm now off to install to see what happens!


Taxes is not shown in the cart. Using Drupal Commerce module I'm using the Drupal Commerce module and I need to add some taxes to be shown in the cart.

Then, I added 2 taxes in admin/commerce/config/taxes following this video directions: video

First one is a VAT tax type which is shown correctly

Second one is a Sales Taxes tax type which is not shown at all in the cart

What am I missing? As far as I can see is not a permission related problem.

Drupal commerce will by default not show taxes on the cart, the cart is more simple minded with focus on products. The review and checkout pages, will however have taxes displayed by default.

The shopping cart is based on views, so it's pretty easy to change how the order total is displayed. Instead of using Commerce Line Item: Line item summary area handler you should instead use the Commerce Order: Total


format_date() not working I've got a field in a content type called "field_program_date" of type "Date". I'm using Drupal's format_date() function to format the date in the content template like this:

$program_date = format_date($node->field_program_date[$node->language][0]['value'], 'custom', 'F j, Y');
print $program_date;

Something is wrong because nothing gets printed out at all.

Since the date is not coming out as a timestamp, you can to use strtotime. Something like:

$date = strtotime($node->field_program_date[$node->language][0]['value']);
$program_date = format_date($date, 'custom', 'F j, Y');
print $program_date;


Render link in twig with 'entity:node/n' as uri in array With the module "config pages" I've set some variables global to render in templates.
In mytheme.theme I've added a function:
function mytheme_preprocess(array &$variables, $hook)
{
    $myConfigPage = \Drupal\config_pages\Entity\ConfigPages::config('config_name');
    $variables['my_settings'] = $myConfigPage->toArray();
}

In the config_pages I've created a link field.
I would like to render them, but I get below output.
How can I render the link in Twig?
  ^ array:3 [▼
      0 => array:3 [▼
        "uri" => "entity:node/186"
        "title" => "Title 3"
        "options" => []
      ]
      1 => array:3 [▼
        "uri" => "entity:node/189"
        "title" => "Title 1"
        "options" => []
      ]
      2 => array:3 [▼
        "uri" => "entity:node/195"
        "title" => "Title 2"
        "options" => []
      ]
    ]

Twig:
  {{ dd(my_settings.field_links) }}
  {% for link in my_settings.field_links %}
    <div class="field__item">
      {{ dd(link) }}
      {{ link.uri|render }}
      {{ link.title }}
    </div>
  {% endfor %}

None of above are working.

You can render a link with core's link function:

This helper function accepts as first parameter the text and as second parameter the uri
Examples:
{{ link(item.title, item.uri, { 'class':['foo', 'bar', 'baz']} ) }}

In your case, this might look like:
{% for link_item in my_settings.field_links %}
  <div class="field__item">
    {{ link(link_item['title'], link_item['uri']) }}
    // or
    {{ link("My link text", "entity:node/123") }}
    // or
    {{ link("My link text", "internal:/some/internal/path") }}
    // or
    {{ link("My link text", "route:my.module.route_name") }}
    // or
    {{ link("My link text", "https://drupal.stackexchange.com/") }}
  </div>
{% endfor %}

Alternatively, and preferably imo, you can just render the field from the config_page entity (as with any content entity).
For example, in your preprocess:
// Load your config page.
$my_config_page = \Drupal::entityTypeManager()
  ->getStorage('config_pages')
  ->load('my_config_page_identifier');
// Build the render array for my links per the config page's `default` view mode.
$vars['my_links'] = $my_config_page->field_links->view('default');

Then, in twig:
{{ my_links }}


Hash method not providing password that is stored in database I created a custom form for the registration, but I am not getting how to store the password in hash format in the database.

I am using the following code, but I am not getting the value Drupal saves in the database for the password.

require_once DRUPAL_ROOT . '/' . variable_get('password_inc', 'includes/password.inc');
echo user_hash_password('taliadmin');

Why am I getting a different value?

That's pretty much the point. user_hash_password uses _password_generate_salt, which in turn uses drupal_random_bytes. This means hash returned will always contain randomization and is designed not to return the same result twice. Or at least do it as rarely as possible, because there is 2^(6*8) possible outputs of 6 random bytes.

To test passwords, Drupal uses user_check_password. This function extracts salt from stored password and applies it to the one user provided.

Note that by design Drupal does not have any function that would allow to recreate hashes perfectly, and it's not possible to write one (without using original hash to extract salt, that is). You can get pretty close if you need to, copying logic from  user_check_password, but it is actually better to leave salt changing as much as possible.


Commerce Create Cart/Order without product function create_init_order() {
  global $user;

  $order = commerce_cart_order_load($user->uid);

  if(!$order) {

    $new_order = commerce_order_new($user->uid, 'pending');

    // just consider i have generateEmail() and randomName($len) functions

    $new_order->order_number = $order_number = randomName(10);
    $new_order->mail = generateEmail();
    $new_order->hostname = randomName(10);

    commerce_order_save($new_order);
    unset($new_order);

    $order = commerce_cart_order_load($user->uid);
    $order->data['suburbs'] = $_REQUEST['suburb'];
    $order->data['truck'] = $_REQUEST['truck_size'];
    commerce_order_save($order);

  }
}

Hi guys this is for anonymous user creation of order if not existing yet, anything I missed why is not working well.

Specifically this part:

    $order = commerce_cart_order_load($user->uid);
    $order->data['suburbs'] = $_REQUEST['suburb'];
    $order->data['truck'] = $_REQUEST['truck_size'];
    commerce_order_save($order);

As i need suburbs and truck data before adding the line item.

Thank you in advanced.

You are unsetting $new_order and then calling commerce_order_save($new_order); when $new_order is null. It should use $order there.  i.e.

not:

commerce_order_save($new_order);
unset($new_order);

$order = commerce_cart_order_load($user->uid);
$order->data['suburbs'] = $_REQUEST['suburb'];
$order->data['truck'] = $_REQUEST['truck_size'];
commerce_order_save($new_order);

but instead:

commerce_order_save($new_order);
unset($new_order);

$order = commerce_cart_order_load($user->uid);
$order->data['suburbs'] = filter_xss($_REQUEST['suburb']);
$order->data['truck'] = filter_xss($_REQUEST['truck_size']);
commerce_order_save($order); // here

It also looks like there's no need to save and reload the order there when one save would suffice.

Edit: OP has changed the $new_order code typo.

No need to save and load the order, the order_id is already in $new_order->order_id after saving in commerce_order_save($new_order);

Your problem is probably a NULL or empty $_REQUEST var.
Alternatively, you could add the fields to the order entity itself via the Fields UI.


Creating a view which lists all taxnomy terms and the number they appear in a content type? So i have a taxonomy called Product Warnings, and it has around 10 terms. This taxonomy is referenced in several content types (Small products, Large products, etc), and can be selected multiple times (so a user can select in the content type 1 or up to all 10 terms from the Taxonomy).

I want to create a view which lists all terms from the given taxonomy (that's the easy part), and also count the number of times each terms is referenced in a specific content type (i.e. Small products)

So it would look like:

Eye damage: 44
Skin irritation: 13
Hair lose: 1
.
.
.

Now, this is fairly easy to do with a db_query and custom code, but the trick is to do it in a view (if it's possible)

Found the answer i was looking for, and that is to turn on Field Aggregation from the 3rd panel in the view.