Alter render (array) of a field in a View? How do I alter the rendering of a field in a View?
Where can I access the render array before the html is generated for output?

For example, if I have an image field included in my view, where can I add to the attributes of the image before the image is rendered using theme_image?  Assuming that the field is eventually still rendered using theme_image.

I want to add attributes to the image tag and NOT the surrounding divs that Views inserts into the markup.

EDIT based on answer by Jimajamma:

Editing the $view->result as suggested is causing the View to crash.  Page doesn't render correctly anymore:

function MYMODULE_views_pre_render(&$view) {
   if ($view->name=='viewyouarelookingfor') {
      foreach($view->result as $row) {
         $row['field_body'][0]['rendered']['#markupe'] = '
Test!
'; // causes View to crash
      }
   }
 }

I'd take a look at the views_pre_render(&$view); hook.  There, in your module, you can do stuff like:

 function MYMODULE_views_pre_render(&$view) {

   if ($view->name=='viewyouarelookingfor') {

      // do whatever you want

   }

 }

and do whatever you want meaning you have access to $view->result which is an array of all the raw data making up each row.  Throw in  a drupal_set_message('<pre>' . print_r($view->result, true) . '</pre>'); or its equivalent to take a peek at that and you should be able to work all kinds of magic.

If this doesn't work to your needs, you can still render the field any way you like from a view template for that row or field itself.


Contextual Links add destination=node to URL - can i restrict that from happening? - stopping delete functionality I have a contextual link on a block that will take the user to an admin screen with a delete button on the admin screen.  The delete button works fine when not coming from the contextual link.  I noticed the contextual link adds "destination=node" to the end of the URL.  The fact that the contextual link adds that to the URL does not allow for my admin screen to redirect to the delete confirm admin screen.  If i remove the "destination=node" from the admin screen URL, it goes to the delete confirm admin screen with no issues.  Has anyone else had this issue?  I noticed this is for absolutely any module or block in drupal.  If going to the admin screen from a contextual link and it has a delete button on the admin screen, the delete functionality will not work!  Any suggestions?

The accepted answer is not entirely correct.  When hook_menu_contextual_links_alter() gets to act on the array of contextual links, no destinations have been set yet.

Instead, just a few lines after menu_contextual_links() (and so its alter hook) is called in contextual_pre_render_links(), there is this line adding the destination to the contextual link:

$item['localized_options']['query'] += drupal_get_destination();

If you set a query destination in hook_menu_contextual_links_alter(), the one you set will win.  But if you just want to get rid of the destination so for instance a redirect set in the form can do its thing (including, say, adding a fragment)... removing the destination before it is added here doesn't work.

This being Drupal, however, two lines later another alter hook is called:

drupal_alter('contextual_links_view', $element, $items);

(This is all in contextual module.)

So implement that hook instead.  For a module named example removing the destination from all node edit alter hooks on a given array of content type machine names available with the function example_selected_node_types(), the implementation would look like this:

/**
 * Implements hook_contextual_links_view_alter().
 */
function example_contextual_links_view_alter(&$element, $items) {
  if (isset($element['#element']['#entity_type']) &&
      $element['#element']['#entity_type'] == 'node' &&
      in_array($element['#element']['#bundle'],
               example_selected_node_types()))
  {
    $element['#links']['node-edit']['query'] = array();
  }
}


Poll in two languages I've installed Poll Core module in Drupal 7 trying to display the same poll with the same result in two languages (English and Arabic) but Drupal treats each one as a separate poll with different result ...

How could I do this?

Is there any other module can handle this?

I've tried Advanced Poll but I cannot use it I do not know how?

I've solved my problem as follows:

Download the i18n patch from here
Apply the patch using any preferred technique, you can refer to Drupal
Applying should be on a test drupal installation in order to avoid any problems
After that go to modules page and enable the Poll Aggregate module under i18n, this will synch the voting results for all installed languages
After testing the patched module and getting happy result, install the module on your live site.

I have test this solution and it is OK with some small problems that I am trying to solve, and I will share the new things.


Watchdog messages and string replacement Hello I would like to know which of the following ways (or some other) of logging messages is better and why.
I am writing lots of .install files since I create content types and fields programmatically and I often write statements as following:

$t = get_t();
watchdog('mymodule',$t('Field !field_name created.', array('!field_name' => $file_field_name)));

OR

$t = get_t();
watchdog('mymodule',$t('Field !field_name created.'), array('!field_name' => $file_field_name));

Note: in the first example I am doing string replacement in the $t function in the second in the watchdog() function.

Just use this:

watchdog('mymodule', 'Field !field_name created.', array('!field_name' => $file_field_name));

watchdog() function will translate the string you pass as the second parameter. You shouldn't translate the message before passing it to the watchdog().

Check out this answer for more information and references.

Or consult the following document from Drupal's documentation.


How do I get Drupal to use my themes page.tpl.php template for the front page? I'm writing a new Drupal theme. I have a html.tpl.php and a page.tpl.php (soon to add a set of node.tpl.php's for each different content type). I want my page.tpl.php to be used for every page, including the front page — every page is going to have exactly the same layout, so I don't need a page-front.tpl.php.

When I visit www.example.com/node/whatever, my page.tpl.php is applied.

When I visit www.example.com (the front page), my page.tpl.php is completely ignored — I'm assuming that Drupal is looking for page--front.tpl.php, not finding it, and then ignoring my page.tpl.php.

How do I get Drupal to use my themes page.tpl.php template for the front page?

edit:

Apparently my front page isn't even being counted as a node?!? The below code will die on any page except for the front page:

function cefmap_preprocess_page(&$vars, $hook) {
    if (isset($vars['node'])) {
        die;
    }
}

How do I get my front page to be treated as a node like any other node?

edit:

Think I've worked this out, and it's really dumb of me. I set that node to "be the front page" through structure, menus, main menu and then set the path for the link to be "<front>".

Of course, that just changes the link in the menu to be "/", without changing the actual path of the node. So I don't actually have a node at "/", and so I don't get to have a page template or a node template applied.

It is page--front.tpl.php - note the double dashes.

The cascading matches my understanding. page.tpl.php should be called if there are no higher priority page templates. You need devel themer to work this out http://drupal.org/project/devel_themer. It will print out on the screen the template matches.

Details are in the drupal theming guide. in this section:

page--[front|internal/path].tpl.php
base template: page.tpl.php


How do I attach CSS styles to all the pages? i have a theme installed his name is 'businessplus_lite' i want to add some custom style to my sub theme , but i can't see any css applicable , can anyone help me please !

  .info.yml

name: mysub-theme
type: theme
description: 'my sub-theme Commissions'
core: 8.x
base theme: businessplus_lite

libraries:
  - my-sub-theme-name/my-sub-theme-style

  libraries.yml

my-sub-theme-style:
  css:
    component:
      css/components/style.css: {}

Please try using below code
info.yml :

name: mysub-theme
type: theme
description: 'my sub-theme Commissions'
core: 8.x
base theme: businessplus_lite

libraries:
  - mysub-theme/my-sub-theme-style

mysub-theme.libraries.yml :

my-sub-theme-style:
  version: 1.x
  css:
    theme:
      css/style.css: {}


Drupal 7 completely offline, avoid Boostrap via CDN I need to move my Drupal site to completely offline environment.
 The bootstrap library takes the correct Bootstrap JS and CSS from sites/all/libraries, but there is a CDN call to download Bootstrap that screws up the bootstrap functions (ex: popup is undefined) in other JS.

So, I have all necessary JS files locally, they are correctly loaded but when I switch off internet, bootstrap functions are undefined.

As far as I see in Bootstrap module, there is no way to avoid this CDN call. I setup in boostrap module settings[bootstrap_cdn] = 0  but it's still calling.

Would appreciate a lot any idea, its kind of urgent.


What is the preferred way to delete la arge amount of data from a Drupal site? We have a client site that currently has a very, very large data set in Drupal. We are working on generating a 'stripped' copy of the database to be used for testing new code by eliminating the bulk of the site content.

To this end, we need to periodically delete 40 million+ nodes and field collection entities from Drupal to strip down a copy of the production database so it can be used more readily on our staging and local development instances.

This is somewhat beyond what VBO or Bulk Delete (Nodes) or other similar contrib solutions can handle in a reasonable time, not to mention that many of the field collections are not on node objects. I suspect that using node_delete_multiple() and entity_delete_multiple() for millions of items may be a non-starter time-wise, even if batched through either the queue API or the batch API.

Is there any way to 'cheat' by TRUNCATING the field_data_* and field_revision_* tables in MySQL to speed the record deletions?

I'm not seeing any simple way to truncate (or truncate from X) a table like this.   The tables that would contain field data would be all mixed up and not nicely sorted.

In this case I would;

Start with a view that generated a list of node IDs based on your
select criteria (content type, status, older than date published,
etc)
Write a custom module with a drush command
Load the node IDs
Either node_delete($nid) OR...
Examine what node_delete() does and delete * from {table} where nid= $nid

The tables node_delete() may touch will largely be dependant on your content types.  node_delete() will do the job, doing it my hand will take more time to prepare but may be faster to run. With the volume of records you're talking about a few milliseconds per delete may save a decent chunk of time.


Common Exposed filter for each tab I have different fields and showing in different blocks, and want to apply exposed filter to all but my problem is it shows different exposed filters for each different block. I want to make it common for each block.

Below are the steps,

I made 5 blocks to be displayed for each buttons.
Added exposed filter for languages for each block.

Now each block showing its different exposed filter.
But I want the exposed filter should be shown above the buttons and should work for each block display. Attached screenshot for the issue.

I installed Views Global Filter but is gives Session error.

After 3 days, I haven't found the solution, even by programmatically.

Then what I had the last option(in my mind, huh) is,

I get all the fields in one block only, not creating the different blocks for different tab or buttons.
Used the description of Better Exposed Filters, in which I pasted my buttons/tab UI HTML as its.
Now on changing the language all the fields are fetched according to the selected language. But in this case my active tab/button get lost its activeness.
Now, I need to get the last active tab/buuton, so that I can click it again to get the active tab after filtering my languages.

Below is the piece of code which is need to my js file.

// Active target element to make the tab/button active after
// ajax responds in filter
var activeTargetElement;
Drupal.behaviors.events = {
    attach: function (context, settings) {
        $('#views-exposed-form-MY_VIEW_MACHINE_NAME-BLOCK_NAME', context).ajaxStart(function () {
            // my tabs/button are active on the basis of data-target attribute,
            // so need to memorise which tab/button is active before fitering any language
            activeTargetElement = $('#MY_TABS li.active a').data('target');
        }).ajaxSuccess(function () {
            // if any target is memorised, then simply click it or trigger a click event for it
            if($('[data-target="'+activeTargetElement+'"]').length){
                $('[data-target="'+activeTargetElement+'"]').click();
            }
        });
    }
};


How to return content with shortcodes from drupal module? I'm using drupal 7 to develop a module.

This module has a menu with a page callback 'page callback' => 'my_function' and the function has to return HTML.

In the function I'm returning array('#markup' => $markup); where $markup has HTML with shortcodes: [button path="node/2" (class="additional class")]Order now[/button].

The shortcodes are appearing directly in the browser without transformation.
I created a page on the web administration page with the same content and the shortcodes are transformed.

How can I return HTML that has shortcodes from a module?

Shortcodes are processed with a filter, so the most reliable way to get what you need would be:

Create a new input format (shortcodes_only or something)
Enable and configure the shortcodes filter for that format, but disable any HTML or other processing that you don't want to apply to your string
Process the string before adding it to the render array like so:

$markup = check_markup($markup, 'shortcodes_only');

If you need to do it programatically it's a bit of a hack, as the shortcode processing code isn't completely decoupled from the filter concept. You need to mock a filter object and give it a couple of properties (a dummy format ID and an array of shortcodes keyed by ID, with a boolean value indicating each shortcode's status).

This is untested but should get you close:

$filter = new stdClass();
$filter->format = 'not_a_real_format';
$filter->settings = array_fill_keys(array_keys(shortcode_list_all()), 1);
$markup = _shortcode_process($markup, $filter);

If you choose the programmatic method, there's something else to bear in mind: by convention, any function whose name begins with an underscore is considered to be private to the module, and its implementation is subject to change in future releases without warning (potentially breaking your code in unpredictable ways). It's probably not that likely in this case, but you never know.


Lightbox2 image formatter in view not adding click event I have a view with an image field in it. I also have two different image styles, "timelinr" and "timelinr-modal". What I want is the thumbnail image to be the first style, and when its clicked on have it come up in a modal with the second style.

I have setup my settings on my image like the following,

For some reason though, this is not adding a click event to my image in the view. Am I doing something wrong here, or should I go about this a different way?

Create a view and do settings as per the screenshot below.

Choose Formatter as described below for content:image

Now you will have thumbnail image of the style "timelinr" and when clicked it will come up with image style "timelinr-modal".
I tested above and it is working.


Are there any issues with installing memcache on a VPS running multiple Drupal sites? I have a VPS running a few independent Drupal sites (not multi-site). What considerations do I need to make (if any) when installing memcache?

Make sure your settings.php file has a unique prefix for each site that has memcache enabled.  I got tripped up by this, and everything went berserk. This thread fixed it for me.  Basically, this is the only issue you would have as far as conflicts.

http://drupal.org/node/1416102

Like APC, memcache works indepedently of your sites.  Make sure you have enough memory for it to function correctly.  You can get a rough idea idea by seeing how much disk space all of your drupal databases take up.  Not all tables in each database will be cached of course, but so long as you have that much memory to dedicate to memcache, you are good to go.

Said differently, as an example I have 12 sites on my VPS 4 gigs of RAM total with 1 Gig dedicated to memcache.  I have never had a problem. Total size of databases on disk is around 400 mb.


Display date field labels within selectors Is there a way to move the labels of the day/month/year components inside the selectors (like Facebook has it on their registration page, see 'Birthday')? I have placeholders in all my text fields and it looks silly that the labels of date fields sit on top.

Ok I've just quickly whipped up a sandbox module to modify date options array. And here's the code, hope this helps:

/**
 * Implementation of hook_form_alter()
 * @param array $form
 * @param array $form_state
 * @param string $form_id
 */
function sandbox_form_alter(&$form, &$form_state, $form_id) {
  if($form_id == 'article_node_form') {
    // Only call after builder if we're using date_combo type which is 3 select fields
    if($form['field_date'][$form['field_date']['#language']][0]['#type'] == 'date_combo') {
      // Add our after build function
      $form['field_date'][$form['field_date']['#language']]['#after_build'][] = 'sandbox_field_date_after_build';
    }
  }
}

/**
 * After build callback
 * @param array $element
 * @param array $form_state
 * @return array
 */
function sandbox_field_date_after_build($element, &$form_state) {
  // Loop through each delta if more than 1 value
  foreach(element_children($element) as $delta) {
    // Loop through each granularity e.g. month, day, year, hour, minute, second
    foreach(element_children($element[$delta]['value']) as $key) {
      // #options not set means this type of granularity isn't set, so we skip
      if(isset($element[$delta]['value'][$key]['#options'])) {
        // If there's an empty value, change the option label to be '- [#title] -'
        if(isset($element[$delta]['value'][$key]['#options'][''])) {
          $element[$delta]['value'][$key]['#options'][''] = '- ' . $element[$delta]['value'][$key]['#title'] . ' -';
        }
        // Otherwise insert an empty value at beginning with label '- [#title] -'
        else {
          array_unshift($element[$delta]['value'][$key]['#options'], array('' => '- '. $element[$delta]['value'][$key]['#title'] . ' -'));
        }
        // Make the title invisible
        $element[$delta]['value'][$key]['#title_display'] = 'invisible';
      }
    }
  }

  return $element;
}

Which produces this result provided you have set "No default value" in the field instance setting:

Or you can always do it in the Advanced Settings of any date field.


create online "diagnostic" questionnaire with results based on choices Is this possible to achieve in drupal 7?
The example I found is here http://www.hairloss-research.com/alopecia-areata-diagnosis/

I tried to use webform module or quizz module but no luck. Thank you for answers.

Maybe this helps: Module for decision tree / guided entry. There is nothing which appears do the job out of the box. So you need to evaluate the modules if they full fill your needs. I am going to check following modules to build a so called decision tree:

Decision Tree
D.A.I.L.
Core Book
Outline Designer
Choose Your Own Adventure
Hierarchical Select
Conditional Fields
... to be continued ;)


Do i really need to hack core to install Amazon S3 Module? I want to run my site through Amazon's Elastic Beanstalk but to do so i need to configure an S3 bucket and the Drupal Amazon S3 module requires that i have to hack core. Surely there must be a way around this? Would Storage API module be a way around this?

I think you should give a try to S3FS module

  S3 File System (s3fs) provides an additional file system to your
  drupal site, which stores files in Amazon's Simple Storage Service
  (S3) or any other S3-compatible storage service. You can set your site
  to use S3 File System as the default, or use it only for individual
  fields. This functionality is designed for sites which are
  load-balanced across multiple servers, as the mechanism used by
  Drupal's default file systems is not viable under such a
  configuration.


Favicon not loading from https I have enabled https for my site. All images and files are served with https url, but favicon it is serving from http://example.com/sites/default/files/favicon.ico instead it should show as https://example.com/sites/default.files/favicon.ico. When I open the site in Firefox it is displaying below error message in console

  Loading mixed (insecure) display content on a secure page
  "http://example.com/sites/default/files/favicon.ico"[Learn More]

Suggest me a way to resolve this.

I have also faced same situation where favicon is serving from http whereas all images including logo are serving from https. I am using Metatag module, in the module configuration default favicon path is given as http://example.com/sites.default/files/, so favicon is serving from http. I have changed the path to https://example.com/sites/default/files/favicon.ico. This fixes the problem, this may also the reason in your case.

If this is the case you can change the favicon default path, go to  https://example.com/admin/config/search/metatags/config/global Under favicon and touch icon tab change the path.


How do I get a link to an image CCK in Drupal 7 in the node view? If I do this:

print_r($node);

I get this:

 [field_main_photo] => Array
    (
        [und] => Array
            (
                [0] => Array
                    (
                        [fid] => 86
                        [uid] => 1
                        [filename] => 01.jpg
                        [uri] => public://01.jpg
                        [filemime] => image/jpeg
                        [filesize] => 28385
                        [status] => 1
                        [timestamp] => 1409510061
                        [alt] =>
                        [title] =>
                        [width] => 600
                        [height] => 400
                    )

            )

    )

How can I turn that information into a usable link? I want to know how to link directly to 01.jpg?

You want to use the Drupal link function l()  for this.

  $link_html = l('some cool link text', $node->field_main_photo['und']['0']['uri'];

then you can either print that $link_html variable OR you can return it some other function will be rendering it.

Bonus:
You can replace the 'some cool link text' with the name of the file by using this:

$node->field_main_photo['und']['0']['filename']

So that would give us:

$link_html = l($node->field_main_photo['und']['0']['filename'], $node->field_main_photo['und']['0']['uri'];

Make sense?

Also... print_r() can often ve difficult to parse through. I recommend that you enable the DEVEL module and instead do the following:

dpm($node);

This will render the node on the page in a manner that you can click through and inspect each element and array and object. Even better, you can double click the value and the variable path to that value shows up for you to copy and paste into your code.

I hope this helps! :-)


How do I remove the rollover effect from Rubik tooltips I am using Rubik and the tooltips are rollovers. Generally this is fine, but for one site I need them to display with the field instead. Is there a setting to disable the rollover effect and just make it look like help text?

I have not used this theme before, but there is a checkbox on the theme settings page to toggle "Display form field descriptions inline". I believe this is what you are looking for.


Force redirect back to password form until password got set after one-time-login When my users click on a one-time-password-reset link then I log them in and then show them a page where they can choose their new password.
Problem is that there are two additional links on that page (one for dashboard and some other one) and they can click on them and visit the linked pages.

I want that until they change their password they cannot navigate to other pages. For now I managed to set a custom value in $_SESSION, but I can't figure out how I can intercept their further request (once they land on password change page). How can I check for such a session value and redirect them back to password-reset page (if they haven't changed their password yet) and allow them to navigate to other pages only after they changed their password?

You should be able to use hook_init to check for your custom $_SESSION variable (along with other conditions), and then leverage drupal_goto() to send the user back to the password change page.

Rough example:

function MODULE_NAME_init() {
  // Check that the session key exists.
  if (!empty($_SESSION['my_special_session_key'])) {
    // Check to verify the path the user is currently visiting is not the
    // password change form, or related path.
    // This needs to be customized according to your needs.
    if (arg(0) != 'user' || arg(1) != $GLOBALS['user']->uid || arg(2) != 'edit') {
      drupal_goto("user/{$GLOBALS['user']->uid}/edit");
    }
  }
}

You'll also need to unset that $_SESSION key after the user successfully changes their password. You'll likely want to do this using another hook related to the password change form.

Usinghook_form_FORM_ID_alter to add a custom submit callback to the form is a reasonable choice.

Here is an example that adds the submit callback to the user's edit form if the $_SESSION key exists.

/**
 * Implements hook_form_FORM_ID_alter().
 */
function MODULE_NAME_form_user_profile_form_alter(&$form, &$form_state) {
  if (!empty($_SESSION['my_special_session_key'])) {
    $form['#submit'][] = '_MODULE_NAME_unset_session_key';
  }
}

/**
 * Custom callback for removing the special session key.
 */
function _MODULE_NAME_unset_session_key() {
  unset($_SESSION['my_special_session_key']);
}

Hope this helps.


Alter menu structure when using Superfish menu I am using Superfish menus. I wanted to add a  tag before each  tag for menu links. I tried the following code:

function mytheme_menu_link($variables) {
    $element = $variables['element'];
    $sub_menu = '';
    if (empty($element['localized_options'])) {
        $element['localized_options'] = array();
    }
    $element['localized_options']['html'] = TRUE; //let l function know that our link title includes html
    $output = l($element['#title'], $element['#href'], $element['#localized_options']);
    return '
' . $output . "
\n";
}

but it did not take any effect. Since I am using Superfish menus do I need to write any other code?

The Superfish module bypasses the usual Drupal theming hooks for menus and implements its own. You will need to override the theme_superfish() function in order to change the HTML around those menu items. Copy that function out of superfish.module into your theme's template.php file. Replace the word "theme" in the function name with your theme's machine name, and make your edits.


Count how many children have a reference to the parent Explanations:

1) I have a node "parent"

2) I have 2 nodes "child"

3) Each child has a reference field (filled with a reference to the node "parent")

Now, I'm trying to create a list with the Views module.

First problem: This list is a list of "parent" nodes AND should include a column with the following result: COUNT(child with a reference to the parent).

Second problem: The count result should include only published children.

Example 1 with 2 children published (2 children have a reference to the parent):

Title of parent node | 2

Example 2 with 1 child published (2 children have a reference to the parent):

Title of parent node | 1

Sorry if it's not totally clear, it's hard to explain

Above all of this, if the result could be sortable it will be a good news but I don't think it will be possible...

Second problem: the views results will only include published entities if you add the filter: Published (= True).

It's a lot more difficult if you want unpublished node to show in view results, but not be counted.

First problem:
The easiest way to solve this is by using the Summary option of a Contextual filter.

List the Child nodes in your Views, then add the Contextual filter for the Entity reference field to the Parent, and set it to display the Summary (adjust Validation and other options to your needs).

The Summary will list the Parents links, with the Children count next to them. When you click through the Parent links you will see the original Views Children list (but only for that clicked-on parent).

Don't forget the base path if the Views Display you're working on isn't the first Page Display in your Views.

The Summary also gives you the option to sort according to the Count :)

Your Contextual filter options should looks something like this:

When the filter value is NOT in the URL
Display a summary
Sort order: Descending
Sort by: Number of records
Format: List
Display record count with link

̣̣̣̣̣̣̣_______________

Alternativelly you could count with the Agreggation option (under Advanced settings). You would count the children title field for example, their Entity IDs, while grouping the Parent reference field.


Commerce checkout does not work when loading from AJAX In D7, I have a dropdown form field that has an #ajax attribute pointing to a callback function that triggers when the drop down value is selected. In the callback function, I load the current Commerce order and then the Commerce checkout form using:

$commerce_form = commerce_checkout_router($order);

I then render the checkout form and display in the template:

$commands[] = ajax_command_html('#checkout-section', '');
$commands[] = ajax_command_append('#checkout-section', render($commerce_form));

return array('#type' => 'ajax', '#commands' => $commands);

When I do that, it looks like my checkout form does not get properly bootstraped and I lose all the interactivity of the checkout form I've set up using hook_info's etc.

When I visit the checkout form without AJAX everything works well.

Do I need to somehow bootstrap Drupal Commerce inside AJAX callbacks if I want to use AJAX so all my hooks that customize the Commerce Checkout?

PS: I am doing a

require_once '../contrib/commerce/modules/checkout/includes/commerce_checkout.pages.inc';

inside the callback. Without this I get functions not defined errors on core Commerce functions. (The Drupal Commerce and all related modules are enabled and it only happens in the AJAX callbacks.)

Thank you

I had exactly the same Problem, i think this page should help you: Loading a form by ajax.

I have solved this problem, but I think its a little bit ugly. The Problem was that I have loaded the checkout form, but not the scripts which are necessary on the checkout page. So i have loaded the scripts from the checkout page, too. After that i have done a

Drupal.attachBehaviors();

So all scripts can attach there functionality to the checkout form.


"Parameter expected to be reference, value given" error in menu page callback I have a custom module that adds a couple action links via menu items:

function monographs_menu() {
  $items['node/%node/clone_comment'] = array(
    'access callback' => 'clone_access_cloning',
    'access arguments' => array(1),
    'page callback' => 'monographs_node_check',
    'page arguments' => array(1, 2),
    'title' => 'Create For Comment version',
    'type' => MENU_LOCAL_ACTION,
  );

  $items['node/%node/clone_authorized'] = array(
    'access callback' => 'clone_access_cloning',
    'access arguments' => array(1),
    'page callback' => 'monographs_node_check',
    'page arguments' => array(1, 2),
    'title' => 'Create Final Authorized version',
    'type' => MENU_LOCAL_ACTION,
  );

  return $items;
}

and the function signature for the page callback is

function monographs_node_check(&$node, $type)

On my local machine and my dev server, this all works just peachy.  However, on the client's server, with a clone of my db and the repo, whenever this link is clicked on, they get a WSOD and this error in watchdog:

  Warning: Parameter 1 to monographs_node_check() expected to be a reference, value given in menu_execute_active_handler() (line 517 of ...\public_html\includes\menu.inc).

Since it's on a remote server that I don't have access to, I can't debug it, but the fact that it works without error on my own local machine and dev server makes it even weirder.

What could be different in the other environment that would cause this error?

Thanks.

I got the answer from the support list, and all I needed to do was remove the reference for the node object in my callback function signature:

function monographs_node_check($node, $type)

$node is passed as an object anyway, so I don't need to mark it as being by reference in the signature.


Change from email id when admin approved user account I want to change  FROM Email id, when admin approved an user account.

Currently it is using admin email id. I want to use different email  and my admin email id will remain same

Any Suggestions

I don't have enough reputation to comment, so I am expanding user1081275's answer -

The message id for the confirmation message you want to alter is 'status_activated'.

You can intercept outgoing mail with hook_mail_alter() in a custom module as described at https://api.drupal.org/api/drupal/modules!system!system.api.php/function/hook_mail_alter/7

function mycustommodule_mail_alter(&$message) {
  if ($message['id'] == 'status_activated') {
    $message['from'] = "mail@whatever.com";
  }
}

Per user.module, the ids for other messages defined by the User module in _user_mail_notify() are:

 *   - 'register_admin_created': Welcome message for user created by the admin.
 *   - 'register_no_approval_required': Welcome message when user
 *     self-registers.
 *   - 'register_pending_approval': Welcome message, user pending admin
 *     approval.
 *   - 'password_reset': Password recovery request.
 *   - 'status_activated': Account activated.
 *   - 'status_blocked': Account blocked.
 *   - 'cancel_confirm': Account cancellation request.
 *   - 'status_canceled': Account canceled.


Trying to get an "About the author" view to work on a multi user blog (contextual filters) I'm working on a Drupal 7 install sub-theming zen. I have a blog and I want to have an "About the author" view on each blog post. I've created a custom post type (Profile) for this, but I'm not sure how to make my view aware of the user who has created each post to show the Profile depending on the post author. I know this used to be done with the view arguments but that's part of Contextual Filters in Drupal 7, but I still don't know what filter I should have there, or if I should add any fields in the Profiles so that the filters can tell which profile belongs to which author.

Any help will be most welcomed!

You don't need to create separate content types in D7, You are able to attach fields to the user directly (admin/config/people/accounts/fields). If you need more flexibility, use the Profile2 module.

If you just add fields to the user, you can create a new block view of users. Under "Contextual Filters" (which is under Advanced on the right side), add a filter of User: Uid, set it to Provide default value, with a type of User ID from URL, and check the checkbox for Also look for a node and use the node author.

Then add the fields normally as you see fit.


Product Bundles & referenced products in Drupal Commerce What is the preferred way of retrieving referenced products when using hook_commerce_checkout_complete on a line item that is of type Product Bundle.

As an example, the customer has added Product ID 5 (which is a bundle consisting of Products 3 & 4).

How can find it's referenced products at the point of checkout completion?

In case anyone stumbles across this, you can use the following function:

function commerce_product_bundle_get_sub_line_items(&$parent_line_item, $reset = FALSE){
    //...
}


Undefined offset: 1 in gcm_action_send_message() I am using Google Cloud Messaging for one of my projects. I think I have configured everything correctly. I am getting the following error when I tried to send some message.

  Notice: Undefined offset: 1 in gcm_action_send_message()

I can't find any information in the module documentation.

I found the answer by looking the code used from the module.

function gcm_action_send_message($tokens, $keyValues, $delay_while_idle, $time_to_live, $collapse_key) {

    $gcm_message = array();
    foreach (explode(",", $keyValues) as $keyValue) {
      $temp = explode("=", $keyValue);
      $key = $temp[0];
      $value = $temp[1];
      if (isset($key) && isset($value)) {
        $gcm_message[$key] = $value;
      }
    }
    gcm_send_message(array_unique(explode(',', $tokens)), $gcm_message, $delay_while_idle, $time_to_live, $collapse_key);
}

So we need to use for key-values a value like 0=[site:name], 1=[site:mail].


How can I change the default link to the email contact form? I'm trying to change the default link generate by the email_field module so It shows an image instead of the text (Contact person by email).

I went into the module and foun the part I need to change, but because I'm new to drupal and php I have no clue how to change it...

The code I think I need to override:

function email_field_formatter_view($object_type, $object, $field, $instance,    $langcode, $items, $display) {
  $element = array();
  switch ($display['type']) {

    case 'email_contact':
      $ids = entity_extract_ids($object_type, $object);
      foreach ($items as $delta => $item) {
        $element[$delta] = array('#markup' => l(t('Contact person by email'), 'email/' . $object_type . '/' . $ids[0] . '/' . $instance['field_name']));
        // Since email is always sent to first item's email, break after any email address found.
        break;
      }
      break;
  }
}

The contact person by email is the part I want to change to
'< div class="email_image">< /div>'

Anyone who can help with this? Or knows where I can find some help?

Thx up front.

You have two options to solve your issue:

CSS Option: You can replace text with image using css, add the following code to your css file and make sure to replace field name accordingly

.field-name-field-custom .field-item a {
  display: block;
  text-indent: -99999em;
  background-image: url('../images/image_name.ext');
  background-position: left top;
  background-repeat: no-repeat;
}

Note: field-custom should be replaced with your email field

Field Formate Option: You can create a new field formate in a new module and then you can choose from Field UI the new formate that you created.

Implement the following code in a Drupal module.

/**
 * Implements hook_field_formatter_info().
 */
function mymodule_field_formatter_info() {
  return array(
    'email_contact_image' => array(
      'label' => t('Email contact form image link'),
      'description' => t('Display an image link to a contact form.'),
      'field types' => array('email'),
    ),
  );
}

/**
 * Implements hook_field_formatter_view().
 */
function mymodule_field_formatter_view($entity_type, $entity, $field, $instance, $langcode, $items, $display) {
  $element = array();

  switch ($display['type']) {

    case 'email_contact_image':

      $ids = entity_extract_ids($entity_type, $entity);

      if ($ids[0] !== NULL) {
        foreach ($items as $delta => $item) {

          $img_vars = array(
            'path' => drupal_get_path('theme', 'THEME_NAME') . '/images/IMAGE_NAME.EXT',
            'alt' => t('Contact person by email'),
            'title' => t('Contact person by email'),
            'attributes' => array('class' => 'some-img', 'id' => 'my-img'),
          );
          $img = theme('image', $img_vars);

          $options['html'] = TRUE;

          $element[$delta]['#markup'] = l($img, 'email-contact/' . $entity_type . '/' . $ids[0] . '/' . $instance['field_name'], $options);
          // Since email is always sent to first item's email, break after any email address found.
          break;
        }
      }
      break;
  }

  return $element;
}

Notes:

make sure to replace mymodule with your own module name
make sure to replace THEME_NAME with your own theme name
make sure to replace IMAGE_NAME.EXT with your own image name

Creating modules - tutorial


trending topics view based on read counts I am trying to setup a view where it shows the most popular articles and couldn't find any answer to this. My readers will all be anonymous as it's my company's blog.

Looking forward an answer as this is pretty useful on blogs!

Cheers!

If your site is relatively low traffic, you could possibly use the statistics module, or as @clive pointed out, the radioactivity module.

For higher traffic sites, I'd be wary of writing to the db for every visit, however. Moreover, if you're using varnish or some other reverse proxy caching system (which you probably should), Apache and PHP normally aren't invoked for anon visitors, so you'd need to do something different.

I've landed on using google analytics for this. To do it, the site obviously needs a google analytics account, and you need to install the google analytics and google analytics reports modules. Once you've configured them, you can fetch an array of the most visited nodes from the google analytics api. You can then simply serialise it, and save it to the variable table. This uses hook_cron, and needs to be done in a custom module:

function YOUR_MODULE_cron() {
  $last_time = variable_get('YOUR_MODULE_last_time', 0);
  // DO EVERY 24H
  if ((REQUEST_TIME - $last_time) > (60 * 60 * 24)) {
    $data = array();
    $dates = array();
    $params = array(
      'metrics' => array('ga:uniquePageviews'),
      'dimensions' => array('ga:pagePath'),
      'segment' => 'gaid::-11',
      'filters' => 'ga:pagePath=@/PATH/TO/NODES',
      'sort_metric' => array('-ga:uniquePageviews'),
      'start_date' => strtotime('-7 days'),
      'end_date' => strtotime('-1 day'),
    );
    $feed = google_analytics_api_report_data($params);
    if (!$feed->error) {
      $k = 0;
      $nids = array();
      foreach ($feed->results as $f) {
        // SAVE 6 MOST VIEWED
        if ($k < 6) {
          $nids[] = (int) array_pop(explode('/', drupal_lookup_path('source', ltrim($f['pagePath'], '/'))));
          $k++;
        }
      }
      $nids = serialize($nids);
      variable_set('YOUR_MODULE_ga_items', $nids);
      variable_set('YOUR_MODULE_last_time', REQUEST_TIME);
    }
  }
}

Every 24 hours, this would save a serialised array of the most popular nodes that appear under the path http://yoursite.com/PATH/TO/NODES/REST_OF_PATH. To use the nids, you'd simply unserialise the variable after retrieving it:

$nids = unserialize(variable_get('YOUR_MODUE_ga_items', '');
foreach($nids as $nid) {
   $node = node_load($nid);
   ...
}


How to save content created by selected roles in an external database? My Drupal 7 site needs to have articles, faq, pages, blog (not confirmed) and forum. But client can't store any data coming from front end. It can include the registrations from front end. That data need to be stored on external database and admin and users will access that data from the drupal site.

More specific, if user add comment or topic in forum, it should be saved in external database, and if admin adds a page from admin, it should be saved in local database. Moreover, even registration done from front end, needs to saved in external database

I suggested that we can use complete database externally which can be done easily but suggestion is rejected. Anyone can tell me any solution?

Note: the only solution I can think of is to create a custom module and use hooks for database functionality where I will check which content type is been called (means create, read, update and delete) and depending on that I will switch the database execute the query and return the data. I need to confirm which hooks I need to use.

Yes you can do that.

There are two method for configuring external database.

Inside settings.php
Inside Module directly.

1. Inside settings.php

$databases = array();
$databases['default']['default'] = array(
  // Drupal's default credentials here.
  // This is where the Drupal core will store its data.
);
$databases['my_other_db']['default'] = array(
  // Your secondary database's credentials here.
  // You will be able to explicitly connect to this database from your modules.
);

In your module:

// Use the secondary database we set up earlier
db_set_active('my_other_db');

// Run some queries, process some data
// ...

// Go back to the default database,
db_set_active();

2. Inside Module directly.

If your module will be alone in using the secondary database you can define the connection directly in your module:

  $other_database = array(
      'database' => 'databasename',
      'username' => 'username', // assuming this is necessary
      'password' => 'password', // assuming this is necessary
      'host' => 'localhost', // assumes localhost
      'driver' => 'mysql', // replace with your database driver
  );
  // replace 'YourDatabaseKey' with something that's unique to your module
  Database::addConnectionInfo('YourDatabaseKey', 'default', $other_database);
  db_set_active('YourDatabaseKey');

  // execute queries here

  db_set_active(); // without the paramater means set back to the default for the site
  drupal_set_message(t('The queries have been made.'));

Refer https://www.drupal.org/docs/7/creating-custom-modules/howtos/how-to-connect-to-multiple-databases-within-drupal


Argument 2 passed to Drupal\Console\Command\Test\RunCommand::__construct() must be an instance of Drupal\simpletest\TestDiscovery I'm trying to install drupal console with Drupal 9.0.5, so I ran this command:
composer require drupal/console:~1.0

However when I try run the drupal command with any arguments I get this error:
root@6dc17ce2d4bf:/opt/drupal# drupal --version
TypeError: Argument 2 passed to Drupal\Console\Command\Test\RunCommand::__construct() must be an instance of Drupal\simpletest\TestDiscovery, null given in /opt/drupal/vendor/drupal/console/src/Command/Test/RunCommand.php on line 58 #0 [internal function]: Drupal\Console\Command\Test\RunCommand->__construct('/opt/drupal/web', NULL, Object(Drupal\Core\Extension\ModuleHandler), Object(Drupal\Core\Datetime\DateFormatter))
#1 /opt/drupal/vendor/symfony/dependency-injection/ContainerBuilder.php(1144): ReflectionClass->newInstanceArgs(Array)
#2 /opt/drupal/vendor/symfony/dependency-injection/ContainerBuilder.php(618): Symfony\Component\DependencyInjection\ContainerBuilder->createService(Object(Symfony\Component\DependencyInjection\Definition), Array, true, 'console.test_ru...')
#3 /opt/drupal/vendor/symfony/dependency-injection/ContainerBuilder.php(558): Symfony\Component\DependencyInjection\ContainerBuilder->doGet('console.test_ru...', 1)
#4 /opt/drupal/vendor/drupal/console-core/src/Application.php(468): Symfony\Component\DependencyInjection\ContainerBuilder->get('console.test_ru...')
#5 /opt/drupal/vendor/drupal/console-core/src/Application.php(214): Drupal\Console\Core\Application->registerCommands()
#6 /opt/drupal/vendor/drupal/console-core/src/Application.php(119): Drupal\Console\Core\Application->loadCommands()
#7 /opt/drupal/vendor/drupal/console/src/Application.php(64): Drupal\Console\Core\Application->doRun(Object(Symfony\Component\Console\Input\ArgvInput), Object(Symfony\Component\Console\Output\ConsoleOutput))
#8 /opt/drupal/vendor/symfony/console/Application.php(147): Drupal\Console\Application->doRun(Object(Symfony\Component\Console\Input\ArgvInput), Object(Symfony\Component\Console\Output\ConsoleOutput))
#9 /opt/drupal/vendor/drupal/console/bin/drupal.php(89): Symfony\Component\Console\Application->run()
#10 /opt/drupal/vendor/drupal/console/bin/drupal(4): require('/opt/drupal/ven...')
#11 {main}
TypeError: Argument 2 passed to Drupal\Console\Command\Test\RunCommand::__construct() must be an instance of Drupal\simpletest\TestDiscovery, null given in Drupal\Console\Command\Test\RunCommand->__construct() (line 58 of /opt/drupal/vendor/drupal/console/src/Command/Test/RunCommand.php).

I don't really understand this error. Any ideas what might cause this?

This is really just kiamlaluno's answer, but they never posted it so I'll just copy it here verbatim:

Drupal Console has not been updated to run on new Drupal versions.
It's even less compatible with Drupal 9, as many classes or methods
have been removed.


Module available for forcing users to re-enter their password to view/edit certain user account fields? My users have custom fields for their user account that can contain some sensitive information. To protect against privilege escalation vulnerabilities, I'd like to make these fields only readable and editable after users enters their password.
Is there a module available for this?

Most likely this/these fields appear on a certain page/form so you can use the securepages module to define the node/id or page path to assure that only logged in/authenticated users can access it.  If not, then the login page will display.
You could also use the loginlogout to return to the calling page upon successful login.


How to add a line item to show total cost in Ubercart 2? I am using Ubercart 2 and I want to add a line item, which should add the total cost of all items instead of sell price. I tried to take the code from generic line item hook and used this to callback:

for each($op->products as item) {
  $cost += $item->cost;
}

I want this line item to appear in the AJAX cart, which I am using now. It should appear in the user panel before checkout and it should also shown in the user and store admin order emails. It is not working as of now. Is the code I am adding correct or I have done any misplacement?

There is uc_order_pane_line_items_add

  Order pane submit callback: Add a line item to an order.

function uc_order_line_item_add($order_id, $type, $title, $amount, $weight = NULL, $data = NULL) {
  if (is_null($weight)) {
    $weight = _uc_line_item_data($type, 'weight');
  }

  $line_item = array(
    'order_id' => $order_id,
    'type' => $type,
    'title' => $title,
    'amount' => $amount,
    'weight' => $weight,
    'data' => $data,
  );
  drupal_write_record('uc_order_line_items', $line_item);

  return $line_item;
}


Drush does not work on my Mac I use MAMP on Mac.

When I try to use drush en omega command on drupal root directory to install omega, But the terminal throw me an error:

drupal-7.23 tangmonk $ drush en omega

Command pm-enable needs a higher bootstrap level to run - you will   [error]
need to invoke drush from a more functional Drupal environment to run
this command.

The drush command 'en omega' could not be executed.                  [error]
Drush was not able to start (bootstrap) the Drupal database.         [error]

Hint: This may occur when Drush is trying to:
 * bootstrap a site that has not been installed or does not have a
configured database. In this case you can select another site with a
working database setup by specifying the URI to use with the --uri
parameter on the command line. See `drush topic docs-aliases` for
details.

Drush was attempting to connect to:
 Drupal version         :  7.23
 Site URI               :  http://default
 Database driver        :  mysql
 Database username      :  root
 Database name          :  drupal
 Default theme          :  garland
 Administration theme   :  garland
 PHP executable         :  /usr/bin/php
 PHP configuration      :
 PHP OS                 :  Darwin
 Drush version          :  7.0-dev
 Drush configuration    :
 Drush alias files      :
 Drupal root            :  /Users/tangmonk/Sites/drupal/drupal-7.23
 Site path              :  sites/default
 File directory path    :  sites/default/files
     * connect the database through a socket. The socket file may be
    wrong or the php-cli may have no access to it in a jailed shell. See
    http://drupal.org/node/1428638 for details.

It seems mysql issue. But my site run perfect.

I run drush command as MAMP Integrated PHP, It works!

I add alias command to my shell:

$ vim ~/.bash_profile
alias drush='/Applications/MAMP/bin/php/php5.5.3/bin/php /opt/drush/drush.php'


Enabling AJAX in Views breaks Form API AJAX button (Drupal 8) On a product node there is form with a button "add to cart" that is implemented with form API (ajax):

$form['add_to_cart'] = array(
  '#type' => 'button',
  '#value' => $this->t('Add to cart'),
  '#ajax' => array(
    'callback' => 'Drupal\custom_cart\Form\AddToCartForm::addProductToCart',
    'event' => 'click',
    'effect' => 'fade',
    'wrapper' => '#custom-cart',
    'progress' => array(
      'type' => 'throbber',
    ),
  )
);

...

public function addProductToCart(array &$form, FormStateInterface $form_state) {
if ($parent_node_id = $form_state->getStorage()['parent_node_id']) {
  if ($product_node = Node::load($parent_node_id)) {
    $pid = $product_node->get('field_product_bid')->value;
    $price = $product_node->get('field_product_price')->value;
    $renderer = \Drupal::service('renderer');
    $response = new AjaxResponse();
    Cart::addLineItem($pid, $form_state->getValue('amount'), $price);
    $cart = Cart::getThemedCart();
    $elem = ['#markup' =>  $cart];
    $response->addCommand(new ReplaceCommand('.cart-nav', $renderer->render($elem)));
    return $response;
  }
 }
}

This works as expected.

For a product overview page we render out product nodes with a view (node teasers) and the view includes some exposed filters.
If the view is ajax enabled the ajax callback from the "add to cart" button (breaks) and returns a 404 error:

Request URL:http://foobar.lo/views/ajax?_wrapper_format=drupal_ajax
Request Method:POST
Status Code:404 Not Found

Does somebody know how to fix this (core patches anywhere?) or a workaround you know?

Thanks for any advice

The issue is in this line of RenderElement::preRenderAjaxForm:

$settings['url'] = Url::fromRoute('<current>');

When the form with the button "add to cart" is rendered inside of an ajax request of a view, then the url is set to the wrong endpoint /views/ajax.

A workaround would be to add a static url in the ajax setting of the form element, so that it won't be set dynamically:

use Drupal\Core\Form\FormBuilderInterface;

  '#ajax' => [
    'callback' => '::add',
    'wrapper' => $wrapper,
    'url' => Url::fromRoute('<front>'),   // set this to the route of the view page
    'options' => ['query' => \Drupal::request()->query->all() + [FormBuilderInterface::AJAX_FORM_REQUEST => TRUE]],
  ]

If you use the form in multiple pages you would need to adjust the code to only set the url when the form is rendered in this view.


how to create a new node of a content type when a new node created of another content type? my problem is :
I have a content type called job posting, every job post will associated with a test set that every candidate should write to get qualified for that job i.e., when I create a node of job posting content type another node of type test has to be automatically created.

what is the best approach towards it. It thought to try actions, but it is won't help me in any way. could any body suggest me a way to do it.

As said by @drupality

function hook_node_insert($node) {
 if ($node->type != 'job_posting') {
   return;
 }
$node = new stdClass(); // Create a new node object
$node->type = "test";
node_object_prepare($node); // Set some default values

$node->title    = "YOUR title";
$node->language = LANGUAGE_NONE; // Or e.g. 'en' if locale is enabled

$node->uid = 1; // UID of the author of the node; or use $node->name

.
.
.//Enter your other field values
.
node_save($node);
}


store session variable and access it through javascript? In drupal, how do you store/read session variables? Also, how can i access a stored session variable through javascript?

I'm trying to store whether if a user has closed my modal or not so it doesn't pop up for another day.

Accessing a session variable in Drupal is not different from how it is done with plain PHP: with $_SESSION.

As for reading them with JavaScript, it is enough to use code similar to the following one.

// PHP
drupal_add_js(array('myModule' => array('key' => $_SESSION['key'])), 'setting');

// JavaScript
key = Drupal.settings.myModule.key;


If folders don't exist in URI path, file_save_data() fails I am programmatically importing images and saving them via file_save_data();

$fileContentsPath = 'http://mypathtofile.com';
$uri = 'public://myfolder/mysecondfolder/filename.jpg';
$image = file_get_contents($fileContentsPath);
$file = file_save_data($image, $uri, FILE_EXISTS_REPLACE);

When I run this I get the following error: The specified file temporary://fileJ4LL4o could not be copied, because the destination directory is not properly configured. This may be caused by a problem with file or directory permissions. More information is available in the system log.

I am pretty sure my temporary directory is configured correctly and the files folder is assigned to the apache user.

If I go into the files directory and make the directories (myfolder/mysecondfolder) via command line and rerun it works correctly.

So the problem is that if the folders don't exist from the $uri path, it fails instead of creating the folders.

I Noticed Similar issue while saving files using

 file_save_data();

In Drupal 8.

First I gave only first level directory to save the file as

$file = file_save_data($object->vertex_data, 'public://vertex_data.txt', FILE_EXISTS_REPLACE);

This worked fine.

But when I tried saving the file inside a subfolder as

$file = file_save_data($object->vertex_data, 'public://objects/vertex_data.txt', FILE_EXISTS_REPLACE);

it gave me the following Error :

File temporary://fileh1Gpl2 could not be moved/copied because the destination directory public://objects/ is not configured correctly.

The Solution for this is simple. Just use file_prepare_directory();

$directory = 'public://objects/'
file_prepare_directory($directory, FILE_CREATE_DIRECTORY);
$file = file_save_data($object->vertex_data,  $directory . 'vertex_data.txt', FILE_EXISTS_REPLACE);

This, first creates the folder if it does not exists and then proceeds to save the respective file.


How to prevent drupalSettings to sort settings object I attach drupalSettings in a preprocess hook using code similar to the following one.

$settings = [
  'bcd' => 'BCD',
  'abc' => 'ABC'
];

$variables['#attached']['drupalSettings']['options'] = $settings;

When I print the content of drupalSettings using console.log(drupalSettings.options); I  get a sorted object.

{ 'abc' : 'ABC','abc' : 'BCD'}

Is this the normal behavior? How can I prevent it?

It's not Drupal that sorts the drupalSettings array, but it's console.log() that sorts the properties of drupalSettings.options before outputting it. See Show original order of object properties in console.log where the answer explains this.

If you really want to avoid console.log() sorts the object properties, you could call console.log() using code similar to the following one.

console.log(JSON.stringify(obj, drupalSettings.options, null, 2));

I would rather use this code if it's really important to see the object properties in the order they are set.


why filters are not working in view query alter? why filters are not working in  view query alter here is my code what i am doing wrong:

     if ($view->id() == 'answer_key_form' && $view-
     >getDisplay()->display['id'] == 'page_2') {

     $competetive_array=array('234','235' );

           foreach ($query->where as &$condition_group) {
           foreach ($condition_group['conditions'] as
            &$condition) {

            if ($condition['field'] == '

 node__field_akf_select_product.field_akf_select_product_target_id') {

      $condition = array(
        'field' => 'node__field_akf_select_product.field_akf_select_product_target_id',
        'value' => $competetive_array,
        'operator' => 'IN',
      );

    }
  }
}

if my url arguments are www.test.com/field_akf_select_product_target_id=234 its giving me same result if i pass any random no in url parameter like field_akf_select_product_target_id=886 still its giving same result it should show no result found..

I solved it by myself ,i have added condition for operator where i was doing mistake ,on first page load "IN" operator will work then "=" on selection of select list :

  function get_purchased_product_id() {
  //Get current user id
  $user_id = \Drupal::currentUser()->id();

  $uid = ($user_id ==1)? 267 :$user_id;

  $query_get_product_name =  db_select('commerce_order', 'c');
  $query_get_product_name->join('commerce_order_item', 'ci', 'c.order_id = ci.order_id');
  $query_get_product_name->join('commerce_product_variation_field_data', 'cf', 'ci.purchased_entity = cf.variation_id');
  $query_get_product_name->fields('c', ['uid']);
  $query_get_product_name->fields('ci', ['purchased_entity']);
  $query_get_product_name->fields('cf', ['product_id','title']);
  $query_get_product_name->condition('c.uid', $uid,'=');
  $query_get_product_name->condition('c.state', 'completed','=');
  $result = $query_get_product_name->execute();

  $arr_var=array();

  foreach ($result as $value ){
  $arr_var[]= $value->product_id;
   }
  return $arr_var;

 }

 function classroom_common_views_query_alter(ViewExecutable $view, QueryPluginBase $query) {

if ($view->id() == 'answer_key_form_management' && $view->getDisplay()->display['id'] == 'page_2') {
  //function call to get product id of purchased item by current user
  $arr_product_id = get_purchased_product_id();

  $product_target_id = Drupal::request()->query->get('field_akfp_select_product_target_id');
  if(!empty($product_target_id)){
     $arr_product_id = $product_target_id;
  }
  $operator = !empty($product_target_id) ? '=' : 'IN';

foreach ($query->where as &$condition_group) {
      foreach ($condition_group['conditions'] as &$condition) {
        if ($condition['field'] == 'node__field_akfp_select_product.field_akfp_select_product_target_id') {

          $condition = array(
            'field' => 'node__field_akfp_select_product.field_akfp_select_product_target_id',
            'value' =>  $arr_product_id,
            'operator' => $operator,
          );

        }
      }
    }
}


Create node via REST from Android app I use restful between Drupal 7 and Android app.
I logged in  successful and got 3 variable session_id, session_name and token
When I use POST method to create node. I getting error : "node type is required"
This is my code :

private class addArticleTask extends AsyncTask<String, Integer, Integer> {

    protected Integer doInBackground(String... params) {

        HttpClient httpclient = new DefaultHttpClient();
        HttpPost httppost = new HttpPost("http://mysite/endpoint/node");

        try {

            //get title and body UI elements
            TextView txtTitle = (TextView) findViewById(R.id.editTitle);
            TextView txtBody = (TextView) findViewById(R.id.editBody);

            //extract text from UI elements and remove extra spaces
            JSONObject json = new JSONObject();
            String title=txtTitle.getText().toString().trim();
            String body=txtBody.getText().toString().trim();

            //add raw json to be sent along with the HTTP POST request
            StringEntity se = new StringEntity("{ \"title\" : \"Sample post\" , \"type\" : \"article\" , \"body\" : { \"und\" :[{ \"value\" : \"comments about something\" }]} }");
            se.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
            se.setContentType(new BasicHeader("Cookie",session_name+"="+session_id));
            se.setContentType(new BasicHeader("X-CSRF-Token",token));
            httppost.setEntity(se);

            HttpResponse response = httpclient.execute(httppost);
            Log.v("Return add article", EntityUtils.toString(response.getEntity()));

            return 0;

        }catch (Exception e) {
            Log.v("Error adding article",e.getMessage());
        }

        return 0;
    }

In Logcat : Return add article : ["node type is required"]
any one help me.

You must mention the node type while doing the POST.

node_type will the machine name of your content type

for example try creating page with this,

StringEntity se = new StringEntity("{ \"title\" : \"Sample post\" , \"page\" :


Change Created Date to date from field_post_date I am changing a large amount of news content types 'Created' dates. I figured out to use VBO with execute php and this code...

$entity -> created = strtotime($entity->field_post_date[LANGUAGE_NONE][0]['value']);
node_save($entity);

This code works!

I had 'create' not 'created' - Doh!
Now it works...


How do I show only the latest post from each user in a view? I'm trying to show a list of only the most recently published post by every user (not including the logged in user) in a view. What should my Views filters look like in order to accomplish this? I'm completely stuck!

At the moment, my view shows all posts from all other users. I now need to filter it down once more so that it ONLY shows the most recent post by all of these users.

Reference (issue):

The problem is that you are trying to filter based on two things:

Show the most recent content by an individual user.
Show each user.

In Views, you can generally only filter one kind of entity (content OR users) at a time.

However, there is a module that can help, Views Field View.  This module lets you embed one view inside another.

So, you can do something like this:

Create a view that shows the most recent content for a single user (takes a contextual filter of UID, returns one result, sorted by descending most recent).
Create another view that shows all users except the logged in user.  Use Views Field View module to embed the first view and show the most recent post by each user.

I haven't done this exact implementation before, but I've used Views Field View for similar things.  There is a tutorial here.

If you use this module, do note this warning from the documentation:

  Please note that using this module can impact the performance of your
  site, if the views being rendered are very resource-consuming. It's
  highly recommended to use this module in conjunction with other
  modules that provide views caching.

  Good candidates to cache your views are the modules Views content
  cache and Cache Actions.


correct way to load JS library for custom module I am trying to use d3.js in my module, but I am facing some issues.

I have the D3 module installed in sites/all/modules/d3/ and d3.min.js installed in sites/all/libraries/d3/, and I can see the d3/examples fine.

Now I have a js script in my custom module that is supposed to use D3, but I fail to load it. Here's my attempt to load the library:

drupal_add_library('d3','d3');
# retrieve some data as JSON
$setting = mymodule_load_data($param);
# create the render array
$content = array(
  '#attached' => array(
    # attach JS
    'js' => array(
      array(
        'type' => 'setting',
        'data' => array('mymodule' => array('json_data' => $setting)),
      ),
      array(
        'type' => 'file',
        'data' => drupal_get_path('module', 'mymodule') .'/js/myscript.js',
      ),
    ),
    'css' => array(
      drupal_get_path('module', 'mymodule') . '/css/mystyle.css',
    ),
  )
);
# return result
return $content;

but I don't see d3 included in the source code of my page and myscript.js of course doesn't work.

I have checked the return value of drupal_add_library as suggested in the comments and it's FALSE.

Any hints?

drupal_add_library() works only with libraries defined from hook_library() implementations. Since the d3.js module implements hooks used from the Libraries API module, you need to use the functions this module make available.

See Using Libraries API 2.x (as a module-developer) or Using Libraries API 1.x (as a module-developer), basing on which version of the Libraries API module you are using.

Normally, with the 2.x branch of the Libraries API module, you just call libraries_load('d3') which will call drupal_add_js(), or drupal_add_css(), or both, depending on what the library contains. Otherwise, if you need to check when a library has not been loaded, you use code similar to the following one.

if (($library = libraries_load($name)) && !empty($library['loaded'])) {
  // The library has been loaded.
}

Even better, using a render array, you just need to use code similar to the following one, which is for the case the library needs to be attached to a form element.

$form['myelement']['#attached']['libraries_load'][] = array('d3');

For an hook_page_build() implementation, adding the library at the page bottom requires code similar to the following one.

function mymodule_page_build(&$page) {
    $page['page_bottom']['d3_library']['#attached']['libraries_load'][] = array('d3');
  }
}


How to hide a field in a views row if the row is about content type article? I have a view that is showing all my content types. What I want is to hide a certain field in its row if the content type on this particular views row has a content type of Article.

How can I do that?

One of solutions is using Views Conditional module

  Views Conditional is a simple module that allows you to define
  conditionals (if xxx then yyy) with fields in views. Conditions
  include:

Equal To
Not Equal To
Greater Than
Less Than
Empty
Not Empty

  Views conditional allows you to output text based on the result of the
  condition.

  How to use Views Conditional in your Views:
  1. Create a view. Add some fields under "FIELDS".
  2. Click on "ADD" next to fields. Scroll down to "Views: Views Conditional", probably found near the bottom of the list.
  3. Add and configure fields...
  4. Choose a field to run a condition against, and provide values accordingly.
  5. Save, views conditional handles the logic and returns as specified.

For findout how it work  at Views Conditional Module (Drupal 7 Tutorial) - YouTube


Populate drop down fields according to other fields in Drupal 7 Let's say I have a content type car with content fields brand and model. Now I want to populate the field model according to the value of brand that the user will select. So for example if have:

BMW

series 1
series 3

mercedes

a class
b class

So if a user chooses BMW as a brand the model field should be populated with series 1 and series 3.

May be hierarchical select is what you are looking for.

Use one taxonomy field with hierarchy to store brands and models. hierarchical_select module will create nice widget for choosing them.


"Drupal calls should be avoided in classes, use dependency injection instead" In my module using below code for getting url alias of given url:

$alias = \Drupal::service('path.alias_manager')->getPathByAlias($_POST['url']);

But one I run Automated Review(http://pareview.sh/) in my module I am getting below warning:

  16 | WARNING | \Drupal calls should be avoided in classes, use dependency injection instead

How can I update above code using dependency injection? My entire class code is given below.

<?php

namespace Drupal\my_module\Controller;

use Drupal\Core\Controller\ControllerBase;

/**
 * MyModule Class defines ajax callback function.
 */
class MyModule extends ControllerBase {
/**
 * Callback function for ajax request.
 */

  public function getUserContent() {
    $alias = \Drupal::service('path.alias_manager')->getPathByAlias($_POST['url']);
    $alias = explode('/', $alias);
    $my_module_views = views_embed_view('my_module', 'default', $alias[2]);
    $my_module= drupal_render($my_module_views);
    return array(
      '#name' => 'my_module_content',
      '#markup' => '
' . $my_module. '
',
    );
  }

}

Take the BlockLibraryController class as example; it extends the same class as your controller.

You define:

A static and public create() method that gets the values from the dependency container, and creates a new object of your class
A class constructor that saves the values passed from the previous method in object properties
A set of object properties to save the values passed in the class constructor

In your case, the code would be similar to the following one.

class MyModuleController extends ControllerBase {
  /**
   * The path alias manager.
   *
   * @var \Drupal\Core\Path\AliasManagerInterface
   */
  protected aliasManager;

  /**
   * Constructs a MyModuleController object.
   *
   * @param \Drupal\Core\Path\AliasManagerInterface $alias_manager
   *   The path alias manager.
   */
  public function __construct(AliasManagerInterface $alias_manager) {
    $this->aliasManager = $alias_manager;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container) {
    return new static(
      $container->get('path.alias_manager')
    );
  }

  /**
   * {@inheritdoc}
   */
  public function getUserContent() {
    $alias = $this->aliasManager->getPathByAlias($_POST['url']);
    // Omissis.
  }

}

Don't forget to put use \Drupal\Core\Path\AliasManagerInterface; on the top of the file containing the code you are showing.

As side note, the code you use to render the view is wrong: You don't need to use drupal_render() because views_embed_view() already returns a renderable array.
Then, the render array you are returning is probably not giving the output you expect. #name is probably not going to be used from Drupal, and #markup filters the markup you are passing to it, as described on Render API overview.

  #markup: Specifies that the array provides HTML markup directly. Unless the markup is very simple, such as an explanation in a paragraph tag, it is normally preferable to use #theme or #type instead, so that the theme can customize the markup. Note that the value is passed through \Drupal\Component\Utility\Xss::filterAdmin(), which strips known XSS vectors while allowing a permissive list of HTML tags that are not XSS vectors. (I.e, <script> and <style> are not allowed.) See \Drupal\Component\Utility\Xss::$adminTags for the list of tags that will be allowed. If your markup needs any of the tags that are not in this whitelist, then you can implement a theme hook and template file and/or an asset library. Alternatively, you can use the render array key #allowed_tags to alter which tags are filtered.
  #allowed_tags: If #markup is supplied this can be used to change which tags are using to filter the markup. The value should be an array of tags that Xss::filter() would accept. If #plain_text is set this value is ignored.


Why don't I get any CSS output? I did a fresh install of Drupal 8.
Everything had a nice style while installing, but when it was done, there was no CSS anymore.
Did the installation change some file rights?

I tried flushing the cache
I did check if the core/theme folder has CSS files in it
I did a re-install, but again there is just raw HTML

I checked and it looks like I have an HTTP/1.1 500 Internal Server Error on all CSS and JavaScript files.

Update:
The issue is with the .htaccess file in /sites/default/files/.htaccess
I changed the permission of the file to 644, then once changed,
i did edit the file via the file manager and commented out these lines:

#Options -Indexes -ExecCGI -Includes -MultiViews php_flag engine off

It works now but is tis a safe way to do it?

In my case, I was getting this in the apache error log:

.../sites/default/files/.htaccess: Option MultiViews not allowed here

Checking .htaccess, I found:

# Turn off all options we don't need.
Options -Indexes -ExecCGI -Includes -MultiViews

Even though it's turning MultiViews off, it's still not allowed, and removing it fixed the CSS.
Enabling sites to set it int he global apache config would also resolve it.


Views 3 Relationship Handler I am trying to write a relationship handler for Views 3 in Drupal 7, but am failing even to begin.

Basically, I have a bunch of nodes of various types all with the same field attached to them. This field is a reference field linking off to a Civicrm contact - but that's not important, as essentially these fields just contain integers.

Now, let's say I have a node of content type 'story', and its reference field contains the integer, oh, let's say 55. In addition, there are nodes of content type 'news' which also contain the reference ID 55.

I want to build a block view, that sits on the story page, that reads in the node's nid as its argument, and then through a relationship it discovers all other nodes that contain the same reference integer as itself.

(In my head, the sql looks something like: SELECT n.nid FROM node n INNER JOIN node n2 ON n.reference = n2.reference [Assuming, for the sake of simplicity, the field data is kept in the node table]).

How do I create a Views handler that caters for this relationship? The only documentation I can find is the views api, which is for version 2 and not 3, and besides is utterly unhelpful. Reading various module's views handlers is not helping either, and views tutorials on the web are almost non-existent.

Are you really sure you need a relationship handler for this?

In general the default relationship handler is already quite flexible because it uses the default join class which is really powerful.

There are some use cases for relationship handlers, for example the relation module, but this module does some vodoo stuff.

So back to the problem. It might be enought if you define 'relationship' with the right field and base field.

PS: There is a big reason why there is no documentation about api=3 because the difference to api=2 isn't big at all.

Here is an example how to define a relationship.

  $data['node_revision']['vid'] = array(
    'relationship' => array(
      'handler' => 'views_handler_relationship',
      'base' => 'node',
      'base field' => 'nid',
      'title' => t('Content'),
      'label' => t('Get the actual content from a content revision.'),
    ),
  );


Why is hook_update_N not running? I am porting a module to Drupal 7. The module has hook_update_N() functions called from hook_install(). There are some insert queries made inside one of the hook_update_N() functions. But my hook_update_N function is not running. Is there any way to explicitly invoke hook_update_N functions?

I know my question is almost same as this How to get hook_install() to run all hook_update_N()?. But I don't understand how hook_update_N() is called. I have run updates in my Drupal site which I think also run updates of custom modules but it seems hook_update_N() is not getting triggered. Because, I have added error_log() function inside hook_update_N() but the log file is empty.

Another reason why an update hook would not run is a mismatch between the update hook name and the major release number of the module (see .info file).

For example: the update hook mymodule_update_7001 does not run if the module version is 7.x.1.0. In such case you must rename the hook to mymodule_update_7101.

See the hook_update API documentation


How to have html not just sitename or logo in site heading block? (via subtheme or preferably editing WITHIN drupal) Can someone give examples of using html not just a text string or logo graphic in the header for a site?

I ask because I'd like to use several web typography fonts to make a logp rather than a bitmap.

Update

Editing "editing WITHIN drupal" - would be nice, sorry to adjust question. Thanks for your answers so far.

Keep it simple. Just disable the logo in your theme settings and use a block in it's place. You can throw anything you want in there.

Just place a block using Drupal UI into the header region of your theme. No coding, no template files creating/hacking is needed.


Why can't I change values in my cookies? I'm storing my users city in a cookie.

I want that cookie to expire by browser session, so I don't want to store this information in $_SESSION, because I want $_SESSION to persist for the default 23ish days.

So I'd like to stick with Drupal storing all of its stuff in $_SESSION as normal, but also set a cookie with a custom lifetime. When the user selects a city I set a cookie in my forms _form_submit() hook:

$c = 'Washington'; // ...or whatever
$_COOKIE['city']['cityname'] = $c;
setcookie('city[cityname]', $_COOKIE['city']['cityname'], 0);

If I print this out with print_r($_COOKIE['city']) I get:

Array ( [cityname] => Washington [state] => 65 )

Yay, it works!

Then the user selects a new city and the same code runs again (I know it's running because I've tried inserting a die; in there):

$c = 'New York';
$_COOKIE['city']['cityname'] = $c;
setcookie('city[cityname]', $_COOKIE['city']['cityname'], 0);

I print the $COOKIE value out again and get:

Array ( [cityname] => Washington [state] => 65 )

So the value hasn't changed and I'm left with the previous city. Why aren't my cookies values changing? Is there a way I can fix this, or a recommended workaround available?

OK, found the issue I think. The first cookie is set from the homepage. The second was set from a different page.

I looked in the Chrome "cookies" dialog and found out that I had multiple cookies all set with different paths.

setcookie() has a "$path" argument:

  The path on the server in which the cookie will be available on. If set to '/', the cookie will
  be available within the entire domain. If set to '/foo/', the cookie will only be available
  within the /foo/ directory and all sub-directories such as /foo/bar/ of domain. The default
  value is the current directory that the cookie is being set in.

So in my setcookie() I now do:

setcookie('region[state]', $state, 0, '/');

...and the path gets saved to "/" every time, and I don't end up with duplicate cookies causing confusion.


Validation at node_presave in drupal 6 I received a somewhat complicated Drupal 6 application to maintain and unfortunately I am quite a newbie with Drupal.

The task is to verify certain system variable is set before saving the node. Is the node_presave ok place to do this? And how can I abort the saving process?

It should fail silently with a log message.

No, hook_nodeapi op=presave is the wrong place for that.

You should instead use hook_nodeapi op=validate

  "validate": The user has just finished editing the node and is trying
  to preview or submit it. This hook can be used to check the node data.
  Errors should be set with form_set_error().

https://api.drupal.org/api/drupal/developer%21hooks%21core.php/function/hook_nodeapi/6

However, it won't fail silently, instead showing an error on the node form.


How to close login-popup after successful login I'm working on a FF-extension, that displays user-specific information on 3rd-party websites. Users need to be logged in to my Drupal-website. I'm checking login state with a cross-domain-proof jQuery.ajax(). If a user is not logged in, the FF-extension opens a popup-window (window.open()) showing a Drupal login/register/passwordlost page (/user/login).

Now I would like this window to close and the FF-extension to carry on, as soon as the login (registration/password-request) is successful. And now I'm lost. How would I do this?

I know how to close the popup from my FF-addon (window.close()), but I don't know how to tell the addon, when to do it. I thought of polling the login-state. But that seems kind of clumsy, no? I have also tried redirecting the drupal-page after successful login (login destination module) to a self-closing page, but in newer browsers window.close() works only on windows, that were created with the same script. And then I would still have to find a way to tell the FF-addon to proceed.

How do other people solve this?

The user login form is the one returned from user_login(), or user_login_block(). In both the cases, user_login_submit() is the form submission handler that is invoked for the login form.

Adding a form submission handler that is executed after user_login_submit() would be possible to set a Drupal variable.

function mymodule_form_user_login_form(&$form, &$form_state) {
  $form['#submit'][] = 'mymodule_login_submit';
}

function mymodule_login_submit($form, &$form_state) {
  global $user;

  variable_set('mymodule_user_logged_in', (integer) !empty($user));
}

The addon could then periodically ping a URL handled from the module, which would return the value of "mymodule_user_logged_in," and close the window when its value is not 0.
The code I wrote here is not optimized, and it serves only as example of what is possible to do.

To allow to the added form submission handler to be called after the submission handler added by user.module, the weight of the module should be changed to a value that is different from the default module weight, in hook_install() or hook_update_N().

function mymodule_install() {
  db_update('system')
    ->fields(array('weight' => 10))
    ->condition('name', 'mymodule')
    ->execute();
}


Behavior not attaching to a form element I have a module for relating pieces of content to each other. My module successfully adds a field to all content-types that is essentially a list of integers, meant to hold node ID's. I want AJAX functionality such that when the user begins typing the title of a node, autocomplete suggestions begin appearing. I've already implemented the web service via Drupal to retrieve nodes based on partial titles, and that's working very well. The problem is now attaching the behavior I want to the form element.

Two problems:

1) No way to uniquely identify the form element in question. The class name is not going to be usable if there are more than one of them, which there may be. How can I force a unique class name? Something like class="content-relation" for each one?

2) The behavior I want to attach is failing to do so. I've tried a couple different ways...here they all are.

Way 1:

Drupal.behaviors.content_relation =  {
    attach: function(context) {
        jQuery('input.form-text').change(function() {
            var ul = jQuery('<ul />')
                .css({position: 'absolute', top: '0px', left: '0px'});

            jQuery.get(
                '/api/'+jQuery(this).val(),
                function (data) {
                    jQuery.each(data, function(item){
                        var li = jQuery('<li>');
                        li.html(item.title);
                        li.appendTo(ul);
                    });
                }
            );
        });
    }
};

Way 2:

jQuery.ready(function(){
    jQuery('input.form-text').live('change', function() {
        var ul = jQuery('<ul />')
            .css({position: 'absolute', top: '0px', left: '0px'});

        jQuery.get(
            '/api/'+jQuery(this).val(),
            function (data) {
                jQuery.each(data, function(item){
                    var li = jQuery('<li>');
                    li.html(item.title);
                    li.appendTo(ul);
                });
            }
        );
    });
});

...but none of the inputs with a class of form-text have this function listed in their change-listeners, nor do they respond to changes. Thoughts?

You shouldn't need a single line of JS to have autocomplete textfield working in D6/D7. Please see the Form API refrence.


How to wrap a View output with a link? I have a view with no fields but a special format (An openlayer map). I would like to wrap the whole output (a map) with a static link. Typically I would like something like:

        /*the map*/

Is this achievable?

EDIT
My view doesn't use fields, so I can't use custom texts fields.

There might be a couple of method to do this.

Using Views: you can add a "Custom Text" global field and add view content to it and wrap it on the link or you can "Rewrite results" on the same file and output the field as a link.

Using a template file: view let you have a custom template file for your view, so you can use it to wrap your view content with the link.

Using jQuery: you can do something like this:

$('div.VIEW-CLASS').click(function(){document.location.href='URL.COM';});

And that will wrap the view on a link.

See the images below to see how to add a "Custom text" field and how to make it a link:

Select custom text field

Add views fields into the custom text field and make it all a link


Can users be forced to insert only plain text by default in CKEditor? I know there is "Paste Text" button in CKEditor, and I can limit allowed HTML tags.
But it's very hard to explain clients to use specific button when they insert text.
As result they often insert "dirt" texts with HTML tags.
As I remember there was setting in early versions of CKEditor to force insert plain text by default but cannot find it in current version.
Is there any solution for the problem?
UPDATE:
I don't want to restrict user to use some tags. But user should get "clean" plain text without HTML tags when insert text.

You want to change the ckeditor configuration to always paste as plain text.
This defined in https://ckeditor.com/docs/ckeditor4/latest/api/CKEDITOR_config.html#cfg-forcePasteAsPlainText
It comes down to the following JavaScript configuration:
// All content will be pasted as plain text.
config.forcePasteAsPlainText = true;

Have a look here for where to set it
Is there advanced configuration for CKEditor in Drupal 8?
Or just use module CKEditor custom config and set in custom configuration: forcePasteAsPlainText = true


Get field_collection values in field template I have installed field_collection and have a collection called field_contact,
each entry of which has a field called field_contact_url

I'm trying to customise the display of that field by overriding the view template, using the file views-view-field--field-contact.tpl.php

The template is being used, if I put a simple print 'hello' I can see the hello come up, but I cannot figure out how to access the field_collection properties.
I've gone through every answer and example I can find on google, but all of them seem to rely on a variable that is not there.

$content is not present
$node is not present
$field is present, but $field->field->id is empty
$items is not present

I tried using this example, but the $rows is not showing up (perhaps because I put the functions in the wrong file... I put them both in the template.php file.

I have spent 6 hours trawling through Drupal docs, would really appreciate if someone could help me figure out what variables I need or where I need to put the template file so the right variables become available.

This is the solution I came up with. The first line is a bit of a hack and I think is not very robust.

Also, I think i'm not using the entity_metadata "way" of accessing the contact fields - but it works for now.

Would welcome suggested improvements.

$candidate_node = node_load($row->node_node_nid);
$survey_node = node_load($row->{$field->field_alias});

$candidate_wrapper = entity_metadata_wrapper('node', $candidate_node);
$survey_wrapper = entity_metadata_wrapper('node', $survey_node);

foreach ($candidate_wrapper->field_contact->value() as $contact) {
    if (array_key_exists('und', $contact->field_type)) {
            $key = $contact->field_type['und'][0]['value'];
            $value = $contact->field_contact_url['und'][0]['safe_value'];
            print sprintf($format[$key], $key, $value, ucfirst($key), $score);
    }
}


Custom module to validate fields I am trying to create a custom module using webforms drupal 7 to carry out some form of validation. All i want the module to do to check if a value of one field (A) is entered then the other field (B) should be zero and if the value of field (B) is entered then the value of field (A) is zero. Anybody able to help? I am a newbee to drupal.

Webform Validation to the rescue!

  This module adds an extra tab to each webform node, allowing you to
  specify validation rules for your webform components. You can create
  one or more of the predefined validation rules, and select which
  webform component(s) should be validated against those.


Admin approval of Commerce order I am building a proof of concept ecommerce solution using commerce kickstart v2

I wish to implement a system where a user can submit an order but an admin must approve orders before the customer can pay - I have a feeling I can do this with rules & extra order statuses but I cannot figure out which part of the checkout process to intervene in.  Heres what I have so far:

extra order status "Awaiting Admin Approval"
extra order status "Approved by Admin"
Rule that fires when order status changes from 'shopping cart' to 'checkout' and sets order as "Awaiting admin Approval"
Rule that fires when order status is "Awaiting Admin Approval" and path contains 'checkout'. this rule redirects user to a page that says 'your order is awaiting approval'
Rule that should allow user to checkout once admin has changed order status to "Approved by admin"

Rule 5 above (in italics) is giving me problems, no matter what I try - rule # 3 always fires, even after the order has been approved, which results in the user being redirected.

The problem arises because once the order has been set as "Approved by Admin", it must then go back to "shopping cart", then "checkout"... which then fires rule 3, which brings me nicely back around in a circle.

Any tips or suggestions?

You might consider one of two methods:

Define another status/branch in the checkout logic (approved shopping cart -> checkout) wherein Rule 5 would redirect to the approved cart step instead of the standard shopping cart.

or

Implement an "admin approved" flag on the Order that you could set in your actions for Rule 5 and then test in your conditions for Rule 3, redirecting the user only if that flag was false. That flag could be implemented as a new field on the Order entity (assuming Order is an entity).

Method 1 might be somewhat redundant and more work than method 2, but I think it's the better of the two because it extends the current shopping cart/checkout/Rules logic and workflow. I think there's merit in that.

In addition, method 2 would bury a critical aspect of that logic into a field on the Order. I think the state of an Order in a checkout process should be defined separately from the Order itself.

Perhaps there's a third way that uses a little bit of both methods.

Hope this is helpful.


How to send a notification to a user at specified time (between 9am to 10 am) daily? I have created a form which contains a CCK field "send sms" (checkbox) with two options:

Send sms between 9am to 10am  (= option 1)
Or anytime (= option 2)

If the user selects option 1, then notification should send between time 9am to 10am to user.

If the user selects  option 2, then notification should send at any time.

How to achieve this functionality?

Part 1: Rules

Have a look at my answer to "Rule to store user's last post date and scheduled rule based 30 day reminder", a question that is a variation of part of your question. It explains how you can use the Rules module for this (using the Rules Scheduler also).

Part 2: Message Stack

Have a look at the Message Stack, these are the basic components and dependencies of it:

Some more details about the Message-related modules (=quotes are from the module's project page):

Message:

  The Message module is the core of the message stack. It enables logging and displaying system events in a number of different use cases. Events that are recorded over time are sometimes call activity streams. Exportable messages subtypes can be created for different use cases with custom fields and display (view) modes.

Message Notify.

  This module provides a method for sending a message via a notifier plugin. Message Notify comes with plugins for email and SMS and may be extended to other transport mechanisms as required.

Message Subscribe.

  With this module, users who subscribe to content will be notified when events occur that involve that content. The module leverages the Flag module, which provides a subscribe functionality to users.

Quite a few popular Drupal distributions already adopted to this Message Stack, Open Atrium is one of them.


What is the purpose of key_value_expire table? In Drupal8, what purpose does the key_value_expire table data serve?  Can that be excluded from a database backup?

I ask because, during development, I backup the database using "drush sql-dump --ordered-dump" and exclude tables like "cache*", but after making a few minor content changes in a node/page (did not create a revision) and re-dumping the database, git diff is saying that all of the data in the key_value_expire table changed.

key_value_expire is one of the larger tables in Drupal, in terms of # of rows of data, so it will balloon the storage requirements for Git if the data in this table changes completely for every minor change on the site.

Also, is there a detailed explanation of the functionality/purpose of each Drupal table?

Thank you very much in advance.

Beside the form cache and the update status the key_value_expire table is mainly used by the private and shared temp store. There you find a good explanation what the purpose of this data is:

  class PrivateTempStore

  Stores and retrieves temporary data for a given owner.

  A PrivateTempStore can be used to make temporary, non-cache data
  available across requests. The data for the PrivateTempStore is stored
  in one key/value collection. PrivateTempStore data expires
  automatically after a given timeframe.

  The PrivateTempStore is different from a cache, because the data in it
  is not yet saved permanently and so it cannot be rebuilt. Typically,
  the PrivateTempStore might be used to store work in progress that is
  later saved permanently elsewhere, e.g. autosave data, multistep
  forms, or in-progress changes to complex configuration that are not
  ready to be saved.

  The PrivateTempStore differs from the SharedTempStore in that all keys
  are ensured to be unique for a particular user and users can never
  share data. If you want to be able to share data between users or use
  it for locking, use \Drupal\user\SharedTempStore.

Reference:
https://api.drupal.org/api/drupal/core%21modules%21user%21src%21SharedTempStore.php/class/SharedTempStore/8.2.x
https://api.drupal.org/api/drupal/core!modules!user!src!PrivateTempStore.php/class/PrivateTempStore/8.2.x