Can 1 FullCalendar show dates from more than one content type? I want to show "dates" and "Board Meetings" on my FullCalendar.  How?

Background info:
In D7 I created a Calendar using the wizard, which shows titles and dates/times of events that I create using a content type "Date" that the wizard created.  Works great.  But then I added another content type "Board Meeting" with a date field, the Board meetings only show up on the preview, not on the calendar month view itself.  How to get them to show on the calendar?

Dave N

Well I found the answer before I even finished posting this.  Thanks to those "Similar Questions" over there on the right...

I got my answer from How to use multiple content types in a "Calendar" View sorting by the field type of "Date"?


Why do both Text- and Data comparison seem to not work in my Rules conditions? I’m using Drupal 7.56, the Rules module 7.x-2.11, and CiviCRM 4.6.31.

I've been using the Text comparison and Data comparison conditions.

Using the Text comparison condition, the condition is always met, so the action is always executed, despite the value of the data.

Why does this condition always evaluate to TRUE, for all the possible values, even when the text of the data is different to the matching text?

This is the log entry.

  The condition text_matches evaluated to TRUE.

This is the export of the rule.

{ "rules_create_a_drupal_account_for_a_civicrm_contact" : {
    "LABEL" : "Create a Drupal account for a CiviCRM contact",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "civicrm", "rules", "devel" ],
    "ON" : { "civicrm_membership_create" : [] },
    "IF" : [
      { "NOT civicrm_entity_user_exists" : { "civicrm_contact" : [ "civicrm-membership:contact-id-contact" ] } },
      { "AND" : [
          { "NOT data_is_empty" : { "data" : [ "civicrm-membership:contact-id-contact:contact-sub-type" ] } },
          { "AND" : [
              { "text_matches" : {
                  "text" : [ "civicrm-membership:contact-id-contact:contact-sub-type" ],
                  "match" : "Parent"
                }
              }
            ]
          }
        ]
      }
    ],
    "DO" : [
      { "devel_debug" : { "value" : [ "civicrm-membership:contact-id-contact:contact-sub-type" ] } },
      { "civicrm_entity_action_create_user" : {
          "USING" : {
            "civicrm_contact" : [ "civicrm-membership:contact-id-contact" ],
            "is_active" : "1",
            "notify" : "0",
            "signin" : "0",
            "username_format" : "email"
          },
          "PROVIDE" : { "civicrm_user" : { "civicrm_user" : "Created Drupal User" } }
        }
      },
      { "user_add_role" : { "account" : [ "civicrm-user" ], "roles" : { "value" : { "5" : "5" } } } }
    ]
  }
}

Using the Data comparison condition, the condition is never met and the action is never executed, despite the data to compare.

Why does this condition always evaluate to FALSE, for all the data, even when it is the same to the value to compare?

This is the log entry.

  The condition data_is evaluated to FALSE.

This is the export of the rule.

{ "rules_create_a_drupal_user_account2" : {
    "LABEL" : "Create a Drupal User Account2",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "civicrm", "rules" ],
    "ON" : { "civicrm_membership_create" : [] },
    "IF" : [
      { "NOT civicrm_entity_user_exists" : { "civicrm_contact" : [ "civicrm-membership:contact-id-contact" ] } },
      { "AND" : [] },
      { "data_is" : {
          "data" : [ "civicrm-membership:contact-id-contact:contact-sub-type" ],
          "value" : "Parent"
        }
      }
    ],
    "DO" : [
      { "civicrm_entity_action_create_user" : {
          "USING" : {
            "civicrm_contact" : [ "civicrm-membership:contact-id-contact" ],
            "is_active" : "1",
            "notify" : "0",
            "signin" : "0",
            "username_format" : "email"
          },
          "PROVIDE" : { "civicrm_user" : { "civicrm_user" : "Created Drupal User" } }
        }
      }
    ]
  }
}

Any clue about what might be happening?

I am not sure it is your only problem, but for sure you are not correctly using the AND constructs in your rule. It is one of the typical mistakes many Rules users make, but if you want to model a condition like A AND B, then first you must have a line with AND, and that should be followed with A and then also folowed by B. Something like so:

AND
  A
  B

For way more details, refer to my answer to Combining AND and OR in Rules.

So start with fixing this, and then verify if your issue is solved or not.

As a sample, just import this minor variation of your last rule (note I slightly renamed the rule to not overwrite your existing one, and moved the AND construct to where it belongs):

{ "rules_create_a_drupal_user_by_pierre" : {
    "LABEL" : "Create a Drupal User By Pierre",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "civicrm", "rules" ],
    "ON" : { "civicrm_membership_create" : [] },
    "IF" : [
      { "AND" : [] },
      { "NOT civicrm_entity_user_exists" : { "civicrm_contact" : [ "civicrm-membership:contact-id-contact" ] } },
      { "data_is" : {
          "data" : [ "civicrm-membership:contact-id-contact:contact-sub-type" ],
          "value" : "Parent"
        }
      }
    ],
    "DO" : [
      { "civicrm_entity_action_create_user" : {
          "USING" : {
            "civicrm_contact" : [ "civicrm-membership:contact-id-contact" ],
            "is_active" : "1",
            "notify" : "0",
            "signin" : "0",
            "username_format" : "email"
          },
          "PROVIDE" : { "civicrm_user" : { "civicrm_user" : "Created Drupal User" } }
        }
      }
    ]
  }
}

If the above still doesn't solve your issue, then I suggest you do some extra Rules debugging as explained in my answer to "How can I display the value of a variable inside a condition?".

Update:

The above (related tot the AND-construct) is for sure "a" reason why it doesn't work. However, yet another issue you may have to correct, is related to what you wrote in a comment below this answer, i.e. this part of it:

  ... The value of the variable is the expected, but I'm not sure if I'm accessing in the right way to the variable, as it's an array: ... (Array, 1 element) 0 (String, 6 characters) Parent

If what you're trying to compare is an array (a "list of values"), then you should NOT (repeat: NOT) use something like a "Data Comparison", because that's like trying to compare an array with a single value (which doesn't make sense). To get your rule to work like you want it to work, you should use the Rules Condition  List contains item. For an example Rule (in Rules export format) in which you can see this at work, refer to the answer to "How to check for product taxonomy term in Rules actions (Ubercart)". In that case it's about a list of taxonomy terms, but the idea is the same.


Javascript Error on User sign up page I have suddenly started getting these errors on my sign up page:

Failed to load resource: the server responded with a status of 406 (Not Acceptable) .co.uk/misc/jquery.cookie.js?v=1.0
Uncaught TypeError: Object function (j,s){return new b.fn.init(j,s)} has no method 'cookie' form.js:69

Any ideas what might be causing this...

This is due to using Autocomplete functions. Disable autocomplete module and Sure error will be gone.


Remove items in taxonomy entity relation on node edit form If a field on the node edit form is a entity relation to a taxonomy term vocabulary, I want the taxonomy terms be restricted on certain conditions. I don't know how to do it safely. I have tried it in hook_form alter(). Deep in the "array stack" of the form variable is the definition of the entity reference form field.

Is the only way to "hack" the "#process" array, or is there any object-oriented way to filter the items in the drop down element?
Is there any form "plugin" to filter the items in Drupal 8?

You're deep in the field definitions there, that's the wrong place, you can't change anything there and you don't need to.

In case of a select, the available options are already part of the form; they should be in $form[$field_name]['widget'] somewhere.
You could also try to use hook_options_list_alter().


How to show mySQL BLOB data Is there a simple way to look at BLOB data that Drupal 7 stores in some tables?

There is a trick to configure phpmyadmin but apparently it's not working with version 3.3.9.2 that comes with MAMP.

If you need to peek, say into user->data, which is seralised data array, just use drush sqlc to bring yourself to an sql command line, then type:

 select uid, name data from users where uid = <whateveruidyouwant>;

This works for any data, and if you are brave you can even edit the serialized data via command-line but is not recommended unless you know what you are doing.


Create a template for a specific view I have a view containing an unformatted list of fields. I want to create a specific template for the view. I have turned on Twig debug, but it suggests 'views_view_unformatted' for the file name, which would apply to all unformatted lists, but I want it specific to this view. What should be file name be?

I think the issue here is that Twig debug does not suggest all possible names.

Names containing the view display id or type are possible, but don't seem to be suggested by Twig debug.

The following are the possible template names sorted by precedence:

[base template name]--[view machine name]--[view display id].html.twig
[base template name]--[view machine name]--[view display type].html.twig
[base template name]--[view display type].html.twig
[base template name]--[view machine name].html.twig
[base template name].html.twig


How to change view mode of view row using hook_views_pre_render? Is it possible to change the view mode of a view result in hook_views_pre_render?

For example I have 3 different view modes (teaser, teaser-full, teaser-short). The goal is to have the view repeat these 3 teaser templates in the view page/listing, but I'm firstly struggling to change the view mode at all.

I tried the below, but it doesn't seem to do anything.

function themename_views_pre_render(ViewExecutable $view) {
  foreach ($view->result as $index => $row) {
    $view->row_index = $index;
    $view->rowPlugin->options['view_mode'] = 'teaser';
  }
}

Note: If I drop a breakpoint into the code, it is being hit. But still gets rendered out as default view mode.

I was able to change the view mode in the hook_views_pre_execute() hook. I believe _views_pre_render() is too late.

function custom_module_views_pre_execute(ViewExecutable $view) {
  // Some logic to determine view mode...

  $view->rowPlugin->options['view_mode'] = 'list';
}


How to query paragraphs content? Does any one have an example how I can query the paragraph entity type of a given node ?

Let's say I have a node that contains a field 'field_paragraph' that is linked to the paragraph module . How do I query all that data ?

Thanks,
Yaron

There are different ways to query (output? render?) paragraph field values.
If the idea is to print the value in a template, you may find some clues in this page: https://www.drupal.org/node/2532824

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

But that will also depend on the theme you are using and how do you use it


How to resize an image programmatically when creating node? I have created a content type with an image field. I have to add the content type programmatically.  From my form submit function I can get the fid like:

$product_image = $form_state['values']['announced_product_image'];

I'm wondering how I can programmatically resize an image when creating a node.

I have tried:

$test = file_load($product_image);
$img = image_load($test->uri);
image_resize($img, 200, 200);

But the image is not saving as 200x200.

Don't forget to use image_save() after you've resized it!


Hook theme path to template in a folder For my template I need to point to a subfolder in templates folder: templates/sub-folder/my-wall1.html.twig, the file is there, but nothing works.

What are the rules?

translate minus (-) to underscore (_)
...

function my_module_theme() {
  return [
    'wall1' => [
      'template'  => 'sub_folder/my_wall1',
      'variables' => [
        'w1' => NULL
      ],
    ],
  ];
}

Update: According to the answers, I tried the following:

test/test.html.twig < does not work
test.html.twig < works, without subfolder and a name like this

An example or point to documentation would be great too?!
Thanks.

Drupal uses filenames only for theme suggestions 'template' => 'my_wall1'. But you can still place the template in a subfolder below templates and Drupal will still discover it.

Not tried this myself, but according to hook_theme() documentation: You can add a drupal root relative path if you want a very specific directory for the Twig file:

function my_module_theme() {
  return [
    'wall1' => [
      'template'  => 'my_wall1',
      'variables' => [
        'w1' => NULL
      ],
      'path' => 'DRUPAL_ROOT_RELATIVE_PATH'
    ],
  ];
}


Run Simpletest tests on Jenkins I am trying to run a group of tests(Simpletest) for my custom modules through Jenkins.

Firstly I tried drush test-run (...) which has been removed from drush.
Then I tried php scripts/run-tests.sh --xml logs_tests [GROUP_NAME], but for every test class it returns /usr/bin/daemon: unrecognized option '--url'. I haven't defined any URL, maybe is something Simpletest specific.
Finally, I created a fairly simple Phing task <exec command="php scripts/run-tests.sh --xml logs_tests ${group_name}" error="build_error"/> only to get the response Unknown argument: --url, from Phing this time.

It seems like you have tried everything except to supply the URL.

You must supply a --url argument to execute simpletest. This is what I use, where "IAS" is the test group I have selected to execute:

php scripts/run-tests.sh --url http://localhost/drupal7 --concurrency 4 IAS

It follows that you must have a Drupal install to do this.


Node reference shows as empty to anonymous users I'm sure this is a simple configuration issue, but (I think) I've looked everywhere and I can't see what's wrong...

I have a content type "Sponsor" that is basically just a name (title) and a logo (image field). I created a few sponsors for my tests.

I also have another content type ("City") with two node reference fields, both of which allow to pick an unlimited number of sponsors (nodes). (I use two fields because one should display the sponsors logos, while the other should only display the name of the sponsors.)

On "Manage display" (for the City content type), the first node reference field format is "rendered node", while the second is "Title (no link)".

So when I visit a "City" page, I should see two lists of sponsors (one with logo, the other one without).

It works for me (admin), but for anonymous users, the sponsors simply don't show up. They are published, though, and anonymous users can access the sponsors pages (and see the logo as well as the title). But when they are referenced through the "City" nodes, the sponsors somehow become invisible (not rendered).

What am I missing here?

Weird thing is, I have another page where I use Views to output the list of sponsors for a city: in that View, the sponsors are still invisible (nor anonymous users, not admin), but the list elements (containing each sponsor) are indeed rendered --so anonymous users see empty bullet points and it matches the number of sponsors that should be visible there.

Note: I also use Panels to display the city. But the problem is still there when I disable the node template Panel, so it's not that...

Found it!

I'm using Organic Groups on this site, and I didn't realize that you could grant access permission (view/edit) on a field level (contrary to the base Drupal permissions system, which works only with content types). Since it doesn't show up on the "normal" Permissions page, it's easy to miss. (It's in configuration > Organic groups > OG permissions overview).

So it was indeed a simple configuration issue.


How can check if a field is empty in a node template? I am using Drupal 8. I have a paragraphs field (field type: paragraphs of reference revisions) in node template, I tried lots of ways to check if the field is empty (purpose is to show the field only it has a value).

<code>
{# Below codes in node.html.twig #}
{# Below codes NOT work #}
  {% if content.field_notes.0 is empty %}
    This field is empty-1.
  {% endif %}

  {% if content.field_notes[0] is empty %}
    This field is empty-2.
  {% endif %}

  {# Enable module:twig field value #}
  {% if content.field_notes|field_value is empty %}
    This field is empty-3.
  {% endif %}

  {% if node.field_notes.isempty %}
    This field is empty-4.
  {% endif %}

  {% if node.field_notes.value is empty %}
    This field is empty-5.
  {% endif %}
</code>

How can check if a paragraphs field is empty in node template in Drupal 8?

UPDATE:
Codes tested and result below, the way NOT work for paragraphs but work for some other field types.

{% set count_field_element_1 = node.field_paragraphs|length %}
  {{ count_field_element_1 }}
  {# when field has or no value: count_field_element_1 = 2 #}
  {# paragraphs type contains two field type: image and text plain long #}

{% set count_field_element_2 = node.field_image|length %}
  {{ count_field_element_2 }}
  {# when field has value: count_field_element_2 = 1; #}
  {# when field has no value: count_field_element_2 = 0; #}

{% set count_field_element_3 = node.field_text_plain_long|length %}
  {{ count_field_element_3 }}
  {# when field has value: count_field_element_3 = 1; #}
  {# when field has no value: count_field_element_3 = 0; #}

Maybe my question is not very clear, let me explain more as below:
The purpose of this question is to check if paragraphs field (not other field types) has a value. When a field value is input and saved, node page will show the field and its value; when no field value is input and saved, node page will NOT show the field (including the div element).

{% set count_field_element = node.field_paragraphs|length %}
  {{ count_field_element }}

count_field_element is 1 for below:

count_field_element is 0 for below(removing all form items of paragraphs in node form):

In short, up till now, I still NOT figure out a way to check if a paragraphs field has a value, node page will show paragraphs field empty only when removing all form items of paragraphs in node form.

Check on node.field_notes something like

 {% set count_paragraph_element = node.field_notes | length %}
  {% if count_paragraph_element == 0 %}
      Empty
  {% else %}
      Not empty
  {% endif %}

Update
if you want to check if text plain long field has empty value try this.
I assume that your field machine name is field_text:

{% for item in node.field_notes %}
      {% if item.entity.field_text.value is empty %}
        text value is empty
      {% else %}
        text value not empty
      {% endif %}
{% endfor %}


Sending message body to email with PrivateMsg module PrivateMsg Module sends email notifications that you have received a message to users. How to send the "Message Body" to the user in the email. So no need to login and see the message .

Any clues ?
thanks

If you navigate to admin/config/messaging/privatemsg, you will find the template of mail which  get send by system when somebody private message to message some user.

You can modify the template. If you navigate to tokens below, you will find several tokens, one is - [privatemsg_message:original:body]. You can insert it in above template to send it in mail according to your need.

I think you need Token module for all this & I hope you must have this installed in your instance.


custom module folder In Pro Drupal 7 Development: Third Edition, the authors suggest moving custom modules inside subfolders of /sites/all/modules/custom/, i.e.

/sites/all/modules/custom/mymodule1
/sites/all/modules/custom/mymodule2
/sites/all/modules/custom/mymodule3

Does this have any special meaning for Drupal core? For example, is this folder omitted when checking for new versions of modules? I haven't checked this so far so I'm just curious.

Before I read the book I put my custom modules like this:

/sites/all/modules/mymodule1
/sites/all/modules/mymodule2
/sites/all/modules/mymodule3

It shouldn't break anything, and it has no special meaning to core: as long as it's in a modules directory, it will be searched recursively (which is why larger projects often have submodules in a subdirectory).

However, it does allow site-builders to organize their modules more neatly than just lumping everything together. You'll often see modules/ directories structured in a way similar to this:

/path/to/modules/contrib: Modules downloaded from contrib
/path/to/modules/custom: Custom modules that you write for this site
/path/to/modules/devel: Modules not meant to be enabled on live
/path/to/modules/features: Modules created by Features

This organizational setup is often used when building installation profiles and distributions as well, so if you download a few you'll probably see more examples of this sort of organization put into practice.


Stop markup being pasted into WYSIWYG? Im making a CMS for a client who will be copying and pasting content into the body of nodes. I want to remove certain markup from coming through (eg inline styles) but allow other markup (p and br tags).

With the html filter I can stop certain markup being displayed but its still there in the content when you edit the node. Is there a way of stopping some markup from coming through at all? Thanks

Try out the WYSIWYG Filter module. It allows to restrict all described things.

After installation you will be able to configure its settings in the "Input formats" section.


What drives the main menu? Hi I'm trying to understand the main menu but it appears to be self populating with the product categories category plus a built in search API (All Products). The main menu also appears disabled in the blocks area?
Can someone explain the mechanics behind this menu please?

Well it looked like from Category>Product category>Edit vocabulary there is an option for Taxonomy menu with a selection list showing Main Menu. I added a new Category to this same structure and now both my new category and the main menu have disappeared from the menu?
I have tried "Select to rebuild the menu on submit." and also removed my new category from main menu... but still the original is missing.

You can see region--menu.tpl.php which is rendering main menu..

<div<?php print $attributes; ?>>   <div<?php print $content_attributes; ?>>
    <?php if ($main_menu || $secondary_menu): ?>

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

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

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


PrePopulate a Node URL from Previous Node via Rules Link to Add Content Form Scenario

A Content Node's URL needs to be incorporated into an Application (Node Add) for a future reference so the users can view their Applications made. The user clicks on a Rules Link (i.e.'Contact User') button and the user is taken to a Form (which for my purposes creates a new content Node 'Application',so the entity is Prepopulated with the referring Node URL (or a linked Title) so the user can later view it in a list and for backend managment purposes, the Application Nodes will be CRON purged once in a while as required.

I have installed https://www.drupal.org/project/entityreference_prepopulate module along with Tokens but it doesn't included the previous Node URL as expected although it does add the 'current' mydomain.com URL, so it's working to some degree. And yes, I have looked at online Youtube etc videos, but they don't seem to cover my requirements.

I'm at a loss understanding how the process is working backend in Drupal. I'm not sure if in the Rules Link Component if I need to add the URL first then move to the Form page next (using Rules), or if that is completely an incorrect approach on my part and I need to use an API or whatever.

Any advice is very much appreciated. Thanks.

You need to have an entity reference field in your form and set it to reference nodes.

Normally, you would then build your link with the current node's Nid to fill the entity reference field on the next page.

http://example.com/node/add/article?field_previous_page=123

However, because you are using rules link, I guess you have to create a redirect to the form based on the current node replacement pattern available.

Or below is a solution if that doesn't work out.

  If you really must use rules link and can't get normal methods to work, then Rules Session Variables
  would be an easy solution. It will give you actions to let you add the
  node's id into $_session.

  Then when you the user saves the form, have another rule that
  checks if $_session exists and if so, take the Nid, fetch the node and then
  set the entity reference field with it.

So yeah, do you need to use rules link?


How can I get the content type for which a certain comment belongs? I have a comment type that's associated to various content types.

I have the comment entity but I want to get which content type(s) it belongs to.

How can I do that? Given that I can in the first place.

You can use Comment::getCommentedEntity() to get the entity, and if it's a node, grab the type:

$entity = $comment->getCommentedEntity();
if ($entity instanceof \Drupal\node\Entity\Node) {
  $type = $entity->getType();
}


Is it possible to collect credit card info and address info on separate pages in Commerce 2? I want my checkout flow to look like this:

Users enter their credit card information and press "Next."
Users enter their address information (customer profile), then press "Next."

In the default Commerce workflow, users enter their credit card info and address on the same page.

I want to split credit card info and address info into different pages.

How can I do this safely?

Why do this?

Because if a user makes an error when typing their address and validation fails, it also resets the credit card information.  I want to have the user do the credit card and address info separately so if validation fails, they only have to re-input one or the other.

Creating a checkout flow plugin may solve your problem. Create a Plugin in your custom module like an example shown below:

namespace Drupal\my_checkout_flow\Plugin\Commerce\CheckoutFlow;

use Drupal\commerce_checkout\Plugin\Commerce\CheckoutFlow\CheckoutFlowWithPanesBase;
use Drupal\Core\Form\FormStateInterface;

/**
 * @CommerceCheckoutFlow(
 *  id = "custom_checkout_flow",
 *  label = @Translation("Custom checkout flow"),
 * )
 */
class CustomCheckoutFlow extends CheckoutFlowWithPanesBase {

  /**
   * {@inheritdoc}
   */
  public function getSteps() {
    return [
      'login' => [
        'label' => $this->t('Login'),
        'previous_label' => $this->t('Return to login'),
        'has_order_summary' => FALSE,
      ],
      'card_info' => [
        'label' => $this->t('Card information'),
        'previous_label' => $this->t('Return to Card information'),
        'next_label' => $this->t('Continue to Card information'),
        'has_order_summary' => FALSE,
      ],
      'address_information' => [
        'label' => $this->t('Address information'),
        'previous_label' => $this->t('Return to Address information'),
        'next_label' => $this->t('Continue to Address information'),
        'has_order_summary' => FALSE,
      ],
      'review' => [
        'label' => $this->t('Review'),
        'has_order_summary' => TRUE,
      ],
    ] + parent::getSteps();
  }

}

After creating a plugin, you need to change the checkout flow settings for your order type.

For more information visit: https://docs.drupalcommerce.org/commerce2/developer-guide/checkout/create-custom-checkout-flow

Update

CustomCheckoutFlow

<?php

namespace Drupal\my_checkout_flow\Plugin\Commerce\CheckoutFlow;

use Drupal\commerce_checkout\Plugin\Commerce\CheckoutFlow\CheckoutFlowWithPanesBase;

/**
 * @CommerceCheckoutFlow(
 *  id = "custom_checkout_flow",
 *  label = @Translation("Custom checkout flow"),
 * )
 */
class CustomCheckoutFlow extends CheckoutFlowWithPanesBase {

  /**
   * {@inheritdoc}
   */
  public function getSteps() {
    return [
      'login' => [
        'label' => $this->t('Login'),
        'previous_label' => $this->t('Go back'),
        'has_sidebar' => FALSE,
      ],
      'card_information' => [
        'label' => $this->t('Card information'),
        'previous_label' => $this->t('Go back'),
        'has_sidebar' => TRUE,
      ],
      'order_information' => [
        'label' => $this->t('Order information'),
        'has_sidebar' => TRUE,
        'next_label' => $this->t('Continue to Order information'),
        'previous_label' => $this->t('Go back'),
      ],
      'review' => [
        'label' => $this->t('Review'),
        'next_label' => $this->t('Continue to review'),
        'previous_label' => $this->t('Go back'),
        'has_sidebar' => TRUE,
      ],
    ] + parent::getSteps();
  }

}

Then create CheckoutPanes as shown below:

BillingInformation

<?php

namespace Drupal\my_checkout_flow\Plugin\Commerce\CheckoutPane;

use \Drupal\commerce_checkout\Plugin\Commerce\CheckoutPane\BillingInformation;

/**
 * Provides the billing information pane.
 *
 * @CommerceCheckoutPane(
 *   id = "custom_billing_information",
 *   label = @Translation("Billing information"),
 *   default_step = "order_information",
 *   wrapper_element = "fieldset",
 * )
 */
class CustomBillingInformation extends BillingInformation {

}

PaymentInformation

<?php
namespace Drupal\my_checkout_flow\Plugin\Commerce\CheckoutPane;

use Drupal\commerce_payment\Plugin\Commerce\CheckoutPane\PaymentInformation as PaymentInformationBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Render\Element;

/**
 * Provides the payment information pane.
 *
 * @CommerceCheckoutPane(
 *   id = "custom_commerce_payment_information",
 *   label = @Translation("Custom Payment information"),
 *   display_label = @Translation("Payment information"),
 *   default_step = "order_information",
 *   wrapper_element = "fieldset",
 * )
 */
class PaymentInformation extends PaymentInformationBase {

  /**
   * {@inheritdoc}
   */
  public function buildPaneForm(array $pane_form, FormStateInterface $form_state, array &$complete_form) {
    $pane_form = parent::buildPaneForm($pane_form, $form_state, $complete_form);

    // Add an after build callback in order to make modifications on the address form.
    $pane_form['#after_build'][] = [$this, 'paneFormAfterBuild'];

    return $pane_form;
  }

  /**
   * After build callback for the pane form.
   */
  public function paneFormAfterBuild(array $pane_form, FormStateInterface $form_state) {
    // Get billing form element. Where it is located depends on the payment method that is chosen.
    if (isset($pane_form['add_payment_method']['billing_information'])) {
      $billing_form = &$pane_form['add_payment_method']['billing_information'];
    }
    elseif (isset($pane_form['billing_information'])) {
      $billing_form = &$pane_form['billing_information'];
    }
    else {
      // No billing information found.
      return $pane_form;
    }

    // Get the address form element.
    $address_form = &$billing_form['address']['widget']['0']['address'];

    // Add element validation callback to autofill the address.
    $billing_form['#element_validate'] = array_merge(
      [[$this, 'profileSelectValidate']],
      \Drupal::service('element_info')->getInfoProperty('commerce_profile_select', '#element_validate', [])
    );

    // Set all address fields to non-required.
    foreach (Element::children($address_form) as $key) {
      $address_form[$key]['#required'] = FALSE;
    }

    // Hide the address form.
    $address_form['#access'] = FALSE;

    return $pane_form;
  }

  /**
   * Element validation callback for the profile select element.
   */
  public function profileSelectValidate(array &$element, FormStateInterface $form_state) {
    $billing_profile = $this->order->getBillingProfile()->get('address')->getValue();
    $form_state->setValue($element['address']['widget'][0]['address']['#parents'], $billing_profile[0]);
  }

}

PaymentProcess

<?php

namespace Drupal\my_checkout_flow\Plugin\Commerce\CheckoutPane;

use Drupal\commerce_payment\Plugin\Commerce\CheckoutPane\PaymentProcess as BasePaymentProcess;

/**
 * Provides the payment process pane.
 *
 * @CommerceCheckoutPane(
 *   id = "custom_payment_process",
 *   label = @Translation("Custom Payment process"),
 *   default_step = "payment",
 *   wrapper_element = "container",
 * )
 */
class PaymentProcess extends BasePaymentProcess {

  /**
   * {@inheritdoc}
   */
  public function isVisible() {
    // This pane can't be used without the PaymentInformation pane.
    $payment_info_pane = $this->checkoutFlow->getPane('custom_commerce_payment_information');
    return $payment_info_pane->isVisible() && $payment_info_pane->getStepId() != '_disabled';
  }

}

After this set checkout panes for your custom checkout flow as shown in the image below:

Find full code at https://github.com/patilvishalvs/my_checkout_flow


Relation vs. References vs. Entity Reference for managing node-reference-type relationships References
Entity Reference
Relation

It seems like there are several active modules that all have similar functionality. Can anyone offer any information as to which branch appears to be the most promising / likely to survive & thrive? Any advice is welcome.

As of March 2012, the References module project page is now recommending Entity Reference as a replacement.

For basic node-type references, Entity Reference is certainly easier to set up than Relation.  I think a good general rule would be

  If you can do what you want with Entity Reference, use that.  Otherwise, go with Relation.


How to change the email recipient for contact form On a Drupal 8 site, I have a content type called TeamMember which has an email field.  From the view where I show all the TeamMembers, I'd like to link to a form where the user can email that person directly.  Is there a way to customize the recipient of the email from a contact form?

What we do in a few places is to have a hidden reference field to the team node in your contact message entity.

Then you pre-fill that when displaying the contact form and later on in hook_mail_alter(), use that information to change the recipient.

Requires a bit of custom code but then you don't have to create a lot of contact forms.


Displaying menu in theme How do I render a menu in a theme? Is there an easy way to do this?

I would prefer just a line of code that calls all the menu items in for a custom menu.

Say for example I had a menu named "brands"

How would I put that on my page--front.tpl.php?

I pulled this out of one my themes:

<div class="menu">
    <?php
        print theme(
            "links",
            array(
                "links" => menu_navigation_links("MENU-NAME"),
                "attributes" => array(
                    "class" => array(
                        "links",
                        "menu-links"
                    )
                )
            )
        );
    ?>
</div>

Alternatively, you can use Menu Block module and assign a menu block to a region, thus removing all of the ugly code from above from your theme file.


Get error when displaying a token in a header view I have a view working fine. Now I added a header text (Global Text) printing a token for the first contextual filter :

<?php print t('Subastas de ') . !1 ; ?>

The token is printed right but I get this error. The token value is: DIBUJO

Notice: Use of undefined constant DIBUJO - assumed 'DIBUJO' en eval() (línea 1 de /Applications/MAMP/htdocs/subastaspintura.com/sites/all/modules/ds/ds.module(954) : eval()'d code).

In this capture you can see how the Global text header is set up:

I think you can do it without PHP code. Just enter "Subastes de !1".


eCommerce : Definitions? Where can I find the definition of the meaning of terms in eComerce and Drupal iself . It is a bit confusing. F.e. there is :

Product
product type
product attribute
product variation
product variation type
product field
entity reference

and then :

 display field
 display form field

what are they and how they interact. I understand some of it ... but how do the COMPOSE and interact that is abit confusing.

===========

I read abit and here is the flow of creating product as I understand it.

Create Product attributes
Bundle attributes in Product variation types
Make Product types out of PVT
In the Create Product create the final Product-Variations, out of PT

Why so convolved !???

It's very open structured, and adaptable ..

Think of it like this: You sell variations of a product to a customer.
Where attributes handle the actual variation.
Products and variations can be arranged by types (like content types)

  Different types can have different properties (ie. fields) a variation
  can be referenced to a product no matter of their types. So here the
  attributes come into place and should available for all variation
  referenced to a instanciated product.

A product field can be on a content type to show your product on a regular node. (and is a referenced entity)
Otherwise products can be shown with the search api.

The variations are also referenced entites on the product. But provide already good AJAX and add to cart functionalities out of the box.

Regarding display:
Fields can be everywhere ... and are in the end displayed. (a basic drupal concept: fieldable-ness)
Forms are only used in the backendfor composing the content.

Maybe the doc from the commerce guys gives you the point (it's d7):

Product Types. (and variation types for d8)
A product type is a specific bundle based on a custom product entity. Each bundle can have fields attached to it, including pictures and other kinds of information.

Product "Informational" Fields. (and variation fields for d8)
Any field on a product can be a simple "informational" field. Typical informational fields include an image of that specific configuration of a product. For example, if you sell a tshirt with a cool print in multiple colors, each product with a different color could have an image field that, when displayed on the product display node, will change when you select different attributes (like color).

Product "Attribute" Fields. (actually variations attributes for d8)
Any field on a product type with a defined list of options (list of text options, list of taxonomy terms, list of colors). The attribute fields are special because of the way they turn into selection widgets on a product display. Often you will pair an attribute field (like a color dropdown) with an information field (like an image field) to let the user "select" the blue tshirt and the Drupal Commerce system will quickly load the picture associated with the blue product.

Product Displays.
If needed at all, these are groupings of products. You can reference any type and number of products on a product display. In order to make use of product displays, we recommend only showing one type of product per product display. The product display is where you typically see the product with drop downs to "configure" or "order" the right kind of product.

taken form here https://drupalcommerce.org/user-guide/product-attributes-variations


User edit url for profile I have create menu link named as my account

Now i want to link that my account link to  user/user_id(currnt login user)/edit

Anybody  tell me how to do that

Thanks

This looks like something that you could use the Menu token module for. Install and enable the module, then use a link path like this:
user/[current-user:uid]/edit


How to set which node a module loads on? I have a module that works on the hook_user (updates) it pushes details to another DB. I only want this module to load on the admin user edit screen where you can assign roles to a user. Currently I have a message that either says because you are role X you are allowed to send data, else sorry you do not have the rights to send data. However these messages display on every page in my drupal 6 website. I was wondering how I can limit this module to just the admin user edit screen, that would help a lot.

Check the current user having admin role, if you are using drupal superadmin, then check current logedin user's id equals 1.

<?php
  function custommodule1_user($op, &$edit, &$account, $category = NULL) {
    global $user;
    if($op == 'update') {
      if (in_array("administrator", $user->roles) || $user->uid == 1) {
          // Show message that only for admin.
          // Do whatever you want do for admin.
          drupal_set_message('You are Administrator you are allowed to send data');
      }
      else {
          // Show message for author users.
          drupal_set_message('Sorry you do not have the rights to send data');
      }
    }
  }
?>


How to rewrite Views filter URLs when based on an aliased node URL? I realize this seems confusing, but let me give some background first ...

I have a node (say node/123) with a path alias (call it: /books).  So if I go to http://example.com/books I'm viewing a page that's already been aliased by Drupal from /node/123.

However, now I put a Views block on that page and that block has an exposed filter. So, when I filter results I end up with an URL that looks something like so: http://example.com/books?type=fiction

Now here's the problem: I want to rewrite the above URL into something like http://example.com/fiction-books

This isn't as easy as it seems:

You can't use the pathauto module to set a new alias.
You can't use a function like hook_url_inbound_alter or even custom_url_rewrite_outbound because the querystring doesn't exist in any of those.

I attempted a rewrite in htaccess, which seems like the best solution, but I can't get anything there to work (I suspect this is because of Drupal rewriting the alias already so the pattern to use there is confusing).

For the record I know almost nothing about rewrites, but I've got this in htaccess which doesn't work:

RewriteCond %{REQUEST_URI}^/books$
RewriteCond %{QUERY_STRING}^type=fiction$
RewriteRule %{REQUEST_URI}^/fiction-books$ [L,R=301]

So, how do I do it? Advice on an internal Drupal-way would be ideal. But if not, then help via an htaccess RewriteRule would be really appreciated.

Have a look to Query Parameters To URL, I believe it fits your need :

  This module provides the ability to rewrite URL query parameters into Clean URL components on specified paths.

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

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


Exact link of vertical tabs I am using Field Group.

With 2 Vertical Tab, 'Step 1' and 'Step 2'.

I want to put a link "NEXT" on 'Step 1' that should open 'Step 2', same a back link on 'Step 2' that should go back to 'Step 1'.

I tried different combinations with Multipage but did not work here. How can I do this? I can put text but I don't know how to get the link of the other tabs directly.

Just add the ID of the pane (fieldset) to the URL as a fragment, e.g.

http://example.com/node/[ID]/edit#edit-metatags

Assuming metatag is installed, that code will open the metatags tab directly on page load.

An example for core might be:

http://example.com/node/[ID]/edit#edit-options

For the "Publishing options" tab.


How to find out the terms which are not being used for some duration I have vocabulary and it contains more terms, so I want to implement purge logic on it. i.e. I want to delete all the terms which are not used for some duration say 1 week.

Example

term1 was associated to node1 on Oct 1st
term2 was associated to node1 on Sep 30
term1 was associated to node2 on Oct 5th

So now term 2 was not being used for last one week, so now I need to delete that term alone.

I have tried following query,

SELECT ti.tid, td.name, ti.nid
FROM taxonomy_index ti
JOIN taxonomy_term_data td ON ( td.tid = ti.tid )
WHERE td.vid =48
AND ti.created < UNIX_TIMESTAMP( DATE_SUB( NOW( ) , INTERVAL 2 WEEK ) )

However this query gives me both term1 and term2

Actually the reason for that is that the ti.created column is "The Unix timestamp when the node was created."  It does not track the time when the tag was applied to the node, rather the time the node was created.

So that will always have the same value for each row that describes the tag associated with any one node.  Look at this screenshot of my taxonomy_index table that displays three different tags I just applied to my node at different times:

From what I can tell, if you wanted that functionality, you'd have to store that timestamp (when a node was actually tagged) in your custom module yourself and you'd have to query that value.

Anyway, hope this helps clarify the issues a little.  :-)


Show administrative description in Views I am needing to do a Views report for all webforms on our site (we currently have 27 forms) that can show me the total submission count per form.

The issue I am having is that we need the Views report to also show the Administrative Description of the form but I do not see that as a field option in Views.

Any ideas on how I can achieve this?

Ok here is one way to do it does however involve creating a custom twig Extension. its not to hard and there are a few youtube videos on the subject ...
for others it is good to note that custom Twig Extensions has replaced php input fields in older versions of Drupal.

in a nut shell you create a custom module,
you add a MODULENAME.services.yml  file.

in it you put...

services:
modulename.getWebformDescription:
  class: Drupal\modulename\getWebformDescriptionTwigExtension
  arguments: ['@entity_type.manager']
  tags:
    - { name: twig.extension }

then you need here is your class file (getWebformDescriptionTwigExtension.php)

<?php

namespace Drupal\modulename;

use Drupal\Core\Entity\EntityTypeManagerInterface;

/**
 * Provides twig function getWebformDescription()
 */
class getWebformDescriptionTwigExtension extends \Twig_Extension {

  /**
   * Load entity type manager.
   *
   * @var EntityTypeManagerInterface
   */
  protected $entityTypeManager;

  /**
   * {@inheritdoc}
   */
  public function __construct(EntityTypeManagerInterface $entity_type_manager) {
    $this->entityTypeManager = $entity_type_manager;
  }

  /**
   * {@inheritdoc}
   */
  public function getName() {
    return 'getWebformDescription';
  }

  /**
   * {@inheritdoc}
   */
  public function getFunctions() {
    return [
      new \Twig_SimpleFunction('getWebformDescription',
        [$this, 'getWebformDescription'], [
          'is_safe' => ['html'],
        ]),
    ];
  }

  /**
   * Provides getWebformDescription function to Twig templates.
   *
   * Use example {{ getWebformDescription( webfrom_id) }}.
   *
   * @param string webfrom_id
   *   The webform id eg 'contact'
   */
  public function getWebformDescription($webfrom_id) : string {
    // Invoke __toString and cast to int.
    $webfrom_id = $webfrom_id->__toString();
    $webform_storage = $this->entityTypeManager->getStorage('webform');
    $webform = $webform_storage->load($webfrom_id);
    return $webform->get('description');
  }

}

after all that is done and the module is enabled you can then in views add the webform id field (and exclude it from display)

then add a new custom field and look at the replacement patterns you will see
some thing like {{webfrom_id}} ...

in that field you can then enter ...

 {{ getWebformDescription(webfrom_id) }}

if stuck
see stuff like https://medium.com/@thihathit/extending-custom-twig-extension-to-drupal-8-twig-extension-class-d4b99c2177ae

or google "create custom twig extension for drupal 8"


Send user email through rest services I made a view, with a contextual filter in the user id. The fields are:

Name
uid
Email.

[
    {
        "username": "pruthiswebar",
        "id": "8"
    }
]

If I am logged, I can see the email, if I go to anonymous user, I can´t.
There is not a permission for "show user email" or something? How can I configure this?

To add informations to the view, which are not displaying of whatever reasons - you can hook into the view and "print" the informations manually.

Step 1 Create a custom module
(https://www.drupal.org/docs/8/creating-custom-modules)
I'm not sure, but probably you can add the preprocess in the MYTHEME.theme-File. Then you do not need your own module for this.

Step 2 Add the preprocess hook (https://api.drupal.org/api/drupal/core%21modules%21views%21views.theme.inc/function/template_preprocess_views_view/8.5.x)

MYMODULE_preprocess_view(&$variables) {
    // Todo: check if the view is the view you want to add the user email.
    $user_id = 1; // Change for other users.
    $user = Drupal::entityTypeManager()->getStorage('user')->load($user_id);
    $variables['users'][$user_id] = $user;
}

Step 3 In the twig-template of the view you can add the userdata (https://api.drupal.org/api/drupal/core%21modules%21views%21views.theme.inc/group/views_templates/8.5.x)

{{ dump(users) }}     {# for the user array. #}
{{ dump(users[1]) }}  {# for the user with the id 1 #}


Override orders page with a panel page How can I create a panels page for path admin/commerce/orders/*
I've set a existing page override

And created the panel with selection rules.

It still doesnt work. Is this the correct way to do this?

Deactivate the view with the same URL so there is no collision. Clear the cache and it should work.


Possible to add a organic group role programmatically? Im trying to programmatically add OG group roles and assign permissions through an update hook. Is this possible?

It seems that hook_og_default_roles() will only assign the role to new group members. The role must first exist in the roles table. You can do this by creating it in the OG UI or by using og_role_create() and og_role_save () as above.


Remove drag table in field collection module drupal 7 Hihi. Hi all. I have a content type and in which I created a collection field using field collection module. I set the value for the field collection that is unlimited. In field collection including some certain fields. Then I proceeded to create content for this content type. I discovered that the field collection module enables drag row and show weight of the current row. Now I want to remove drag and drop function and the weight of that row without knowing how processing. Expect people to help me handle this problem. Thank all.

To removing ajax dag and drop table widget for multiple value field you need use "hook_theme_registry_alter" to override theme registry function. Here you can find all information regarding your question.


How do I show a coupon code to customers? I've enabled a Ubercart Discount Coupons module in my eshop site and created some coupons with multiple one-time use only codes for testing purposes.

Now I would like to get one of the active coupon codes to customer who submits a newsletter registration form. Are there any functions to retrieve one of unused coupon codes?

The UC coupon module doesn't have a general purpose coupon retrieval function.

If you're solely looking to retrieve an active coupon, you can follow what the module itself does: query the DB table uc_coupons for rows with column status = 1. Using a DB query will let you modify it to whatever your particular case (e.g. 1 or more results, bulk codes, date range, etc.).


Custom maintenance page breaks module install process I followed the steps on this page: https://drupal.org/node/195435 to style drupal's maintenance page.

All well until the moment I try installing another module (doesn't matter which one) via an url. It does not install the module and it just shows me my maintenance-page--offline.tpl file (-which should only be shown when the database is offline).

The problem also shows up when installing a new theme.
I'm running the latest drupal version (7.23).

Anyone having the same problem? What could I be doing wrong here?

Be sure to add the $content variable in the template even though you customized some texts in your template file. A sample would be:

<?php if ($content): ?>

<?php print $content; ?>

<?php else: ?>

Offline due to an unknown issue. Our engineers are working on it 24/7 to resolve this.

<?php endif; ?>

Apparently, Drupal limits/locks access to the database during module/theme install, thus triggering the maintenance-page--offline.tpl.php. Take note that if you don't have the mentioned file, it will trigger maintenance-page.tpl.php.


page--user--login.tpl.php is not recognized drupal isn't recognising the page--user--login.tpl.php file.  Tried clearing the cache. Still not working. I've never themed the user login page before. Any idea's?

I am running Drupal 7 and I want to theme the whole page.
The other page template is being picked up.
There isn't any other page--user--login.tpl.php in my theme directory

the page--user.tpl.php is being recognised but the page--user-login-tpl.php is not.
bummer because i want the login page to be considerably different to the user page.

This question is similar to https://stackoverflow.com/questions/8712061/style-drupal-7-log-in-page

It looks like you need to also have:

a page.tpl.php in your theme for page--anything-else.tpl.php to work
a page--user.tpl.php in your theme

You should also always clear the theme cache after adding/removing template files.


How to force a cron run after a Rules component is scheduled? This question is a sequel on Why is the database not updated before a next Rule is launched?. I have a Rule that schedules a Rules component 5 seconds after the current time (this number is arbitrarily chosen). Since this component uses information from a frequently changing View, it should be executed as soon as possible. However, in my current configuration, that only happens when cron is run; which takes place once in an hour.

Can I somehow force a cron run (eventually with Rules) when the Rules component is scheduled?

you can give this module a try , it makes it possible to run cron via configurable rules
Ultimate cron


Page Not Found Old CSS References Recently, we did a complete overhaul of our theme. We have been working with a subtheme of Zen. We are still working with one, but we made it from scratch. Though it is now in place, we are receiving "Page Not Found" errors with calls to the old css files. Has anyone experienced this before, where could they be getting called from?

I've checked to make sure no css file is importing them and no info file is calling them.

You should do a search of the entire codebase (not just theme files), as well as a database search in all tables (it should only take about 3 minutes).

UPDATE:

Also, make sure you have taken any content delivery network (CDN) caching into account. Are these files causing "File-not-found" errors from a remote browser, or from a browser on the local machine (dev laptop, for instance).

If you do have a CDN in place (MaxCDN, CloudFront, Akamai, etc.) you can try uploading a mostly blank CSS file with the same name as the one that you're attempting to get rid of.


Drupal 7 hook_form_alter and submitting the form I added some custom field so that i can get more information when someone registers into the website but i want to alter one field on the form. I created a module which has a hook_form_alter function so that i can alter the field_first_name of the registration form. here is the code

function user_registration_form_alter(&$form, &$form_state, $form_id){
if ($form_id == 'user_register_form'){

    $form['field_first_name'] = array(
        '#type' => 'textfield',
        '#title' => t('First Name'),
        '#description' => t('Enter your first name.'),
        '#maxlength' => 255,
        '#required' => TRUE,
        );

}
if (isset($form['actions']['submit'])) {
 $form['actions']['submit']['#submit'][] ='user_registration_form_submit';
   }

}

I also created a the function which handles the form submission.

function user_registration_form_submit(&$form, &$form_state)
{

$fe_id = db_insert('field_revision_field_first_name')
    ->fields(array(
        'field_first_name_value' => $form_state['value']['field_first_name'],
        ))->execute();
    drupal_set_message(t('your form entry has been added'));
}

My problem is that when i submit the form and i check the user details. i find that the first name details does not exist in the database or when i login as the administrator and click on the 'people' link. i find that all information is are submitted except the first name field which i am trying to alter. I also tried to submit the form without the form submit function but it still doesn't work.

and i get the following error message if i add the form_submit function

  Notice: Undefined index: value in user_registration_form_submit() (line 37 of /var/www/html/lite/sites/all/modules/user_regestration/user_registration.module).

  PDOException: SQLSTATE[HY000]: General error: 1364 Field 'entity_id'
  doesn't have a default value: INSERT INTO
  {field_revision_field_first_name} (field_first_name_value) VALUES
  (:db_insert_placeholder_0); Array ( [:db_insert_placeholder_0] => ) in
  user_registration_form_submit() (line 38 of
  /var/www/html/lite/sites/all/modules/user_regestration/user_registration.module).

THIS IS LINE 37 AND 38 OF MY CODE

'field_first_name_value' => $form_state['value']['field_first_name'],
))->execute();

I am creating the module on localhost first before i push it to the live website

There's a typo, change value to values

To get the user id use:

<?php
global $user;
print $user->uid;
?>


Remembering the address of the calling page of a form (Drupal 7) I have created a little module that implements hook_menu and when the menu item is selected it displays a form that is defined as so:

function documentation_menu_nameform() {

  $form['documentation'] = array(
    '#type' => 'text_format',
    '#title' => t('Documentation'),
    '#default_value' => 'This project has not been documented.',
    '#format' => NULL,
    '#weight' => 0,
  );
  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Submit')
  );
  return $form;
}

Now when this menu item is selected it brings up a form at the address ?q=documentation_menu and in my form submission hook I would like to return to the page the user was on before they selected the menu item but I can't figure out how to access and/or store this path.

I would do this like so:

Have your menu item URL generated with destination parameter, for example:

/?q=documentation_menu&destination=some/path/where/user/had/just/been

add a hidden field to your form and populate it with destination path

$form['destination'] = array(
  '#type' => 'hidden',
  '#value' => drupal_get_destination()
);

if you for some reasons can't add destination parameter to that URL, then you'll need to extract that URL from $_SERVER['HTTP_REFERRER'] and populate hidden field with it.

Then in your submit function just do a redirect to the path specified in that hidden field:

function documentation_menu_nameform_submit() {
  ...

  drupal_goto($_POST['destination']);
}


Views arguments as part of path Is it possible to create views pages with urls like "prefix-%-postfix" instead of "prefix/%/postfix"?

No. The menu router system only understands % as placeholder within / characters as an argument to pass through to the callback function that will render it. It won't understand prefix-%-postfix other than its literal value. The underlying function, arg(), that the Views Content ID from URL contextual filter relies on to retrieve an argument relies on this system so it wouldn't be able to pull the argument.


How to change position of a block in a region? I just added a block to the 'content' region. It shows up at the bottom of this region. How do I do to move it to the top of this region?

I'm using the Drupal default theme: Garland

thanks

If it's showing up below the page content (and you want it above), you'll need to add a new region. It's recommended to copy Garland and rename it as your own custom theme in sites/all/themes.

In the .info file, add a new region. e.g.:

regions[content_upper] = "content upper"

In the page template file, place that region just above $content.

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

Then place the block in "content upper"


Sanitizing User Input using Form API - Creating Nodes I'm using D7 Form API to make some custom forms for users that create nodes on submit (using node_submit & node_save functions). This is an example form I'm using:

function create_article_form($form, &$form_state) {

$form['node_title'] = array(
    '#type' => 'textfield',
    '#title' => t('Node Title'),
    '#size' => 20,
    '#required' => TRUE,
 );

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

return $form;
}

This works great, but I'm just wondering about sanitization. From my research it seems like the check_plain() function should be used for text fields for security. However, it also causes raw HTML entities to be saved.

For example, I am setting the node title in the submit function like this:

$node->title = check_plain($form_state['values']['node_title']);

This problem is, if the user enters something like this:

Mike's Tacos

it gets saved in the node title like this:

Mike&#39;s Tacos

So if I output that title anywhere (in a view, in a custom node--XX.tlp.php, etc, it shows in this way.

Can anyone help with how to still use check_plain (or whatever function will provide the best security) but have the value saved with the human-readable format (Mike's Tacos)?

Filters are used for output, not input. It's the Drupal way; save the raw, un-sanitised data in storage, and filter (and cache) when it's being rendered.

You shouldn't run check_plain() on your node title before saving it, as it will be run through the same function by core/contrib when the node is being rendered, hence the double-encoding you're probably seeing.

If you're responsible for rendering the node title yourself at any point, you should always run it through check_plain() first:

echo check_plain($node->title);

But always on output, never on input.


HTML comment based tokens in hook_views_post_render() I am trying to figure out why my HTML comment based tokens are not getting replaced in hook_views_post_render(). I have a view where I've got a couple of fields, let's say, nid and the content title. I want to replace the title with something else.

So, I've edited the content title and checked the box to rewrite the output of the field and added something like this:

<!--something-->

Now, in hook_views_post_render() I am doing this:

strtr($output, array('<!--something-->' => 'my changed output');

But the problem is, nothing happens. For some reason, $output doesn't have the HTML comment, it's like it is being stripped out. I have specifically looked at the options for the field in my view and I don't have any of the checkboxes checked that strips out the HTML. I can add other html in $output and they all work fine, so there is no problem with the html going through. So, I am wondering what the issue is. Would appreciate any help on this.

It is being stripped -- rewritten views field output still gets run through filter_xss_admin(), which strips out any HTML tag-like construct that isn't in the default allowed_tags list.

Instead of using a <!--something--> format, try using [SOMETHING] instead.


How to use a view as a search result page with facets? I've created a pretty nice view with faceted filters following this guy's tutorial. It's basically a cheap way of doing getting the faceted feature without having to set up Solr.

The problem I have is that I would actually like to pre-query the index with some search terms from the homepage with a search form...basically:

search for a term and get redirected to the view with the facets.
use the facets to further filter my nodes.

How would something like this be possible?

Currently I have configured (in the Search API configurations) one server that uses database search as service class, and one Index hooked to that server, which indexes different fields (Content type and three different taxonomy terms) which are exposed as search facets in the view.

Number 2 is basically covered: I have a view page where all the nodes are listed and can be filtered through the facets... what I want is for the users to get to the front page, enter their search query (could have autocomplete or not, I'll figure later) hit "submit" and find all their search results in a page similar to the one I have with the facets... so they can further narrow their search. Kind of like when you look for something in linkedin.

For #1 You could try using Rules to catch the term and do a redirect.  You could also use hook_form_FORM_ID_alter to catch it

Edit:

You can use "Drupal is initializing" for the event, and add a condition that examines the args coming in.  For instance, search/some%20search%query would be:

arg(0) = search
arg(1) = some search query

So here are the steps:

Event -> Drupal is initializing
Condition -> Execute Custom PHP

$arg0 = arg(0);
$arg1 = arg(1);
if ($arg0 == 'search' && $arg1 == 'some search query') {
  drupal_goto('search/my-predetermined-facet');
}

That should do it.


Product feeds import I have a CSV of data which I am importing as Commerce-Products.

The issue is the price data gets rounded up or down when loading the price field data from the CSV into the price field of commerce-product entities.

For example, one CSV field has a price value of £71.89. I configure the price under manage display with the provided options and I get the following results:

Raw Amount: £72
Formatted Amount: £0.72
Formatted Amount with components: £0.72

So, I need help in importing the price data exactly as it is in the CSV, please.

Try Convert Excel Data Types in the corresponding column.

Excel 2010

Click the File tab, Click Excel Options, Click Advanced.
In the Editing Options, verify that the AllowEditing directly in cells check box is selected. Click OK.
Double-click the cell you want to format, and then press ENTER.
Click the error button next to the cell, and then click Convert to Number on the shortcut menu

How to convert text to numbers in Excel


Comments don't want turn off I forgot to turn off the comments while creating a content type. Now when i set the Comments to Closed, the form for adding a comment is still being displayed in full node view.

Any suggestions?

Thanks!

This setting only sets the default for nodes, so already created nodes will still have their comments turned on. Easiest way to update all the nodes is with a couple of SQL statements, back up your database first.

UPDATE node SET comment = 0 WHERE type = 'your_content_type';

UPDATE node_revision nrev
  INNER JOIN node nd ON nrev.nid = nd.nid AND nd.type = 'your_content_type'
  SET nrev.comment = 0;

then clear cache.

Note that comment can equal the following:

0 = disabled
1 = readonly
2 = read/write.

More details at How to finally disable comments on content type?


How to hide rating field when adding comment to own node? On my website, users can rate nodes with the Fivestar module while adding a comment. In other words, the rating field (called 'stars') is part of the comment. Now, I'd like to hide the rating field for users when they comment on their own nodes (or when they already have commented before - see: How to hide Fivestar rating field after first comment?).

How can I do that?

Edit 1: I applied this patch (patch 97 on https://drupal.org/node/189527), but my problem still isn't solved. I now have the following option at Administration > Structure > Content types > MyArticle > Comment fields:

But after clearing caches and creating new content, the rating field is still displayed when I add a new comment.

Edit 2: I sent an e-mail to the patch's author and he answered this:

  The purpose of the patch I created is to prevent a user from rating
  their own node.  I believe the problem you are having with this patch
  is that, since the fivestar field is on the comment, that the patch I
  wrote would probably reference the comment itself (as the entity id)
  instead of the node - freely allowing someone to vote.

Edit 3: I tried to solve my problem with a custom module called 'hiderating'. This is the code I'm using:

function hiderating_form_alter(&$form, &$form_state, $form_id) {
  global $user;
  if ($form_id == "comment_node_stuff_form") {
   if ($form['#node']->uid == $user->uid) {
      $form['field_stars']['#access'] = 0;
      }
      else {
      $form['field_stars']['#required'] = 1;
      }
    }
}

I made the 'Stars' field not required from the interface. The code is nearly working: the 'Stars' field isn't displayed when one comments on his/her own node, but unfortunately, it isn't turned to 'Required' when one comments on someone else's node. In other words, my code's else part doesn't work properly.

How can this be fixed?

You should use unset($form['field_stars']); instead of $form['field_stars']['#access'] = 0;

You can keep the fields as required and also remove the else condition.

So your final code would be something like this

function hiderating_form_alter(&$form, &$form_state, $form_id) {
  global $user;
  if ($form_id == "comment_node_stuff_form") {
   if ($form['#node']->uid == $user->uid) {
      unset($form['field_stars']);
      }
    }
}


Backup an enterprise application server and restore What is the best practice to back up a server running Drupal?
I have backed-up server A, and I want to restore it on server A using server B (both are not on same network).
On both server I have Windows Server 2008, and for backup I am using "Windows server backup."

I am not sure what you're exactly asking for.

Do you want to do this automatically on a regular basis, or just as a cold/manual standby? We are very happy with Drive Snapshot for full Windows Server backups.
If you're looking for hot failover solution you have to work with redundant machines on all levels (Load Balancer, Web Server, DB Server, File Server). Be prepared to spend some weeks of work (or about 1000 Euros/month) to get this working.
About Drupal 6 itself: You have to backup the DB and the files. For the files the backup & migrate module is very handy. You could combine drush and rsync, but on Windows you will face some problems. Cygwin could solve some of them.


Drupal 7 Bartik plus theme drop down menu This is actually, must be easy question, ive been fiddling around for some hours trying to figure it out.

The short version is I am making a drop down menu in Bartik,

I am aware of superfish,nicemenues,megamenues, But I am not interested in these.
Since Bartik runs with superfish built in.

I came across this Drupal 7 Bartik Plus Theme
with a fresh install of Drupal

But this menu isnt working. The default menu is not showing.

as you can see here this is how it supose to work

Drupal 7 Bartik Plus example

Any good ideas to how I get it to work?.

The answer I found was here Changing Bartik theme to dropdown

and I used this CSS file with fixed issue

CSS file to put into superfish folder


D7 views node references. Do not displays first node I have 2 content types: Page and Paragraph.
Page has field node reference which made through view(outputs as checkboxes). View has contextual filter - Paragraph node author id (uid).
I create user, then create 2 nodes of type Paragraph.

Then I create node of type Page and in node reference field I see only one node of type Paragraph. I search for my Paragraph nodes in http://example.com/admin/content and open each paragraph in devel.

Both of Paragraph nodes are published. Both has user id in uid. But in the field I see only one of them.

Trying to figure out what's happening I call views_get_view_result with my view. And see only the second node.

Any help appreciated, thanks!

After hours of googling found how to deal with this issue.
Thanks to this Actual output in view is different than preview

In view settings go to other section -> query settings -> Disable SQL Rewriting.

After saving the view I've seen all my nodes into the node reference field.


Form is not submitting after ajax callback I have a form which has a checkboxes field.

This field has an ajax callback attached

$form['checkboxes'] = array(
  '#type' => 'checkboxes',
  '#title' => 'test',
  '#ajax' => array(
    'callback' => 'mymodule_ajax_callback',
    'wrapper' => 'test-wrapper',
    'method' => 'replace'
  );
);

function mymodule_ajax_callback(&form, &$form_state) {
  return $form['another-field'];
}

When I check a checkbox, the ajax callback is executed. Then when I try to submit the form through form submit button, it reloads the same page with values in the fields, but the form is not submitted.

I have tried $form_state['rebuild'] = TRUE in the ajax callback also but it did not help.

I have added the #name and #id properties also to the submit button but no luck.

Is there any other solution which I can try?

I think the problem is that you only return the another-field in the ajax callback.

You probably have to make a wrapper for the submit and the another-field.

So you willl have:

$form['ajax_wrapper'] = array(
  'submit' => array(
    // Submit button...
  ),
  'another-field' => array(
    // Another field...
  ),
);

And then return $form['ajax_wrapper'] in your ajax callback.
Make sure to use $form_state['rebuild'] = TRUE;


How do I add custom order fields for users to fill out at checkout Drupal 7 - Commerce

I have 2 fields related to the order. one is radio button where user selects Pickup, Delivery. the other one I won't mention as it might confuse some people. I want the user to select which one they want at checkout. How do I do this?

I've added the fields the order. admin/commerce/config/order/fields. They don't show up on the checkout, but they do show up when the admin tries to edit the order.

I tried setting the fields as required, but the order gets created with these fields blank (this is a bug).

There are no options to add these fields on Checkout Settings admin/commerce/config/checkout.

I am not looking to add fields inside Billing Information nor Shipping Information.

I was able to solve this problem using Commerce Field Group.   What you do is:

create the fields you want.
create the field group.
put the new fields inside the field group.

Then

goto the Checkout Settings (admin/commerce/config/checkout) and add the group inside Review


D7 Node Field: Create OG Member Checklist in Node Edit Form I'm using Drupal 7 to create an intranet site. I'm using OG groups to create committee and department pages. I want to create a field in a "Meeting Minute" node type where a list is populated with all group members. The node author could then select whether the committee member was present or absent at a meeting.

I'm able to use an Entity Reference field to select from all users on the site, but I want to limit these checkboxes to just group members.

I'm striking out here; any ideas on where to start would be much appreciated.

Using the OG 7.x-1.x branch.

UPDATE: I have tried to use the "Entity Reference View Widget" module to accomplish this, but that doesn't seem to work either.

I'm going to try to restate this for clarity — I need a field on a node edit page that allows me to select one or more users who are also members of a group from the organic groups module.

Use hook_form_alter to do a entity field query or SQL query to get a list of UIDs that belong to 1 group ... OG may have a function to retrieve that list I dunno.

Once you have a list of UIDs use Devel and dpm($form); the form object and you can simply unset() the #options values for UIDs that dont belong in the OG group. Here's a similar thing I did for limiting to a taxonomy term_reference field to a given level of a nested taxonomy.

If you're paranoid you can also append your own validator function to the form_submit function and cross check that valid UIDs (members in the OG group) are being saved .... but I dont usually bother to do that for intranet sites (I have "trusted" users / staff members ... not joe blow public).

Sample code doing basically the same thing for a taxonomy term reference field.

/**
 * Implements hook_form_alter().
 */
function eap_student_videos_form_alter(&$form, &$form_state, $form_id) {
    switch ($form_id) {
      // Field specific overrides.
      case 'eap_studentvideos_node_form':
          $form['field_eap_video_country']['#after_build'][] = 'eap_country_term_limit_to_countries';
          break;
    }
}

function _eap_region_tids() {
  return array(24,35,48,8,4);
}

function eap_country_term_limit_to_countries(&$element) {
    $options = $element[LANGUAGE_NONE]['#options'];
    $result = db_query('
        SELECT tth.tid, ttd.name AS term_name
        FROM taxonomy_term_hierarchy tth
        LEFT JOIN taxonomy_term_data ttd ON tth.tid = ttd.tid
        WHERE tth.parent IN  (:tids)
        ORDER BY 2 ASC
    ', array(':tids' => _eap_region_tids()));
    $country_tids = $result->fetchAllAssoc('tid');
    $country_tid_array = array_combine(array_keys($country_tids), array_keys($country_tids));
    $new_options = array_intersect_key($options, $country_tid_array);
    array_walk($new_options, function(&$value, &$key) { $value = str_replace('-','',$value); });
    // array_merge() destroys the array keys.
    $new_options = array('_none' => '- Select a value -') + $new_options;
    $element[LANGUAGE_NONE]['#options'] = $new_options;
    return $element;
}


Linking to #targets when promoting to homepage On a Drupal 6 site, I want my article to start with a bullet list of section headings, linked to in-page targets; and I want to include this list in the teaser text which is promoted to the homepage.

But the links don't work from the homepage, because Drupal doesn't work out that the on-page target in an article is an off-page target or the teaser, so it doesn't include the node reference.

Is there some way for content authors to achieve this easily?  Maybe there's a module which handles it?

Use URL's relative to the site root. Suppose your node lives at http://example.com/node/123 and your named anchor is called "target", write your link like this:

Target

This should work on the home page and the node page itself.


drush rsync among sites I have the following alias group set in the setA.aliases.drushrc.php:

  $aliases[‘site1'] = array(
      'root' => '/var/www/site1',
      'uri' => '88.88.88.11/site1',
      'remote-host' => '88.88.88.11'
  );

  $aliases[‘site2’] = array(
      'root' => '/var/www/site2',
      'uri' => ‘88.88.88.22/site2',
      'remote-host' => '88.88.88.22'
  );

  $aliases[‘site3’] = array(
      'root' => '/var/www/site3',
      'uri' => ‘88.88.88.33/site3',
      'remote-host' => '88.88.88.33'
  );

Now, I have updated @site1, and would like to sync with other sites in setA alias group, can I just use the following command "drush rsync @site1 @setA"?

Or how can I exclude @site1 from destination @setA as it is actually the source?

In Drush 6 and earlier, the rsync command did make some attempt to operate on site alias lists; however, we recently decided that this feature was not useful enough to continue to maintain it, so we removed it from Drush 7.  Truthfully, I'm not even sure that it's working right in Drush 6 -- casual tests showed inconsistent results.

Therefore, the best way to do this would be to just call drush rsync once for every destination site.  You could do this with a simple script.

#!bin/bash
for site in $(drush sa @setA --format=csv --fields=name)
do
    if [ "$site" != "site1" ]
    then
        drush --yes rsync @site1 "@$site"
    fi
done


Get all available promotions for specific commerce product How to get all available promotions, which apply to specific product?

You can do it via commerce_order.price_calculator service:
$context = new Context($this->currentUser, $this->currentStore->getStore(), NULL, [
    'field_name' => $items->getName(),
]);
/** @var \Drupal\commerce\PurchasableEntityInterface $purchasable_entity */
$purchasable_entity = $items->getEntity();
$adjustment_types = array_filter($this->getSetting('adjustment_types'));
$result = $this->priceCalculator->calculate($purchasable_entity, 1, $context, $adjustment_types);

//Get promotions
$promos = $result->getAdjustments();


How to detect devel user switch I need to detect if I'm currently browsing the site as a different user, having used the devel user switch module.

The LDAP module I have triggers some profile updates on every login, based on some server variables set from AD/SSO. But by using devel switch, it's writing MY user details, to the profile of the person I've switched to.

I need a way of detecting it, so I can prevent the profile write.

I've had a look through the devel API here but can't see that anything is set when running as another user.

Running D7.

The Devel switch feature passes the login straight to the user module in devel_switch_user(); it doesn't give other modules the chance to intervene, and doesn't provide any context that would let you know how the login has been instigated.

I guess as a simple low-tech solution you could patch that function and set a session var before it invokes the login, something like

...
if (!$old_uid) {
  // Switch from anonymous to authorized.
  drupal_session_regenerate();
}

$_SESSION['login_from_devel_switch'] = TRUE;

$edit = array();
user_module_invoke('login', $edit, $user);
...

Then you can check for the existence of that session var wherever you need to prevent the profile from writing.


How to retrieve a file via REST from the services module? Which URL format should I use when retrieving a file via the services module?
I figured that it would be formatted like this:

http://<domain>/<endpoint>/file/fid

I've tried several file ids but all I get is an empty result.   Is this the correct url format for retrieving a file?

Services module version is 3.

I managed to get this working in the end.  I used the poster plugin to request the url and received a message saying that the file doesn't exist.  I'd been using the wrong file ids!  I had looked at the wrong drupal database to choose the file ids.


Services Using views having search I am using Drupal 6.  and using services and view_service module .

I have created a exposed filter view.
here is screenshot for that view

now i am using service module

here is screen shot

now i want to  pass filter result to get name . does anybody tell me how to pass exposed filter arguments in web services.
Thanks

If you try using filters via the UI on the page itself (not via a services endpoint request), check how the URL changes. If you are not using AJAX in your view, the URL should append all filter values to itself. Then in your services request (poster), try sending in that same URL pattern with the filter arguments in it.

For example, when I used a node title filter on my view and submitted it, I got this URL returned .../testpage?title=testfilter. Then try sending the poster request to this URL with the filter value of your choice.


How can I add pagination to the comments of advanced forum in drupal 7? I use Drupal 7 but don't see any pagination on the comment pages, how can I add a pager there please?

I think that this can help you.

Let me know if this is working.


In "Status report" it just outputs the string "version", which causes problems when querying Drupal version When I go to "Status report" menu, only the string "version" is getting printed, which can cause problems with some modules like Webform.
I have Drupal 6.22, but in the "Status report", Webform writes "Webform requires at least version 6.16 of Drupal core.", which means the problem above can be a possible reason.
How can I fix that?

Here are some screenshots:

EDIT

The file system.module contains

define('VERSION', '6.22');

on line 11, which is correct, BUT the return value of this function was bool(false) (after checking it with a var_dump()), which means a failure (like when this was defined earlier or sg similar). After that, I put the following line BEFORE the above mentioned define function:

var_dump(defined('VERSION'));die();

and it gave back bool(true), which means this constant has already been defined!
I still don't know where, why and how...

There's a function with the name _drupal_bootstrap_full() (in /includes/common.inc, line 2673), in which module_load_all() function is called. The "VERSION" constant is defined after calling this function (and its value is "version" then), but knowing that doesn't make an advance.

That is weird. What does line 11 of the file modules/system/system.module read? For me, it is define('VERSION', '6.22'). How did you obtain the Drupal source files? Via a zipfile or through a git check out perhaps?


Javascript variable value in page source for seo from Drupal.settings Declared a variable in settings.php

$conf['my-variable'] ="my-variable-value";

Added inline javascript

drupal_add_js("array('my-variable'=>variable_get('my-variable'))");

Need to print variable values from Drupal.setttings in inline js

drupal_add_js("jQuery(document).ready(function(){
  window.my-val = Drupal.settings.my-variable;

})",'inline');

So the output on page is comming up like

<script type="text/javascript">
window.my-val =Drupal.settings.my-variable;
</script>

But I need it should be like below for seo requirement

<script type="text/javascript">
window.my-val = "my-variable-value";
</script>

I think you're over-estimating the potential SEO value of making such a change, but if you don't want to use Drupal settings you can just interpolate the value into a static string and use that:

$var = variable_get('my-variable');
$js = <<<EOF
function() {
  window['my-val'] = '{$var}';
}
EOF;
drupal_add_js($js, 'inline');

I'll leave data-sanitising up to you, how far you need to go will depend on the source of the variable.


Are spam registrations a threat to a Drupal 7 site Yesterday, as I was explaining to a client that someone would need to remove spam registrations, the client asked me what difference it made if they are in the system because we can just turn off all privileges that anonymous users don't have.

I was not able to give her a compelling argument of why this clean up is important. The fact that I like to keep everything on a website nice and clean was not a compelling argument for her. What are the security or other risks in not cleaning up the spam users?

Will there be a number of authenticated users on this site who are not spammers, or does your project only require a few users to create content? If it's the latter, the best bet is to simply turn off user registration, and have the owner create accounts as needed. If the former, programs like Mollom should help with cutting down spam and the basic package doesn't cost.

As far as performance goes... if spammers can post content, the obvious issue is comment/content spam. You can use the Disqus module to mitigate this, i.e. offloading the work to Disqus. If not, then if you need to send emails to all users through a service, then you will necessarily have email list bloat. If the volume gets very high, then you could potentially have availability issues, though I don't see that very often.


preventing access to php files using htaccess doesnot allow ajax to use php files i am using the following code in .htaccess to prevent access to php files from the browser

<Files ~ "\.php">
Order allow,deny
Deny from all
</Files>

the problem whit that is that when i deny access to php files ajax cannot use those php files either... how can i solve this... any help would be appreciated... thanks in advance... :)

I've no idea what you're trying to accomplish, but I believe you're seriously misguided about how a PHP-based website works.

If you set up .htaccess-rules to stop the browser from accessing any PHP-file, it is not only ajax that will be affected.  Every page on your Drupal website will return 403 to any visitor, including index.php in the root directory.  I doubt that you want this.

If you've got Apache configured correctly for PHP, the contents of a PHP-file are never transmitted to the client - only the result of processing it server side.  Just point your browser to sites/default/default.settings.php to see how this works.  Unless you've really munged your Drupal configuration, you should not need to do anything to stop the PHP-files from being browsed.


Rule to create user on webform submission by anonymous user I'm trying to create a user with rules on webform submission by anonymous user, as the title says. I set my event (After a webform has been submitted), set my conditions and set my actions. Create a new entity of user whose name will be [data:name-value] and e-mail address [data:email-value] as seen below . But I get Unable to evaluate action entity_create. However, I know [data:name-value] works it prints when I show it on the screen. User creation also works because a user is created when I enter fixed values. What could I be missing?

PS: I could roll my own module for this small task, but why bother when I can do it with rules?

It looks like your issue is about what is described in "Create entity fails when the user is anonymous" (which is an open Rules issue, current status = RTBC).

That issue also contains a patch (attached to comment #4 of that issue), which might help as a (temporary?) work around.

Note: another way to get it to work, appears to be to use the token [data:email-value-raw], as suggested in a comment to this answer (credits: olisb).


Manipulate search results on site We have a few scenarios on a project where we want results to be presented at the top of the of the page despite not having any keywords in the body copy related to the search keyword.

For instance, if someone on our site searches for "baseball," we'd like a few choice results about "football" to come up, even though the nodes are strictly about baseball.

Are there any modules that allow for this behavior in the search functionality of Drupal?

If you are using ApacheSolr then I imagine this could be solved with the use of 'Synonyms'.

See the documentation on this.

Example synonyms file you might use:

#Equivalent synonyms may be separated with commas and give
#no explicit mapping.  In this case the mapping behavior will
#be taken from the expand parameter in the schema.  This allows
#the same synonym file to be used in different synonym handling strategies.
#Examples:
ipod, i-pod, i pod
baseball, football


How can I change the text: "Images must be larger than 200x200" in the image field for a specific content type? How can I change or replace the text: "Images must be larger than 200x200" in the image field for a specific content type?

I have created a image field CCK and I have put the Minimum resolution for Images of 200x200.  When I put this restriction appears the text:   Images must be larger than 200x200.  I need to replace or change this text by:  Minimum size for images:  200x200, in some content types.  Is it possible?

I am working with Drupal 6.x.

Thanks.

you can use string overrides module or a hook_form_alter and override the text with

$form['PHOTO_FIELD_NAME']['#description'] = 'Images must be larger than 200x200';


How to limit number of nodes a user can create per day? In order to curb ardent spammers in Drupal 6, I'd like to limit the number of forum nodes that an authenticated user can create per day. So for example ordinary users can not create more than 3 posts each day. I am wondering how can I do so? Thanks

For Drupal 6 I have used Node Limit Number with great success.

  Limit the amount of nodes or comments your users create over a given
  time period. This module has been rewritten to integrate with Rules.
  Instead of going to a page to assign limits you now just need to
  create rules. A default rule has been provided as an example.

The 2.x branch also integrates with the Rules module to make it really flexible.


Views: Get total results I am trying to get a total count of the results using Views.  Looking at this link, Count results in Views using aggregation, I use aggregation, but Views counts each row as 1.  For example, this is what I get:

TITLE         Results
"A title"     1
"A title2"    1
"A title3"    1
etc...

I want it to be

Title
"A title"
"A title2"
"A title3"

Results: 3

Any way to do this in Views?  If not, is there a way I can weak the current Views SQL or its output instead of having to write my own module and SQL query from scratch?

Add a Global: Result summary field to the footer. There is no need to turn on aggregation.


When adding Content: has taxonomy term id contextual filter to view and check specify validation criteria box, why don't I see validation options? My request is closest to these two questions:

Filter by multiple taxonomies in URL

Views contextual filters taxonomy name

I have a view which is a page and displays node titles in a table format after the user selects a state, school year, school division, and school using exposed filters. And since each resultset can have dozens of nodes (nodes about that school for that school year) in it, the results are pages of links to 10 nodes at at time. I have exposed filters for state, school year, school division, and school. The view works fine, but the urls for each page of 10 node titles pertaining to an individual school looks like this:

http://www.mydomain.com/schools?field_state_tid=123&field_school_year_tid=456&field_school_division_tid=789&field_school_tid=999&page=1

when I would prefer it look like this where instead of term_ids I have terms in the url:

http://www.mydomain.com/schools/arkansas/2012-2013/little-rock/clinton-elementary/page1

I have created state, school year, school division, and school taxonomies and each node is tagged appropriately with 1 term from each taxonomy.

But when I try to follow the instructions in the above mentioned questions, I get stuck at the part where it says to "specify validation criteria".

I check that box, but I have no options - the options are unavailable.

In the second question referenced above there is a part that says:

"Make sure Specify validation criteria is checked and you should be presented with more options."

[emphasis added]

That is exactly my problem - I should be presented with more options, but I am not.

Can anybody tell me why I am not presented with more options?
Am I doing something else wrong?

Thanks in advance.

Duh, in case anyone else runs in to this problem:

This really boiled down to after adding a contextual filter, if I clicked any of the checkboxes under the heading "When the filter value IS in the URL or a default is provided":

Override title
Override breadcrumb
Specify validation criteria

I did not see any of the options for any of those checkboxes appear after checking it.

Turns out I didn't have the most up to date version of the chaos tools module.

When I updated to chaos tools 7.x-1.3 (sometimes referred to as ctools) problem fixed.


Cloned node entity reference field stay in sync with parent node I have three content types A, B and C. A have entity reference fields to B and C. I create a Node of type A say a1. When i clone a1 node as a2 with node clone module i get the same value for entity reference fields in a2 same as a1. In a2 i can change the entity reference field value so that they refer to another nodes of B and C content type.

But with node clone module there is no way to maintain relationship between parent node and cloned node.

So I basically have two requirements:

In cloned node i can override the entity reference field value or leave it same as parent node. If i override, later i should be able to revert back to those values same as parent node. Currently there is no way to do this.
If parent node change the value of those entity reference fields then in all the cloned node of this parent node also change their respective entity reference field value except overridden cloned nodes.

The solution i found so far during searching is using Replicate, replicate_ui module which provide more hook to alter the cloning process. The another module is Corresponding Entity References which create entity reference field back to parent node.

I don't need comprehensive solution but anything existing solution can do almost this functionality?

1) You could use a hidden field of the same type with the same information. This way, the information relating the parent to child can be reverted, regardless of the changes or overrides. Use Rules to populate the duplicate field. Create a "Revert" button on the node and again use Rules, or as a form submit to react to copy the information from the hidden field to the visible one.

2) Use Rules to adjust any child nodes when the parent is saved/updated. This would act on both the hidden and visible field, with a condition on the visible (not to change if it has been overridden).

You could also write a module to do this, but I think it can be done with just Rules.


“&” displaying as “&” I'm Using File (Field) Paths

“&” displaying as “&” in the file name

i tried to solve it by change the the display of the field to plain text and use the token view mode but nothing change

Any help?

You should always prevent special characters in filenames, this can lead to strange behavior. Specifically because certain characters can be part of a query string (example.com/index.php?var1=value1&var2=value2).

I recommend the Transliteration module (assuming Drupal 7) to remove these charaters form the filename. If that does not help (or if you are using Drupal 8), you might want to take another look at you upload configuration. There might be a token provided by File (Field) Paths that does provide you with a good encoded name.