How do I alter the form submission handler? For some reason I need to replace some characters (if exist) in every single textfields in any form just right before they stored in database. In other words I need a hook in which I could get all submitted data and replace their characters.
I found this solution:

function hook_form_alter($form, $form_state, $form_id) {
  $form['#submit'] = 'my_custom_submission_function';
}

But this isn't a good idea since I have to take care of the rest of the submission progress too. I just need to replace some characters.
Is there any hook to do this? What are the solutions?

$form['#submit'] stores an array of form submit handlers. With the code you provided you're overwriting it by adding only your own. To get the result you want you should add your submit handler as the first element in the array like this:

array_unshift($form['#submit'], 'mymodule_custom_submission');

Getting the right values in the right forms and replacing some characters is probably a bigger issue in itself. You may want to narrow down the forms/fields you need to change to make sure you don't break anything.


How to add html tag in a form element? How to add html tag in a form element drupal 8?

$form['buttons']['submit'] = [
  '#type' => 'submit',
  '#value' => T('Send'),
  '#prefix' => '
',
  '#suffix' => '<button type="button" class="btn btn-sm btn-default" data-dismiss="modal">' . $this->t('Close') . '</button>
',
  '#attributes' => [
    'class' => ['btn-success'],
  ]
];

I try to add allowed_tags:

$form['buttons']['submit'] = [
  '#type' => 'submit',
  '#value' => T('Send'),
  '#prefix' => '
',
  '#suffix' => '<button type="button" class="btn btn-sm btn-default" data-dismiss="modal">' . $this->t('Close') . '</button>
',
  '#allowed_tags' => ['button'],
  '#attributes' => [
    'class' => ['btn-success'],
  ]
];

OR

$form['buttons']['#allowed_tags'] = ['button'];
$form['#allowed_tags'] = ['button'];

Not working...
Help me please!

I can't tell which element is giving you trouble.

For the div, instead of prefix/suffix you can create a container element:

$form['submit_container'] = array(
  '#type' => 'container',
  '#attributes' => array(
    'class' => ['modal-footer'],
  )
);

And then you can put a submit input inside of that:

$form['submit_container']['submit'] = array(
  '#type' => 'submit',
  '#value' => $this->t('Submit'),
  '#attributes' => array(
    'class' => ['btn', 'btn-sm', 'btn-default'],
    'data-dismiss' => 'modal',
  )
);

If you need a button type='button' just to fire Javascript and not submit the form, that is somewhat problematic, it seems. One method is to override the button template.

Type inline_template may be the best bet:

$form['submit_container']['button'] = array(
  '#type' => 'inline_template',
  '#template' => '<button type="button" class="btn btn-sm btn-default" data-dismiss="modal" onclick="closeButton()">Close</button>',
);

Change a normal submit 'input' type to 'button' type with button tag


Export views result as json, xml, csv etc? In Drupal 7 we had

https://www.drupal.org/project/views_data_export
https://www.drupal.org/project/views_datasource

Can Migrate in Drupal 8 replace these, for example to export view results with Migrate as JSON, CSV, etc?

There are some options to export Views data in CSV format in Drupal 8

Views Data Export Module

  This module is designed to provide a way to export large amounts of
  data from views. It provides a display plugin that can rendered
  progressively in a batch. Style plugins are included that support
  exporting in the following types:

  CSV Microsoft
  XLS (or really simple HTML understood by Excel)
  Microsoft DOC
  Basic TXT

VBO Export Module it adds CSV export feature for Views Bulk Operations  Moule

  The module adds 2 new Views Bulk Operations actions: Export to csv and export to Excel.

3.CSV Serialization Module

This module provides a CSV encoder for the Drupal 8 Serialization API. This enables the CSV format to be used for data input and output in various circumstances. For example:

  Drupal 8's REST module can accept or return data in CSV format Views
  can output CSV data via a 'REST Export' view Module developers may
  leverage CSV as a format when using the Serialization API


What does Drush error "Unknown option: --db-url" mean? Somehow user 1 has become blocked on a Drupal site I manage.   As a result, I can't issue a uli command via Drush.  I tried to use the command

drush @pantheon.xxxxxx.dev user-unblock --uid=1

but it returns error

Unknown option: --db-url.  See `drush help user-unblock` for available options.

I have checked the help for user-unblock for but it does not mention --db-url.  The site is working and and other users can log in, however I can't get in as admin.

Thanks.

Pantheon site aliases are only compatible with Drush 5. I had the same message when trying to use Drush 6.

On a Mac with Homebrew, I ran "brew install drush5" and then symlinked the resulting file (/usr/local/Cellar/drush5/5.9/libexec/drush) to "/usr/local/bin/drush5" not to interfere with my existing Drush installation.

Now I can run commands such as "$ drush5 @pantheon.xxx uli" when needed for Pantheon.


Drupal + Solr, boost result based on custom node weight I use Drupal 6 with the ApacheSolr search module.

On my website, all visitors can flag any node with a yes/no answer to the question "Did you find what you were looking for?". Based on those answers, I calculate a custom ranking score for each node which is stored in a separate DB table.

Now I would like to include this score when sorting/boosting the search results in Solr, so that those nodes with the best relevancy / score come out on top.

Can it be accomplished with hook_apachesolr_prepare_query()?

All suggestions are welcome :)

To provide the score as a sort option add it in the prepare_query hook:

function mymodule_apachesolr_prepare_query(&$query, &$params, $caller) {
  $query->set_available_sort('field_score', array('title' => t('Score'), 'default' => 'desc'));
}

To boost by it you'll need to either:

Go to Site settings -> Apachesolr -> Search fields and if the score field appears there give it a value bigger than all the other fields to make it the most relevant.
If the field doesn't appear (due to the type it might not appear) or you want more control (like calculate the boost value on every query) you can add the boost in the modify_query hook with something like this: $params['qf'][] = 'field_score^10';.


How to create a node from a Webform using rules? I want to create a node based on a webform data using the Rules module. This is because of a complication surrounding relationships within the associated CRM system.

I am already at the point where I have the webform created and have got to the following (and working) point within Rules:

{ "rules_member_news_import_" : {
"LABEL" : "Member News (cloned)",
"PLUGIN" : "reaction rule",
"OWNER" : "rules",
"REQUIRES" : [ "webform_rules", "rules" ],
"ON" : { "webform_rules_submit" : [] },
"IF" : [
  { "webform_has_id" : {
      "form_id" : [ "form_id" ],
      "selected_webform" : { "value" : { "webform-client-form-730" : "webform-client-form-730" } }
    }
  }
],
"DO" : [
  { "entity_create" : {
      "USING" : {
        "type" : "node",
        "param_type" : "newsfrommembers",
        "param_title" : "[data:title_member_news-value-raw]",
        "param_author" : [ "user" ]
      },
      "PROVIDE" : { "entity_created" : { "entity_created" : "Created entity" } }
    }
  }
]

What I need to do is use the rest of the fields in the webform to transpose the information across, for example the body text and an image.

What I am trying to learn is how to also incorporate the body and other information. I used the export to add what I thought would work, for example:

"param_body" : "[data:body]"

within the entity_create action, however when I imported the edited text it simply disappeared, so I am assuming that I have to add a separate action to add entity variables.

I went back to using the menus and I again could not get it to work. I must be doing something basic wrong.

1st attempt

Before using a Rules Action like "Set a data value" for your a field, you have to make sure to add a Rules condition Entity has field (related to the  field for which you want to set a value). And make sure to add that Entity has field condition BEFORE other Rules Conditions in which you might want to refer to this field.

That's also what is mentioned in the Rules UI, e.g. when you're adding a "data comparison" condition: somewhere it says "The data selector helps you drill down into the data available to Rules. To make entity fields appear in the data selector, you may have to use the condition 'entity has field' (or 'content is of type')".

The above applies to any of your "... rest of the fields in the webform" (as in your question).

For a video tutorial that illustrates the importance of this Entity has field condition, refer to Data types and data selection, especially what is shown between about 13:30 and 17:30 in it.

2nd attempt

The prior attempt is more or less like a Getting-started-with-Rules that resolves various situations where some variables appear to not be available in Rules Actions, etc. However, for this specific question, which is about using Rules in combination with Webform, things are a very little bit more complicated, as further explained below.

Let's assume I have a webform created with some of its fields with machine names like so:

contact_us_first_name.
contact_us_last_name.
contact_us_subject.

After you add these fields (with identical machine names) to any of your own forms, you should be able to import the prototype-rule below (using the Rules UI) in your own environment (without running into an integrity constraint):

{ "rules_create_a_node_from_a_submitted_webform" : {
    "LABEL" : "Create a node from a submitted webform",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules", "webform_rules" ],
    "ON" : { "webform_rules_submit" : [] },
    "IF" : [
      { "user_has_role" : { "account" : [ "user" ], "roles" : { "value" : { "2" : "2" } } } }
    ],
    "DO" : [
      { "drupal_message" : { "message" : "The webform component submitted by [data:contact_us_first_name-value] (= [data:contact_us_first_name-title]) [data:contact_us_last_name-value] (= [data:contact_us_last_name-title]) contains a field labeled \u0022[data:contact_us_subject-title]\u0022 which has value \u0022[data:contact_us_subject-value]\u0022." } }
    ]
  }
}

In the above rule I included an extra Rules Condition to prevent the Rules Action from being executed for anonymous users (feel free to adapt the role id of it, or just remove that Rules Condition. And the rule is triggered via Rules Event "After a webform has been submitted".

The Rules Action only displays an (informational) message on the site (my recommended way of writing and debugging Rules ...) after a webform gets submitted. Here is what I specified (in the rules UI) as the message to be shown:

  The webform component submitted by [data:contact_us_first_name-value] (= [data:contact_us_first_name-title]) [data:contact_us_last_name-value] (= [data:contact_us_last_name-title]) contains a field labeled "[data:contact_us_subject-title]" which has value "[data:contact_us_subject-value]".

Here is a sample of the message shown in my own setup:

  The webform component submitted by Dries (= First name:) Buytaert (= Last name:) contains a field labeled "Subject:" which has value " Rumour goes that the rules module can even replace the node_convert module! ".

What the above prototype-rule shows is that the "clue" to answer your question is that you have access to all labels and all values of any field of a webform available, ie:

[data:MachineFieldName-title] contains the Label of a field with machine name MachineFieldName.
[data:MachineFieldName-value] contains the Value of a field with machine name MachineFieldName

3rd attempt

The above is a good start, but still not sufficient to achieve your goal (= "... use the rest of the fields in the webform to transpose the information across, for example the body text ...", as in your question). However, you can use a technique similar to what is described in my answer to "How to do a data comparison to submitted webform data when using the Rules module?". For short:

Add an extra Rules Action to Add a variable (for each of the Webform components to transpose the information across, with a value assigned to it equal to your [data:ComponentName-value-raw] (and with a data type which equals the data type of your Webform component).
In your subsequent Rules Actions you can refer to the value of these variables you just added (that's the clue!).

Demo

Webform components

Assume a webform with form_id=191 and with these Webform Components:

Label = Title, Machine name = demoform_title, Data type = Textfield.
Label = Text, Machine name = demoform_text, Data type = Textarea.
Label = Number, Machine name = demoform_number, Data type = Number.
Label = Option, Machine name = demoform_option, Data type = Select options (single value).

Article content type

Assume an Article content type with these fields:

Label = Title, Machine name = title, Field type = Node module element.
Label = Body, Machine name = body, Field type = Long text and summary.
Label = Free Format Nr, Machine name = field_free_format_nr, Field type = Integer.
Label = OptionList, Machine name = field_optionlist, Field type = List(text).

Custom Rule

Here is a custom rule (in Rules export format), which is an extended (improved) version of the rule included in the question. This rule will create a new node (of type Article), and which will use the data included in the above mentioned Webform components:

{ "rules_create_a_node_from_webform_data" : {
    "LABEL" : "Create a node from webform data",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "webform_rules", "rules" ],
    "ON" : { "webform_rules_submit" : [] },
    "IF" : [
      { "webform_has_id" : {
          "form_id" : [ "form_id" ],
          "selected_webform" : { "value" : { "webform-client-form-191" : "webform-client-form-191" } }
        }
      }
    ],
    "DO" : [
      { "drupal_message" : { "message" : "The webform submitted contains these fields:\r\n\u003C\/ul\u003E\r\n\u003Cli\u003Ethe field labeled \u0022[data:demoform_title-title]\u0022 which has value \u0022[data:demoform_title-value-raw]\u0022.\u003C\/li\u003E\r\n\u003Cli\u003E the field labeled \u0022[data:demoform_text-title]\u0022 which has value \u0022[data:demoform_text-value-raw]\u0022.\u003C\/li\u003E\r\n\u003Cli\u003E the field labeled \u0022[data:demoform_number-title]\u0022 which has value \u0022[data:demoform_number-value-raw]\u0022.\u003C\/li\u003E\r\n\u003Cli\u003E the field labeled \u0022[data:demoform_option-title]\u0022 which has value \u0022[data:demoform_option-value-raw]\u0022.\u003C\/li\u003E\r\n\u003C\/ul\u003E" } },
      { "variable_add" : {
          "USING" : { "type" : "text", "value" : "[data:demoform_text-value-raw]" },
          "PROVIDE" : { "variable_added" : { "var_demoform_text" : "Form variable text" } }
        }
      },
      { "variable_add" : {
          "USING" : { "type" : "text", "value" : "[data:demoform_number-value-raw]" },
          "PROVIDE" : { "variable_added" : { "var_demoform_number_text" : "Form variable number text" } }
        }
      },
      { "data_convert" : {
          "USING" : { "type" : "integer", "value" : [ "var-demoform-number-text" ] },
          "PROVIDE" : { "conversion_result" : { "var_demoformvar_number" : "Form variable number" } }
        }
      },
      { "variable_add" : {
          "USING" : { "type" : "text", "value" : "[data:demoform_option-value-raw]" },
          "PROVIDE" : { "variable_added" : { "var_demoform_option" : " Form variable option" } }
        }
      },
      { "entity_create" : {
          "USING" : {
            "type" : "node",
            "param_type" : "article",
            "param_title" : "[data:demoform_title-value-raw]",
            "param_author" : [ "user" ]
          },
          "PROVIDE" : { "entity_created" : { "article_created" : "Created article" } }
        }
      },
      { "data_set" : {
          "data" : [ "article-created:body:value" ],
          "value" : [ "var-demoform-text" ]
        }
      },
      { "data_set" : {
          "data" : [ "article-created:field-free-format-nr" ],
          "value" : [ "var-demoformvar-number" ]
        }
      },
      { "data_set" : {
          "data" : [ "article-created:field-optionlist" ],
          "value" : [ "var-demoform-option" ]
        }
      },
      { "data_set" : { "data" : [ "article-created:comment" ], "value" : "0" } },
      { "entity_save" : { "data" : [ "article-created" ], "immediate" : "1" } },
      { "drupal_message" : { "message" : "A new article got created, with nid=[article-created:nid] and url=[article-created:url]" } }
    ]
  }
}

Some more details about the Rules Actions that were added:

Show a message on the site: This is just for debugging/demo purposes (remove it you don't want/need it anymore). Here is a sample message that gets displayed after submitting a webform:

  The webform submitted contains these fields:

  the field labeled "Title" which has value "Some interesting title of
  my webform".
  the field labeled "Text" which has value "Just some text,
  with some additional text and yet another line and another one".
  the field labeled "Number" which has value "842316".
  the field labeled "Option" which has value "A".

Add a variable (twice): To make the value of the Webform components demoform_number and demoform_option available in subsequent Rules Actions. Note that for demoform_number an additional Rules Action Convert data type is needed to get it to work.
Set a data value (3 times): To populate the node's body and the 2 node fields, using the variables created in a preceeding Rules Action.
Set a data value: To set "Comments closed" for the node being created (this is an optional Rules Action, just an illustration of other things you can do with such node being created).
Save entity: To actually save the node.
Show a message on the site: This is just for debugging/demo purposes (remove it you don't want/need it anymore). Here is a sample message that gets displayed after submitting a webform:

  A new article got created, with nid=123
  and url=http://www.example.com/node/123

Final result

After submitting the webform with data as in the sample above, a new article (with node id = 123) got created, and with these details about that node:

Title: Some interesting title of my webform
Body:

  Just some text,

  with some additional text

  and yet another line

  and another one

Free Format Nr: 842316
OptionList: Advanced (the label corresponding to key-value "A")

Additional possibilities

With some further refinements, the above prototype-rule can also be used to create a Rules based alternative for the Node Convert module ... and seems to have the potential also to create like an Entity Convert equivalent also.


My form validate function will not run. I am using Organic Groups. That module has a form where you add new members to a group. I would like to run additional validation on that form. I use hook_form_alter and can identify the form. I add a validate callback and verify its been added to the form array. Yet that function never runs. I don't know why.

function organization_control_form_alter($form, &$form_state, $form_id){
  if($form_id == 'og_ui_add_users'){
    dpm("Validation Added");
    //This dpm displays.

    $form["#validate"][] = 'organization_control_og_size_control_form_validate';
    //I have also tried running my validate function first, like this
      //array_unshift($form["#validate"],'organization_control_og_size_control_form_validate');
    //I have also tried only running my validation, like this
      //$form["#validate"] = array('organization_control_og_size_control_form_validate');

    dpm("form");
    dpm($form);
    //This dpm shows the validate callback has been added.
  }
}

function organization_control_og_size_control_form_validate($form, &$form_state){
  dpm("Validation Started");
  //This dpm NEVER shows

  //hard code an error for testing
  $subscriptionInfo['field_total_seats_value'] = 4;

  dpm("Validation Run 2");
  //This dpm NEVER shows

  if($organzational_control_organization_size >=  $subscriptionInfo['field_total_seats_value']){
    dpm("ERROR");
    //This dpm NEVER shows

    form_set_error('edit-name', t('Your Organization has reached is current license size limit.'));
    //This error is not displayed and the form submissions continues and succeeds.
  }
  else{
    dpm("It thinks its Okay");
    //This dpm NEVER shows
  }
}

It's not working because you're not using a reference to $form.

Change your function declaration to:

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

Note the & in front of $form.  This means you're actually working on the variable as passed to the function, not a copy, or at least that's my understanding of it.

A useful thing to do to avoid this kind of error with hooks is to check out the API for the hook you are trying to use and copy the parameters verbatim.


Cardinality Violation during Views contextual filter setup, how to fix this? I'm currently getting this error in my views setup:

SQLSTATE[21000]: Cardinality violation: 1241 Operand should contain 1 column

I'm not sure why its giving this error as it seems like it should work. I have a contextual filter that matches taxonomy term id's. I have it configured to pass in an array() of tid's, but it throws the error if its more than one. What could be wrong?

Below are screenshots of my setup and sql statement generated by views:

http://img14.imageshack.us/img14/8079/f4bw.jpg

Reading the instructions for multiple views contextual filter arguments you get the solution:

  Allow multiple values:
  If selected, users can enter multiple values in
  the form of 1+2+3 (for OR) or 1,2,3 (for AND).

So if you need an OR operator you should return a string of "1+2+3" and if you need an AND operator you should return a string of "1,2,3".

So don't return an array() but a string.


How to get Panelizer to only affect a specific node I have Panelizer installed on my Drupal 7 site. I would like to use Panelizer for only specific nodes and not have it apply on all my nodes (as it currently is). Reading the documentation it seems it is possible to do this but I can't get it to work.

In Admin->Structure->Pages I have the node_view enabled, and I see an entry for my particular node there as well (page-videos_view with the correct url path). If I disable the node_view, then Panelizer is effectively disabled as it doesn't apply any panels even though the view I want is still active.

I assume I am missing a setting somewhere but don't know what it is. Can anyone help out?

I have figured out my error. You need to go to Admin->Configuration->Content Authoring->Panelizer and make sure you don't have the Provide Default Panel option selected for the content type you are using Panelizer on.


How to load taxonomy terms from user profile field using entityfieldquery()? I want to write hook_node_form_alter() and limit taxonomy terms with only user checked terms on his profile in field_companies.
I can't pass the 1st step - load array of user checked terms from field_companies using entityfieldquery.
This code does not work:

$query = new EntityFieldQuery();

$result = $query
  ->entityCondition('entity_type', 'user')
  ->entityCondition('bundle', 'user')
  ->fieldCondition('field_companies', 'entity_id', $user->uid)
  ->execute();

The error message is:

PDOException: SQLSTATE[42S22]: Column not found: 1054
Unknown column 'field_data_field_companies0.field_companies_entity_id' in 'where clause':
SELECT DISTINCT field_data_field_companies0.entity_type
AS entity_type, field_data_field_companies0.entity_id AS entity_id, field_data_field_companies0.revision_id AS revision_id, field_data_field_companies0.bundle AS bundle
 FROM {field_data_field_companies} field_data_field_companies0
WHERE (field_data_field_companies0.field_companies_entity_id = :db_condition_placeholder_0)
AND (field_data_field_companies0.deleted = :db_condition_placeholder_1)
AND (field_data_field_companies0.entity_type = :db_condition_placeholder_2) ;
Array ( [:db_condition_placeholder_0] => 1 [:db_condition_placeholder_1] => 0 [:db_condition_placeholder_2] => user ) in function field_sql_storage_field_storage_query()
(line 632 in file modules/field/modules/field_sql_storage/field_sql_storage.module)

This query does not give terms, but only array with user[uid]=1 :

$query = new EntityFieldQuery();
$term_entities = $query
  ->entityCondition('entity_type', 'user')
  ->entityCondition('bundle', 'user')
  ->entityCondition('entity_id', $user->uid)
  ->fieldCondition('field_companies', 'tid', 0, '>=')
  ->execute();

SOLVED with my module user_referenced_taxonomy_terms
code has quality 60%. you need to read it and correct if your fields has other names. this code works in my site.

/*displays only user checked companies in node addition form in field_company*/
/* field_companies - user profile field  */
/* field_company - node field */

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

  global $user;
  //if current user has roles administrator or editor return
  foreach ($user->roles as $role) {
      if (($role == 'administrator') || ($role == 'editor')) return;
  }
  if (isset($form['field_company'])) {
    //get user checked terms companies
    $terms = db_select('field_data_field_companies', 'c')
       ->fields('c', array('field_companies_tid'))
       ->condition('c.entity_id', $user->uid)
       ->execute()
       ->fetchCol();
    if ($terms) {
        //forming array of firms using $terms array
        $count=count($terms);
        foreach ($form['field_company']['und']['#options'] as $key=>$value) {
            if ($key == '_none') continue;
            $delete=true;
            for ($i=0;$i<$count;$i++) {
                if ($key == $terms[$i]) $delete = FALSE;
            }
            if ($delete) $form['field_company']['und'][$key]= array('#access' => FALSE);
        }
    }else {
        //hide field firm if user has no access to any term
        $form['field_company']['#access'] = FALSE;
    }
  }
}

PS: with ur comment i optimized this code.
fetchAll() gives array of objects i do not need in objects and this is not optimal.
fetchCol() gives array that exactly i need.
but fetchAllKeyed() gives only one element.
thank you Paul!


Views ajax not enabling i'm trying to use an exposed filter with my views but i'm not getting my ajax to enable under the advanced link so my content can be dynamic. I try jquery update module to fix it but didn't work tried another browser didn't work too i really need help here...

The "use ajax" checkbox in Views refers to the pager only. Any other magic you may want to work with ajax would require some custom code or additional modules, depending on what you're doing.


How to know what is slowing down my drupal site My site is still in early stages of development and the page load is getting slower day by day. Even though i really think twice before installing a module for something and try to get it done with jQuery.

Is there a way to know "What Exactly (A module or my theme templates) is slowing down the site ?".

thanks

you can install devel module and enable show queries so you can look at what queries run your website.Find out havy query and try to optimize.


How to export Panels and Mini Panels with Features? I am trying to export the Panels and Mini Panels on my website with Features.

On the features drop down menu, there is an option for "Panels: panels_renderer_pipeline". However, when I click on it, no checkboxes appear.

I have looked though the "StrongArm" option but cannot find anything related to Panels and Mini Panels.

Thanks for any help!

Make sure the panel was not already added to another feature-module. You need to add the pagemanager stuff (handlers and pages) to the feature too.

BTW the pagemanager status enabled/disabled is set via a drupal variable, so check also strongarm: If i.E. node/%node is enabled, then the variable page_manager_node_view_disabled is set to FALSE.


D7 errors given when authenticated user changes password but pwd still changes I have a user role for content managers and I don't want to give them the permission to administer users. I do want them to have the ability to change their passwords so they aren't stuck with the temporary one I set them up with.

I have been able to add a link to their own 'edit profile' page on the default user landing page, and the link works and displays the change password form as expected. If they try to change their password, they are then given an access denied error because they are not authorized to view /admin/people, which is where they are sent after a password change.

HOWEVER: THE PASSWORD DOES GET CHANGED

So, it's confusing to the user because they think their password change has failed when it hasn't.

Is it possible to change what page they are directed to after a password change? I would prefer to send them back to their profile or even the homepage. (I would REALLY like to send them right to the content page so they can get to work.)

I would even settle for being able to edit the access denied error to better explain the situation to them.

Something doesn't add up with what the information you have given. When a user edits their own profile, the default is to simply reload the same page.

You said that you have added a link on their profile (view) page, that points to the user edit page.

I'm guessing that the following is part of the link you've added:

destination=admin/people

If there is, then you need to remove this. Anytime there is a destination=[SOMEPATH] in the URL and a form is submitted, it will redirect the user to the path given in the URL.


How do you remove the default Drupal 7 administration menu? I have disabled the "Toolbar" module, and cleared the cache; yet, it persists.

How do I remove it?

Weird, it just took time. I came back a few hours later and it was gone. Perhaps there are cache clearing issues in Drupal 7.


Why exposed filter doesn't appear, when ajax is off in block view I have a view as a block and I am using the exposed filter for content.I need a exposed filter value in the url but due to ajax ON its value doesn't pass to url, when ajax OFF then exposed filter is not appear. Please give me solution. how to resolve this problem.

Simply because it is not a page. If you notice on page view, with ajax off, you will see a parameter passes through the url.

/example?something=yes

If you go to that url directly, it automatically filters your value.

Since blocks are not pages (do not have urls), you cannot do that. Therefore, reloading the block with AJAX is the only option for exposed filters in blocks.


The %element-title is using the following invalid tokens I have defined few tokens that are grouped in few separate groups similar to [node:content-type:name] scheme. For example I'd like to have a token like [master:sub_group_1:tokan_A]. So This is how hook_token_info() looks like:

function MY_MODULE_token_info() {
  $tokens = array();
  $types = array();

  $types['master'] = array(
    'name' => 'Master group',
    'description' => 'This is the master group',
  );

  $types['sub_group_1'] = array(
    'name' => 'Sub group 1',
    'description' => 'This is the first sub group',
    // this tells this group that it's parent is 'master' group.
    'needs-data' => 'master',
  );

  $tokens['sub_group_1']['token_A'] = array(
    'name' => 'Token A',
    'description' => 'This token prints letter A',
  );

  return array(
    'types' => $types,
    'tokens' => $tokens,
  );
}

I'll skip MY_MODULE_tokens() as it's irrelevant here, but token_replace() works perfectly. It replaces [master:sub_group_1:token_A] correctly. But the problem is that token module does not list my custom tokens in available tokens section and when I try to use [master:sub_group_1:token_A] in forms that get validated by token module, I get The %element-title is using the following invalid tokens error message.

What is the correct method to define custom tokens and group them to avoid conflicts with tokens defined by other modules?

It seems that in order to nest those tokens a "dummy" token is needed that matches group name:

function MY_MODULE_token_info() {
  $tokens = array();
  $types = array();

  $types['master'] = array(
    'name' => 'Master group',
    'description' => 'This is the master group',
  );

  // This is needed in order to nest tokens:
  // a dummy token that is the same as nested group/type
  $tokens['master']['sub_group_1'] = array(
    'name' => 'Sub group 1',
    'description' => '1st tokens group',
    'type' => 'sub_group_1',
  );

  $types['sub_group_1'] = array(
    'name' => 'Sub group 1',
    'description' => 'This is the first sub group',
    // this tells this group that it's parent is 'master' group.
    'needs-data' => 'master',
  );

  $tokens['sub_group_1']['token_A'] = array(
    'name' => 'Token A',
    'description' => 'This token prints letter A',
  );

  return array(
    'types' => $types,
    'tokens' => $tokens,
  );
}


Definition join on field and where other field has value I am building a views plugin and I need it to do this:

LEFT JOIN my_table mt ON (mt.nid = node.nid AND mt.value = 'some argument');

I have found documentation for creating a views plugin, but all of the documentation that I have found doesn't say anything about creating view joins like this.

Is it possible? If so, how do I go about doing something like this?

Drupal has an extra field in the join in which you can inject the extra where conditions, you can get to it by using a views_query_alter:

function my_module_views_query_alter(&$view, &$query) {
    if ($view->name === 'my_view' && $view->current_display === 'the_display') {
        $args = $view->args[0];
        $query->table_queue['my_joined_table']['join']->extra = array(
            array(
                'value' => $args, // pass the args through
                'numeric' => FALSE, // or true if it is
                'field' => 'the_field',
                'operator' => '='
            ),
        );
    }
}


How to Display Empty Fields in views How do I Display empty fields in Views? Empty_Fields module does not work for me as there needs to be a custom text for it to display.

I want to display all labels even if the fields are empty. How do i achieve this?

Thanks

In Views field settings add &nbsp; to No results behavior. Your View  will then display a space and a field label if the field is empty.

If you're using Unformatted list format for your View block, then in Format -> Fields -> Settings make sure that Hide empty fields checkbox is unchecked. See screenshots below.


How do I use the field API? Someone told me that most of the time I will probably want to use the field API (CCK module in D6), rather than adding custom tables or modifying nodes by myself. How do I use the field API? Could anyone can make me an example?

If you've ever used CCK in D6, the Field UI will be rather intuitive. And unless you need to do very custom work, you won't need the Field API at all, just the Field UI.

But if you do need custom widgets or formatters, take a look at the Examples module for some very comprehensive usage of the Field API.


Why would a multilingual site sometimes say "Save (this translation)" and other times say "Save (all translations)"? We have a multilingual Drupal 8 site supporting 17 different languages and many more localized versions of those languages.

I have been noticing that sometimes when I am editing a node it says "Save (this translation)" but then other times it says "Save (all translations)".

What is triggering it to act differently at times? Have we configured something wrong with our translations/multilingual setup?

With what we are doing I believe we want them to save independently of each other.

The text of the submit button depends only on the translation settings of the status field. If the field "Publishing status" is not translatable for the content type, the button says "Save (all translations)".

You can change the language settings for content types, taxonomy vocabularies, user profiles here: /admin/config/regional/content-language


Before upgrading, do I need to upgrade the Views module to 6.3.x? I'm going to update a site from Drupal 6 to Drupal 7. It uses the Views module version 6.x-2.

I would like to know if I need to upgrade the Views module to version 6.x-3 before moving to Drupal 7.

It's not necessary. I have migrated one large site from Drupal6+Views2 to Drupal7+Views3 in just one step.

You have to take in account that views3 (views_ui submodule) depends on ctools. If you follow this path you have to disable views_ui before the upgrade and activate views_ui (and ctools) once the upgrade has finished.


Using hook_user_format_name_alter(), how to change username on user paths? I am using hook_user_format_name_alter() to change the way usernames are displayed through my site.

However, on the user paths:

user/UID
user/UID/edit

The page title is set to the username, not the result of hook_user_format_name_alter().

Is there an easy way to override the username here (and preferably anywhere else) and replace it with hook_user_format_name_alter()?

My goto solution would be the Real Name module, but I ran into a bug so I'm trying to do this programatically myself.

This is the title callback you have in core for /user/UID:

UserController::userTitle

/**
   * Route title callback.
   *
   * @param \Drupal\user\UserInterface $user
   *   The user account.
   *
   * @return string|array
   *   The user account name as a render array or an empty string if $user is
   *   NULL.
   */
  public function userTitle(UserInterface $user = NULL) {
    return $user ? ['#markup' => $user->getUsername(), '#allowed_tags' => Xss::getHtmlTagList()] : '';
  }

Unfortunately this uses the method getUsername(), which doesn't invoke hook_user_format_name_alter().

You need a custom title callback, where you get the username with the method $user->getDisplayName(), which does invoke the hook.

Then change the title callback in the user route entity.user.canonical:

$route->setDefault('_title_callback', '\Drupal\mymodule\Controller\MyController::userTitle');

See https://www.drupal.org/docs/8/api/routing-system/altering-existing-routes-and-adding-new-routes-based-on-dynamic-ones.

Had the feeling this can't be right and searched for an issue: https://www.drupal.org/node/2648420. This is committed for D8.5. Until then you can apply the patch, which simply replaces getUserName() with getDisplayName() in UserController.


administer MSSQL databases from Drupal 6 Can you advise on a way to manage my SQL Server databases from Drupal 6x. I am using SQL Server for PHP driver (i.e. sqlsrv_connect()) to connect to my databases. Is there any module I could use to administer my databases?

If any more information about my query is needed, please let me know.

There is no support for MSSQL Server in Drupal 6, so it is higly unlikely that a module that can help you to administer your MSSQL databases exists.

You could maybe write your own, see MSSql or SQL Server Wrapper for custom module? for a possible way to connect to your database while still being able to rely on some API's provided by Drupal.


HTTP error 500 after migration I was able to successfully take a back up of D7 site and then restore to target D7 site. When I visit the site, I get an error

  This page isn’t working. ...com is currently unable to handle this
  request. HTTP ERROR 500.

Added the code in settings.php:

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

  Fatal error: Cannot redeclare views_views_plugins() (previously
  declared in
  /home/.../public_html/sites/all/modules/views/includes/plugins.inc:15)
  in
  /home/.../public_html/sites/all/modules/hjhkjhj/views/includes/plugins.inc
  on line 402

How can I fix the error to bring my site back up?

You need to run YourDomain/update.php and here you can find why.

If the problem is not resolved and (hjhkjhj) is a custom module, then you can't have the same function with the name twice. In your case views_views_plugins.


I need a module like Pageflip I need a stable Drupal module version like Pageflip. Can any one suggest the module which I am searching?

The existing Pageflip module is still a beta version; I need a module that has a stable release.

As kantu's comment suggests, there is no formal "approval" system for modules on drupal.org.  Instead, module maintainers decide when to release their modules and what version number to assign them.

As pageflip is a highly specialized module, I doubt that there is another module that has similar functionality (a quick search returned none).  However, since it is beta 5, it is probably stable enough to use in production, as Countzero pointed out.  The alternative would be to write a module yourself, but since the pageflip module is already far along in its development it would probably be best for everyone if you would extend and contribute back to the pageflip module (assuming you were going to write your own module).

How do you really know whether the module is ready for production?  First, look at the list of open reported bugs.  In this case there are only 3 for the 6.x series, so it shouldn't take you very long.  If these bugs don't affect you, the module is probably safe to install.


Register and pay online I would like our website can register right.
Such registration is: After the user fields to fill out the registration page to enter paid. If payment was successful record in the user database is placed.

These payments are: When users get paid by the banks a record is submitted to my site.
This must be paid to confirm a few fields of this record to send back to the bank.

I think you might want to read this: http://drupaleasy.com/blogs/ultimike/2009/03/event-registration-ubercart

It's a walk through of setting up an "event registration" system in Drupal - however, that is really just a web site that:

1) presents introduction information about a product or service
2) After a customer clicks "Add to cart", presents the customer with a form to complete of
   needed info for that product/service
3) if the customer's credit/debit transaction is successful, the customer's purchase is
   identified as "valid" and your web site does whatever you offered in the way of
   product/service for your customer.

This is achieved with Ubercart, Ubercart's Conditional Actions, and some minor tweaking fully explained in the link above.


Use hook to get the domain configuration from language We have enabled English, Spanish, and French on our site. On Regional and language >> Languages detection we selected URL for Content language detection >> Detection Method. For Part of the URL that determines language, we selected Domain. We then set the following domains.

English: example.com
Spanish: es.example.com
French: fr.example.com

How can we programmatically obtain the domain associated to each language? What code should we use in a preprocess function?
Using the following code, we obtained the list of the language, but we are far
 from getting the domain that has been associated with each language.

function mymodule_preprocess_html(&$variables) {
  // to get all enabled languages
  $languages = \Drupal::languageManager()->getLanguages();

  // Did not find method to retrieve the domain configuration.
  foreach($languages as $key => $value) {
    ksm($languages[$key]);
    //stuck here on how to get domain configuration per language.
  }
}

The domain associated with each language is stored as configuration. Using the following code, $prefix will contain the prefix, and $domain the domain used.

  $config = \Drupal::configFactory()->get('language.negotiation');
  $languages = \Drupal::languageManager()->getLanguages();
  $prefixes = $config->get('url.prefixes');
  $domains = $config->get('url.domains');
  foreach ($languages as $langcode => $language) {
    $prefix = $prefixes[$langcode];
    $domain = $domains[$langcode];
  }

I wrote the code basing on NegotiationUrlForm::buildForm(), which is the form builder for the form that sets the negotiation URL for each language.


How to check if a user has ever ordered a product/list of products Given a list of product IDs, I'm trying to determine if a user has ever purchased any of them.

At the moment my logic consists of loading all the orders related to a user, then looping through the order lines to check individual product IDs:

$ordered = FALSE;

$node_wrapper = entity_metadata_wrapper('node', $node);
$product_ids = array();
foreach ($node_wrapper->field_products as $product) {
  $product_ids[] = $product->product_id->value();
}

$orders = commerce_order_load_multiple(array(), array('uid' => $account->uid, 'status' => 'checkout_checkout'));
foreach ($orders as $order) {
  $wrapper = entity_metadata_wrapper('commerce_order', $order);
  foreach ($wrapper->commerce_line_items as $order_line) {
    $product = $order_line->commerce_product;
    if (in_array($product->product_id->value(), $product_ids)) {
      $ordered = TRUE;
    }
  }
}

This feels like a long way round, and that perhaps I'm missing a helper function somewhere in Commerce that would get me this information.

Anyone know if such a function exists, or if there's a more elegant method to get this data?

NB. I know 'checkout_checkout' isn't the right order status for the production code, this is just test code at the moment.

I'm looking for an API solution to this; building up an SQL query would obviously be very easy, but more verbose and error-prone. What I'm looking for is a more elegant solution than my existing one (if one exists; it might not).

Here's an alternative approach, using an SQL query

$ordered = FALSE;

$node_wrapper = entity_metadata_wrapper('node', $node);
$product_ids = array();
foreach ($node_wrapper->field_products as $product) {
  $product_ids[] = $product->product_id->value();
}

// Query order details for products
// Note this is the line item product reference table
$query = db_select('field_data_commerce_product', 'p');
// Example if you want more fields, but would need to change ->fetchCol()
// $query->fields('o', array('order_id', 'order_number', 'uid', 'mail'));
$query->fields('o', array('uid'));
$query->innerJoin('field_data_commerce_line_items', 'l', 'l.commerce_line_items_line_item_id = p.entity_id');
$query->innerJoin('commerce_order', 'o', 'o.order_id = l.entity_id');
$query->condition('p.commerce_product_product_id', $product_ids, 'IN');
$query->groupBy('o.order_id');
// Fetch array of uids
$result = $query->execute()->fetchCol();

// Check if account->uid in array of order uids
// If so, uid has ordered product.
if(in_array($account->uid, $result)){
  $ordered = TRUE;
}


"Drush cannot find your database connection details" I'm having an issue that is baffling to me as a new user and I'm hoping someone here can answer me how to fix the error.  I'm trying to clone an existing drupal installation into a place on my mac with the commands

echo "Pushing private files"
/usr/local/bin/drush core-rsync @hpc.dev:%private @hpc.local:%private
echo "Pushing webroot files"
/usr/local/bin/drush -y core-rsync @hpc.dev @hpc.local
echo "Pushing database"
/usr/local/bin/drush -y sql-sync --no-cache @hpc.dev @hpc.local
echo "Clearing Drupal cache"
/usr/local/bin/drush -y @hpc.local cc all

This works fine until with the sql-sync piece, where I get the error:

... stuff stuff stuff
Command dispatch complete                                                             [notice]
Copying dump file from Source to Destination.                                      [ok]
Starting to import dump file onto Destination database.                            [ok]
/usr/bin/php /usr/local/drush-master/drush.php --php=/usr/bin/php  --backend=2        [notice]
--verbose --yes --strict=0 --root=/Users/cook47/Sites/drupal-test/html
--uri='http://localhost/~cook47/drupal-test'  sql-query
--file=/tmp/hpc-drupal-dev_20160302_005939.sql.gz --file-delete 2>&1
exception 'Drush\Sql\SqlException' with message 'Unable to find a matching SQL     [error]
Class. Drush cannot find your database connection details.' in
/usr/local/drush-master/commands/sql/sql.drush.inc:591
Stack trace:
#0 /usr/local/drush-master/commands/sql/sql.drush.inc(419):
drush_sql_get_class(NULL)
#1 [internal function]: drush_sql_query()
#2 /usr/local/drush-master/includes/command.inc(366):
call_user_func_array('drush_sql_query', Array)
#3 /usr/local/drush-master/includes/command.inc(217): _drush_invoke_hooks(Array,
Array)
#4 [internal function]: drush_command()
#5 /usr/local/drush-master/includes/command.inc(185):
call_user_func_array('drush_command', Array)
#6 /usr/local/drush-master/lib/Drush/Boot/BaseBoot.php(67): drush_dispatch(Array)
#7 /usr/local/drush-master/includes/preflight.inc(66):
Drush\Boot\BaseBoot->bootstrap_and_dispatch()
#8 /usr/local/drush-master/drush.php(12): drush_main()
#9 {main}

Something appears to be awry with my database on the localhost or perhaps with my alias.

Here is my alias for localhost:

$aliases['local'] = array (
  'root' => '/Users/cook47/Sites/drupal-test/html', //CHANGEME
  'uri' => 'http://localhost/~cook47/drupal-test', //CHANGEME
  //'remote-host' => "localhost",
  //'remote-user' => 'cook47',
  'path-aliases' => array (
    '%drush' => '/usr/local/bin/drush', //CHANGEME
    '%site' => 'sites/default/',
    '%files' => 'sites/default/files',
    '%private' => '../private',
    '%dump' => '/export/www/hpc-drupal-dev.llnl.gov/drush-dump.sql',//CHANGEME
  ),
  'target-command-specific' => array(
    'sql-sync' => array(//CHANGEME
      'enable' => array('devel'),
      'disable' => array(
      ),
    ),
  ),
  'command-specific' => array(
    'rsync' => array(
      'mode' => 'vrlzOk',
      'exclude-conf' => 1,
    ),
  ),
  'databases' => array (
    'default' => array (
      'default' => array (
        'database' => 'hpc-drupal-dev', //CHANGEME
        'username' => 'hpc-drupal-dev', //CHANGEME
        'password' => 'xxxxxx', //CHANGEME
        'host' => 'localhost',
        'port' => '',
        'driver' => 'mysql',
        'prefix' => '',
      ),
    ),
  ),
);

Drush no longer allows you to define a 'database' record in your site alias file for use with sql-sync.  This used to work in earlier versions, but is no longer supported.  Make sure that the source and target sites both have valid settings.php files that include the database information.

To test:

drush @hpc.dev sql-conf

If your database connection is correct, it will be displayed. Using sql-conf on each site can help isolate which one is having a problem with its connection info.


Static Html elements on different pages So, I have a frontpage where I simply have a big image and a button that leads to a second page. On that page I want this:

Which are two sections. However, when I'm on the contact page I don't want the section Questions?

I want to write this in Html as I don't see how I would create these sections in Drupal. So my question is how can I make sure it's not visible on the contact page ?

There are lots of ways you could do it - blocks, panels, template overrides.  The easiest way for you would probably to create a custom block and put the html in that.  Then you'd be able to set the block visibility to exclude the /contact page.


How can i list all display suite layout templates used Is there a way to list all display suite templates that are currently being used in the various view modes?

To clarify: I have many content types, and many view modes, AND many custom made ds layouts. It's becomes a big mix and i would like to get an overview which ds layouts are being used by which view mode / content type.

I think he's asking to get an overview of of which bundle / view mode uses which template file.

That's currently not easy to fine in the backend - however this is something we want to add add some place.

The fastest way to get an overview is to go to the database and look into the 'ds_layout_settings' table. The 'layout' column holds the machine name of the template used.


How do I create a block that has links to site registration and forgot password programmatically? Can anyone help me writing code for a block containing the "Register" and "Forgot your password?" links that are shown to the anonymous users?

If you want to learn, I suggest, look at the relevant part of drupal core:
user_block_info() - this is the block info definition.

user_block_view() - This builds the renderable array of block.

You see here $block['content'] = drupal_get_form('user_login_block'); This makes the complete user login form. If you want to show only the two link, just change this to something like this:

$block['content'] = array(
  '#markup' => 'the pure html of your links',
);

To check, how to generate the core these links, see the user_login_block() in core. The line 1323 is the html markup in you block's content, what do you need


Drush command not found after Drush completely installed I installed Drush 8 with composer.

composer require drush/drush:~8

Unfortunately, error drush command not found after Drush completely installed.

Why's the drush command can't be use?

Installing Drush for Drupal 8 with Composer

https://www.youtube.com/watch?v=ZqY_XsCTmAc

Once you have installed Drush, you need to ensure that you ~/vendor/bin directory is in your $PATH, as explained in the installation instructions (Note: this link no longer works)

Add export PATH="$HOME/.composer/vendor/bin:$PATH" to your ~/.bash_profile or ~/.bashrc, and then run source ~/.bash_profile (or ~/.bashrc).

I would recommend against installing Drush 9 via composer require at this time. Sticking with Drush 8 is probably best; if you want to use Drush 9, use a simpler installation method, such downloading the .phar, or clone the repository and run composer install in the directory Drush was cloned to.


How to use Drupal to encapsule an external site This is the scenario: I have a Drupal 6 site, and another website that doesn't use Drupal. This 'other site' is in the same server, and the same hosting account. I need Drupal to be over the other website with his theme, regions, blocks and sessions/roles/authentication. The other website must conserve its own system of session, authentication, content and their URLs (but like already said, the theme, blocks, regions, authentication, must come from Drupal).

Update: iframe is not an alternative (SEO issues).

Update: This guide Integrating third party applications seems useful, but certainly I do not know how to implement it.

If you've, at least, any control on the second web site you can do it with dynamic includes. It works not so bad with the help of an own module.

The idea its to create a module that do a file_get_content() and return it to Drupal that gonna show the content.

But, for it your second web site should have relative paths between his pages, or you will make the change with a regex.

There an example module, no tested.

function mymodule_menu() {
  $items = array();

  $items['inc/%'] = array(
    'title' => t("Include"),
    'page callback' => 'mymodule_include',
    'page arguments' => array(1)
  );

  return $items;
}

function mymodule_include($path) {
  $http = 'http://example.com/';
  // Maybe check if the page is available
  // better to use drupal_http_request for that
  $content = file_get_contents($http . $path);

  // Perform any change in the content before to
  // send it for render.
  return $content;
}


How do I execute a view in a custom module and print the output (as HTML markup)? I want to print the output from a simple view in my custom module. But is doesnt work. I have tried many options from forums and stackoverflow. All of them print "array" instead of html-markup.

My controller:

class DefaultController extends ControllerBase {

    public function myfunc1() {

        $view = Views::getView('myfirstview');

        $view->setDisplay('page_1');
        $view->preExecute();
        $view->execute();

        // $myresults = $view->preview();  = array
        // $myresults = $view->render();  = array
        $myresults = $view->result; // = array

        return array(
            '#title' => 'Hello World!',
            '#markup' => $myresults,
        );
    }
}

How can I print the result/output of a view programmatically?

I dont want to make it without "embed view" , because I want to set some exposed filters later.

Views implements its own render element type (Drupal\views\Element\View), which you can use like so:

return [
  '#title' => 'Hello world',
  'view' => [
    '#type' => 'view',
    '#name' => 'myfirstview',
    '#display_id' => 'page_1',
    '#arguments' => ['foo', 'bar'],
    '#embed' => TRUE,
  ],
];

If you need to manipulate the View before rendering it, (you mentioned exposed filters), you can do that first and pass along the object:

$view = Views::getView('myfirstview');
$view->setFoo('bar');

return [
  '#type' => 'view',
  '#name' => 'myfirstview',
  '#view' => $view,
  '#display_id' => 'page_1',
  '#embed' => TRUE,
];


Is it possible to give a language prefix to all the nodes without third-party modules? I have a site with about 500 pages (nodes, taxonomy pages, and some views) which are all in Hebrew.
I want to make all paths from, for example, /node/example1 or /taxonomy/categories/term1 to /he/node/example1 or /he/taxonomy/categories/term1.
I want it for all the pages, as a first stage in turning this site to be a sub-site (with a sub-domain).
Is this possible without third-party modules?

These are the rewrite rules to add in the .htaccess file located in the Drupal root directory.
RewriteEngine on
RewriteCond %{REQUEST_URI} !/he
RewriteRule ^(.*) http://www.domain.com/he%{REQUEST_URI} [L,R=301]


Use static function as operations with batch API I can't get batch to work with a static method as callback function for the operation

$batch['operations'][] = ['MyController::MyMethod', [$arg]];

If I use a procedural function and call a static method from that, it works.

It could be a solution, but as I have several methods to call during the same batch, I don't want to create a wrapper function.

Does someone know how to make batch API work with static methods?

The function that Drupal uses to process the batch operation is _batch_process(), which uses the following code to call the operation callback.

  // Build the 'context' array and execute the function call.
  $batch_context = array(
    'sandbox'  => &$current_set['sandbox'],
    'results'  => &$current_set['results'],
    'finished' => &$finished,
    'message'  => &$task_message,
  );
  call_user_func_array($callback, array_merge($args, array(&$batch_context)));

Since call_user_func_array() allows to use a string like MyClass::myMethod as callback, the code you wrote should work, if the Drupal autoloading system is able to find the file containing the class definition, which means:

You need to respect the file structure as per the PSR4 structure expected by Drupal
You need to fully qualify the class name by adding its namespace

In the case the file containing the class it is not in the directory where Drupal looks for class files, such as in the case the class is contained in a my_operation_callbacks.inc put in the same directory containing the module file, then you need to use code similar to the example code shown in Batch operations.

$batch = array(
  'title' => t('Exporting'),
  'operations' => array(
    array('my_function_1', array($account->id(), 'story')),
    array('my_function_2', array()),
  ),
  'finished' => 'my_finished_callback',
  'file' => 'path_to_file_containing_myfunctions',
);

$batch['file'] in that code tells Drupal which file it needs to load before executing the operation callbacks.
Even in this case, the class must be referenced using its namespace, which could simply be \ in the case the class is put in the global namespace.


How to tell variable_get to get the value from the database and not the $conf array? variable_get seems to always used $conf array which is fetched a single time.  In a long running process where the value of a variable may have changed during operations this causes problems.  Is there a simple mechanism in Drupal to tell variable_get to refetch the array from the database rather than using the in-memory variable?

I don't think Drupal core has anything like that, no. For speed and efficiency, the variables array is in memory pretty much as soon as settings.php has been processed.

You've always got db_query():

$var = db_query('SELECT value FROM {variable} WHERE name = :name', array(':name' => 'var_name'))->fetchField();
$var = unserialize($var);

It would be trivial to build up an efficient variable_get_from_db function based on that.


Search API + Apache SOLR - No highlighted excerpts returned for stemmed terms I have a Drupal 7 site using the Search API and Search API Apache SOLR modules to provide search functionality to site visitors.

I'm running Apache SOLR 4.10.2 within my development Vagrant VM environment, and search results are returned for both stemmed and unstemmed terms which is great:

Example search term: "car"

Apache SOLR returns nodes with fields containing the text "car" and "cars"

The problem is, when Apache Solr returns nodes containing the stemmed term "cars", no highlighted excerpts are returned. However results containing the exact term "car"  are returned with a hightlighted excerpt as expected.

After extensive searching I found this blog post which contains instructions on how to enable stemming for highlighted excerpts, but no luck.

Here is the excerpt of my schema.xml config file as per the instructions in the blog post:

<!--  Setup simple analysis for spell checking -->

 <fieldType name="textSpell" class="solr.TextField" positionIncrementGap="100">
   <analyzer>
     <tokenizer class="solr.StandardTokenizerFactory" />
     <filter class="solr.StopFilterFactory" ignoreCase="true" words="stopwords.txt"/>
     <filter class="solr.LengthFilterFactory" min="4" max="20" />
     <filter class="solr.LowerCaseFilterFactory" />
     <filter class="solr.RemoveDuplicatesTokenFilterFactory" />
     <filter class="solr.PorterStemFilterFactory"/>
   </analyzer>
 </fieldType>

I have restarted my VM and cleared and reindexed all the nodes, but still no dice.

Has anyone else had this issue before?

Thanks in advance!

I'm guessing that you, like me, had the "Highlight" filter enabled, which you shouldn't actually do for Solr. I found this nugget of info here:

https://www.drupal.org/node/2358065#comment-9319765

Though Solr returns the excerpt, that processor removes it if there's not an exact match.


cache_form has been truncated. Permanent error MYSQL Incorrect key file when a form is accessed On a site I inherited, I can see cache_form is empty. It has been truncated some time ago. I have got an error crashing my site when accessing many type of forms: views exposed forms, forms to edit Views and node edit forms. The error is a MYSQL Incorrect key file error and is triggered by clear_cache_all().
There is an attempt to DELETE FROM cache_form, where a given form ID is found. However the table is empty so it does not work.
I do not know why Drupal has to delete a cache entry from the table even for a new node.
Is there a way to bypass the step where Drupal try to delete the cache entry?

This sounds like someone tried to do some optimization to {cache_form} through a MySQL interface and did something that makes it incompatible with Drupal, or the table is damaged due to a dull disk (see this happen before).

First make sure you have free disk space, and then do a CHECK TABLE cache_form; and see if there are any errors.  If you see some, you can try the standard repair techniques, but it is often best to just re-create the table.

These steps are dangerous and can destroy your site.  Make sure you have backups.

To re-create {cache_form} I would

Start a MySQL interface , and delete {cache_form}, eg DROP TABLE cache_form;

Recreate the table from a known good Drupal 7 install.  I think this is the default:

CREATE TABLE `cache_form` (
  `cid` varchar(255) NOT NULL DEFAULT '' COMMENT 'Primary Key: Unique cache ID.',
  `data` longblob COMMENT 'A collection of data to cache.',
  `expire` int(11) NOT NULL DEFAULT '0' COMMENT 'A Unix timestamp indicating when the cache entry should expire, or 0 for never.',
  `created` int(11) NOT NULL DEFAULT '0' COMMENT 'A Unix timestamp indicating when the cache entry was created.',
  `serialized` smallint(6) NOT NULL DEFAULT '0' COMMENT 'A flag to indicate whether content is serialized (1) or not (0).',
  PRIMARY KEY (`cid`),
  KEY `expire` (`expire`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='Cache table for the form system to store recently built...';


413: File entity too large ugly error When uploading an image that exceeds the server PHP upload image, I get the following error:

My question is: Why is this error displayed so ugly and is there a way to display it more nicely, for example, in the form itself?

To be clear: I know why this error is thrown, it's just a matter of userfriendliness.

If you are experiencing it on Chrome only it's a problem with your setup, not Drupal itself. Here you have a bug report about it.

But more probable is that it happens on all browsers, and it's a problem with nginx config - you need to set up client_max_body_size about 35% larger than max file size you want to allow people to upload using Drupal (to have safety margin for Base64 and alike). That way your Drupal will catch "to large" exceptions, and not your nginx.

Note - HTTP does not force body encoding, so 35% margin may well stay unused. But nothing stops applications from doing it, and 35% is what I experienced to be safest bet to avoid future surprises. Hardly any encoding or wrapping wastes as much as Base64 with it's 4/3 overhead. Better safe than sorry and if your server is willing to accept 20MB files, then 27MB will not kill it.


Drupal 7: Cron claims webform module function to be undefined I cant really figure this out.

I have a module which interacts with the webform module which just works perfectly fine.

But now I wanted to create a cron which updates certain submissions, but the cron function claims that suddenly the webform function webform_get_submission is undefined although all other mymodule functions use webform functions without any issues. How come?

// a whole lot functions which use webform functions
// [...]

function mymmodule_cron() {
    $conf = mymmodule_defaults();

    // check cron run
    if(true /* for testing */){

        // set writable User
        global $user;
        $original_user = $user;
        $old_state = drupal_save_session(FALSE);
        $user = user_load(1);

        // fancy sql statement
        $sql = array();
        // [...]
        $sql = join(" ",$sql);
        $result = db_query($sql);

        $queue = DrupalQueue::get('mymmodule_cron_archiveanon');

        foreach ($result as $row) {
            $row->anon = true;
            $queue->createItem($row);
        }

        // restore default user
        $user = $original_user;
        drupal_save_session($old_state);
    }

}

function mymmodule_cron_archiveanon_wrapper($item){
    $node = node_load($item->nid);

    if( function_exists('webform_get_submission')) {
        die("Yep.");
        // $submission = webform_get_submission($item->nid, $item->sid);
    }
    else {
        die("Nope.");
        // dies here
    }

    // custom function
    // mymmodule_contract_archive($node, $submission, $item->anon);

}

That function is in a file that isn't included by default; you just need to include it yourself:

module_load_include('inc', 'webform', 'includes/webform.submissions');


How do I only render the main content without wrapping it with the theme or side blocks and menus? I want to output a google map div with a side panel in my drupal 8 moodule. So no need for blocks surrounding my main content.

The question is how do I tell Drupal to only render main content using a Twig template of my module without outputting the entire Drupal theme stuff a long with the menus and the blocks?

All online materials I found so far talks about concepts behind Drupal rendering mechanism and render arrays but none really tell something about their implementation.

Take for instance, the concept of page variants in the following link. HTMLRenderer fires an event to determine which type of page will be used to wrap the main content around:
RenderEvents::SELECT_PAGE_DISPLAY_VARIANT. Its also says the SimplePageVariant, which will only output the main content, is suppose to be used by default but in case the Block module is enabled like my case, the BlockPageVariant kicks in to allow the placement of blocks in the regions around the main content. It continues, if you want, you can subscribe to this event in your own module and provide your own variant. However, I couldn't figure out how to do this subscribing.

I feel what I want is simpler than creating my own Page variant. I just want to output simple html with two divs in the Twig template of my own module.

Anyone has an idea what to do?

Edit

So there are two ways to do this as mentioned in the answer below, I will just summarize them and add a little more clarification of naming convention in drupal 8:

Return a basic Symfony response  with out any drupal specific rendering:

$element['#title'] = 'Title';
$html = \Drupal::service('renderer')->renderRoot($element);
$response = new Response();
$response->setContent($html);
return $response;

Doing so, you will not be able to attach css or js libraries with render arrays. However, if you want to do that you can override the page.html.twig by following dupral 8 template naming conventions link with out returning "pure symfony" response and hindering drupal from finishing its theming.

There are two similar questions.

Problems creating a custom blank page with my custom module

How to output from custom module without rest of theme

You can use a symfony response or replace the page template with a blank twig in hook_theme().


How do I show multiple nodes on the same page without writing code? Let's say on my "contact" page, I want to use a google map (module), contact form (webform module), show our address (node using Address field), and list some social icons. Let's say stacked on top of each other in the "content" region.

What is the easiest way to do that?

Note: this similar question involves code, I want to avoid that:

How do I create multiple nodes on the same page?

I came to a similar situation of your question before. I need a page, divided to two parts. On left shows company info such as Google map, company address, phone number etc. On the right side, shows a "Webform-ed" Contact Us form. The single page is actually a Panel node of a combination of two other nodes.

My solution is use Panel modules.

Enable modules:

Create a Panel Node, pick a layout of the Panel node.

Add content to each place.

Select existing node you created. (e.g Company info node  & Contact us node)


After creating a node in activity module I am getting an error "undefined index" After installing the Activity module, there is a default view activity/all.

After creating an activity template I am able to see the view result as I required.
But why am I getting this error?

Notice: Undefined index: table in _node_query_node_access_alter() (line 3364 of C:\modules\node\node.module).
Notice: Undefined index: table in _node_query_node_access_alter() (line 3364 of C:\modules\node\node.module).
Notice: Undefined index: table in _node_query_node_access_alter() (line 3364 of C:\modules\node\node.module).
Notice: Undefined index: table in _node_query_node_access_alter() (line 3364 of C:\modules\node\node.module).
Notice: Undefined index: table in _node_query_node_access_alter() (line 3364 of C:\modules\node\node.module).
Notice: Undefined index: table in _node_query_node_access_alter() (line 3364 of C:\modules\node\node.module).

Have a look at the issue queue for Activity.

In particular: Causes undefined index _node_query_node_access_alter

  Not sure why activity would be a culprit of this, but non admin users
  see this error when viewing default activity view or any other
  acitivity views created. This error will also occur on a page when the
  view is a block.

  Notice: Undefined index: table in _node_query_node_access_alter()
  (line 3197 of /var/sites/my/modules/node/node.module).


Programmatically create a discount code Does anyone know how to programmatically create a discount code in Drupal  Commerce?

The best solution is to always review the tests. The tests create promotions and coupons programmatically.

Here's how to create a promotion.

$promotion = Promotion::create([
  'name' => 'Promotion test',
  'order_types' => ['default'],
  'stores' => [$this->store->id()],
  'offer' => [
    'target_plugin_id' => 'order_percentage_off',
    'target_plugin_configuration' => [
      'amount' => '0.10',
    ],
  ],
  'start_date' => '2017-01-01',
  'status' => TRUE,
]);
$promotion->save();

And then coupons.

$coupon = Coupon::create([
  'promotion_id' => $promotion->id(),
  'code' => 'coupon_code',
  'usage_limit' => 1,
  'status' => TRUE,
]);
$coupon->save();


How do I update Drupal 7 to Drupal 7 DEV via Drush command line? I have an old drupal 7 installation and I would like to update this via drush. Usually I download the drupal 7 dev version through the website using wget and untar it into the public_html directory and overwrite everything.

I know i can update drupal modules via "drush dl " but not sure how to do it for core easily using drush.

drush dl is for downloading modules the first time, not updating.

To update core to dev version:

drush up drupal-7.x-dev


Term translations not working as View's path contextual filter Let's say you have a taxonomy called Animals and you have terms like Dog, Cat, Horse, etc. Every term has its translation, so for example for dogs you have Hund and Chien. Now you want to make a View which generates a page that lists content tagged with the Animals term reference, contextually filtering the tag based on the URL part.

And this is the part I'm having difficulties with.
The contextual filter I made works perfectly with source language values and converts properly to term ID. So I'm getting correct listing (both in preview pane and generated page) for /animals/dog but incorrect for /tiere/hund.

The contextual filter is set to Content: Animal Genre (Translated) and validation to Localised term or synonym converted to term ID (actually I tried perhaps every possible combination of i18n and non-i18n options here, no joy).

I trie out another solution - with Content: Has taxonomy term ID + relationship (as described here).

Is it something I'm not setting up correctly or is there a bug around i18n, Views, i18nviews...? I'd be grateful for any guidance

Implementing hook_language_switch_links_alter() is definitely the way to go.  Here is the code along with two (2) helper functions, assuming there are display variants for each language.

/**
 * Implements hook_language_switch_links_alter().
 *
 * This is a workaround for Path Translation not supporting Views' contextual filters.
 * Alter the language switcher to switch between path/to/[term] and different
 * paths for different languages.
 */
function mymodule_language_switch_links_alter(array &$links, $type, $path) {

  // Load the current view if there is one.
  $view = views_get_page_view();

  // Act only if we're looking at the view in question.
  if (($type == "language_content") && isset($view) && ($view->name == 'myview')) {

    // Skip situations where there's no argument.  This is handled by Path Translatoon.
    if (isset($view->args[0]) && ($view->args[0] != mymodule_get_myview_view_all_term($view))) {

      // Iterate across all language links.
      $language_active = $GLOBALS['language']->language;
      $displays = mymodule_get_myview_view_language_displays();
      foreach ($links as $language_current => &$link) {

        // Skip the active language.
        if ($language_current == $language_active) {
          continue;
        }

        // Set the path for the current language.
        $path = $view->display[$displays[$language_current]]->display_options['path'];
        $link['href'] = strtok($path, '/') . '/' . $view->args[0];
      }
      // Break the foreach reference.
      unset($link);
    }
  }
}

/**
 * Returns the list of displays for the view in question, keyed by language.
 *
 * @return array
 *   The list of displays.
 */
function mymodule_get_myview_view_language_displays() {
  return array(
    'en' => 'page_myview_en',
    'fr' => 'page_myview_fr',
  );
}

/**
 * Get the language-specific term representing all items.
 *
 * @param view $view
 *   The previously loaded view in question.  Optional.
 * @return string
 *   The term.  If there's no translation in the current language, "all" is used.
 */
function mymodule_get_myview_view_all_term($view = NULL) {

  // Load the view if it wasn't provided.
  $view = (is_null($view) ? views_get_view('myview') : $view);

  // Get the current language and the display names for each defined language.
  $language = $GLOBALS['language']->language;
  $displays = mymodule_get_myview_view_language_displays();

  // Return the language's "all" term, or the default if there isn't one.
  if (isset($view->display[$displays[$language]]->display_options['arguments']['tid']['exception']['value'])) {
    return $view->display[$displays[$language]]->display_options['arguments']['tid']['exception']['value'];
  }
  else {
    return 'all';
  }
}

Note that this doesn't handle the translation of the term itself within the path, only the part of the path leading up to it.  For now, that will always be in the default language. This is the separate issue Views contextual filter validation: Support ET-translated taxonomy term name.


How to use NUSOAP in my custom module? My users have to be guided to Bank Gate to pay the money After filling a Form in my custom module. the process of leading them has to be done through NUSOAP but it seems it is not functioaning inside module! it works find when i have the same code in a php file but in module ... I have no idea what is wrong with that! this is my submit function:

function my_module_my_form_submit($form, &$form_state) {

  $nusoap_path = drupal_get_path('module', 'myblock') . '/nusoap.php';
  include_once($nusoap_path);

    $client = new nusoap_client('https://de.....com/pg/services/WebGate/wsdl', 'wsdl');
    $client->soap_defencoding = 'UTF-8';
    $result = $client->call('PaymentRequest', array(
                                                    array(
                                                            'MerchantID'    => 'XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX',
                                                            'Amount'        => 1000,
                                                            'Description'   => 'some texts',
                                                            'CallbackURL'   => 'http://......./verify.php'
                                                        )
                                                    )
    );
    //Redirect to URL
    if($result['Status'] == 100)
    {
        $form_state['redirect'] =('https://www.......com/pg/StartPay/'.$result['Authority']);
    } else {
        echo'ERR: '.$result['Status'];
    }

}

thanks in advanced for you help

I think I've had a similar issue in the past with a different payment gateway.

Inspect each variable (print_r or var_dump) one after another comparing the values between your stand alone php file and the drupal module.

When you find the point at which there is a difference you know what line it's going wrong.

Maybe shout at it a bit at this point, give it a prod, read some more API documentation and then you should almost be there ;)


Cache field / entity / node I have a custom field/widget that has a format view function that is highly resource intensive.  I currently am caching the result using cache_set()/cache_get() inside the hook_field_formatter_view function for my field.

Is there a better way I could be doing this?  I tried to use drupal_render()'s #cache property and it cached the output but still ran my hook_field_formatter_view function.

Basically, I know how to do full page cache (for anonymous users) but how do you cache a field/node/entity (for everyone)?

I currently am caching the result using cache_set()/cache_get() inside the hook_field_formatter_view function for my field

Honestly this is not a bad way to go about doing it. When you have custom logic which is resource intensive, taking responsibility for your own caching decisions is usually the right idea. Honestly, I really wish more developers would familiarize themselves with cache_get/set().

Entitycache appears to be an effort to do this generally, and over time I am sure that some best practices will emerge as more people work in this space. However as of today, for anyone looking at a similar problem-set: "Figure out how to cache it yourself" is a good answer.


requesting suggestions on using core poll module I'm working in Drupal 6.22.I have a peculiar requirement with my poll module as below

Display the most recent poll block such that anonymous user could
vote in it.
Once the user has voted display the vote results block with link to all
previous polls page.
In all polls page again display the poll-vote block of the most recent poll
with links to previous polls.

I'm not expecting a contributed module that fits all my requirement in a tailor made fashion but wish to know if there's any module that would aid me in satisfying some portion or giving better ideas in implementing it. I did my search and found Poll Enhancements Module and Poll Improved Module which sound promising for D7 but are not quite there for D6.

Is there a better option of implementing this than arm twisting the poll module with coding?
If anyone could share their suggestions, ideas or experiences it would be nice...

Thanks in advance!

You can try Decisions module in your site. This module depends on VotingAPI module. This module have some nice features. I havent tested much but its good module to look at. Good Luck.


How to include the AddThis sharing buttons on the home page of a site? I'm using the AddThis module to expose sharing features for nodes to users.

Is there a way to include these buttons on the home page of a Drupal 7 site?

For nodes it's easy enough to add this as a field for each content type and have it show for each content type-based node. But I'm unsure how to add this for the home page.

Find the block that comes with the AddThis module and make it available (expose this block) only on the <front>.


Reset password after creating user account programmatically I'm creating a user account programmatically using the code below (Drupal 8). Everything works well except when the user suppose to change their password via the Drupal generated 'one-time login link'. The password reset doesn't work and it seems the 'pass-reset-token' is not generated properly. What am I doing wrong?

public function submitForm(array &$form, FormStateInterface $form_state)
    {
        $the_user_email = $form_state->getValue('user_email');
        $the_user_name = $form_state->getValue('user_name');
        $language = \Drupal::languageManager()->getCurrentLanguage()->getId();

        $user = \Drupal\user\Entity\User::create();
        $user->setPassword(user_password());
        $user->enforceIsNew();
        $user->setEmail($the_user_email);
        $user->setUsername($the_user_name);
        $user->set("init", $the_user_email);
        $user->set("langcode", $language);
        $user->set("preferred_langcode", $language);
        $user->set("preferred_admin_langcode", $language);
        $user->addRole('price_list_users');
        $user->activate();

        //Create the account
        $user->save();

        _user_mail_notify('register_no_approval_required', $user);

        drupal_set_message($this->t('A welcome message with further instructions has been sent to your email address.'));
        $form_state->setRedirect('/price-list');
    }

I guess you could utilize function user_pass_reset_url of user.module to generate reset link and send it via your custom _user_mail_notify function.

Generates a unique URL for a user to log in and reset their password.
Parameters
\Drupal\user\UserInterface $account: An object containing the user account.
array $options: (optional) A keyed array of settings. Supported options are:
langcode: A language code to be used when generating locale-sensitive URLs. If langcode is NULL the users preferred language is used.
Return value
string A unique URL that provides a one-time log in for the user, from which they can change their password.


How to link to section in same static page? How to create a menu link to the section that will display when I click on the link and hide when i again click on the link..

link is

    contact me

the above link should open

//some code

You need to use Jquery and a tiny bit of css.

Javascript

$('.page-scroll').click(function() {
    $('.cat-pages').toggle('slow');
});

css

.cat-pages { display: none; }

JS FIDDLE DEMO EXAMPLE

edit:

To use jquery in drupal you use

(function ($) {
    // code goes here
})(jQuery);

go to drupal/sites/all/themes/YourTheme/

look for your  theme.info file and add this line in there

scripts[] = js/myscript.js

Then go drupal/sites/all/themes/YourTheme/js and create myscript.js file.

put this inside it

(function ($) {
    $('.cat-pages').hide();
    $('.page-scroll').click(function() {
        $('.cat-pages').toggle('slow');
    });
})(jQuery);

If the above doesn't work, try

(function ($) {
    $(document).ready(function () {
    $('.cat-pages').hide();
            $('.page-scroll').click(function() {
                $('.cat-pages').toggle('slow');
            });
    });
        })(jQuery);

PS:

Don't worry about .cat-pages { display: none; }css anymore, since I added the hide in the jquery $('.cat-pages').hide();


How to grep Rules to search for a deprecated function? I'm removing an obsolete custom module, but I want to make sure it isn't referenced in any rules.

Is there a way for me to search / grep for a function name within all the rules on my site?

Consider a rule, actually a rules component, as in this (random) sample (in Rules export format):

{ "rules_grant_access_to_a_node" : {
    "LABEL" : "Grant access to a node",
    "PLUGIN" : "rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "USES VARIABLES" : { "node_containing_classified_ad" : { "label" : "Node containing classified ad", "type" : "node" } },
    "IF" : [
      { "node_is_of_type" : {
          "node" : [ "node-containing-classified-ad" ],
          "type" : { "value" : { "article" : "article" } }
        }
      }
    ],
    "DO" : [
      { "entity_fetch" : {
          "USING" : {
            "type" : "node",
            "id" : [ "node-containing-classified-ad:field-free-format-nr" ]
          },
          "PROVIDE" : { "entity_fetched" : { "fetched_classified_complete" : "Fetched classified complete" } }
        }
      },
      { "drupal_message" : { "message" : "Trying to grant access to node with Id = [fetched-classified-complete:field_free_format_nr]" } },
      { "content_access_action_user_grant" : [] },
      { "redirect" : { "url" : [ "fetched-classified-complete:url" ] } }
    ]
  }
}

The above rule (Rules Component) has a Rules Action content_access_action_user_grant (= machine name) which is available if (a) you have the Content Access module enabled and (b) the ACL module is enabled also. So ACL is a weak module dependency of the Content Access module.

However, that content_access_action_user_grant Rules Action is only available if, and for as long as, ACL is enabled (if you disable the ACL module, then any rule that refers to that Rules Action content_access_action_user_grant will show a "... fails the integrity check").

With the above example (and Rules Action) in mind, execute an SQL query on the Drupal database which looks like so:

SELECT id,plugin,name,label
FROM `rules_config`
WHERE `data` LIKE '%content_access_action_user_grant%'

The results I get by using this query looks like so:

id  plugin   name                             label

216 rule     rules_grant_access_to_a_node     Grant access to a node

Obviously, this result with id=216 matches with my (random) sample rule.

To execute the above query, you can use whatever SQL query tool, such as PhpMyAdmin.

Replace the machine name of the Rules Action in my example by whatever fits with your "function name" (as in your question), and a similar SQL query should list all "rules in your site" (as in your question) that reference your custom module.

Note: another approach (if you can afford to do so), is to simply disable your custom module, and then use the Rules UI to find out which Rules / Rules Components show a similar message containing such "... fails the integrity check".


Make a module out of the mobilize I tried using mobilize and made my drupal site mobile ready very fast i.e. added the java script code directly in the theme page.tpl.php file. I wanted to make this a module and made a new module and added code like below and enabled the module, But mobile version of website doesn't work. Any thing wrong i ma doing? mobilize is the module name

<?php
function mobilize_init() {
 $path = drupal_get_path('module', 'mobilize');
 drupal_add_js($path . '/site.js', 'file');
drupal_add_js('http://cdn.mobilizejs.com/releases/0.1/js/mobilize.core.min.js','external');
}
?>

Your hook seems to be named as if it was a mobilize one, where it should be named by your module's. something like "my_module_init".


Correct way to disable /node in Drupal 7? I find going to /node as being very useful to pinpoint exactly what content non-authorized users can see. But for two reasons I don't want anyone to access "/node".

I don't want that to end up in Google Search Results.
I don't want prying eyes to go through each and every content in case something should accidentally not have been made public.

So my question is: what is the most correct way to block /node? Or should I keep it open and rather let robots.txt avoid that path?

UPDATE

To make matters worse, it seems I have set everywhere in my permissions that certain content types must not be viewable by certain roles. However, those pages are still showing up under /node ?

You can probably use this code with your custom module:

function hook_menu_alter(&$items) {
 $items['node']['access callback'] = FALSE;
}

Note: If you want specific people to access this page, you can set "access arguments" declared with hook_permission


Exposing inline images to Views I'm using Media module to insert inline images in the nodes body through the wysiwyg.

I'm trying to make an Views slideshow to list all these images and I've been banging my head at Views interface for the past hours, trying to find the related field which should be included but I can't find anything.

Is this simply not possible? If that's the case is there any Views plugin/add-on that can do the job?

Regards

If an image is inserted into a textarea like your wysiwyg editor, the node does not retain an entity relationship with that image, you would need to parse the full content of that field for images, figure out if they are internal, get their ID...

Your node should ideally have a field of type image, that way your saved node has an association with one or more images you have uploaded. You can then insert the images inline wherever you wish.


How to render two views in the same twig template I want to render two views in the same twig template, but only one of them is rendered, and the second is always override with the same content as the first one.
I have a content type 'contacts' and when its nodes are displayed (full view) I want to render two views in the same page after the node fields. I use a twig template node--contacts.html.twig :

.....  node fields twig template ....
{{ viewCalls }}
....
{{ viewAppointments }}
....

And my function my_theme_preprocess_node(&$variables) in my .theme file:

....
$view = \Drupal\views\Views::getView('view_calls');
$view->setDisplay('default');
$view->setArguments(array($variables['node']->id()));
$view->setOffset(0);
$view->execute();
$variables['viewCalls'] = $view->render();

$view2 = \Drupal\views\Views::getView('view_appointments');
$view2->setDisplay('default');
$view2->setArguments(array($variables['node']->id()));
$view2->setOffset(0);
$view2->execute();
$variables['viewAppointments'] = $view2->render();
.....

As I said, the second view always shows the same content as the first. If I reverse the order of rendering, then the content is reverse too, and the one which is first rendered is the only one I see, and always two times. It is as {{ viewCalls }} and {{ viewAppointments }} always get the same content.

The reason you get the same content is due to the #cache property of the render array you get when you call the render() method.

Most specifically, by calling setOffset() earlier in your code, you are implicitly setting a cache key on the render array, (see here):

$this->element['#cache']['keys'][] = 'offset:' . $offset;

This cache key setting, in combination with the #theme property of the render array (views_view), which is the same for both views, will result in getting a cached version of the first one when including the second one, since the [#theme] + [#cache][keys] combination is identical for both views.

To work around that you could:

Remove caching completely for these views, or
Avoid using setOffset(), or
Add more specific keys to the cache so that you have a different cache for each view. E.g.

$variables['viewCalls']['#cache']['keys'] =
  array_merge(
    $variables['viewCalls']['#cache']['keys'],
    array('viewCalls')
  );
...
$variables['viewAppointments']['#cache']['keys'] =
  array_merge(
    $variables['viewAppointments']['#cache']['keys'],
    array('viewAppointments')
  );

I tested your case using the 3. option and it worked as expected, I think before resolving to using another module, you could try sticking to your original code and appropriately modifying the #cache property of both render arrays.

Good luck!


Views with logged user contextual filter stop working after adding relationship I have two content types in a project I am working right now. Content type A has a field that hold the user ID of the user that "reserved" a node from that content type. Once the user has reserved a node from Content type A, he/she can then create a node from Content type B referencing the "reserved" node from Content type A. All that is done and working like a charm.

My issue is that I created a View where I want the user to see all the nodes he/she has reserved (Content type A), but I want to exclude the nodes from Content Type A that he/she has already used to create nodes for Content type B. The solution was fairly simple. I added the reserved by field to the contextual filter and I used the ID of the logged user and I added a relationship to "A bridge to the Content entity that is referencing Content via field_USED_FOR_REFERENCE"

The odd thing is that for user 1, the View work like a charm, but for other users the view display a blank page. I have rebuilt the permission, clear the cache, test the preview SQL query with the other users IDs (it does work), but the view page still show me a blank page for any user that is not user 1.

  Note: In my tests I have remove all the views permissions without any luck. If I remove the relationship in the views then everyone can
  see the views results and not only user 1.

What am I missing?

Sounds like a permissions issue.  User 1 has access to everything, others do not.

What I would do is:
1) Either backup your site, or note (screenshot) what permissions you have set currently
2) Start adding several permissions at a time, and going back to check if the view has changed, until you've exhausted all permissions


Vocabularies with terms on a view I need to create a page with listed vocabularies and terms related to it in 3 columns.

Vocabulary 1       Vocabulary 2     Vocabulary 3
Term 1             Term 4            Term 7
Term 2             Term 5            Term 8
Term 3             Term 6            Term 9

If it's possible, I'd like to accomplish that by configuring a view. I'm not very good with custom code.

Do you have any idea?

Unfortunatelly for Drupal 8 @No Sssweat's solution of creating 3 seperate views (blocks) is the ONLY possible solution using views at the moment.  Then you can put them in region of your liking and with css can display them one next to the other (inline).

When Taxonomy vocabulary data not available as views fields is not an issue anymore you will be able to do it with just 1 view and grouping terms by vocabulary name.

Otherwise another solution would be to make your own custom module that gathers and displays the vocabulary terms.


How to use contextual filters to a View for use as a sort criteria? I want a View with a default sort criteria that can be overridden by a contextual filter.  For example, the URL might end like this: ?sort=popular.  popular would be associated with one field and recent, the default, would be associated with another field.
This is on Drupal 7 and Views 3.

I am not sure how this translates to Drupal 7 and Views 3, but I have done the following with Drupal 6 and Views 2 using hook_views_query_alter

function mymodule_views_query_alter (&$view, &$query)
{
    if ($_GET["sort"]) {
        $sort = check_plain(trim(strtolower($_GET["sort"])));

        switch ($sort) {
            case "title":
                $query->orderby = array("node.title ASC");
                break;
            case "order":
                $query->orderby = array("node.nid DESC");
                break;
            case "somefield":
                $query->orderby = array("node_data_field_somefield_field_somefield_value ASC");
                break;
        }
    }
}

The trick is to make the views w/ the sorts, and look at the SQL, and use this to update your code.