Add class to field collection wrapper I've got a field collection with has a div wrapper with the classes "field-collection-container clearfix" I'd like to add an additional class to this div. How would I go about this?

I've tried this:

MYTHEME_preprocess_field(&$variables, $hook){
    if($element['#field_name'] == "FIELD_COLLECTION_NAME"){
        $variables["element"]["#prefix"] = '<div class="field-collection-container clearfix MY_CLASS">'
    }
}

But this doesn't seem to have any affect. I'm not sure what else to try, I also found an answer here https://drupal.stackexchange.com/a/142389/39899 but that doesn't seem to do anything either. The code I put above actually runs as I did a var_dump() and saw the results but when I tried that with the answer I linked to I got nothing.

[UPDATE]

Just to clarify, I'm looking specifically to amend the div with the class "field-collection-container" not add another wrapper. The reason being that I think it's just tidier to make use of the markup Drupal already outputs rather than just adding more do it.

The wrapper containing the 'field-collection-container' class is added in field_collection_field_formatter_view() and because of this it seems that the usual theme functions (e.g theme_field, templatee_preprocess_field and template_process_field) are not able to alter the #prefix.

I've found that it is possible to alter the #prefix by altering the field collection field at the point it is attached the the parent entity by implementing hook_field_attach_view_alter() in our theme (in template.php):

/**
 * Implements hook_field_attach_view_alter()
 */
function MYTHEME_field_attach_view_alter(&$output, $context) {

  // First check we're dealing with a field collection field.
  if(!empty($output['field_link_collection'])) {

    // Now check for our specific field collection field.
    if ($output['field_link_collection']['#field_name'] === 'field_link_collection' ) {

      // Alter the prefix.
      $output['field_link_collection']['#prefix'] = '<div class="field-collection-container clearfix MYCLASS">';
    }
  }

}

Make sure you replace 'field_link_collection' with the machine name of your field collection field.

Field collections are entities themselves (containing fields) as well being fields attached to other entities which is incredibly powerful but I've found to be confusing when trying to alter specific things.

I think that in this case accessing theme_preprocess_field doesn't change anything as it's the wrong point in the render chain and the field is instead being rendered through field_formatter_view (I'm not certain that this is the case though, it may be more complex).

It might also be useful to look at the Display Suite module as it gives you much more control over the markup Drupal generates.

If you wanted to make this easier in the future, submitting a patch to the field collection module to declare a template in field_collection_theme() would help, this issue looks related.

UPDATE

Another method is to change the field display settings (in 'manage display' of the node) of the field collection field from 'field collection items' to 'fields only'. There should still be a wrapper div which you can amend the classes of by doing something like:

function MYTHEME_preprocess_field(&$variables) {
  if($element['#field_name'] == "FIELD_COLLECTION_NAME"){
    $variables['classes_array'][] = 'MYCLASS';
  }
}


Raw menu data in block.tpl.php I need to access the raw menu data in a menu block, but $content only stores the rendered markup. How can I gain access to this object from within the block--sidebar_second.tpl.php file?

I've looked into creating a View but I couldn't figure out how to select menu nodes. Either solution will work for me...

Here is the output of the $block object:

stdClass Object
(
    [bid] => 196
    [module] => menu_block
    [delta] => 7
    [theme] => theme-name
    [status] => 1
    [weight] => 0
    [region] => sidebar_second
    [custom] => 0
    [visibility] => 0
    [pages] =>
    [title] => Services Menu
    [cache] => -1
    [subject_array] => Array
        (
            [#markup] => Services
        )

    [subject] => Services
    [last_in_region] => 1
)

It sounds like you are using Menu block module, and you would have already successfully placed the menu-tree in your region. If your desire is to access raw menu data from a menu block, just use TEMPLATE_preprocess_block(&$variables).

$variables['content'] is rendered.
$variables['elements']['#content'] is raw.


In Drupal 7, What is a good approach to copy the image from one imagefield to another imagefield? I'd like to allow the user to upload an image once, and have it apply to 3 other image fields on the same page without requiring the user to submit the form. Afterwards I intend to apply different croppings to each image but that may not be related to this question.

Is there an existing module or solution to this? If not, what is a good place to inject this behavior client side?

You should only use one image field, and then setup 3 image styles at:

  admin/config/media/image-styles

For each image style you can define a number of different actions, like cropping. When displaying the image you can use theme_image_style()

This is a part of Drupal core and can be extended by e.g. ImageCache Actions.


Is json_decode parse-ability proof of a safe string? Do I need to use check_plain (or something else) when displaying a user supplied JSON string, when I have previously checked it successfully parses with json_decode?

TL;DR: You should check_plain it.

Because the json-enoded string itself can contain insecure code.

This is our example. $data[1] and $data[2] should not be executed.

$data = array(
  'Hukana Matata',
  '',
  'CLick here',
);

You encode this with json_encode. If you json_decode($data_str), and it's a perfectly valid JSON.

$data_str = json_encode($data);

Now, if you print this:

print $data_str;

Now, you will see that the forward slash is escaped.

["Hukana Matata","',
      'CLick here',
    );
$data_str = json_encode($data, JSON_UNESCAPED_SLASHES);
print $data_str;

Notice how the script tag sneaked in:

["Hukana Matata","","CLick here"]


what is starting point of any drupal module.? Only beginner can ask this type of question. as i am learning drupal recently. what is the first function that executes in .module file..how can i understand which function or hook executed.I just want to analyse the execution..please help me out.

what is the first function that executes in .module file? - none in the C sense. If you came from C, C++ or C# environment, think of modules like you think of dll / so files. If you came from Java, think of them like you think of libraries. Piece of code that is hooked by the program if needed, and provides functions that can be called as needed.

So which function is called first? One that implements hook that, by accident, happens to be needed first.

Drupal modules provide functions that react to certain events. These functions are called hooks. Introduction to hooks is in the Develop for Drupal documentation.

Note: As  Ayesh K helpfully pointed, PHP code placed in module file will usually be executed at every call. But Drupal expects there is no code outside functions in .module files. Placing direct PHP code may cause unexpected behaviour, so please don't do it.


Load a Module versus JavaScript embedded in Theme I am new to theming Drupal and I am trying to create a responsive website based on Bootstrap with an image slider at the top.

I know that there are modules like Views Slideshow and FlexSlider.  However, I don't want to install a module when I don't have to.  I would like to just create a content type specific to the slider with just the fields that I need and have the slider that is "embedded" in the theme simply load the content depending on whether it was published or not.

Can this be done?  Are there benefits/drawbacks to what I am attempting to do here?

I am not fluent in the Drupal theming lingo yet so I don't know if I am asking the question the right way.

You can do pretty much anything you want with custom code, including this.
The question is should you use custom code or an existing module that provides the functionality you're after.

The answer depends on your specific situation.

For example if you have limited time/budget it may be better to go with something that's already available, like views slideshow, and keep as much of your budget as possible for other tasks.
However there might be some reason that option isn't ideal, like maybe the modules have lots of functionality you don't need and you want to code something more specific to your requirements.

Another possible issue might be that the existing module doesn't do something exactly the way you need it to, so then you have to decide whether you write a patch to modify that module or if you want to write custom code.

This question deals with pros and cons of using custom code instead of existing modules.


connect drupalgap app to drupal site i have a problem and the documentation of drupalgap is not too specific.
I have a site for example "www.mysite.com" and i have in a localhost a site built in drupalgap that i want to connect with "www.mysite.com" and the drupalgap app shows the content of the database stored in mysite. It's possible to achieve that? I installed the services module and configured it but i don't know how to proceed. Any help will be appreciated. Thank you.

Install the DrupalGap SDK on localhost, e.g. /var/www/drupalgap
Open its app/settings.js file, and point its site_path to www.mysite.com
Launch Google Chrome w/ security disabled and open http://localhost/drupalgap/index.html (if you're in web app mode, or use Ripple if you're in phonegap mode).

More information available here: http://drupalgap.org/node/223


Get field values in Twig with #markup I want the content to be customized by the user, so I created a simple theme and added some fields like background image, color, size etc.

{%
    set background_image = content.field_image.0['#markup']
%}
{%
    set size  = content.field_size.0['#markup']
%}
{%
    set background_color  = content.field_background_color.0['#markup']
%}

Is this the right way to do it? Is it a safe way to get content with #markup?

{%
  set section = {
    'section_attributes': create_attribute().addClass([
      'section',
      size|clean_class,
      background_color|clean_class,
    ])
    .setAttribute('style', 'background-image: url(' ~ background_image ~ ');' )
  }
%}

Is there any other safe way to do this?

I think that it would be better to use

{{ content.field_size.value }}

Then twig will automatically get the value from the field.

If you just want to render the field then {{ content.field_size}} should be fine.

Hope it helps.


How to do a date countdown (to a future date)? How would one go about doing a date countdown (something like this: https://www.mupromo.com/?kbid=4722). I know I'd need to create a block...and I have boilerplate code for that, but I was wondering whether there's a module that already does something similar...or any other pointers you can give.

The Countdown module has a drupal 6 & 7 version. This may work for you. Here is a quote about it (from the module's project page):

Adds a block titled "Countdown" to count the days, hours, minutes, and seconds since or until a specified event. Can configure to just show days, or days and hours, etc.
See also:

jQuery Countdown.
jQuery Countdown Timer.


Two concerns: Available for security updates / Image captions I am looking at revamping a set of sites from ASP to Drupal. I like a lot of what I see in Drupal, but have two concerns:

In reading about Drupalgeddon, it seems that the problem was that many people didn't even see the security notice before hackers started exploiting the vulnerability. I have no staff, so this means I need to be available immediately to install security updates when they are announced. I don't know that I want to be chained to my websites that way, or leave them potentially vulnerable if I decide to go on vacation for a month.
I've been amazed to find that Drupal has no innate ability to put captions on images. Doing that appears to require choosing between three modules (Image Caption, Image Field Caption, or Image Caption Formatter) with no documentation that compares and contrasts the modules to help with the choice. Putting captions on images is a pretty basic requirement, so it makes me wonder what else I'm going to find out I can't do easily once I start porting content.

Comments?

No matter which CMS you use this will always be an issue. If you do not have time to be proactive about maintaining your software, you should look into paying someone to do it for you.
This is the result of Drupal's modular design. It's done this way so it can accommodate the wide-spectrum of use cases. It's a simplicity/flexible tradeoff that can be good and bad depending on the circumstances.


How to access jQuery plugin added through libraries API I'm working on a Drupal 7 module to integrate an existing jQuery plugin (smallworld.js). I've added it successfully through the Libraries 2.x API in my module:

$libraries['smallworld.js'] = array(
    'name' => 'SmallWorld.js',
    'vendor url' => 'http://mikefowler.me/smallworld.js/',
    'download url' => 'https://github.com/mikefowler/smallworld.js',
    'version' => '1.0', //no version actually defined in code
    'files' => array(
      'js' => array('src/smallworld.js'),
      'js' => array('src/smallworld.jquery.js'),
    ),
  );

and have confirmed that the files are loading correctly. However, when I try and access the file in my Drupal jQuery, ex:

(function ($) {

  Drupal.behaviors.smallworld = {
    attach: function (context, settings) {
      $.getJSON('/sites/all/libraries/smallworld.js/dist/world.json', function (data) {
        $('.map').smallworld({
          geojson: data,
        });
      });
    }
  };
}(jQuery));

It doesn't trigger, giving me the console error message "Smallworld is not a constructer."

The two files it is loading are the Smallworld library and a smaller jquery wrapper that registers the library as a jquery plugin:

  $.extend($.fn, {
    smallworld: function (options) {
      var opts = $.extend({}, $.fn.smallworld.defaults, options);
      return this.each(function () {
        $(this).data('smallworld', new Smallworld(this, opts));
        return this;
      });
    }
  });

Does this wrapper also needed to be added to the same Drupal jquery namespace? If a jquery library is added through Libraries API, is there special namespacing to consider when accessing it?

Found the problem - this library comes with two separate files, one that is a straightup javascript library and another in jquery that registers the file as a plugin (smallworld.jquery.js)

  $.extend($.fn, {
    smallworld: function (options) {
      var opts = $.extend({}, $.fn.smallworld.defaults, options);
      return this.each(function () {

      $(this).data('smallworld', new Smallworld(this, opts));
      return this;
    });

To get this to work, I had to take the whole 'register' script and add it to the jquery file script I created for the module, ex:

(function ($) {

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


Custom Field Plugin With Image Field I have been working on a custom field plugin with which the aim is to create a custom field to be used for content and will consist of a link field and a file field through which a thumb image is to be uploaded. I'm ok with the first part is i.e. the link field for which I have declared a uri data definition with a varchar storage schema and a url type for the form element. But I cannot (based on the available documentation) figure out the proper way to manage the file field. I have used a managed_field type as for the form element but cannot figure out what is the correct datatype and storage schema to use.

Edit: The documentation I have found deals with three parts,

The field class where the propertyDefinitions method is overridden and the properties are defined (ex. $properties['link'] = DataDefinition::create('uri')->setLabel(t('Video Link'));)
Also in the field class where the schema method is overridden and the storage properties are defined (ex. $columns['link'] = [ 'type' => 'varchar', 'length' => 255, ];)
the widget class where the formElement method is overridden to define the input form (ex. $element['link'] = [
        '#type' => 'url',
        '#title' => t('Link'),
        '#default_value' => isset($items[$delta]->link) ? $items[$delta]->link : null,
        '#empty_value' => '',
        '#placeholder' => t('Insert a url'),
    ];)

what should the equivalent parts for an image/file field property be defined?

any input would be appreciated, thanks

I hope I understood correctly:

FileItem.php

Have a look at public static function defaultStorageSettings() and public static function schema(FieldStorageDefinitionInterface $field_definition)


How to assign "Access Results" permission per Webform? On Drupal 7, my client would like to give a user to see a particular Webform's "Access Results". How can I assign the "Access Results" permission per Webform, beside using "Permissions per Webform"?

Thanks,
HL

Sounds like you need Permissions per Webform module

You can set permissions per Webform as it suggests. Under the form settings.


How to translate Boolean field labels? I have created Boolean fields. I have set values 0/1 in database and No/Yes as labels to display in UI. But I cannot translate these labels. I have translated strings "Yes" and "No" using UI on link admin/config/regional/translate/translate but it does not work for field labels.

Can anybody help?

thanks Tomas

I'm relatively new to Drupal but I've had the same problem recently and this is how I solved it:

install the i18n module and enable the "field translation" sub-module (and its dependencies).
in the boolean field settings (admin/structure/types/manage/[your-content-type]/fields and click the edit link next to the field) make sure you have specified a value for the On and Off states (e.g. Yes/No).
then on the same page (boolean field settings), use the translate tab (on top of the page) and click "translate" for each language you need:
under the Field instance tab, you can translate the label for the field.
under the Field settings tab, you can translate the values for the On/Off states.
lastly (and this is perhaps the less obvious step), go to manage display (for your content type), and as "format" for you boolean field, choose "Default translated" instead of "Default".

Hope this helps.


Hide a region from a specific node? (Without CSS) I can hide a region from a specific node via CSS but this is problematic since the Display: none attribute doesn't really clear the space... Any other way to do so?

Try doing it via hook_page_alter

  Perform alterations before a page is rendered.

  Use this hook when you want to remove or alter elements at the page
  level, or add elements at the page level that depend on an other
  module's elements (this hook runs after hook_page_build().

You can then get the page you are on by calling menu_get_object without parameters and inspect the returned node object.

Add this code to your theme's template.php file:

function MYTHEME_page_alter(&$page){
  //dpm($page);
  if ($node = menu_get_object()) {
    if ($node->nid == 72) { // pick your node or add a condition to your liking
      // remove sidebar first region
      unset($page['sidebar_first']); // remove the regeion here
    }
  }
}

If your theme depends on it, and depending on the region you are removing, you should also implement template_preprocess_html and adjust your body classes so that they are in sync.

As to the CSS, dispay:none as a css rule should remove the element from display, whereas visibility:hidden hides an element, but it will still take up the same space as before. CSS Display and Visibility


using hook_update to add a new cck field I am using d6.

I have a live site with an already built content type. I needed an extra column in the table, so I added this on install... I know realize how limiting this is and have rebuilt the content type to include this column as a field and I have unset the field in the form.

I have updated the code for this content type to include the new field, but when I move the code to my dev site, I do not see the new field.

Note: The content type was exported to code using the features module.

I thought maybe I need to run hook_update, but I haven't worked out how to do this.

This is what I have so far.

function mymoduel_update_6004(){
  #REF: http://drupal.org/node/1031548
  drupal_load('module', 'content');
  drupal_load('module', 'mymodule');
  content_notify('install', 'mymodule');
  content_notify('enable', 'mymodule');
  return array();
}

I run update.php... but no visible changes :(

Has anyone got any ideas how I can update my cck content types?

After hours of searching, I finally found a post by Drewish that solves this.

http://drewish.com/node/118

The key to this is letting drupal core know you want to create a new field instance using

content_field_instance_create()


Reload js behaviors after click I'm using boostrap 3 with modals. I've a button that opens a modal, in the modal there are some facet blocks.
The view has ajax enabled, so when I click on a facet the page is not reload but are reloaded the content of the view AND facets blocks.

I've to execute some js functions when I click on facets links, I've added this js to my theme:

Drupal.behaviors.my_theme = {
    attach: function (context, settings) {
        jQuery('#facets a', context).click(function () {
            alert('enter');
        });
    }
};

The problem is that the alert is executed only on the first click. On second, third etc alert does not appear.

What's wrong?

Check to see if the ID has changed. If the content containing #facets is getting ajaxed in then the ID may have changed

Or you could try:

jQuery('body').on('click', '#facets a', function () {
        alert('enter');
    });


When I POST an image file via rest, response is 201: Object Moved, status is temporary I'm attempting to POST images to Drupal 8 via the REST api.  The creation is successful (201) and the images appear in the files list.  However, there are problems. I'm not sure if they are independent of one another of is they are related.

1.The images are created with a temporary status.  Would prefer "permanent".

2.The MIME type is set to "application/octet-stream" and the images don't render.  I've discovered that by chaning the "uri" in the json object I'm posting to be an explicit uri like "public://photograph.jpg", the MIME type gets set to image/* and this work.

This is the code i'm using:

<script>
    function getCsrfToken(callback) {              //get token
        jQuery
            .get('http://vhscms/cms/rest/session/token')
            .done(function(data) {
                var csrfToken = data;
                callback(csrfToken);
            });
    }

    function postImage(csrfToken, image) {         //post image
        console.log(image);
        jQuery.ajax({
            url: 'http://vhscms/cms/entity/file?_format=hal_json',
            method: 'POST',
            headers: {
                'Content-Type': 'application/hal+json',
                'X-CSRF-Token': csrfToken
            },
            data: image,
            success: function(data) {
                console.log('postNode success');
            }
        });
    }

    $('#image-save').click(function() {         //attach fcn to button
        getCsrfToken(function(csrfToken) {
            var $img = $('img[alt="image1"]');  //grab first image
            var imgSrc = $img.attr('src');      //grad base64 source
            imgSrc = imgSrc.replace('data:image/jpeg;base64,',''); //clean
            var package = {
                "_links": {
                    "type": {
                        "href": "http://vhscms/cms/rest/type/file/image"
                    }
                },
                "filename": [{
                    "value": "joggers.jpg"
                }],
                "filemime": [{
                    "value": "image/jpeg"
                }],
                "type": [{
                    "target_id": "image"
                }],
                "uri": [{
                    "value": "public://joggers.jpg"  //forces mime type img
                }],
                "data": [{
                    "value": imgSrc
                }]
            };
            postImage(csrfToken, JSON.stringify(package));
        });
    });

</script>

Suggestions

I think filemime is autogenerated depending on the file you're uploading.
To make the file permanent, have you tried sending the property status: [value: 1]?

A status of 1 indicates that the file is permanent.


Views: combining fields of one content type with another Let's say I have Content Type A and Content Type B.
Both A and B share a taxonomy vocabulary C.
C terms are C:x, C:y, C:z

I want to create a page View of Content Type A which lists every node of Content Type A.
Within the physical layout of each A, I want to also show B, but only if it share's C with A.

The page generated by the View should look like something like this

1st CONTENT TYPE A with taxonomy C:x
=====================
Content Type A field 1
Content Type A field 2
Content Type A field 3
Content Type B with taxonomy C:x
=====================

2nd CONTENT TYPE A with Taxonomy C:y
=====================
Content Type A field 1
Content Type A field 2
Content Type A field 3
Content Type B with taxonomy C:y
=====================

I have everything working except for the Conent Type B with taxonomy C:foo working.
What do I need to do to get this part working?

Check out the module Relations. It will enable you to make relationships between the two content types.  You can see it in action at nodeone.se in the video series on Relations.


Having problems with file_copy in Drupal 7 In my particular situation I am trying to use Drupal's API to import a bunch of files from my computer into a local Drupal installation.  Seems like a smart idea.  So I have the following function:

  function create_picture_file($filepath, $public_place) {
    global $pic_basepath;
    $filepath = "$pic_basepath/$filepath";
    $file = new stdClass();
    $file->filename = basename($filepath);
    $file->filepath = $filepath;
    $file->filemime = file_get_mimetype($filepath);
    $file->filesize = filesize($filepath);
    $file->uid = 1;
    $file->status = FILE_STATUS_PERMANENT;
    $file->uri = $filepath;
    $file->display = 1;
    $file->description = '';
    print_r($file);
    $file = file_copy($file,"public://$public_place",FILE_EXISTS_REPLACE);
    print_r($file);
    return $file;
  }

You'll notice the two print_r statements towards the bottom.  The first one prints the following:

stdClass Object
(
    [filename] => Arctic_HE0302_Central_bathy.jpg
    [filepath] => /home/lpeabody/unclos_data/pics/Arctic_HE0302_Central_bathy.jpg
    [filemime] => image/jpeg
    [filesize] => 516130
    [uid] => 1
    [status] => 1
    [uri] => /home/lpeabody/unclos_data/pics/Arctic_HE0302_Central_bathy.jpg
    [display] => 1
    [description] =>
)

Which looks good.  The second one, however, print's absolutely nothing.  Any pointers or tips as to what I'm doing wrong maybe?

UPDATE
So the public file directory to which this image is being saved in is region_images.  When this directory exists, nothing get's printed by the second print_r statement.  When I remove the directory and all of it's associated style directories, the second print_r statement prints.  However, it prints the following:

stdClass Object
(
    [filename] => region_images
    [filepath] => /home/lpeabody/unclos_data/pics/Arctic_HE0302_Central_bathy.jpg
    [filemime] => image/jpeg
    [filesize] => 516130
    [uid] => 1
    [status] => 1
    [uri] => public://region_images
    [display] => 1
    [description] =>
    [fid] => 2595
    [timestamp] => 1331828075
)

Which is wrong, as [filename] should be Arctic_HE0302_Central_bathy.jpg.  Hopefully this can help shed some light on the situation.

Use "public://$public_place/$file->filename" as $destination parameter for file_copy().


drupal Theme class is missing, I guess! How to fix it? I am using civicrm on drupal 7.26. When I use default theme i can see the link "View all Contribution...." but as you can see from top part of screenshot it does not appear on bootstrap theme. can anyone help me to fix this please? thanks

Make sure your theme has all the appropriate Theme Regions (more details about Theme Regions). Also, there may be some custom PHP overrides provided by the working theme, so you'll want to review the theme's template.php file for any custom PHP theme overrides you may want to help bring over to your other theme.


Organic Groups D7 : How to get custom group list of login user? How to get logged in user group list in select box.

Need to help Please suggest me any one ?

You can use og_get_groups_by_user function.

$current_user_groups = og_get_groups_by_user();


Not able to save the selected custom populated option list I have a cck select list where the options are populated by my custom code. There is no issue for populating the list but after that the selected options are not able to save. Is there any way to fix this. Here is my code snippets:

function pelikan_common_form_alter(&$form, $form_state, $form_id) {
if ($form_id =='monitoring_node_form'){
    $nid = arg(3);
    $node = node_load($nid);
    $index=0;
      foreach ($node->field_test_monitoring['und'] as $key) {
       $show = node_load($key['nid']);
       $form['field_indicator']['und']['#options'][$index++]= $show->title;

     }
   }

List fields are tied to their allowed values and they make sure all the values in the database align with what is in the allowed values.

To programatically populate list fields, there is a lesser known feature, which is that you can set the 'allowed_values_function' setting of your field instance.

If you are programatically creating your field you just add it in the settings.
If not you could do one of these things:

Form alter the field settings form to make the allowed_values_function field a visible text field you can enter a function name into.
Implement hook_enable() in your custom module to load the fields in question and set the allowed_values_function and then save the fields. Then use hook_disable() to reverse the cahnge when you disable the module.
Go in the database directly and set the value in the field settings.

Your allowed value function should be of the form:

function function_name($field, $instance, $entity_type, $entity, $cacheable) {
  // return an array of values.
  $values = array(
    'val1' => t('Value 1'),
    'val2' => t('Value 2'),
    'val3' => t('Value 3'),
  );

  return $values;
}

There is another module though that makes things a little nicer: List field predefined options

It allows you to implement it's hook to define allowed value functions, which you can then select from in the field UI.

For example:

/**
 * Provide information about available predefined list options.
 *
 * @return
 *   An associative array whose keys define the machine name for each
 *   predefined list options and whose values contain the list options
 *   descriptions. Each list options description is itself an associative
 *   array, with the following key-value pairs:
 *   - 'label': (required) The human-readable name of the list options.
 *   - 'callback': (required) The name of the function that will return the
 *     list options.
 *
 * @see hook_list_option_info_alter()
 */
function MYMODULE_list_option_info() {
  $info['FIELD_NAME'] = array(
    'label' => t('Name that describes the values this callback will return'),
    'callback' => 'mymodule_function_that_returns_allowed_values',
  );

  $info['ANOTHER_FIELD_NAME'] = array(
    'label' => t('Name that describes the values this callback will return'),
    'callback' => 'mymodule_another_function_that_returns_allowed_values',
  );

  return $info;
}

Then you can implement the functions you defined in the above hook to return the allowed values and in the field UI you can select to use the function by its label.
Much more user friendly.


How might I find a render array of a parent OG group? If given the node id, how may I get that node's menu's render array?

I'm almost looking for an API function such as

function get_menu_for_node($nid) {}

Where this would return the render array to which node/$nid belongs.

I did the following to achieve this. I'm still not happy with the results but given time pressures, it'll have to do. I'm posting to see if anyone can suggests a better alternative.

I grab the nid of the parent group first and use it to do a query against menu_links. Once I have a result of a menu_id(s), we loop through, get the links, use theme(), and then drupal_add_region_content().

<?php
/**
 *
 *
 * This module creates a block that looks for any parent OG group and displays the menu of that
 * group.
 */

define('_OGPN_NODETYPE', 'user_posted_content');
define('_OGPARENTNAME_TITLE', 'OG Parent Menu');

/**
 * Implements hook_block_info().
 */
function ogparentmenu_block_info() {
    // This example comes from node.module.
    $blocks['_ogparentmenu'] = array(
        'info' => t(_OGPARENTNAME_TITLE),
        'cache' => DRUPAL_NO_CACHE,
    );

    return $blocks;
}

/**
 * Implements hook_block_view().
 */
function ogparentmenu_block_view($delta = '') {
        return [
            'subject' => t(_OGPARENTNAME_TITLE),
            'content' => __ogparentmenu(),
        ] ;
}

/**
 * @return string
 * @throws Exception
 */
function __ogparentmenu() {

    $node = menu_get_object();

    /* Set up menu on UserPosts  */
    if ($node->type == _OGPN_NODETYPE) {

        // get parent link of og
        $parent_og = filter_var($node->og_group_ref[LANGUAGE_NONE][0]['target_id'], FILTER_SANITIZE_NUMBER_INT);

        // Query menu_links based on node/$nid path
        $menu_query = db_select('menu_links', 'ml')
            ->fields('ml', ['menu_name', 'mlid'])
            ->condition('link_path', "node/$parent_og", '=')
            ->execute();

        // if single
        if ($menu_query->rowCount() == 1) {
            $menu_id = check_plain($menu_query->fetchAs()['menu_name']);
            $links = menu_navigation_links($menu_id);

            $themed_menu = theme('links__system_main_menu', [
                '#title' => t('title'),
                'links' => $links,
                'attributes' => [
                    'class' => ['user_post_menu_injected', 'section']
                ],

            ]);

            return $themed_menu;

        }
        // TO DO : handle multiple
        elseif ($menu_query->rowCount() > 1) {

            return 'null';
        }

    }
}


Re-writing SQL statement in Drupal dynamic queries I have the following SQL query, which I need to re-write using Drupal's dynamic query language. I'm new to Drupal development, could you please give me an example for the following SQL?

SELECT
    node.title,
    GROUP_CONCAT(field_data_field_location.field_location_value)
FROM
    node
    INNER JOIN field_data_field_location
        ON node.nid = field_data_field_location.entity_id
    INNER JOIN
        (SELECT DISTINCT
            entity_id
         FROM
            field_data_field_location
         WHERE
            field_location_value IN ('Berlin', 'Stuttgart')) AS IDS
        ON node.nid = IDS.entity_id
GROUP BY
    node.nid

What I currently have is the following:

$query = db_select('node', 'n');
$query->addField('n', 'title', 'title');
$query->groupBy('n.nid');

$subquery = db_select('field_data_field_location', 'loc');
$subquery->distinct();
$subquery->fields('loc.entity_id', array('eid'));
$subquery->condition('loc.field_location_value', $locations, 'IN');

$query->join('field_data_field_location', 'l', 'n.nid = l.entity_id');
$query->addExpression('GROUP_CONCAT(l.field_location_value)', 'locations');
$query->addJoin('INNER', $subquery, 'IDS', 'n.nid = IDS.entity_id');

$result = $query->execute();

return $result->fetchAll();

If I execute the code, I just get nothing back from Drupal. I think the problem is the subquery. Do you have any idea how I can solve that?

Have you turned down the error_level? because if you get nothing back from Drupal then this typically means the query executed successfully but that no results were found. Perhaps check the Reports->Recent log messages for any SQL errors logged instead. This information should help you troubleshoot future Drupal SQL endeavours.

Anyway, looking over the code, I don't think this is correct:

$subquery->fields('loc.entity_id', array('eid'));

and should probably be:

$subquery->fields('loc', array('entity_id'));

or if you want to give the field an alias, use addField:

$subquery->addfield('loc', 'entity_id', 'eid');

I've just run a similar query on a fresh database (so no custom fields) and set that fields() call correctly, and this seems to get results back:

$bundles = array("page", "blog");

$query = db_select('node', 'n');
$query->addField('n', 'title', 'title');
$query->groupBy('n.nid');

$subquery = db_select('field_data_body', 'data');
$subquery->distinct();
$subquery = $subquery->fields('data', array('entity_id'));
$subquery = $subquery->condition('data.bundle', $bundles, 'IN');

$query->join('field_revision_body', 'rev', 'n.nid = rev.entity_id');
$query->addExpression('GROUP_CONCAT(rev.bundle)', 'mybundles');
$query->addJoin('INNER', $subquery, 'IDS', 'n.nid = IDS.entity_id');

$result = $query->execute();

dpq($query); // Let's look at the query
dpm($result->fetchAll()); // Let's see all the results

Note, you'll need the devel module installed to use the dpm() and dpq() functions. Hope that can help!


How do I hide a local task (tab) if a module is disabled? I would like my local tasks (tabs), defined in mymodule.links.task.yml, to appear only if a certain module is enabled. If a certain module is disabled, I want the tab to be hidden.

mymodule.alpha:
  route_name: mymodule.alpha
  base_route: mymodule.alpha
  title: 'Alpha'

mymodule.bravo:
  route_name: mymodule.bravo
  base_route: mymodule.alpha
  title: 'Bravo'

My understanding is that this can be acheived by adding a _module_dependencies key to my routing.yml file.

  _module_dependencies: Optionally use this key to specify one or more modules that are required to serve this path. You can combine module names with a + (plus) for an AND relationship or , (comma) for an OR relationship. For example, _module_dependencies: 'node + search' means both node and search are needed, _module_dependencies: 'node, search' means either node or search are needed. If your module already depends on other modules for its behavior (via info.yml dependencies), there is, of course, no need for specifying the dependency here as well; however, for optional dependencies, where routes are provided only if those optional dependent modules are also enabled, this is a useful option.

https://www.drupal.org/docs/8/api/routing-system/structure-of-routes

mymodule.alpha:
  path: '/admin/reports/mymodule/alpha'
  defaults:
    _controller: Drupal\mymodule\Controller\AlphaController::render
    _title: 'Alpha'
  requirements:
    _permission: 'access site reports'
    _module_dependencies: 'comment' # this is module is enabled, this line does not cause a white screen on cache rebuild

mymodule.bravo:
  path: '/admin/reports/mymodule/bravo'
  defaults:
    _controller: Drupal\mymodule\Controller\BravoController::render
    _title: 'Bravo'
  requirements:
    _permission: 'access site reports'
    _module_dependencies: 'statistics' # this is module is disabled, this line does cause a white screen on cache rebuild

However, if a module is disabled, I get this error:

  Symfony\Component\Routing\Exception\RouteNotFoundException: Route "mymodule.bravo" does not exist. in Drupal\Core\Routing\RouteProvider->getRouteByName() (line 187 of /var/www/mysite/core/lib/Drupal/Core/Routing/RouteProvider.php).

The error is thrown even when I visit: /admin/reports/mymodule/alpha.

I believe my problem was that if the module was disabled then the route would not exist - and this would have my links.task.yml trying to create a local task from a non existent route.

My solution was to generate a dynamic local task instead, so that the local task is only created, if the module is enabled:

mymodule.links.task.yml

mymodule.bravo:
  deriver: 'Drupal\mymodule\Plugin\Derivative\BravoLocalTasks'

src/Plugin/Derivative/BravoLocalTasks.php

namespace Drupal\mymodule\Plugin\Derivative;

use Drupal\Component\Plugin\Derivative\DeriverBase;

/**
 * Generates local tasks.
 */
class BravoLocalTasks extends DeriverBase {

  /**
   * {@inheritdoc}
   */
  public function getDerivativeDefinitions($base_plugin_definition) {
    $moduleHandler = \Drupal::service('module_handler');
    if ($moduleHandler->moduleExists('statistics')) {
      $this->derivatives['mymodule.bravo'] = $base_plugin_definition;
      $this->derivatives['mymodule.bravo']['route_name'] = 'mymodule.bravo';
      $this->derivatives['mymodule.bravo']['base_route'] = 'mymodule.alpha';
      $this->derivatives['mymodule.bravo']['title'] = 'Bravo';
    }
    return $this->derivatives;
  }
}

I believe I will have to create a distinct class for every route that requires dynamic local tasks.

If you have a better solution, please post.


how to disable a class in migrate module I have already deleted a migrate class in the .inc file and also deleted it in the .install file but i still get an error saying:

Class ForumTermMigration no longer exists
Class ForumUserMigration no longer exists

whenever i access the migrate UI in drupal site.

how to fix this?

<?php

/**
 * @file
 * Set up the move2drupal module module.
 */

function move2drupal_enable() {
  //Migration::registerMigration('ForumTermMigration');
  //Migration::registerMigration('ForumUserMigration');
  Migration::registerMigration('ForumNodeMigration');
  Migration::registerMigration('ForumCommentMigration');
  }

function move2drupal_uninstall() {
  //
}

function move2drupal_disable() {
  //Migration::deregisterMigration('ForumTermMigration');
  //Migration::deregisterMigration('ForumUserMigration');
  Migration::deregisterMigration('ForumNodeMigration');
  Migration::deregisterMigration('ForumCommentMigration');
}

the above is my .install file. see ive commented the class i deleted in the .inc file.

I have also tried clearing the cache. uninstalling the module and reinstalling it again.

I'm currently using Drupal 7.22.

For my migration class, in my migrate_mypages.install file I have:

function migrate_mypages_enable() {
  Migration::registerMigration('MyPagesMigration');
}

function migrate_mypages_disable() {
  Migration::deregisterMigration('MyPages');
}

I haven't looked into the actual Migrate module, but it seems that when registering a migration in code, you have to use the full class name, whereas when de-registering the migration in code, you use only the name of your migration (machine-name).

If you are stuck with old classes, you can either add the de-register lines back in, and enable/disable your module, or, manually clear the class lines out of the table "migrate_status" in your database (as per Neograph734's comment).

As well, if you use drush, there is also:

drush migrate-deregister --orphans


Using views to display complex content I am using Drupal 8 to build a little complex website. Here is an example of what the content is like:

Content Types: Books, Chapters, Paragraphs
For instance a book content type would contain fields to hold author, cover pic, etc. then the chapter will have a link to the related book, and paragraphs will have links to its related chapter and an ordering number.

Now I'd like to have the website to have pages as following:

/books - will show all books by cover photo with links to go to the contents
/books/<book-name> - will show info about a specific book with list of chapters each with a link to go to the content of that chapter
/books/<book-name>/<chapter-number> - Will show all paragraphs in that chapter

My question is can this be achieved just by the view module that is installed with d8 vanilla?
Can I achieve all of this with one view? If multiple views are needed, can they all use the same path structure (/books is common in that case)?

Yes this can be achieved by using views module. And the structure should go something like:
a. Content Type Book.
b. Content Type Chapter.

Now chapter CT will have node references field of CT Book.

Create a view of books content type which will show all books then create a page within same view with some changed filters to show /books/book-name.

Now create another view  with link /books/book-name/chapter-number where book-name will match the node reference field or /books/book-name/ from previous view to get book name.


Drupal Commerce - (free) Shipping , Pickup option , Order Comment? I'm still facing some issues with my Drupal Commerce.

The shop is only available for authenticated users. When they want to checkout they should be able to pick a shipping option or a pickup option.

When the order total is less than 25 euro and they want to get it deliverd they will be a shipping fee of x euro's. When it is higher than 25 euro shipping will be free. When they pick the option to pick it up, it will be free.

I also want in both cases that a text fields appears so they can give a date/time that they want the package to be delivered.

I also have customer profiles enabled, but when I'm at the checkout my profile isn't getting filled in.

Any thoughts on how to achieve this?

Best regards.

Install https://www.drupal.org/project/commerce_flat_rate
Go to "admin/commerce/config/shipping/methods" and create following flat rate services

Pickup at store (0 $)
Free shipping (0 $)
Shipping (x $)

Configure the last 2 flat services (free shipping / shipping) by clicking "configure component"

Free shipping rate -> add condition "Order amount comparison" >= 25 $
Shipping -> add same condition, but check "negate"

Now picking up at store will always show up, the other 2 depending the order amount.

For the textfields, you can put that in the shipping profile for the customer.


Moving a contrib module from /modules into the sites/all/modules folder I need to run a simple fix in my Drupal 7 website. The website administrator, not being a Drupal specialist, installed the SMTP module in the root /modules folder, instead of the /sites/all/modules folder. Now I need to upgrade the SMTP module and noticed the mistake. My first impulse was to move the SMTP folder from /modules into /sites/all/modules, and then proceed with the regular upgrade.

My question is: do you think that moving the SMTP folder from root /modules into /sites/all/modules could cause any problems, like data loss or website crash?

It’s OK (in most cases). Drupal 7 will find new destination of module after registry rebuilding. So, just move folders in proper destination and clear all cache.

It works for moving modules, but not for disabling and uninstalling. Don't remove module folder before complete uninstalling.

Update: I can move module folder even without disabling that module, because I use Drush for immediate cache clearing. In other situations it will be useful to disable module before moving.


Lightbox2 doesn't open html content and links I installed Lightbox2 module and I tried to link an image to a webpage, say google.com, this is my code

<img  src="<?php print $base_url;?>/sites/all/themes/MY-THEME/image/fp/map.jpg">

but it displays nothing in Lightbhox. This is the print screen of the Lightbox using Firebug

as you can see there is nothing in body.

This link works to get google search in the ligtbox:

Search

I got it from this post: How to show google.com in an iframe?


Change "Enter your (website) username." I am setting up a personal site in Drupal, and at the Login page it will have "Enter your Josh Mustillo username." Is it possible to change the "Josh Mustillo" to something else like "Enter your Username"?

(Domain is www.joshmustillo.com),

You could do that by implementing the hook_form_alter, in your custom module.

function MODULE_form_alter(&$form, &$form_state, $form_id) {
  if($form_id == 'user_login') {
    $form['name']['#description'] = t('Enter your username');
  }
}


Duplicate field values in views for a custom entity I have a custom entity. I'm using hook_entity_property_info() to tell views what fields are in my custom entity.

However for some reason I am getting duplicate fields when it comes to views. As in, I go to add a field in a view, and it is listed twice. It's not a problem, but cosmetically it is ugly.

Why would this be?

I am using this as my views controller class:

'views controller class' => 'EntityDefaultViewsController',

Could that be the problem?

This is the link that is most relevant to what I am doing:

https://www.drupal.org/node/1208874

My hook_entity_property_info():

/**
 * Implements hook_entity_property_info().
 */
function stockinfo_historical_entity_property_info() {
  $info = array();

  $info['stockinfo_historical']['properties']['sid'] = array(
    'label' => t('SID'),
    'description' => t('The ID of the stockinfo historical row.'),
    'type' => 'stockinfo_historical',
    'schema field' => 'sid',
    'entity views field' => TRUE,
  );
  $info['stockinfo_historical']['properties']['symbol'] = array(
    'label' => t('Symbol'),
    'description' => t('Symbol of the stock.'),
    'type' => 'text',
    'schema field' => 'symbol',
    'entity views field' => TRUE,
  );
  $info['stockinfo_historical']['properties']['name'] = array(
    'label' => t('Company Name'),
    'description' => t('Name of the company.'),
    'type' => 'text',
    'schema field' => 'name',
    'entity views field' => TRUE,
  );
  $info['stockinfo_historical']['properties']['date'] = array(
    'label' => t('Date'),
    'description' => t('The day this happened on.'),
    'type' => 'date',
    'schema field' => 'date',
    'entity views field' => TRUE,
  );
  $info['stockinfo_historical']['properties']['stockinfo_historical_high'] = array(
    'label' => t('High'),
    'description' => t('The high on this day.'),
    'type' => 'decimal',
    'schema field' => 'stockinfo_historical_high',
    'entity views field' => TRUE,
  );
  $info['stockinfo_historical']['properties']['stockinfo_historical_low'] = array(
    'label' => t('Low'),
    'description' => t('The low on this day.'),
    'type' => 'decimal',
    'schema field' => 'stockinfo_historical_low',
    'entity views field' => TRUE,
  );
  $info['stockinfo_historical']['properties']['stockinfo_historical_close'] = array(
    'label' => t('Close'),
    'description' => t('The close on this day.'),
    'type' => 'decimal',
    'schema field' => 'stockinfo_historical_close',
    'entity views field' => TRUE,
  );
  $info['stockinfo_historical']['properties']['stockinfo_historical_volume'] = array(
    'label' => t('Volume'),
    'description' => t('The volume on this day.'),
    'type' => 'decimal',
    'schema field' => 'stockinfo_historical_volume',
    'entity views field' => TRUE,
  );
  $info['stockinfo_historical']['properties']['stockinfo_historical_adj_close'] = array(
    'label' => t('Adjusted Close'),
    'description' => t('The adjusted close on this day.'),
    'type' => 'decimal',
    'schema field' => 'stockinfo_historical_adj_close',
    'entity views field' => TRUE,
  );
  return $info;
}

Setting EntityDefaultViewsController is not really required as entity API sets this by default and yes it does conflict with hook_entity_property_info().

The solution can be found here: https://www.drupal.org/node/1208874 and it is as simple as defining the 'module' property in hook_entity_info().

<?php
/**
 * Implements hook_entity_info().
 */
function entity_test_entity_info() {
  return array(
    'entity_test' => array(
      'label' => t('Test Entity'),
      // Entity API needs to know about your module for the views integration to work
      'module' => 'entity_test',
     ..
?>

Once the 'module' property is defined the entity API will no longer try to guess the property types and follow hook_entity_property_info() implementation.

This same trick also solved errors related to string and array conversions I was having such as:

  strpos() expects parameter 1 to be string, array given in
  entity.property.inc:363


User registration without email address OR registration with pseudo-email address I am programmatically creating users for the roles Parent (Adult) & Child (minor). During registration, minors (Children) typically will not have email addresses but Drupal user registration requires email address.

During registration of minor, unfortunately, the adults email address cannot be reused based on Drupal’s one email rule.

My queries are as follows:

Is it possible that we can create users without email address?
If not 1. can we use some pseudo-email address that we can created for each minor. However, emails for any minor should be sent to the adults address instead.

I think you need an email address, but I could be wrong about this.

You can definitely provide a fake email address though.

For example, you can use hook_form_alter() to modify the registration form:

function MYMODULE_form_user_register_form_alter(&$form, FormStateInterface &$form_state, $form_id) {
  // Hide the mail form
  $form['account']['mail']['#access'] = FALSE;
  // Set the email address to minor+UID@mydomain.com
  // You need to write this code yourself...

Make sure you set the email address to include the UID or something similar that will ensure the email is unique; Drupal has to have a unique email for each account.

Then, use hook_mail_alter to check the user's role and, if the user is a minor, query the parent's email address and send the parent an email instead.


How to disable a permission for a moderator role which is granted to an authenticated user? There are two roles I have created 1. Authenticated user 2. Moderator,

Authenticated user can post the content as I expected.

But for Moderator role, I don't want to give permission to add content on site.

Because of moderator is an authenticated user, he is getting all permissions of authenticated user.

And the checkbox of permission is selected and disabled, how can I uncheck it ?

Or there is any other way to prevent moderator for upload content ?

Your key challenge is to get around what seems to be a contradiction, which is that a user with role "moderator" is, by design of Drupal, also an authenticated user.

By using the Rules module, it is possible to implement something that looks like restricting access to URLs that start with node/add, and this for one or more selected role(s). So you could use this as a kind of workaround, as further detailed below.

To "add content to a site" (as in your question), a user needs to enter such URLs (starting with node/add) to actually start doing so (or click some link that matches with such URLs). By "redirecting" those URLs for users with a specific role you can implement what you're asking for.

Here is a rule (in Rules export format) which should be pretty close to implement such access restrictions like you're asking for:

{ "rules_limit_access_to_node_add_urls_" : {
    "LABEL" : "Limit access to URLs to add nodes",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "ON" : { "init" : [] },
    "IF" : [
      { "user_has_role" : {
          "account" : [ "site:current-user" ],
          "roles" : { "value" : { "4" : "4" } }
        }
      },
      { "text_matches" : {
          "text" : [ "site:current-page:path" ],
          "match" : "\/node\/add",
          "operation" : "starts"
        }
      }
    ],
    "DO" : [
      { "redirect" : { "url" : "no_access" } },
      { "drupal_message" : {
          "message" : "You are not allowed to use such path...",
          "type" : "warning"
        }
      }
    ]
  }
}

The above rule performs a redirect for users who have a role with role id = "4". Just adapt that role id to fit your moderator role (if needed) and import (using the Rules UI) the above rule and you should be good to go.


Only show the cart block if it contains items How can I set a Drupal Commerce shopping cart block to only display if it contains items? I'd like to hide the cart block when the cart is empty.

Here is the solution. Add these lines in template.php file of a theme you`re using. Change THEMENAME on the name of your theme.

function THEMENAME_commerce_cart_empty_block() {
  return '';
}


How to retrieve ConfigEntity instance from config factory? I have defined a config entity in my module (schema and class that extends ConfigEntityBase) - MyConfigEntity.

When I use config factory to get config, Drupal returns instance of Config or ImmutableConfig. How can I retrieve instance of MyConfigEntity instead?

$config = \Drupal::config('my_module.config.something');
// Now $config is instance of ImmutableConfig.

\Drupal::config()

  Retrieves a configuration object.

  This is the main entry point to the configuration API.

The configuration API is a different system than the entity API.

$entity = \Drupal::entityTypeManager()
  ->getStorage('my_config_entity')
  ->load($id);

Configuration entity types should be used to store configurable content like content types or other site builder-esque things that you want to deploy from environment to environment that is not managed content (Something a content author would write).

If you're looking for a complex configuration object, then you should define that in config/mymodule.settings.yml and use the configuration API like in your question.


Is it possible to setup reports per individual user when using the Commerce Reporting Module? My project involves multiple users selling products on the site. I am liking the simple displays of the Commerce Reporting module and I am wondering if it can be set up per user.

  For example :

  User1 when logged in would see sales reports that relate to them (all
  products created by that user).

  User2 when logged in would only see products they created.

What I can see so far is that I have Views options to display Views Blocks of these charts on a specific page. That way i can make duplicate views and add a relationship. This is now where i get stuck. In the relationship options of these specific views there are no "user id" options.

  List of relationship options

  Commerce Order: Owner

  Commerce Order: Payment Transaction

  Commerce Order: Referenced customer profile

  Commerce Order: Referenced customer profile

  Commerce Order: Referenced line items

  Commerce Order: Representative payment transaction

  Commerce Order revision: Order

  Commerce Order revision: User

This question seems fairly similar to the question "https://drupal.stackexchange.com/questions/141473/how-to-only-include-data-in-a-commerce-reporting-report-about-products-created-b" ... Which has a comment that might be the answer to what you're looking for ... Did "I" hereby answer "this" question?

Aso, while waiting for the Commerce Reporting handbook to get some real content (cfr. your valid comment in the other reply), you may want to look at the Visualization documentation, which includes a link to a video about Commerce Reporting (the Visualization module is the charting API used by the Commerce Reporting module).

Be Aware: I'm a co-maintainer of the Visualization module


AJAX form submit by clicking on any element with the #ajax property I have been searching for this a lot but all the tutorial on the net only show how to create an ajax form with #ajax on the submit button if you want to submit the whole form.

What I am trying to achieve is this: I've got a custom form with lots of checkboxes, all of which set values in an array stored in $_SESSION. When I attach #ajax to a checkbox the form gets replaced, but the $_SESSION array does not change as if the form as a whole has not been submitted.

How can I achieve that when I click on a checkbox the form submits as if I clicked on the submit button and the $_SESSION array is set correctly?

Thanks a lot in advance.

Maybe this code:

$( "[type="checkbox"]' ).change(function() {
  $( "form" ).submit();
});

When a checkbox is change, it submits the form.


How to fill checkout form fields with values from a previous custom form? Basically I have a few landing pages with forms with fields that are a subset of the checkout page form fields. I'd like for the user to submit the form and be redirected to the checkout page with the form values already filled.

I'm using Übercart and I think it's this function here that controls it:

function uc_checkout_pane_delivery($op, &$arg1, $arg2) and the values of $arg1 needs the be set by the previous form. My question is how? What would be an appropriate method for populating the checkout form fields? Thanks.

I think you could get away with this by using hook_form_alter (checkout is still a form) and just setting #default_value on the required field. The previous form could save it in $_SESSION somewhere.


How to get the raw value of the url in a link field I'm doing this:

$link = $node->field_link->first();
if ($link) {
  $url = $link->getUrl()->toString();
  ...
}

If the value in the link field is /node/123 but there is a URL alias defined as:

Alias: /about-us    System path: /node/123

I get /about-us in $url. I want to get /node/123.

How do I get the raw url value instead of the aliased value?

Instead of rendering the URL object with toString() use the method Url::getInternalPath:

$url = $link->getUrl();
if ($url->isRouted()) {
  $path = $url->getInternalPath();
}


How to put a custom form inside node form with own submit button? I have a small custom form which has its own submit button.

$form['activity']['submit'] = array(
      '#type' => 'button',
      '#value' => t('Execute'),
      '#name' => 'test_button',
      '#submit' => array('my_custom_form_submit')
    );

I placed this in the page manager in the node edit form.

But the problem is the function my_custom_form_submit is not get executed. Instead the node form gets submitted and redirected to node view page.

Is there any way to to execute 'my_custom_form_submit' function on clicking on the custom form submit button?

Note: I don't need ajax, I want it without ajax.

you should use an ajax in inner form on submit like :

  $form['activity']['submit'] = array(
  '#type' => 'button',
  '#value' => t('Execute'),
  '#name' => 'test_button',
  '#ajax' => array(
    'callback' => '_handle_form_submit',
    'effect' => 'fade',
),
);

 function _handle_form_submit($form, $form_state) {
 // your stuff here
 }

you can see ajax example modules Ajax Examples


node theming doesn't work I am a Drupal beginner. I'm using Drupal 7. I created a blog using views. I'm trying to theme the blog node using node--blog.tpl.php but it doesn't work. When I change it to simply node.tpl.php it works. I don't know what is the problem. How can I make it work?

That's a known issue in some Drupal versions: Drupal will not pick up node--blog.tpl.php from your theme directory unless there is node.tpl.php too. Just place them both in your theme, clear cache, and you should be fine.


node-edit-protection module not working in CK Editor window I am using node-edit-protection module to alert a user if they are navigating away from a modified Node Edit form without saving. It worked fine if we edit title or any other fields. But not worked if we change the body part. I am using CKeditor in body part.

Open node-edit-protection.js file in module's folder,
Find this code

window.onbeforeunload = function() {
     if (edit && !click) {
     click = false;
            return (Drupal.t("You will lose all unsaved work."));
     }
}

replace above code with following

    window.onbeforeunload = function() {
    if (typeof(Drupal.settings.ckeditor) != 'undefined' && typeof(CKEDITOR) != 'undefined' && typeof(CKEDITOR.instances) != 'undefined') {
         for (var i in CKEDITOR.instances) {
          if (CKEDITOR.instances[i].checkDirty()) {
           edit = true;
           break;
          }
         }
        }

         if (edit && !click) {
          click = false;
          return (Drupal.t("You will lose all unsaved work."));
  }
}


Returning body values only I have the following function that simply grabs nodes:

function getWords() {
    $query = new EntityFieldQuery();
    $query->entityCondition('entity_type', 'node', '=')
            ->propertyCondition('status', 1, '=')
            ->propertyCondition('type', 'wall_of_words', '=');
    $result = $query->execute();
    return node_load_multiple(array_keys($result['node']));

}

Right now it's working but it's returning everything, is there a way I can return the contents of the body or title field only?

You can leverage field_attach_load() for this:

$query = new EntityFieldQuery();
$query->entityCondition('entity_type', 'node', '=')
  ->propertyCondition('status', 1, '=')
  ->propertyCondition('type', 'wall_of_words', '=');
$result = $query->execute();

$nodes = $result['node'];

// Get all fields attached to a given node type
$fields = field_info_instances('node', 'wall_of_words');

// Get id of body field
$field_id = $fields['body']['field_id'];

// Attach a field of selected id only to get value for it
field_attach_load('node', $nodes, FIELD_LOAD_CURRENT, array('field_id' => $field_id));

Now you have $nodes array of "half-loaded" nodes, where you can get your field data from like it were a usual node, just do something like this:

foreach ($nodes AS $nid => $node) {
  print $node->body['und']['value'];
}

Note. I used 'und' for language here. You may want to query for node language field here to get a dynamic language data if needed.

So this should work.

UPD. One note to this. field_attach_load() doesn't invoke hook_node_load(), so if some data is being manipulated via hook_node_load() you won't get its representation via described method. This is the only drawback of this method. But in most cases it is safe to use. Just check if it works in your circumstances.


WSOD with error when login as administration I was working on website and suddenly noticed that a particular page had a error message and lost a lot of css styles.

When I went back to the back-end I saw a white page with following message and nothing else (no administration menu, no content overview, ...

Error message

Additional uncaught exception thrown while handling exception.

Original

PDOException: SQLSTATE[HY000]: General error: 2006 MySQL server has gone away: SELECT s.uid, c.updated FROM {ctools_object_cache} c INNER JOIN {sessions} s ON c.sid = s.sid WHERE s.sid &lt;&gt; :session_id AND c.obj = :obj AND c.name = :name ORDER BY c.updated ASC; Array ( [:session_id] =&gt; HWv-9jPhNMHqjMdxRprJh-YmmBQc2y0jWXrbR_68TeA [:obj] =&gt; view [:name] =&gt; article_4pc ) in ctools_object_cache_test() (line 145 of /home/admin/domains/peace-in-the-city.be/public_html/sites/all/modules/ctools/includes/object-cache.inc).

Additional

PDOException: SQLSTATE[HY000]: General error: 2006 MySQL server has gone away: INSERT INTO {watchdog} (uid, type, message, variables, severity, link, location, referer, hostname, timestamp) VALUES (:db_insert_placeholder_0, :db_insert_placeholder_1, :db_insert_placeholder_2, :db_insert_placeholder_3, :db_insert_placeholder_4, :db_insert_placeholder_5, :db_insert_placeholder_6, :db_insert_placeholder_7, :db_insert_placeholder_8, :db_insert_placeholder_9); Array ( [:db_insert_placeholder_0] =&gt; 1 [:db_insert_placeholder_1] =&gt; php [:db_insert_placeholder_2] =&gt; %type: !message in %function (line %line of %file). [:db_insert_placeholder_3] =&gt; a:6:{s:5:&quot;%type&quot;;s:12:&quot;PDOException&quot;;s:8:&quot;!message&quot;;s:382:&quot;SQLSTATE[HY000]: General error: 2006 MySQL server has gone away: SELECT s.uid, c.updated FROM {ctools_object_cache} c INNER JOIN {sessions} s ON c.sid = s.sid WHERE s.sid &amp;lt;&amp;gt; :session_id AND c.obj = :obj AND c.name = :name ORDER BY c.updated ASC; Array ( [:session_id] =&amp;gt; HWv-9jPhNMHqjMdxRprJh-YmmBQc2y0jWXrbR_68TeA [:obj] =&amp;gt; view [:name] =&amp;gt; article_4pc ) &quot;;s:9:&quot;%function&quot;;s:26:&quot;ctools_object_cache_test()&quot;;s:5:&quot;%file&quot;;s:103:&quot;/home/admin/domains/peace-in-the-city.be/public_html/sites/all/modules/ctools/includes/object-cache.inc&quot;;s:5:&quot;%line&quot;;i:145;s:14:&quot;severity_level&quot;;i:3;} [:db_insert_placeholder_4] =&gt; 3 [:db_insert_placeholder_5] =&gt; [:db_insert_placeholder_6] =&gt; http://peace-in-the-city.be/admin [:db_insert_placeholder_7] =&gt; [:db_insert_placeholder_8] =&gt; 178.118.99.54 [:db_insert_placeholder_9] =&gt; 1426611072 ) in dblog_watchdog() (line 160 of /home/admin/domains/peace-in-the-city.be/public_html/modules/dblog/dblog.module).

Uncaught exception thrown in session handler.

PDOException: SQLSTATE[HY000]: General error: 2006 MySQL server has gone away: SELECT 1 AS expression FROM {sessions} sessions WHERE ( (sid = :db_condition_placeholder_0) AND (ssid = :db_condition_placeholder_1) ); Array ( [:db_condition_placeholder_0] =&gt; HWv-9jPhNMHqjMdxRprJh-YmmBQc2y0jWXrbR_68TeA [:db_condition_placeholder_1] =&gt; ) in _drupal_session_write() (line 209 of /home/admin/domains/peace-in-the-city.be/public_html/includes/session.inc).

I was able to login as another users without any problems. I flush caches and run cron and this have not solve my issue.

How can I troubleshoot this problem ?

You can find the website here.

To troubleshoot, add these lines to your settings.php:

error_reporting(E_ALL);
ini_set('display_errors', TRUE);
ini_set('display_startup_errors', TRUE);

Once you add these, you should see some error output.


Problems in recovering the fields with php How do I retrieve a field without first being written its title? Now I'm doing so: print render ($ content ['field_text']);
I tried to recall the title of a node: print render ($ content ['title']);
but this is not the way

In node.tpl.php, the title is available as $title.

http://api.drupal.org/api/drupal/modules%21node%21node.tpl.php/7

In the case of full-page view of nodes, the title may be printed via page.tpl.php, so you may also need to modify that template to get the desired behavior.

http://api.drupal.org/api/drupal/modules%21system%21page.tpl.php/7


Why is suggested not to use symlink for sites/all and sites/default? The status report for Pantheon (Drupal 7) says that sites/all sites/default and sites/default/settings.php is not a symbolic link, and it is considered as best practice. Why?

You'd have to ask Pantheon to be 100% sure (they even did the initial development of the module). However, the warning message in response to a situation where sites/all is a symbolic link, is:

  Avoid changing Drupal's site structure; remove the symbolic link and recreate sites/default.

So I think it's safe to assume this is just warning you not to mess with the structure of a Drupal site, which would probably cause problems or unexpected results when updated in future.


How do I reference an image inside my custom module directory? I want to ship a default image in my custom module. I know I can reference images in the files directory with public://, but how can I properly reference my module's URL path?

Update: I need to pass this URI to image_style so a raw path to the module directory won't be enough:

  $render_image = [
    '#theme' => 'image_style',
    '#style_name' => 'blah',
    '#uri' => $uri,
    ...
  ];

The \Drupal class has many useful static functions such as moduleHandler. I recommend (for future issues) to first search there, then in the core.services.yml & system.services.yml files for a service or a method that could help.

\Drupal::moduleHandler()->getModule('foo')->getPath()


How to hide node by Role similar to the Hide Block by Role module? Does anyone know of a module similar to the "Hide Block by Role" module, but for nodes?

The scenario I'm looking to achieve is:

User 1 has Role A and Role B
User 2 has Role A and Role C

I need to be able to create a node and limit access to Role A and Role B, but also hide/block it for Role C. So, User 1 would see the node but User 2 would not. Currently, because User 2 has Role A, he is able to see the page which is why I need something similar to "Hide Block By Role".

I'm currently using the Content Access module to control access.

Rules (the module) is your friend ... Here is a prototype of a rule (in Rules export format) that you could use (assuming that the Role ID (rid) for Role B is "4", adapt the value of this rid to fit your case):

{ "rules_limit_access_to_some_urls" : {
    "LABEL" : "Limit access to some URLs",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "ON" : { "init" : [] },
    "IF" : [
      { "NOT user_has_role" : {
          "account" : [ "site:current-user" ],
          "roles" : { "value" : { "4" : "4" } }
        }
      },
      { "data_is" : {
          "data" : [ "site:current-page:path" ],
          "op" : "IN",
          "value" : { "value" : [
              "node\/123",
              "node\/456"
            ]
          }
        }
      }
    ],
    "DO" : [
      { "redirect" : { "url" : "access_denied" } },
      { "drupal_message" : {
          "message" : "Access to the content located at \u0022\u003Cstrong\u003E[site:current-page:path]\u003C\/strong\u003E\u0022 is not allowed.",
          "type" : "warning"
        }
      }
    ]
  }
}

After you enable the above rule, you can grant Access (view) permission to the nodes "node/123" and "node/456" for users with role A (using the Content Access module). That will already prevent access to these nodes for any user who does not have that role A.

The above rule will ensure that users who do not have role B, will NOT be able to actually "view" these nodes. Instead they'll get a message starting with "Access to the content located at ..." (change this message to whatever fits).


Drupal 7 custom block.tpl.php for specific region I am new to drupal 7 and really struggling with this one:

http://drupal.org/node/104319

I have a region called navigation

in my .info
regions[navigation]     = Navigation bar

for this region I want to use a custom tpl.php file. I have tried

  block-navigation.tpl.php

like in the example, and put it at the theme root and in the templates folder with no luck. I've cleared the cache and insured that a standard working block.tpl.php is in place. To no avail.

ANSWER:

I needed BOTH a region--navigation.tpl.php AND a block--navigation.tpl.php with a double -- both times.

1000 views on this question earned me the popular question badge. But you guys can't find it in your heart to upvote it more than 1 time. Laaaammmmmeeee....

To use a custom tpl.php file for "navigation" region, you should use region--navigation.tpl.php


What are the list of Drupal 7 image cropping modules out there? Currently I use EPSA crop for cropping images as it uses the same image field without making a new one. What are the list of image cropping modules out there that provide a similar functionality? Epsa crop gives me the ability to crop different sized images for different image styles.

You can use the Image Javascript Crop Module.

  This module makes an Imagecache 2 (D6) or Styles (D7) 'javascript crop' toolbox action available for use with several modules.


Disable module while running command I have a custom drush command that does some pretty heavy node creation etc. I would like to disable certain modules only for the duration of the script to improve their performance.

I can not do a drush dis module_name before running my command because I need the modules to be active on the site while the script is running, but not active for the runtime environment of the current command.

I would rather not have to hack core, but from what I can see, I'm probably going to need to alter something in either module_list() or drupal_load() since neither of them have any hooks.

Is there any way to do what I'm after without hacking core?

Here is one solution that I came up with after looking around in core's code. It seems to work as expected.

$module_list = module_list();
if (isset($module_list['token'])) {
    unset($module_list['token']);
}
// Reset the list to our new list of modules!
module_list(false, false, false, $module_list);
// Force to regenerate the stored list of hook implementations.
module_implements('', false, true);


Content in Lightbox dialog Is this possible to pass some content (cck fields values) to Lightbox dialog when image belongs to the same content type is opened?

Lightbox is specifically design to preview images. For General purpose overlay preview for images, videos, iframe and any custom html/text I recommend to use Fancybox. Fancybox module is available for integration in druapl.

$.fancybox("Your HTML");


Pass query parameters through local response I'm trying to pass query parameters received on a controller from an external redirect through TrustedRedirectResponse or LocalRedirectResponse. None of the options seem to be working.

Receive the query parameters through the request you've added as parameter to the controller and pass them via the URL of the redirect.
Caching is a bit tricky because generating an absolute local URL bubbles up cacheable metadata which you need to collect by Url::toString(TRUE):
public function view(Request $request) {

  $url = Url::fromRoute(
    '<front>',
    [],
    [
      'query' => $request->query->all(),
      'absolute' => TRUE,
    ]
  )->toString(TRUE);

  $redirect = new LocalRedirectResponse($url->getGeneratedUrl());
  $redirect->addCacheableDependency($url);
  $redirect->getCacheableMetadata()->addCacheContexts(['url.query_args']);

  return $redirect;
}


Provide an interface to edit only one field of a content type? I am trying to create a 'start a bounty' system, just the same as on this site using userpoints. There should be a link 'Start a bounty' which allows the question creator to start a bounty using his points. I am using userpoints for this purpose and I created a field where the user can select the number of points he would liek to give out for a correct answer. But this can only be done on node creation or while editing the entire node. The question is - how to be able to select the number of points only after clicking on 'start a bounty' without the need of editing all the remaining fields. So ideally there should be a popup with dropdown field that edits only this particular field. I guess one approach is to create a node edit form with this field only (is this possible at all?) and put it in the ajax popup... Any ideas / advice?

There is a new module by Earl Miles, the creator of Views, that does this in Drupal 7 called the Field API Pane Editor.  Unfortunately, because this is a new solution for D7 and Earl Miles tends not to reinvent the wheel, I don't think there is any existing module that you can download for this use case in D6.


Getting Drupal 8 to use an external index? I have two sites one is maintained by us in drupal 8 and the other is maintained by another company that does the news updates etc for our company. I'm trying to figure out the best way to get a combined search in drupal. So set up a Solr instance and setup a web crawler to crawl the other site, set up drupal 8 to use the search api and solr search. But now i'm not sure what's the best way to integrate the index created by the web crawler with drupal 8. Any ideas?

What you could do is use the Migrate module to migrate content from one site to the other. What you need to do is:

Build a custom source plugin for it so that it fetches its data from an external source (i.e. the other site) and map it to a content type in your Drupal install.
Then set up a cron job to run the migration periodically to update the data on your end. Make sure you set the migration to "update" since by default, migrations won't happen on already-migrated content.
Create your search however you want in your site (Views, Search API, etc.) using that content type.

In D7, this was a job for the Feeds module but they don't appear to have a D8 version yet.


Multisite - Commerce reference between sites Setup

Main website: www.example.com
LMS website: lms.example.com

The Main website is public facing for visitors to browse the courses.
The LMS website is for the users/commerce to be managed and the actual Course material to be used/viewed.
Drupal Commerce manages the payments and Access modules manage the users access once purchased.

The 2 websites are setup as Drupal multi-sites:

On the same server
Separate databases
All modules/theme files are under the sites/all folder.

Question

How do I create a 'Buy' button on the main website that will take the visitor to the LMS website with that particular course added in their cart?

Note: there is only a hand full of courses so the link on the main website can be manually added for each course.

So I have discovered that I will need to create a Rule using the module Rules URL Argument that will take the URL /add-to-cart/[SKU] and add this to cart.

I can create a field on the main site for the SKU and this then outputs the link to the LMS website.

The source is here:
https://www.youtube.com/watch?v=6Rn7FLFytTU


User Registration with REST How do you register a user account via REST in Drupal 8?

Here's how far I've made it (not sure if this is the right direction though):

I've enabled the Form mode resource under admin/config/services/rest for POST, cookie authentication, and hal_json and json formats. I then make a call to the site:

POST: http://localhost/d8/entity/entity_form_mode
Content-type: application/hal+json
Accept: application/json

The JSON to POST will start something like this:

{"_links":{}}

It will of course be filled in with various properties and values. What are these properties and values though? I've tried many combinations, and the furthest I've got is the server responding with this:

{"error":"Entity type parameter must be included in context."}

This now works in Drupal 8.3-x-dev. This is an example to do it from Angular:

  /*
   * Register new User.
   */
  register: function (email, password) {

    var defer = $q.defer();

    $http({
      method: 'POST',
      url: config.endpoint + '/user/register',
      dataType: 'json',
      data: {
        'name': {
          'value': email,
        },
        'mail': {
          'value': email,
        },
        'pass': {
          'value': password,
        }
      },
    })
      .success(function (data, status, headers, config) {
        defer.resolve(data);
      })
      .error(function (data, status, headers, config) {
        defer.reject(data);
      });

    return defer.promise;
  }

Make sure you enable the resource to enable user registration (I use the REST UI module).

The last step is enabling the permissions on this resource:

Now you are all set!


How can I make special non-Drupal URLs without file extensions? As I understand it, Drupal is supposed to check the web root for any URLs it doesn't recognize, to see if it's a non-Drupal file on disk.  Also, Apache is supposed to assume that anything without a file extension is a request for whatever.html, correct?

Here's what I'm trying to achieve: a user requests mysite.com/FOO, Drupal doesn't find any path/alias for FOO, and thus turns it over to Apache.  Apache doesn't see a file extension, and thus looks for a file called FOO.html (which exists) and serves up that file.

If I request mysite.com/FOO.html, the file is returned just fine.  I'm just trying to make it so that people can access FOO.html by simply requesting /FOO, since you can't trust the user to type in the full URL.  (And because it looks nicer in a print ad.)

I'm guessing that there's some .htaccess magic that needs to happen, but I haven't been able to come up with the right trick. I think that Drupal passes to Apache, which doesn't find /FOO, then the .htaccess file punts the request to Drupal's index.php, which returns the Drupal 404 page.

If the file exists serve it.

  RewriteCond %{DOCUMENT_ROOT}%{REQUEST_URI}\.html -s
  RewriteRule .* %{REQUEST_URI}\.html [L,T=text/html]

You'll need to put it above this inside your .htaccess file.

  # Pass all requests not referring directly to files in the filesystem to
  # index.php. Clean URLs are handled in drupal_environment_initialize().
  RewriteCond %{REQUEST_FILENAME} !-f
  RewriteCond %{REQUEST_FILENAME} !-d
  RewriteCond %{REQUEST_URI} !=/favicon.ico
  RewriteRule ^ index.php [L]

You can't pass the request back to apache once you've passed it to Drupal. The code above will hit the .html file first if it exists.

To do exactly what you want, you can set the 404 handler inside of drupal to a custom page; that page could then check to see if the file exists and use that. Config page for 404: admin/config/system/site-information. The handler would use something like this

<?php
$path = substr(request_uri(), strlen($GLOBALS['base_path'])) . '.html';
if (file_exists($path)) {
  echo file_get_contents($path);
  exit;
}
return MENU_NOT_FOUND;
// OR this, not sure.
return drupal_not_found();
?>


Clear cache after save orders using draggable views in Drupal 7 I've used Draggableviews 7.x-2.1 module to enable drag & drop options for particular views. It works well.

I've enabled cache for Anonymous users. Due to this, after save the ordering, the changes didn't affect orders for Anonymous users.

So I've tried to clear cache after submitting handler of draggable views. I've used below code:

function phponwebsites_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'views_form_test_views') {
    $form['#submit'][] = 'phponwebsites_draggable_custom_submit';
  }
}

function phponwebsites_draggable_custom_submit(&$form, $form_state) {
  print_r('ss');exit;
  drupal_flush_all_caches();
}

But my custom submit handler doesn't call. Is any other solutions?

Sometimes "#submit" functions of HOOK_form_alter are get changes. SO please try adding $form['#after_build']. Your code will be like.

function phponwebsites_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'views_form_test_views') {
    $form['#after_build'][] = 'phponwebsites_draggable_custom_afterbuild';
  }
}
function phponwebsites_draggable_custom_afterbuild($form, $form_state) {
  $form['#submit'][] = 'phponwebsites_draggable_custom_submit';
  return $form;
}
function phponwebsites_draggable_custom_submit(&$form, $form_state) {
  print_r('ss');exit;
  drupal_flush_all_caches();
}


Access hook_preprocess_node variables from page controller I have a custom controller created for a custom URL, where the URL is a URL for an existing node with an additional parameter. The display for the URL defined by the controller needs to use the the same template for the base node route, and the controller just uses a service to get additional data and merge it with the base node data.
To be more specific, I have a node type called product_group. It has an entity reference field called field_products that attaches commerce_product entities. The URL alias pattern for product_group nodes is /products/[node-title]. My controller is for the URL /products/[node-title]/[sku], where sku is the commerce_product sku. The controller gets the data from the URL, loads the base product_group node object, uses the sku value to get the commerce_product object, and then I have a custom service that gets a bunch of additional data from the product and associated variation.
The tricky part is that the display at the /products/[node-title]/[sku] URL is the same as the display at the /products/[node-title] URL, with some additional data from the product itself added in. Therefore, I need to get all of the $variables data that is available in hook_preprocess_node() function in my controller and add my new data on top of it. The problem is, I can't figure how to access it. From what I've seen, you can't access data in a preprocess hook directly from a controller, but I'm guessing there has to be some way I can render the product_group node and get the variables that are available in hook_preprocess_node. Am I correct, and if so, how do I do it?

So the problem turned out to be an incorrect #theme template name in my returned render array. The node type I was adding content to was called product_group, but in my controller, I returned this:
 return [
   '#theme' => 'node__product_resource__full',
   '#product_group' => $content,
   '#node' => $pg_node,
   '#view_mode' => 'full',
 ];

product_resource is a valid content type in the site. Once I changed it to
'#theme' => 'node__product_group__full',

It worked fine.


How to set default form fields value from controller How to setup default form fields value from a form created in a controller?

I tryed to set the $form_state param but it does not work.

...
$form_state = new FormState();
$form_state->set('myfield_1', 'car');
$form_state->set('myfield_2', 'bus');
$form = $this->formBuilder->buildForm('Drupal\mymodule\Form\MyForm', $form_state);
return $form;

Add the default values to getForm():

return $this->formBuilder()->getForm('Drupal\mymodule\Form\MyForm', $default1, $default2);

And set the default values in the form class:

class MyForm extends FormBase {

  public function buildForm(array $form, FormStateInterface $form_state, $default1 = NULL, $default2 = NULL) {

    $form['field1'] = [
      '#type' => 'textfield',
      '#title' => $this->t('Field 1'),
      '#default_value' => $default1,
    ];

    // ...

  }
}


Remove http:// from $base_url I am trying to generate a email address that reads as no-reply@example.com.

Using the global base_url the output is http://example.com.

Is there another global, or some other easy solution, to remove the "http://", so that I get the string example.com?

Thanks in advance

Think you're looking for $_SERVER['HTTP_HOST']. Also see $base_path, $base_url, $base_root


Change the link of a view block Hi I need to change the url path of the view which appears to be a block also,its a button and I want that it redirects to the correct URL, how do I change it?
Please help me..
Answers and directions will highly be appreciated thanks.

Blocks do not have URLs.  Pages that blocks are on have URLs.
Check the gear icon when you hover over the view area.

If it says configure block, you are on a page created somewhere else and depending on how it was created may need to edit the code where it is defined in hook_menu() or if it is a page node, you can just go to admin/content and search for that page, and at the bottom you will see URL settings.

If it says does not say configure block and only edit view, then that page was likely created by that view you are about to edit.  In this case you can click Edit View and in the middle of the window you will see Page Settings section with a Path field.  You can edit that Path field which is the URL of the view.


How can I authenticate against a non-drupal database? We have a non-Drupal intranet system built on php/mySQL. We're adding a Drupal install to handle some social functions, and would like (if possible) to not duplicate all of our login information. Is there a module (or technique) that would let us authenticate against our existing users table, rather than needing to create separate user records in the new Drupal install?

I did find this, but it's been abandoned for 6 years, so I don't know how relevant it is anymore.

We have not started the new install yet, so either 6 or 7 is possible - if there's a module that would work for only 6, we're perfectly willing to do that.

My suggestion would be to take a look at LDAP integration or Lightweight Directory Access Protocol modules to see how they handle authentication.

My recollection is that they hook_form_alter the user_login form to add a new validation function that calls out to the LDAP server if Drupal authentication fails.  You should be able to do this for your own authentication.  We modeled a custom authentication on this method, but I don't recall all of the details.

Just remember that you want to use the external authentication in addition to and not instead of Drupal authenticaion so you don't lock out any admins if/when your other site is down.


Which mysql tables contain the URL Alias path data? Im looking to manually change a node's URL path as my edit button throws me an error upon clicking it since this was due to orphaned data left over from some other uninstalled modules. Which tables contain the URL alias path data in Drupal 7?


For a personal-use module, what would be good practice for database tables? I've a set of tables that install with my module, but I worry about mixing them in with Drupal's tables.  I shouldn't simply create a separate database for my own tables, should I?

Is there a 'good' approach to this?

Creating tables to go along with a custom module is acceptable and perhaps event "best practice" in the Drupal world. Using a separate database would require an additional connection via PHP which I suspect would be a waste of server memory but an option if you insist on doing so. Often there's no one "right" answer in Drupal. There are of course "best practices" which I encourage you to follow but there's a lot of room for personal style.


Read data using countries module in view I am using the countries module to add countries in my content type project.

I create a view with type = Default node index to display my content.

I added the Indexed Nœud: Countries (Countries)

But the data saved in my field_countries is not displaying yet it is displayed well in the details page (node project).

Any idea to display the countries data in my view?

Thank you

While adding relationship with countries, the most important, Check the checkbox Require this relationship and then add Countries: Name as fields you want.

It works for me (see) and hope for you too


How to override a twig template for only a specific page? The title of this user view page contains the name of the user. I want modify it and, thanks to twig debug, I see the template used is page-title.html.twig:

{% if title %}
  <h1{{ title_attributes.addClass('page-header') }}>{{ title }}</h1>
{% endif %}

If I override it, how can I make twig use my overrided template only in the user view page?

As you mentioned your main issue is whatever data you are fetching it is overriding the all page-title on the site which you do not want. So to solve that follow following steps,

For common understanding I am referring bartik theme. I am showing with example to my local site so it will be very practical to understand.

In bartik.theme file,

function bartik_preprocess_page_title(&$variables) {
  $variables['staticString'] = 'Explorer ';
  $variables['user_profile_view'] = (\Drupal::routeMatch()->getRouteName() == 'entity.user.canonical'); }

in page-title.html.twig file,

{% if title %}
  {% if user_profile_view %}

{{ staticString }}{{ title }}

  {% else %}

{{ title }}

  {% endif %}
{% endif %}

Output image,
On user page,

On other page(It will not interfere),

So, this way you can Override the page-title of user-profile page and can insert your own defined variable. So, this answer is with static variable, now same way, you have to just replace that variable with your dynamic variable, so it will get change based on your code.

Note: In solving this question, I have asked another question here: How to get the part of URI and pass it to as a argument?.


What causes the error in my custom module for OpenLayers 3? This error gives me a whitescreen with just this message:

Drupal\Component\Plugin\Exception\PluginException:
Plugin (ifplabel) instance class "Drupal\ifplabel\Plugin\Style\ifplabel\ifplabel" does not exist in Drupal\service_container\Plugin\ContainerAwarePluginManager::getPluginClass()
(line 120 of /Users/me/Sites/ifp/html/sites/all/modules/service_container/src/Plugin/ContainerAwarePluginManager.php).

Background: The name of the module is called "ifplabel". I am making a custom module for OpenLayers 3 that will provide me with a custom marker style.

My Repo: https://github.com/joelhsmith/ifplabel

Looks like a mismatch between your annotation (the @ in the comment above your class) and your class declaration.

But you should post your code for more details.


Content Type with Add comment, Post New Article, Share Links I have created a drupal page, I want to add comment,share link to the post I have tried using view to create it it does not work out.

To add Add comment link in view, follow below steps.

Add another field to your view i.e. Content: Nid
In field configuration, remove the title.
Select "rewrite the output of this field" and enter "Add comment" in the text area.
Now select "output this field as a link" and enter comment/reply/[nid]#comment-form in the Link Path field.

To add Share link,

Install ShareThis module.
Now add share field into your view.


Drupal 7: Webform: Send Email Custom PHP on Webform submit 0 down vote favorite

I have a webform and I want to send an email to a user on submit action on this webform.

Note: I do not want to use the inbuild emails module for webform as it has some limitations related to the functionality that i want to achieve. Hence I want to send a test email on Submit action via a custom PHP.

I know how to write PHP for a webform but I need some guidance on how to use it for sending emails.

Also I want to send emails on submit action only if user selects a select option on this form.

How can I do this? Please help I am stuck on this for a long time now.

I tried using Rules module but I can not check the webform field values in rules.

It's possible that you could use either hook_webform_submission_presave or hook_webform_submission_insert in a custom module, check for the your webform component value (i'd assume it's in $submission) and then fire your email.

In a custom module, add your hook like so.

function mymodule_webform_submission_insert($node, &$submission){
  // Use devel to investigate the variable
  dsm($submission);
}

Creating custom modules for Drupal 7 or Drupal 6. Tutorial.

Use Devel module to investigate your variables, as seen in my example above.

Jason.