Views AJAX not work in block node.tpl i have some block with sorting exposed filter on region "tab" and i show his in node.tpl like this:

print render(block_get_blocks_by_region('tab'));

In my block i not have any problem with AJAX in paginator. But my sorting exposed filter not work at all.

After several hours testing i figured out what my block works ( AJAX sorting filter + paginator) if i show his in any another region on page.tpl.

That things i see in header, if show his through any region on page.tpl:

  "better_exposed_filters":{"datepicker":false,"slider":false,"settings":[]},"views":{"ajax_path":"/views/ajax","ajaxViews":{"views_dom_id:7ff6de2549b84f9553122b84f32d822b":{"view_name":"person_books","view_display_id":"block_1","view_args":"61/61","view_path":"node/61","view_base_path":null,"view_dom_id":"7ff6de2549b84f9553122b84f32d822b","pager_element":"0"}}}

That things i see in header, if show his through region "tab" in node.tpl:

  "better_exposed_filters":{"datepicker":false,"slider":false,"settings":[]},"views":{"ajax_path":"/views/ajax","ajaxViews":{"views_dom_id:21d228e5cc07884c39ecda6d29b417c4":{"view_name":"person_books","view_display_id":"block_1","view_args":"61/61","view_path":"node/61","view_base_path":null,"view_dom_id":"21d228e5cc07884c39ecda6d29b417c4","pager_element":"0"},"views_dom_id:a94bccf7913b478becb33a3a27ec903d":{"view_name":"person_books","view_display_id":"block_1","view_args":"61/61","view_path":"node/61","view_base_path":null,"view_dom_id":"a94bccf7913b478becb33a3a27ec903d","pager_element":"0"},"views_dom_id:da94f68eea44bf9ead4034e965977935":{"view_name":"person_books","view_display_id":"block_1","view_args":"61/61","view_path":"node/61","view_base_path":null,"view_dom_id":"da94f68eea44bf9ead4034e965977935","pager_element":"0"}}}

How can i fix it? Why views send many view_dom_id in header if i show my block through region in node.tpl?

P.S. i tryed show views through views_embed_view in node.tpl - same things, not helped me :/

fixed... always, REMEMBER!! always shutdown block in block UI. if not do it, this piece of shit gives something like:

  {"view_name":"person_books","view_display_id":"block_1","view_args":"61/61","view_path":"node/61","view_base_path":null,"view_dom_id":"a94bccf7913b478becb33a3a27ec903d","pager_element":"0"}

in page header and your ajax may work not so clear :)


Is it possible to attach a single field collection to multiple nodes? (And so make updating easier) Firstly is it possible to attach a single field collection to multiple nodes (so when you opened each node, you'd see the same field collection. If you altered one, they'd all change.)

And secondly, if the answer to the first question is yes, how would you go about doing this? Has anyone ever tried this before?

I've been looking through the database tables and it seems like there's no reason you couldn't just point multiple nodes to one fc, however I can't find anything on the topic.

Brief Example

A quick use case to clarify Geoff's question:

When I create node b, I have the option to populate a field collection from node a rather than a blank field collection.

Editing the field collection on node a, would then also change the value in b.

You have to write custom module for this and use hook_node_presave($node) to save fieldcollection value of other node into this and save node.

Then check your DB, now single fc attached to other node(s).


Need to alter "No Paragraph added yet. Select a Paragraph type and press the button below to add one." message - Paragraph Module I am using paragraph bundle and I want to alter this message with my custom text "Please click on below button to add data".

You need to patch the contrib module.
Patch here works for me.


Access callback for user/%user/edit menu item not working I have two roles, client & student. Students can edit their profiles, clients cannot. I thought the easiest way to solve this would be to add a permission as per below:

function si_permission() {
  return array(
    'edit account' => array(
    'title' => t('Edit account'),
    'description' => t('Allow users to edit their account')
  )
}

I then altered the menu item and changed the access callback to my new permission:

function si_dashboard_menu_alter(&$items) {
  $items['user/%user/edit']['access callback'] = user_access('edit account');
}

I then set the permission appropriately in permissions settings, but it does not work. It always appears to be false, so the menu item access is always disabled. I have even debugged   'user_access('edit account')' whilst logged in as the appropriate user and it returns TRUE, so I know the permission is working.

All caches cleared, menus rebuilt using developer tools. Any ideas?

Ok, it appears I have to set the access as per following:

function si_dashboard_menu_alter(&$items) {
  $items['user/%user/edit']['access callback'] = 'user_access';
  $items['user/%user/edit']['access arguments'] = array('edit account');
}


How to translate Views header syntax? not Title In a view, i have filter content using "Language". it works fine. i have added "header" contain HTML syntax (which will be shown with top of view) like:

Text need to translate

i couldn't translate this syntax.

can anyone suggest how it will be translate??

Here's how to translate expressions containing HTML code:

Go to admin/config/regional/i18n/strings
Check "full HTML" in "Translatable text formats" section
Then, go to admin/config/regional/translate/i18n_string
Click on "Refresh strings".


wysiwyg box only shows html I manage a small drupal (openAtrium) site at work that we use for project management. Last week the wysiwyg textbox used to edit content stopped working. By stopped working I mean html was displayed regardless of the setting chosen. At the time I was using tinyMCE although since this I have tried CKEditor and openwysiwyg to no avail. For some users this only only an irritation but for others, who relied on the wrodprocessor features of wysiwyg mode it's more of a show stopper.

I can't find any error messages or indeed any indication that something is wrong in drupal. In terms of browsers I do get one JS error which maybe related.

Error: Syntax error, unrecognized expression: select:[name="field_oa_section[und]"], select:[name="field_oa_space_type[und]"]

All browsers I have tried (IE, Firefox, Chrome, Konqueror) are affected. Does anyone have any ideas? I can't find anyone else who has experienced similar problems.

Thanks.

The problem turned out to be multiple required versions of jquery. A jquery manaement module solved the problem.


Block Permission for user I have faced a new problem, here I have poll block which is already displayed for administrator or user who has the permission of "view published content". When I made another user and give the complete permission for the poll but does not giver the permission of "view published content", it is not displayed for the user. Can any one help me to show that in the block for user except administer or user who has the permission of "view published content".

cheers

You want to be looking at the permission "vote on polls" that is the one you want to enable for that user.


How to attach media item created during migration to media field in node I am migrating content from Drupal 7 to Drupal 8.
There is an audio field that I am currently moving to media via a custom process during migration.

When I get the id of the new media created I can't seem to get it to attach to my new media reference field in the also newly created node.

Can anyone tell me what is wrong with the import below?

field_audio_fileinfo:
-
  plugin: sub_process
  source: field_audio_fileinfo
  process:
    target_id:
      -
        plugin: migration_lookup
        method: process
        source: fid
        migration: upgrade_d7_file
      -
        plugin: my_custom_process
        destination: field_media_audio

In my custom process I can save the media and get it's ID via:

$media_id = $audio_media->id();
$arr[] = array(
  'target_id' => $media_id,
  'display' => NULL,
  'description' => NULL
);
return $arr;

But it doesn't seem to populate the destination field.

This is also the case if I just return the ID directly from the process.

When I have done a similar type of migration at that time I did the following steps:

First I created media type Audio in Drupal 8 and it's fields.
Then I exported all audio file details and FID from D7 and created csv file.
Written migration script to import audio into media.

Example:

source:
  plugin: csv
  path: 'csv file path'
  header_row_count: 1
  keys:
    - fid
  type: audio
  constants:
    bundle: audio
process:
  mid: fid
  bundle: constants/bundle
  langcode:
    plugin: default_value
    source: language
    default_value: und
  name: filename
  uid: uid
  created: upload_date
  changed: upload_date
  field_media_audio_file/target_id: fid
destination:
  plugin: 'entity:media'
  migration_dependencies: {  }
migration_dependencies: null

The same csv I used to import data into file entity and written migration script.

Example:

source:
  plugin: csv
  path: 'csv file path'
  header_row_count: 1
  keys:
    - fid
process:
  uid: uid
  fid: fid
  filename: filename
  created: upload_date
  changed: upload_date
  filemime: mime
  uri: uri
destination:
  plugin: 'entity:file'
  source_path_property: filepath
  destination_path_property: uri
migration_dependencies: {  }

After that, I attached the FID to my node field.

process:
  field_audio/target_id: fid

  I am keeping media id, FID of Drupal 8 same as FID of Drupal 7. So we
  can attach the same FID to the node directly.


How to make one field automatically have the date-time of the last change of another field I need to make one field have the date-time of the last change of another field in a drupal 7 content type.  I tried using a computed field but the calculation is complex and I am having trouble.  Is there an easier way to make one field reflect the date of the last change of one other field?
thanks

You may use hook_node_presave to save time in the field

/**
 * Implements hook_node_presave().
 */
 function jysk_reviews_node_presave($node) {
  if ($node->type == 'my_type') {
    if ($node->my_changed_field[LANGUAGE_NONE][0]['value'] != $node->original->my_changed_field[LANGUAGE_NONE][0]['value']) {
      $node->my_time_field[LANGUAGE_NONE][0]['value'] = time();
    }
  }
}


Add an extra to the price of the product Guests can add a meal plan to their cart. They can compose their own formula. Type of sandwich, drink and dessert.

For example the list of drinks is a list of 'taxonomy' terms.
However some drinks can give a supplement. For example the formula costs 1 € more if I take a coke.

I do not know how to do this possibility. I had imagined adding a field in the taxonomy of drinks where we can put the blow of the supplement. But I did not find with Rules how to add this extra to the cart.

Have an idea of how I could do it? Thank you for your help

We've covered this concept before in our "pizza store" tutorial, though it appears the video may not be online any more: https://drupalcommerce.org/videos/tutorials/customizable-products-pizza-store

The steps would be the same, though. I'd basically add a price field to the taxonomy vocabulary and then include the upcharge in the price field for the options the customer is selecting. Rather than using this taxonomy as a product attribute, you'd put it on the line item type as a custom line item field. Then you'd create a pricing rule that evaluates the fields on the line item type to look for a value in the upcharge price field and adds that amount to the unit price of the line item.

This is about as in depth as I can go on StackExchange. To learn how to use any of those particular features outside of getting this recipe, you should find real-time support at a local meetup or else in the Drupal Slack #commerce channel.


Unlock a file download via callback pls I want to control a file access to download, a user will download the file only if a test condition is true. .... there is going to be an execution of a callback url from an external site, and my site will receive a signal then will unlock the file, so I use my site IP address as a test condition... if Server_remote address of my site is = the $external callback IP address, then....unlock the file, how do I proceed on that?

if you have a better idea of implementing this, let me know too.

cheers,

Sounds like a case for

Private file mode on a file field
A custom hook_file_download


Hide field when creating a node How can I hide a field when creating a node, but displaying it when editing a mode?

If I understand your question, I think that you can use a custom module (in this example, the name of the module is test_remove_field) and include the following code:

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

    if (arg(0) == 'node' && arg(1) == 'add') {
    $form['field_test']['#access'] = 0;
    }

}

Note: remember that field_test must be your respective field name.


Calculate shipping cost by weight in Drupal commerce I've set up a commerce website and I'm trying to calculate the shipping rate.

I have 2 shipping rates: a standard rate and a secure rate.
Now I need to increment the price of both these rates by 2 euros if the weight of the total order is over 2 kg's (or 2000 grams since the weight is shown in grams).

I followed Randy Fay's tutorial: http://vimeo.com/33838479 but he multiplies the cost by an amount and this is not what I need.

Another related question (calculate shipping by weight) is a little closer but I do not need a cost per pound.

I've tried to create rules to achieve this, but I really don't know how to do any of this.

I also added this patch in an attempt to get things working properly.

Right now, I can't figure out how all the pieces fit together, I'm sure I have everything I need but I could use some help putting everything together.
Can someone guide me in the right direction?

For Commerce shipping 2.x this is actually pretty simple.

Create a calculation rule.
Set the condition that the weight for the order is above 2 kg (this can be a bit tricky to do in Rules, but there a plenty of guides how to do it. I believe Randy even shows this in the video you linked to.
Select the "add amount to unit price" for a line item and select the shipping line item. You can even select which component to use for this and could create an weight fee price component if you wanted to.

That's it.


How do I edit a complex entity via dynamically loaded AJAX-forms? I have a "profile" entity with a field "education" (to get started). That field contains various input fields that describe the "education". At the moment I have "institution" and "year". I created that field with the Field API in a dedicated module and attached it to my "profile" entity (currently this is a profile2 bundle). The entity form works as expected, the "education" field widget is included and I can add multiple "education" entries. I can view my entity and the fields get formatted, and I can edit my entity and the form widgets get rendered.

--profile entity
----education field
------education a
--------institution a
--------year a
------education b
--------institution b
--------year b

But I do not like the all or nothing approach here. There are going to be many different fields and I want to display the "profile" entity with various "edit" and "add new entry" buttons, which should load the specified field form widget via AJAX. The profile page on xing.com is a good example of what I am trying to achieve.

Is this possible with the fields form widget and Field API alone, or do I have to implement the ajax callback via a menu hook, which returns a form with the needed input fields? Can I even use my "education" field in that scenario or do I have to work with the entity API and database API?

The forms that FieldAPI can build for you automatically are useful but not terribly flexible. If you're interested in building out a really dynamic form, you're probably better off creating your own from scratch and simply creating/saving the entity programmatically once the finished form is submitted.


How to import webform fields on server? I want to import fields of webform on server.Features will not include webform fields.
Is there any module by which I can import webform fields to server?

Webform Import

  Allows delimited data files to be imported as submission (results)
  into webforms.

  This is useful for importing submissions from other systems in to
  Webform. Can also be used to Edit submissions via Export / Import as
  long as the CSV has the SID column filled.

Webform Share

  This is a helper module to prepopulate newly created webforms and to
  export / import webforms between sites.

I think Webform Share module definitely solve your issue.


Filter under condition based on value checkbox of current user profile I use Views 3.x and Views PHP module.

The task. Make Views filtering criteria that would make two different actions, depending on status of checkbox (TRUE or FALSE) of current user's profile.

Description. Logic diagram:

IF checkbox current user == TRUE
THEN display taxonomy terms, tid == New
ELSE display taxonomy terms, tid == array('New', 'Archive', 'Old', ...) // 50+ taxonomy terms

Please help me.

As you can already display the taxonomy terms from the ELSE part of your logic diagram in a View, it is quite easy to achieve what you want with a template file for your View. Find the suitable template here and adapt the code underneath, where I assume that you use views-view-field--YOUR_VIEW-YOUR_BOULEAN_FIELD.tpl.php:

global $user;
if ($user->field_YOUR_BOULEAN_FIELD['und'][0]['value'] == 1) {
  $output = taxonomy_term_load($tid)->name;
}

The variable $tid for taxonomy_term_load() should be the tid of your taxonomy term New.


author_picture twig variable outputting title and bio? Reading the D8 documentation, it says the appropriate twig for displaying the author's picture is:

{{author_picture}}

When I use that, however, I'm getting the author's title, and description as well.  Is there a way to fix that other than CSS fixes to render the other fields invisible?  Or is there something I'm missing?

According to the documentation, {{author_picture}} is showing the node author user entity, rendered using the "compact" view mode.

In other words, you can adapt it by browsing to http://your_site/admin/config/people/accounts/display/compact


How to convert an HTML website to Drupal 7 nodes? I have a website that I want to move to Drupal 7. It is in HTML. I want the content to be in nodes. I don't know much about Drupal and so I need help doing this. I don't want to create a new theme because I want the design to change. I just want the content in nodes. How can I do this in Drupal? Is there a module that can help?

You don't necessarily need a module to add a content to drupal. Just simply create a content of type page and add your content. To help you with formatting, you may want to install the WYSIWYG module to help you with formatting.


Is it possible to make a nested Search API query? I need to make a query in the following form:

SELECT * FROM {index}
...
AND (
  (field1 = value AND field2 = value) OR
  (field1 = other_value AND field2 = other_value)
)
...

But it doesn’t seem to be possible with the existing createFilter and condition methods, as there is no way to pass another filter to a condition for example. Am I missing something, or is this (basic functionality?) really not there?

The AND ((field1 = value AND field2 = value) OR (field1 = other_value AND field2 = other_Value)) IS possible with sub-filters. For anyone else who ends up here trying to sort this out (as I did before working out the correct solution) you can create the above like this:

$filter = $query->createFilter('OR');

$subfilter1 = $query->createFilter('AND');
$subfilter1->condition('field1',value);
$subfilter1->condition('field2',value);

// Add this subfilter to the main filter.
$filter->filter($subfilter1);

$subfilter2 = $query->createFilter('AND');
$subfilter2->condition('field1',other_value);
$subfilter2->condition('field2',other_value);

// Now add the second subfilter
$filter->filter($subfilter2);

// Apply the filter to the query.
$query->filter($filter);


How to get the referenced node id in a webform? I have a webform that is connected to a node in drupal 8. When the webform loads from the node link I need to get the source entity id from url.
How can I achieve that in my custom module? the url is as follows:
https://example.com/en/form/edu-form?source_entity_type=node&source_entity_id=134

I tried the following but I get an error:

 $node = \Drupal::routeMatch()->getParameter('source_entity_id');
 $nodeId = $node->id();

And also this (I tried to get the node id from the webform object)

/** @var \Drupal\webform\WebformRequestInterface $request_handler */
$request_handler = \Drupal::service('webform.request');
$source_entity = $request_handler->getCurrentSourceEntity('webform');
$node_id=$source_entity->id;

Make sure that the webform's source entity id can be prepopulated via a URL and the below code should work using $source_entity->id() instead of $source_entity->id

/** @var \Drupal\webform\WebformRequestInterface $request_handler */
$request_handler = \Drupal::service('webform.request');
$source_entity = $request_handler->getCurrentSourceEntity('webform');
$node_id = $source_entity->id();


Port database queries from d6 to d7 I have inherited a drupal 6 site with some custom modules, all of which are making use of db_query() commands.

Now I'm porting the site with all it's modules to drupal 7, and consequently have to adjust most of the database queries to work with the new DBTNG abstraction layer.

That's fine, but a very tedious task. Is there any automated way to do this, or a module to at least help you on the way?

E.g.: is there some way to turn this

$query = "SELECT * FROM mytable WHERE id=1";
$result = db_query($query);

into this:

$result = db_select('mytable','t')
    ->fields('t')
    ->condition('id',1)
    ->execute()
    ->fetchAll();

Thanks a lot in advance!

The closest thing I know of to take a string db_query() value would be the Query Coder module.

Be aware of its known issues:

Known issues (taken from project page 01-29-2015):

INSERT queries must be specified in form "INSERT INTO table_name (column1, column2, column3,...) VALUES (value1, value2, value3,...)"
Not support "->expression()" conditions for UPDATE queries.
All tables and fields in SELECT query must be specified with aliases, in other (UPDATE, INSERT, DELETE) queries without aliases
Example:
RIGHT: "SELECT * FROM users u"
NOT RIGHT: "SELECT * FROM users"
All combining conditions in SELECT queries must be specified with aliases.
Example:
RIGHT: "SELECT COUNT() AS user_count FROM users u"
NOT RIGHT: "SELECT COUNT() FROM users u".


Superfish menu - how to remove parent sign: "PARENT_LINK >>"? I built my main menu (horizontal) using superfish module.

All the parent links in the menu (that has drop down menu with childs) has a sign.
For example it looks like that: "PARENT_LINK >>"

I really tried to find a solution through CSS files, but couldn't solve it.

How can I remove the ">>" sign?

In your superfish block settings there should be a setting that reads "AUTO-ARROWS:" with a dropdown.

Set that to no (and save) and you shouldn't have any arrows anymore.


What's the usage difference between element_validate and validate hook? From what i've learned today, there are two ways one can go about validating input.

One is the #element_validate field which is passed along the form hook, and the other is the validate hook.

Why use the validate hook if input can be validated with the #element_validate field? Is it a necessity to implement the validate hook in this case?

Or is it a method that should be implemented for complex validation while all simple validation(is number, is date, is url) can be done via the #element_validate option?

@Haider Ali with #element_validate, we can add our own custom validation functions to a field or we can pass the validation functions provided by Drupal, e.g., element_validate_integer_positive(), element_validate_number(), etc.

This #element_validate works only on the field we added it to.

When we want to add custom validation to multiple fields, we add it in form validate hook, so that we do not need to add separate function to each field and call multiple validate functions.


Views exposed form delta My question is ,I have a views named for sale and it is exposed with some fields . I have created other 2 instances of this view using override this feature of views now I want to alter all three views seperately , for this i have used form alter but I am not getting the seperate ids for delta nor the #id for those .how can i alter those delta .

You can achieve this goal via implementing hook_form_alter

Let e.g.

/**
 * Implements hook_form_alter().
 */
function MYMODULE_form_alter(&$form, &$form_state, $form_id) {

    if ($form_id == 'views_exposed_form' && $form_state['view']->name == 'test' && $form_state['view']->current_display == 'page_1') {
       // do your alteration stuff
    }
    if ($form_id == 'views_exposed_form' && $form_state['view']->name == 'test' && $form_state['view']->current_display == 'page_2') {
       // do your alteration stuff
    }
}


Module to create nodes that are lists of other nodes? I'm looking for a way to allow users on my site create a piece of content that is a list of current content. For example a user can create a "favorite articles list" content piece and then select his favorite existing articles that will populate this new content type.
Is there an exisiing module that does this or something similar?

You could probably try the Flag module. It doesn't create nodes, but the idea is pretty much what you're lining out.

  Flag is a flexible flagging system that is completely customizable by the administrator. Using this module, the site administrator can provide any number of flags for nodes, comments, users, and any other type of entity. Some possibilities include bookmarks, marking important, friends, or flag as offensive. With extensive views integration, you can create custom lists of popular content or keep tabs on important content.

  Flags may be per-user, meaning that each user can mark an item individually, or global, meaning that the item is either marked or it is not marked, and any user who changes that changes it for everyone.


How do I change the redirect page for unpublished nodes? It seems that the standard Drupal behaviour for unpublished nodes is this: If a visitor types in a URL to an unpublished node they are redirected to a login page. To -me- that signals that the content is 'there' but they just need credentials.

So: Is there a way to change this behaviour so that if they type in a URL to an unpublished node, literally -nothing- happens? Or perhaps they are redirected to the home page?

Below is my attempt to redirect to home page. The page still redirects to the Access Denied. What I don't get is that if I alter the Rule so that it tests for role 'Administrator' it works -fine-. So apparently an Anonymous user has some special property?

{ "rules_redirect_unpubished_content_url_to_home_page" : {
    "LABEL" : "Redirect Unpubished Content URL To Home Page",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "ON" : { "node_view--bags_cases" : { "bundle" : "bags_cases" } },
    "IF" : [
      { "NOT node_is_published" : { "node" : [ "node" ] } },
      { "user_has_role" : {
          "account" : [ "site:current-user" ],
          "roles" : { "value" : { "1" : "1" } }
        }
      }
    ],
    "DO" : [ { "redirect" : { "url" : "/" } } ]
  }
}

I also tried this:

function jch_utilities_node_view($node, $view_mode, $langcode) {
  if ($node->status != 1) {
        drupal_goto('/some-page');
  }
}

...and again, the 403 fires before this has a chance to run

Finally, I tried hook_init, but yet again, the 403 fires before this has a chance to run.

What am I missing?

The default behaviour is an "Access denied" page, because a visitor hasn't access to unpublished nodes.
It's not possible "nothing appens".
You could use Rules and create a Rule like this:

event: viewing a node
condition: user has role "anonymous"
condtion: node is unpublished
action: redirect to a custom page


How do I automatically update database tables when changing custom entity fields New Drupal Developer here.

I am currently working on a inventory management module for a friend. And I ran into a bit of a snag with Custom Entities in Drupal 8.

I have a custom "Customer" entity content type which stores various bits of information about the customer, first name, last name, a number which we assign each customer, etc...

When I added a new field post-module-install, after running update.php, cron, etc... The new field was never added to the existing SQL table.

I am wondering if there is something I'm missing, like a way to force update the database without having to manually add the new table.

Here is the new field I added.

$fields['l_number'] = BaseFieldDefinition::create('string')
        ->setLabel(t('L#'))
        ->setDescription(t('The Customer\'s L Number.'))
        ->setSettings(array(
            'default_value' => '',
            'max_length' => 8,
            'text_processing' => 0,
        ))
        ->setDisplayOptions('view', array(
            'label' => 'above',
            'type' => 'string',
            'weight' => -7,
        ))
        ->setDisplayOptions('form', array(
            'type' => 'string',
            'weight' => -7,
        ))
        ->setDisplayConfigurable('form', TRUE)
        ->setDisplayConfigurable('view', TRUE);

There are published examples using hook_update_n().


How to send an email to all members of a group after the group is flagged? I use the Group module. I create a flag to mark groups. I wish that when a group is marked, an email is sent to all members of that group. How to do this ?

I created the following rule, but I find nothing in "conditions" in relation to the groups :

{ "rules_email_groupe" : {
    "LABEL" : "Email groupe",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules", "flag" ],
    "ON" : { "flag_flagged_achats_groupes" : [] },
    "DO" : [
      { "mail" : {
          "to" : "contact@mathieulebert.xyz",
          "subject" : "Invitation \u00e0 la vente group\u00e9e de [flagged-group:title]",
          "message" : "Bonjour,\r\n\r\n\r\nle groupe [flagged-group:title], vous invite \u00e0 sa vente group\u00e9e.\r\nElle commencera [flagging:field-flag-date:value] et se terminera [flagging:field-flag-date:value2].\r\n\r\n\r\nCordialement,\r\nL\u0027\u00e9quipe [site:name]\r\n[site:url]\r\n\r\nPour rester inform\u00e9 des nouveaut\u00e9s et b\u00e9n\u00e9ficier de nos offres promotionnelles, suivez-nous sur :\r\nhttps:\/\/www.facebook.com\/S1biosecom\r\nhttps:\/\/twitter.com\/S1biosecom\r\nhttps:\/\/plus.google.com\/+S1biosecom\r\nhttps:\/\/www.pinterest.com\/S1biosecom\r\n\r\nPS : ceci est un mail automatique, merci de ne pas y r\u00e9pondre.",
          "from" : "[site:mail]",
          "language" : [ "flagging-user:language" ]
        }
      }
    ]
  }
}

Any suggestions?

Some more details about my setup:

An overview of the Flags I've defined:

More info about some of my fields (I also use Display Suite):

The fields I defined for my Group Type "Entreprise":

Update: By using the Rules Component included in the answer to "How to pass a Flag field's value to a Rules Component triggered by the flag?" I'm getting closer, but I still have to find out what to do with those 2 date variables I've to pass to that Rules Component, as shown here:

Looking at the rule you included, it seems that your Rules Event is fine. But obviously your Rules Action (to send an eMail) is to only send it to 1 (hardcoded) eMail ID. Read on for more details about how you can get this to work ...

Step 1:

Create a flag (similar to yours) to flag a group. In my case I named it (surprise ...) "Flag a group", and with machine name "flag_a_group" (just replace in what follows this machine name of that flag with your own flag's machine name).

Step 2:

Create a Rules Component "Send eMail to all members of a Group", which you can do like so:

The type of this component is an "Action Set" (no need for any conditions).
Action 1 is to build a list of all the members of the flagged group. It uses "Fetch entity by property", with these additional specs:

Entity type value = Group Membership.
Property value = Group.
Value of the data selector = Group.
limit result count = blank (we do not want to limit the nr of results).
Provided variables = "Group members" (variable label) and "group_members" (variable name).

Action 2 is to iterate (= loop) over each of the members of the flagged group. It uses "Add a (rules) loop", with these additional specs:

The list to loop over = group-members
Current list item = "Member of group" (variable label) and "member_of_group" (variable name).
Sub-action (i) of this Action 2 is to just "Show a message on the site" (while QA-testing this Rules Component), with message type = Status and with a message something like "Group member named "[member-of-group:user:name]" and eMail "[member-of-group:user:mail]" will receive an eMail because of flagging this "[group:group-type]" group titled "[group:title]" and id "[group:gid]" (note the various tokens which might be interesting).
Sub-action (ii) of this Action 2 is to actually send an eMail to the "member_of_group" being processed in the loop, using various tokens similar to those in Sub-action (i).

Here is how the Rules Component looks like (in Rules export format):

{ "rules_send_email_to_all_members_of_a_group" : {
    "LABEL" : "Send eMail to all members of a Group",
    "PLUGIN" : "action set",
    "OWNER" : "rules",
    "TAGS" : [ "group" ],
    "REQUIRES" : [ "rules" ],
    "USES VARIABLES" : { "group" : { "label" : "Group", "type" : "group" } },
    "ACTION SET" : [
      { "entity_query" : {
          "USING" : {
            "type" : "group_membership",
            "property" : "group",
            "value" : [ "group" ]
          },
          "PROVIDE" : { "entity_fetched" : { "group_members" : "Group members" } }
        }
      },
      { "LOOP" : {
          "USING" : { "list" : [ "group-members" ] },
          "ITEM" : { "member_of_group" : "Member of group" },
          "DO" : [
            { "drupal_message" : { "message" : "Group member named \u0022[member-of-group:user:name]\u0022 and eMail \u0022[member-of-group:user:mail]\u0022 will receive an eMail because of flagging this \u0022[group:group-type]\u0022 group titled \u0022[group:title]\u0022 and id \u0022[group:gid]\u0022" } },
            { "mail" : {
                "to" : "[member-of-group:user:mail]",
                "subject" : "eMail notification to group [group:title]",
                "message" : "Hello [member-of-group:user:name],\r\n\r\nyou are a member of the group [group:title] (which is of type [group:group-type]).\r\n\r\nYou are receiving this eMail since user [site:current-user] just flagged this group.\r\n\r\nGreetings,\r\n\r\nPS: contact the site admin by eMail (via [site:mail]) for more details if needed",
                "language" : [ "" ]
              }
            }
          ]
        }
      }
    ]
  }
}

If you have the Rules UI enabled you can simply import the above rule in your own site, no need to tweak anything in it, though you may want to tune the Subject and Message content of the actual eMail as you want (just remember the various tokens you may want to use).

Step 3:

Create a rule "Send a group notification by flagging a group", which you can do like so:

Rules Event: When a group is flagged with the flag from Step 1.
Rules Conditions: none (no need for it).
Rules Action: perform the Rules Component from Step 2.

Here is how the rule looks like (in Rules export format, disabled as shown here):

{ "rules_send_a_group_notification_by_flagging_a_group" : {
    "LABEL" : "Send a group notification by flagging a group",
    "PLUGIN" : "reaction rule",
    "ACTIVE" : false,
    "OWNER" : "rules",
    "REQUIRES" : [ "rules", "flag" ],
    "ON" : { "flag_flagged_flag_a_group" : [] },
    "DO" : [
      { "component_rules_send_email_to_all_members_of_a_group" : { "group" : [ "flagged-group" ] } }
    ]
  }
}

If you have the Rules UI enabled you can simply import the above rule in your own site, after you adapt the flag's machine name to fit yours. Don't forget to enable the rule also.

Step 4:

Add any additional parameters to the Rules Component to pass any relevant extra data from the rule (from Step 3) to the Rules Component (from Step 2). E.g. that date field you added to the flag to be included in the email also (as in your question, like "Elle commencera [flagging:field-flag-date:value] et se terminera [flagging:field-flag-date:value2].".

For more details about this, refer to the answer to "How to pass a Flag field's value to a Rules Component triggered by the flag?". Some more details about how to use that answer in the context of this question also:

looking at the message of the eMail in your rule here, I see 2 tokens that look like dates: [flagging:field-flag-date:value] and [flagging:field-flag-date:value2]. But your screenprints do not show how this "field-flag-date" is defined.
My best guess is that you have 1 field with 2 values, no?. If so, you only need 1 Rules Condition to check "Entity has field", which I think will be "flagging:field_flag_date". And in the Rules Action you should then be able to specify (drill down) to both [flagging:field-flag-date:value] and [flagging:field-flag-date:value2].

Voilà

So here you go: only 3 (robust) modules (Flag, Rules and Group) is what's needed to be able to trigger an eMail of all members of a Group that is flagged by an authorized user (with zero custom code).

True, the actual eMail is hardcoded in the Rules Component (would be nice to transform that into something with 2 extra Flag "fields", to specify during the flagging what the actual Subject and message content of the eMail should be).

VBO alternative

Another solution could be to use a combination of Rules and VBO. That would have the advantage that you get all the power of Views available to filter which group members you want to be eMailed ...


Twitter Cards with Metatag module not working I've got the metatag module installed and enabled. I've also enabled the MetaTag: Twitter Cards sub-module so that it will render meta tags for twitter cards, but I'm not seeing any twitter: metatags in the head at all.

Here is a page on my site:

http://www.inadaydevelopment.com/app/ios/10bii-financial-calculator

Here is the export of the Node configuration, I believe the only thing I changed is that I set a creator value for my twitter account:

$config = new stdClass();
$config->disabled = FALSE; /* Edit this to true to make a default config disabled initially */
$config->api_version = 1;
$config->cid = '1';
$config->instance = 'node';
$config->config = array(
  'title' => array(
    'value' => '[node:title] | [site:name]',
  ),
  'description' => array(
    'value' => '[node:summary]',
  ),
  'og:title' => array(
    'value' => '[node:title]',
  ),
  'og:description' => array(
    'value' => '[node:summary]',
  ),
  'twitter:creator' => array(
    'value' => '@inadaydev',
  ),
  'twitter:title' => array(
    'value' => '[node:title]',
  ),
  'twitter:description' => array(
    'value' => '[node:summary]',
  ),
);

I created a new default metatag for content type App, here is the export:

$config = new stdClass();
$config->disabled = FALSE; /* Edit this to true to make a default config disabled initially */
$config->api_version = 1;
$config->cid = '2';
$config->instance = 'node:app';
$config->config = array(
  'twitter:image' => array(
    'value' => '[node:field_phone_screenshots]',
  ),
);

However, none of the twitter:card meta tags show up at all... what am I doing wrong?

If you´re using the 7.x-1.0-Beta4 version of metatag module (which is the most recent one at the time of writing this answer), you may want to apply the following patch:

http://drupal.org/node/1846978#comment-6764558

(for Unix-like systems only) For applying the patch, just go to a terminal, change the working directory to the directory of the metatag module and try this:

curl http://drupal.org/files/metatag-fix_theme_hook_mismatch-1846978-0.patch | patch -p1


How to disable/turn-off drupal 7 caching permanently, to not to mess with module's operations? I am using Drupal 7 for a real time web application so I cannot afford any caching at all. I also could not find any such option in performance section of Admin Panel. Kindly suggest a method with involving the command line.

UPDATED:

Let me explain the problem further.

Yes theme isn't problem for me. I am new to drupal ad still exploring.

What problem I face is I have written a module which takes CSV file from user, parses and calls moodle web-services to perform operations. What happens sometimes is it seems like that data or code in module is not managed properly and it generates useless/meaningless errors. When I do 'Clear All Caches' at Home » Administration » Configuration » Development; everything gets fixed.

As per Suppress caching (for development), you can add the following to your settings.php file

if (!class_exists('DrupalFakeCache')) {
  $conf['cache_backends'][] = 'includes/cache-install.inc';
}
// Default to throwing away cache data
$conf['cache_default_class'] = 'DrupalFakeCache';
// Rely on the DB cache for form caching - otherwise forms fail.
$conf['cache_class_cache_form'] = 'DrupalDatabaseCache';

I'd recommend you don't just blindly add that, though. Instead, take the time to think what you do need to cache, and what you don't need to cache, and come up with a proper strategy. For example, it's hardly likely that you need rebuild the cache of hook implementations on every single page load, regardless of how highly available the site is.


Incredibly slow speed in admin pages I've been using my 4 year old Mac Book Pro for a development environment for the past few years, and with memory (8 GB) and hard drive upgrades, speed was pretty decent.  I just got a new iMac with a 3.4 GHz quad core processor and 16 GB RAM, and navigating between admin pages is slower than an arthritic snail.  It literally takes up to 1 minute to just change pages in the admin section.  The same pages with the exact same codebase and db change on my MBP is a matter of seconds.  I'm using the same stack setup on both (Mac's Apache, MySQL and PHP via Homebrew).
I have both XHProf and Webgrind set up, but both are disabled (in Devel settings for XHProf and xdebug.ini for Webgrind), so I know that's not what's causing the problem.

To troubleshoot, I turned on the query log in Devel, and it looks like at least one problem is the cache_set function.  There are multiple calls to it, and every time it takes way more time than any of the other functions.  Also, in looking at webgrind, the top function I'm seeing called is php:sleep, which is being called from the lock_wait() function.  According to the comments in the function, sleep should only be called when a request failed to get a db lock.

So, with that info, it appears that I need to tweak my db settings.  Can anyone give me some suggestions on what to change?  I'm a noob to db tuning like this, so this is unfamiliar ground for me.  I'm still searching myself, but any tips would be welcomed.

As a side note, my PHP memory_limit is set to 256MB, so I don't think that's a problem.

Thanks.

After posting this, I was perusing the site, and came across a similar question where someone had suggested disabling the Update module.  I had noticed a lot of calls to the update_xml_parser object in Update module, so it made sense.  I disabled the module and voila! the page change speed went to a couple of seconds.


In Drupal 7 With Latest CKEditor, Media upload button not working If i do install Wysiwyg + CKEditor 3.6.6.1 ( 2013.02.20) + Media module in Drupal 7 then the upload functionality works on ckeditor. Here is my screenshot:

But, if i install CKEditor Drupal 7 Module + Media Module then the upload functionality do not working on ckeditor. Here is my screenshot:

So, how i can enable the Upload section in Media Module? Thanks

I found the solution:
in order to use the upload plugin, the user has to either have the Edit media or the Administer media permission.


Change user ID of existing users When I check my users list via by ID, I get IDs like these:

User: admin
Id: 1
User: second user
ID: 11
User: another user
ID: 21

I want them to be consecutive numbers from 1 to N.

What's my problem? How can I fix it?

While updating the user id is not recommended, for arguments sake, you could reset the user id column in the database.

This is with the caveat that you must also update all referencing tables that use that user id so that those tables also use the new user id value - to maintain "referential integrity". Otherwise, if you do not update all the related user ids, you will corrupt and mixup private user data

For example, the users_roles, file_managed, node, node_revision and other tables...

To match the users with the new uid, you could make an export first of user id to email address. Then you can make another export later and cross-reference the uid from the mail address - to check the new user id match. Keep in mind email address isn't strictly unique in drupal by default.

SELECT uid, mail FROM users;

Backup the users table first.

Then you could do something terrible like:

ALTER TABLE users DROP COLUMN uid;
ALTER TABLE users ADD uid INT(11) NOT NULL AUTO_INCREMENT PRIMARY KEY FIRST;

That will obliterate and regenerate the users uid column.

UPDATE: As clarified by Berdir, curiously the user id field is not an autoincrement field in Drupal 7 by default. So, you may need to remove the autoincrement property after the UID sequence is recreated and convert to normal int with:

ALTER TABLE users MODIFY uid int(10) unsigned;

Note: you will need to regenerate the anonymous user account with:

INSERT INTO users (name, pass, mail, theme, signature, language, init, timezone) values ('', '', '', '', '', '', '', '');
UPDATE users SET uid = 0 WHERE name = '';

If you just want to hide the uid field value, you could instead try a user alias module like:

https://www.drupal.org/project/me


How to use cron to delete nodes of a content type that does not allow deletion by anonymous users The background for this question is here: Delete nodes using Rules and VBO

Summary: a VBO View selects various nodes of a particular content type. A Rules Action Set is instructed to load this VBO View, loop through the entity objects, and delete them. A Rule runs/is triggered on cron and has this Action Set for its action. So, when cron runs the selected nodes should be deleted.

However, the nodes are not deleted, because cron runs as the Anonymous User (uid=0), and the content type is configured such that anonymous users are not allowed to delete nodes of this content type.

How can this be solved so that the nodes are deleted on cron?

Giving anonymous users permission to delete nodes of this content type is not a good solution on this site.

Presumably, cron runs as Anonymous User (uid=0) for security reasons. Any acceptable solution should not undermine the site's security.

A programmatic solution (e.g. code in a custom module) is certainly acceptable if a "code-less" solution using Rules is not possible.

Not sure if you want to consider using it, but the Rules switch user module might be an acceptable compromise. Some details about it (from its project page):

This module adds two new Rules actions:

Switch to another user
Switch back from another user

These actions could be useful when you have an operation that you want an unprivileged user to use but it fails because the user doesn't have sufficient permissions.

Refer to the image on its project page to get the big picture. So if you'd add these 2 Rules Actions at the start / end of your list of existing Rules Actions, and you'd use some user id that does have the right permission, it should work.
As an alternative you could just reuse the relevant code (it's only 76 lines ...) to create your own custom Rules Actions. Similar to what you wrote in your question (= "**...code in a custom module...").  If you make any useful improvements, please consider contributing your changes back to the module's issue queue.
Be aware, however, that this module only has a DEV version for D7 (= not covered by Drupal’s security advisory policy!). This doesn't mean that the module/code is dangerous to use/reference, but it does mean that the code has not been vetted by the Drupal security team.


Batch operation isn't called I have a module with batch operations, this is my hook_menu

$items['some-pretty-url'] = array(
    'title'            => 'Title',
    'page callback'    => 'drupal_get_form',
    'page arguments'   => array('import_form'),
    'access arguments' => array('access content'),
    'type'             => MENU_NORMAL_ITEM,
);

...and this is my batch config

$batch  = array(
    'title'            => t('Lorem ipsum Elit pariatur Duis et elit aute.'),
    'init_message'     => t('Commencing...'),
    'operations'       => $operations,
    'progress_message' => t('Processed: @current out of @total.'),
    'error_message'    => t('An error occurred during processing.'),
    'finished'         => '_import_finished',
);

Batch works pretty good if I have the module definition in the .module file, but if I move the functions to another file the batch simply does not work at all.

$items['some-pretty-url'] = array(
    'title'            => 'Title',
    'page callback'    => 'drupal_get_form',
    'page arguments'   => array('import_form'),
    'access arguments' => array('access content'),
    'type'             => MENU_NORMAL_ITEM,
    'file'             => 'module_definition.inc', //move module to another file
);

$batch  = array(
    'title'            => t('Lorem ipsum Elit pariatur Duis et elit aute.'),
    'init_message'     => t('Commencing...'),
    'operations'       => $operations,
    'progress_message' => t('Processed: @current out of @total.'),
    'error_message'    => t('An error occurred during processing.'),
    'finished'         => '_import_finished',
    'file'             => 'module_definition.inc', //batch functions are here
);

Batch function is not being called even if I set the file argument in the batch configuration.

When you run a batch the URL automatically changes to /batch...at that path, Drupal doesn't know to include your module_definition.inc file. It'll only process the menu hook when the path is 'some-pretty-url', so module_definition.inc will only be included then.

If you move your batch definition into the module file it'll start working, and the file you've told the batch system to find the processing function in will be included as you'd expect, because now Drupal knows it needs to be included.


Language switcher to non-source language not working I have a Branch content type, which also happens to be an Organic Group. I use the Pathauto module to set the URL to:

branch/[node:menu-link]

I have created a content, and a Menu with a menu item which linked to said content. Everything works well up until now.

Next I enabled Entity translation and translated it into two different languages (French and German). Since, with entity translation, the node ID will be the same, I don't need to change the link in the menu item.

When I go to the English (the default and source language) page, I see that in the 'Language Switcher (Content)' block, the other two languages are not linking. However, manually changing the language prefix in the URL worked. So, the page actually exists.

/en/branch/my-branch ----> /fr/branch/my-branch

When I am on the French page, the language switcher shows 'English' as clickable, but German is disabled. The same for the German page.

So it appears that the language switcher doesn't link to non-source languages. Is this a bug? Any pointer are appreciated!

This looks really similar to what is described in Language switcher (content) does not work, which is an issue on D.O that is not yet resolved (status = active).


How to monitor comment / reviews? What is the best way to set up a page on which people could leave reviews, stories etc (I guess like on Yelp?). It would be a bonus if they could upload images, and or it used gravatars etc.

Additionally, we would need to monitor these posts, where the admin would be notified and then could approve them before they appear on the front end.

Drupal ships with that functionality you are describing out of the box, I mean the comments entity. Can be administered -approved, published, deleted etc- under admin/content/comment and are fieldable (admin/structure/types/manage/%node-type/comment/fields) and themable (admin/structure/types/manage/%node-type/comment/display).

Don't forget the comment's API


When an anonymous user hits '/user/login' route, how can I trigger an event? I want to trigger an event when an anonymous user comes to /user/login. I made an event subscriber, but it only fires one time:

namespace Drupal\mymodule\EventSubscriber;

use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\HttpKernel\Event\GetResponseEvent;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Drupal\Core\Routing\TrustedRedirectResponse;

/**
 * Class LoginSubscriber.
 *
 * @package Drupal\mymodule\EventSubscriber
 */
class LoginSubscriber implements EventSubscriberInterface {

  /**
   * Redirect the user before we let them access a login form.
   */
  public function onLoginRequest(GetResponseEvent $event) {
    $account= \Drupal::currentUser();

    $config = \Drupal::config('mymodule.settings');
    $base_url = \Drupal::request()->getSchemeAndHttpHost();
    $site_key = $config->get('eweb_site_key');

    switch ($config->get('mode')) {
      case 'test':
        $url = $config->get('eweb_base_test');
        break;

      case 'live':
        $url = $config->get('eweb_base_live');
        break;

      default:
        $url = $config->get('eweb_base_test');
        break;
    }

    // User is accessing login page, check for active session
    if ($event->getRequest()->getRequestUri() == '/user/login' && $account->isAnonymous() && $event->getRequest()->query->get('loginFailed') == FALSE) {
      $response = new TrustedRedirectResponse($url . '/StartPage.aspx?Site=' . $site_key . '&URL_success=' . $base_url . '/user/netforum/{token}&URL_failed=' . $base_url . '/user/login?loginFailed=true');
      return $response->send();
    }
  }

  /**
   * {@inheritdoc}
   */
  public static function getSubscribedEvents() {
    $events[KernelEvents::REQUEST][] = ['onLoginRequest'];
    return $events;
  }
}

The purpose is that the external site will look to see if this user has an active session, if so, it will redirect back to my site with a token and that controller will handle logging in that user with some logic and user_login_finalize.

However, it is currently only firing once.

I agree with @Berdir, it shouldn't be a problem if the internal page cache stores a response for each query string.

But the issue here is probably that TrustedRedirectResponse is a cacheable response. When you use such a cacheable response you  have to add the correct cache metadata for the content of the response, here a context for the query arg:

  if ($event->getRequest()->getRequestUri() == '/user/login' && $account->isAnonymous() && $event->getRequest()->query->get('loginFailed') == FALSE) {

    $response = new TrustedRedirectResponse($url . '/StartPage.aspx?Site=' . $site_key . '&URL_success=' . $base_url . '/user/netforum/{token}&URL_failed=' . $base_url . '/user/login?loginFailed=true');

    $cache_metadata = new CacheableMetadata();
    $cache_metadata->setCacheContexts(['url.query_args:loginFailed']);
    // or set max-age = 0 instead
    // $cache_metadata->setCacheMaxAge(0);
    $response->addCacheableDependency($cache_metadata);

    $event->setResponse($response);

    }
  }

Then the dynamic page cache will vary by this context. Or add max-age = 0 to disable the dynamic page cache, because caching won't help here much, this is already cached for anonymous users.


Function for showing thumbnails for nodes with imce I am looking for a function, to show thumbnails for nodes.
There are some sized defined in imce and I want to show on of these.

This is my current function which puts out only the large Version of the Image:

if (isset($content['field_image'])) {
    echo render($content['field_image']);
}

What would be a correct Drupal 7 conform function the show the 'medium' thumbnail in the node template?

You can change style output in display fields settings of your content type. This will affect you render.

Also you can use theme_image_style function to set your image style

Url of image you can find in $content['field_image']['und'][0]['uri']


Is there a way to "hard-reset" a module? I'm not sure why, but I am having extreme problems with several modules, but most noticeably, the signup module. The problems that I am having are sudden, and were not there yesterday, so I know it isn't a problem with the design of the module. I have tried patches, but those have caused other problems. Then it occurred to me: why should I have to do anything like that? Shouldn't there be a way to "hard-reset" a module? (ie remove the module and any remnance of it from the drupal database, and start from scratch as if the module was never installed in the first place, and then go and reinstall it) I have tried uninstalling it, deleting the module files, and the re downloading it and enabling it, but I get the same errors when I enable it again. How can I be delete it as if it was never there to begin with so I can start with a clean slate?

This answer reflects my understanding of how Drupal is working.  Anyone with more or different understanding, please speak up, I'd love to know more.

Removing all remnants of a module by uninstalling it works only as well as the code included by the module for cleaning up after itself.  For instance, if it has made a change such as adding tables or otherwise changing the database and does not properly delete the tables, they will remain  there.  Removing the module, should remove much of its potential to cause a problem provided that Drupal core knows it is gone and does not hang up looking for hooks that the module provided.  Have you run 'update.php' in the URL?  This will cause Drupal to update all the connections to the module.  If the module is gone, then it won't make calls to it that cannot be responded to.

The only way to really reset Drupal is to maintain backups.  Make backups before installing any module and at least every day or so during site development. The module Backup and Migrate is a simple way to simplify  site database backups. In addition, it is also a good idea to look into using Git to keep track of your code when developing a site.  Git is basically a unix tool, but there are windows UI versions such as GitGui that are not difficult to learn and put to work keeping track opf your code.


How do I set a product image? When creating a product node for Ubercart, how do I set the product image?

I am using the following code to create a product node.

$node = new stdClass();

$node->name = "Title";
$node->title = $node->name;
$node->body = "Lorem Ipsum";
$node->type = "configurator_product"; //my own product class
$node->created = time();
$node-> changed = $node->created;
$node->promote = 0;
$node->sticky = 0;
$node->format = 2;
$node->status = 1;
$node->language = "en";
$node->default_qty = 1;
$node->sell_price = 55.00;
$node->shippable = 1;

The product node has a field_image_cache field which expects a file (extensions: png, gif, jpg, jpeg). I tried to set this field.

$node->field_image_cache = "Path/to/module/Images/image1.jpeg";
// Results in Fatal error: Cannot unset string offsets in
// path/to/modules/cck/content.module on line 1248

$node->field_image_cache[0]['value'] = "Path/to/module/Images/image1.jpeg";
// No errors, but when viewing the product in store administration there is no image

What is the correct way to set an image for a product?

$img_file = file_get_contents("Path/to/module/Images/image1.jpeg");
  $img_file = file_save_data($img_file, file_directory_path() .'/path2imagefield_folder/image1.jpeg', FILE_EXISTS_RENAME);
  $node->field_image_cache = array(
    array(
      'fid' => 'upload',
      'title' => basename($img_file),
      'filename' => basename($img_file),
      'filepath' => $img_file,
      'filesize' => filesize($img_file),
    ),
  );


drush sql-dump asking for password Whenever I run drush sql-dump it will prompt me for the database password. Is there a way that this can be done automatically? I don't quite understand why its not just reading this from settings.php

When I do a drush status --show-passwords it is shown there.

I ask because I want to script db backups to happen via drush. Any advice? Thanks!

I presume you are using postgres.

psql, the commandline tool that Drush uses to manipulate the database, has no provision to pass a password as a commandline option, so Drush cannot provide it even if it knows what it is.  You may set up a .pgpass file in your $HOME directory to supply the password; it should contain entries that look like this:

localhost:5432:*:www-data:PASSWORD

If you create this file, and insure that it is chmod 600, then psql will no longer prompt for the password.


Alter pagination start index Is it possible to make the pagination system numbering correspond to the page number you are on?

For example, instead of having /media-releases (page 1), /media-releases?page=0 (page 1), and /media-releases?page=1 (page 2) having /media-releases (page 1), /media-releases?page=1 (page 1), and /media-releases?page=2 (page 2).

This seems like a small change, but I believe an important one for usability.

You could do it by implementing hook_url_outbound_alter(), and hook_url_inbound_alter().

With the first hook, you alter the links that are being output from Drupal; you would increase the value of $options['query']['page'].
With the second hook, you alter the links being received from Drupal; you should find the '?page=' string in the URL, and decrease the number after that string.

Keep in mind that $_GET['page'] can be a string like '1,2,4,5,6' if the page has more than one pager. See the code of pager_find_page().

Also, hook_url_outbound_alter() receive the query parameters in $options, while hook_url_inbound_alter() receives just a string for the URL, which also contains the query part.


How do I add a file upload field to user registration page? I need to add a file upload field to user profile, during registration. How can I do this?

In D7 all entities are field-able, and user profile fields can be manipulated in admin/config/people/accounts/fields

and in D6 you can use content profile module


How to create aliases for file paths? In my content type there is a file field; when I upload files, it creates a file path like sites/default/files/uploaded_file.zip.
Is there a way to change this path to something like dl.example.com/uploaded_file.zip? I checked the PathAuto module, but it doesn't seem to have this feature.

I would solve it on an Apache level by using Alias or mod_rewrite.


How to add /admin/people as a tab to a custom menu? In a custom module (association), I ceated views that are accessible thru tabs:

The paths are defined in the views;

Adhérents et personnes -> /association (this one is also defined as a
menu item)
Adhérents -> /association/members
Personnes -> /association/persons

I'd like to add /admin/people as a fourth tab.
How can I do that?

In a custom module (mymodule), create a mymodule.links.task.yml file, and add the following:

mymodule.admin_people:
  route_name: entity.user.collection
  base_route: route.of.your.custom.menu
  title: 'Tab text goes here'

Here's what each part does:

mymodule.admin_people Is the identifier of your menu tab item (the file being *.links.task.yml means its the menutab file)

route_name  is the route the tab points to, and entity.user.collection is the route that corresponds to /admin/people .

base route displays your tab on the specified route. To find the route for your view, download the Devel module, turn it on, and go to "Routes info" to get your route. Usually a view is of the format view.[view_machine_name].[view_display_id], i.e. view.myview.page_1 . Check the "advanced" section of your view's management page for the display ID.

title is the text that will go into the tab.


Setting value of form element from $form_state not working I need to track previous values of a few form elements on a form to detect when they change to invalidate some other options on the page. Essentially, if the value of these fields change a field that controls pagination should reset.

I'm trying to accomplish this with this:

$values = $form_state->getValues();
$form['element1'] = [
      '#type' => 'radios',
      '#title' => $this->t('Element 1'),
      '#options' => [
        // Omitted for brevity
      ],
      '#weight' => '0',
      '#ajax' => [
        'callback' => [$this, 'my_callback'],
        'disable-refocus' => true
      ]
    ];

// dump($values['element1']);
$form['element1_previous'] = [
      '#type' => 'value',
      '#value' => (isset($values['element1'])) ? $values['element1'] : 'none',
    ];

No matter what I do the value of $values['element1_previous] is none. If I uncomment the dump() statement right before it I can see the value of $values['element1'] changing each time AJAX is submitted so the value is there.

If I do something like:

$form['element1_previous'] = [
          '#type' => 'value',
          '#value' => rand()
        ];

I can see $values['element1_previous'] being set to a different integer each AJAX submission. I just can't assign the value of $form['element1'] to that field.

What am I doing wrong? Is there a better way I could handle this?

This:

(isset($values['element1']))

will always return TRUE, since the form element exists, and therefore a value is always passed to the submit hander, even when the value is empty.

You likely want this:

!empty($values['element1'])


How to change widget's icons in the service-links module? I am using the Service links module in Drupal 7.

I tried to change the icons of the links, but only the "general services" links are changed. The "widget services" staying like the original. I saw that is because the icon is coming from an URL and not from a picture on the computer.

How can I change the widget icon?

Is there a patch or an option on the module?

CSS solution for position:
for services widgets (FB, pinterest, linkedin) you can not change images, for General Services (twitter, G+) you can upload your own images.

Here is my CSS code and links appear centered inline.

/* services share links */`
.service-links ul li {
 text-decoration: none;
 display: inline;
 overflow: hidden;
 list-style: none;
 padding-right: 10px;
 vertical-align: baseline;
 float: left;
 }

.service-links li {
 display:inline;
 vertical-align: bottom;
 position: relative;
 }
.service-links .service-links-linkedin-share-button {
top: 5px;
}

.service-links .service-links-facebook-share {
bottom: 5px;
}


Wrap div around results In a content node, I wanted to wrap a div around some results.
For example:
I have this inputs:

Image
Title
Body
Address
Email
Name

And I wanted to have divs like this:
DIV
Image
Title
/DIV
DIV
body
Adress
Email
/DIV
DIV
Name
/DIV

Is this in any way possible?

So, if you create a new .tpl.php for your content type, you can simply print the divs as html, and echo the vars as php.

example:

<?php print $title; ?>

<?php echo render($content['some_field']); ?>

See https://stackoverflow.com/questions/8074485/drupal-7-how-to-render-custom-field for a starting point on pulling specific custom fields, for separation, if needed.

be sure to have a copy of your original node.tpl.php in your theme folder as well, or your node--my-content-type.tpl.php wont work! Again, see https://www.drupal.org/node/17565.


7 - How can I add a region inside another region? I'm surprised I can't find the answer to this online.

I'm currently creating a custom header for my drupal site, so I've created a custom_header region in the .info and a region--custom-header.tpl.php file. Inside the region, I need to add another region.

I've tried to print the other region inside the header region, but nothing is showing up.

Good practise or not aside, how can I do this?

You cant do it that way. But its drupal and it spread true love, so worry not, heres a solution.

Activate php filter under modules
Create a custom block
add <?php print views_embed_view(yourviewname, block); ?>


Is it possible to make the output of a taxonomy reference field with multiple values grammatical? I have a taxonomy reference field that allows for multiple values.

In Views, when displaying this field, I have configured it as follows:

I was wondering if it's possible to somehow configure Views to make this output grammatically:

EXAMPLE 1

Field label: I like:
Values in node: apples, bananas
Views current output: I like apples, bananas.
Desired output: I like apples and bananas.

EXAMPLE 2

Field label: I like:
Values in node: apples, bananas, pears
Views current output: I like apples, bananas, pears.
Desired output: I like apples, bananas, and pears.

I did this in D6 using a CCK field formatter and using the Multiple Group Values.

What you want to do is inform Drupal essentially of a new radio option for "Display Type" that formats the output how you want for the collection of elements.

Again my solution is for D6, but you basically make a field formatter in D7 as well ...

# expose the formatter to ckk using a hook
function MYMODULE_field_formatter_info() {
  return array(
    'compressed_days_formatter' => array(
      'label' => t('Compressed Days'),
      'field types' => array('date', 'datestamp', 'datetime'),
      'description' => t('Displays a listing of days in a month with commas'),
      'multiple values' => CONTENT_HANDLE_MODULE,
    ),
  );
}

# define our theme function
# this turns array('2011-12-03', '2011-12-04', '2011-12-05')
# into say "december 03,04,05 2011".
# and stradles months / years OK by outputting multiple lines.
function theme_formatter_compressed_days_formatter($elements) {
  $output = array();
  foreach (element_children($elements) as $k) {
    $day = $elements[$k]['#item']['value'];
    $ts = strtotime($day);
    $Y = date('Y', $ts);
    $M = date('M', $ts);
    $d = date('d', $ts);
    $dates[$Y][$M][]=$d;
  }
  foreach ($dates as $year => $months) {
    foreach ($months as $month => $days) {
      $output []= $month.' '.implode(', ',$days).', '.$year;
    }
  }
  return implode('<br>',$output);
}

So I haven't done this in D7 (yet) ... but the approach would be the same. You'd just implode most of your elements with commas, and then the last item you tack on your 'and' as-needed.

A hacky-er way to do this is probably with an alter hook in views_pre_render() that examines each result and looks for the last comma and replaces it with an "and". That would work but its more cryptic and sloppy ... I think you really want a formatter here.


Description field for file field I have a file field in a content type. I have enabled the description field for this field. How can I print this description field in twig???

I have a situation here I need to print description field only for one content in views page instead of all the contents on the same page.

For example:
First content has Download
Second content has Download
Third content has field description

Can I put some condition in twig or views field?

To use the description field directly in twig I found an easier way. Simply add the file field in Views, then rewrite the results and add the token for description and file. Now you can use the field directly into twig file.

Otherwise You might have to do good use of Kint or DSM to find out where does description field come up.


I have a site that is translated in English and French - can't change "Home" link in menu My entire Drupal 8 site has been translated except I can't find where to change the translation of the "Home" link. When the site is in French mode (with the /fr) all my menu items show the appropriate French translation except for "Home" which I would like to read "Accueil" when I've switched to French.
Thanks for any insights.

Most likely, the "Home" menu link is coming from the UI text in Drupal Core.

You should be able to enable the "Interface Translation (locale)" module and then obtain .po or .pot files for the respective language (as described on the Drupal.org internationalization page).

Refer to https://www.drupal.org/node/1814954 for information about editing the .po/.pot files and https://www.drupal.org/node/314231 for info about obtaining them.


How to style block on certain pages? I would like to add a  around a menu block I am displaying on a section of my site to style it differently on a certain page only.

How do I do this? Can I target a certain page with a conditional somehow?

If your theme utilizes body classes and you don't need to modify the HTML structure you can simply do:

body.page-node-1 #block-block-1 {
  /* styles goes here */
}

Replace "1" above with the ID's for the node and the block.


How to set up APC on Drupal 7 with httpd + fastcgi? Can you recommend how to set up APC for a site running Drupal 7 on apache2 with fastcgi ?

I got to the point where apc.php shows only one file cached that is apc.php itself.
I cannot see if APC cache is used at all when accessing Drupal nodes.

PHPinfo shows:

Server API  CGI/FastCGI

apc

APC Support enabled
Version 3.1.9
APC Debugging   Disabled
MMAP Support    Enabled
MMAP File Mask  /dev/zero
Locking type    pthread mutex Locks
Serialization Support   php

Directive   Local Value Master Value
apc.cache_by_default    On  On
apc.canonicalize    On  On
apc.coredump_unmap  Off Off
apc.enable_cli  On  On
apc.enabled On  On
apc.file_md5    Off Off
apc.file_update_protection  2   2
apc.filters no value    no value
apc.gc_ttl  3600    3600
apc.include_once_override   On  On
apc.lazy_classes    Off Off
apc.lazy_functions  Off Off
apc.max_file_size   1M  1M
apc.mmap_file_mask  /dev/zero   /dev/zero
apc.num_files_hint  1024    1024
apc.preload_path    no value    no value
apc.report_autofilter   Off Off
apc.rfc1867 On  On
apc.rfc1867_freq    0   0
apc.rfc1867_name    APC_UPLOAD_PROGRESS APC_UPLOAD_PROGRESS
apc.rfc1867_prefix  upload_ upload_
apc.rfc1867_ttl 3600    3600
apc.serializer  default default
apc.shm_segments    1   1
apc.shm_size    30M 30M
apc.slam_defense    On  On
apc.stat    On  On
apc.stat_ctime  Off Off
apc.ttl 7200    7200
apc.use_request_time    On  On
apc.user_entries_hint   4096    4096
apc.user_ttl    7200    7200
apc.write_lock  On  On

cgi-fcgi

Directive   Local Value Master Value
cgi.check_shebang_line  1   1
cgi.fix_pathinfo    1   1
cgi.force_redirect  1   1
cgi.nph 0   0
cgi.redirect_status_env  no value   no value
cgi.rfc2616_headers 0   0
fastcgi.logging 1   1

I would like to use boost + memcache + apc eventually but currently I have a problem enabling apc on httpd with fastcgi.

We finally managed to set this up properly.

Apc works fine for multiple processes with apache/2 + php 5.3.x + php-fpm + fcgi in FPM/FastCGI mode.

PHP 5.3.x is configured with following options
--enable-force-cgi-redirect
--enable-fastcgi
--enable-fpm


CKEditor simple image upload functionality I'd like to have a simple, one-click, image upload functionality with CKEditor. I'm using D6 and CKEditor 3.6.1. I do not want a server file browsing functionality, only uploading images from the user's own computer.

I've done a thorough search on this subject and have tried different suggested approaches. It seems like the solution that best suits my needs is installing the IMCE module and the CKFinder plugin for the CKEditor module. So I did just that, and followed the installation instructions found here: http://drupal.org/node/738092

The uploaded image manages to get to the destination folder on my server, but when I open CKEditor's 'Image properties' dialog and hit the 'Send to the server' button, nothing changes on the UI.

What I wish to happen is for CKEditor to close the 'Image' dialog and insert the uploaded image into the textarea.

Here are some screenshots to better explain my situation:

- Uploading a file from my desktop

- Expected result - 'Image' dialog automatically closed and image inserted to textarea

- Actual result - 'Image' dialog stays open and nothing changes

Does anyone ever implemented an image upload functionality this way? Is there a better way to get what I want?

If you ever get to D7, this module does exactly what you're looking for:

One Click Upload module

  Button for BUEditor and CKEditor which allows upload files in one click.

  Features

  Upload images and insert into editor image code
  Upload files and insert into editor link code
  Multi-upload files and images
  Integration with image styles
  Editable html templates


Get a 404 page already when calling with trailing slash My SEO agency complains about the following:

Let's assume the URL http://example.com/foo leads to a non-existing page. Then Drupal correctly responds with a 404.

Now,

if I call http://example.com/foo/ (with a trailing slash),
Drupal first redirects to http://example.com/foo (without trailing slash)
and only then responds with 404.

The SEO agency says that this way I loose "crawl equity".

The desired behaviour would be that

I call http://example.com/foo/
and immediately get a 404 page.

What is the best way to achieve this?

Most likely you have a written rule htaссess 301 redirect. Possibly it is written in the code or via modules.


Limit access to a view based on profile field I'm trying to figure out the best way to limit access to a view based on a boolean field in the user profile. If the user checks the box for that field they will have access to the view, otherwise not.

I could use views_php for the access control of the view. Would that prevent the view from getting cached with views caching?

Or should I use a hook_form_alter() to check for the value each time the profile is saved and then add or remove from a special role?

I do this on my site using Rules.  I use the Data comparison condition on profile save and then add or remove the role as necessary.  If you do decide to use the Rules module, make sure to add a NOT Data comparison as well to make sure the Rule doesn't get called multiple times (I had problems with this).

Example:

Event: After updating an existing user account
Condition: NOT Data Comparison: account-unchanged:field_mycheckbox is Yes
Condition: Data Comparison: account:field_mycheckbox is Yes
Action: Add a role


Taxonomy widget - select maximum level depth I want to make a taxonomy field widget that allows me to select the maximum level depth of the taxonomy vocabulary. This widget should be used in node forms and the value (selected term) should be saved in the node object.

What is the best (Drupal) way to approach this?

I don't want to use hierarchal select.

Content Taxonomy is what you're looking for. It extends the default select list widget and adds a maximum level depth.


How can I inspect $element variable in theme function? I would like to change formatter of Field Collection Table, so that class added to a table row corresponds to a value of field of field collection item. As a first step, I would like to inspect theme function of that module. However, if I modify it to:

function theme_field_collection_table_multiple_value_field($variables) {
  $element = $variables['element'];
  $header = array();
  $cells = array();

  // Order field widgets by their widget weight.
  $instances = field_info_instances($element['#entity_type'], $element['#bundle']);
  uasort($instances, '_field_collection_table_sort_items_widget_helper');
  foreach ($instances as $field_name => $instance) {
    if (empty($element[$field_name])) {
      continue;
    }

    $header[] = _field_collection_table_get_title($element[$field_name]);
    $cells[] = array('data' => $element[$field_name]);

    // Remove the original field to prevent duplicate printing.
    unset($element[$field_name]);
  }

  $element['field_collection_table'] = array(
    '#theme' => 'table',
    '#header' => $header,
    '#rows' => array($cells),
    '#weight' => 0,
  );

  $element['#sorted'] = FALSE;
  dpm($element);
  return drupal_render_children($element);
}

no krumo element is displayed. I cleared both opcache and drupal cache several times, but the problem persists. Also, I did deliberate error to make sure, that theme function applies. Do you know, what am I doing wrong?

If dpm($element) isn't returning output at that stage, you can log the data instead (temporarily) to the watchdog log.

e.g:

watchdog('dev', '<pre>' . var_export($element, 1) .'</pre>');

You can then view it at Admin > Reports > Recent log entries


Product catalog site (+ Store) - what strategy? I'm creating a site in Drupal 7 with a 200-item product catalog. Currently the products have only informative pages for which I created a custom content type and taxonomy, but at some point, when the site owner gets ready, I may have to launch a store.

Taking into account that the only store available for D7 is Drupal Commerce in its beta (is my research correct?), I was wondering what strategy you would choose:

a) install beta of DrupalCommerce only for product information pages, turn off the shopping cart, just to save yourselves work later (migrating the product pages content)

b) go on populating the custom content type pages and wait for the DrupalCommerce to go into stable release?

c) split the site into two domains - informative (www.example.com) and store (store.example.com). This solution scares me off a bit in that it'd require maintaining about twice as much content in parallel - this always smells of errors and problems... OTOH, I could employ a Drupal-independent solution, such as PrestaShop.

Has anyone used the DrupalCommerce beta? Does it cause much trouble at this point?

Looking forward to hearing your insights.

Artur

Drupal commerce is not your only bet for a shopping site for Drupal 7, but it is the best one.

At this time of writing commerce is on beta-4 but it wont be long before rc-1 will be released. It's very stable considering that it's a beta release, so I wouldn't worry too much about that.

Talking about personal experience I have launched one site on commerce, which was launched when commerce was still in alpha, most likely the first production on commerce. So I have a good firsthand experience with running commerce in a production environment. Other than the pain of having to do my own upgradings from alpha to beta, commerce has been running very stable without any major problems so far.

Taking into account the above. I would personally go with option a):

Install commerce
Create products
Create nodes with products reference to display the data
Don't display add to cart form anywhere.

You might need to use a bit of time to setup commerce and products types, but it would allow you to quickly and easily convert the catalog to an actual shop and that save you a lot of headaches later on.


How can I allow/facilitate users to upload images and create a slideshow? I want the users of my page (who will not be especially technical) to be able to upload multiple images which other users can comment on etc.

I'm thinking of using the Drupal core module 'book' to create the parent page, which would display the images stored in its children.

Is it possible to do this dynamically so that the users do not have to create a new content type for each of the slideshows?

Sure you "could" use the 'Book' module with the child pages as you described. However that is not really going to help your users a lot. Except maybe from easily navigating from the images posted by 1 user to another user (if that is what you also want to consider)? And it does not really help I think for reducing the number of nodes to be created.

What I think is more important to consider are these items:

Add an image field to the content type you are considering using, in which you allow "multiple images". That way a single user may add all their images to "their" node. And with "permissions" it's straight forward to ensure that they can only edit their "own" node (e.g. to add more images later on). And at the same time avoid they (accidently?) add "their" images to a node of another user.
Use the Field Slideshow module to actually create a slideshow from these images.
To further simplify (for your users) the upload process of images, you may also want to consider using the IMCE module, which is an image/file uploader and browser that supports personal directories and quota.

With only these 3 items you should get pretty close to what you're looking for I think, no?


Compare fields and send a message I want to compare a term_reference field in a node with a term_reference field in a user profile. If certain terms match, I want to message the users with those matching terms. Is this something that could be achieved with rules?

EDIT:
This is my code so far:

dpm($node->field_project_resources);
dpm($node->field_project_resources['und']['0']['tid']);

$users = entity_load('user');
$arrayuids = array_keys($users);

$query = new EntityFieldQuery();
$query->entityCondition('entity_type', 'profile2')
    ->propertyCondition('uid', $arrayuids, 'IN');

$profile = $query->execute();

$arrayofpids = array();

foreach($profile as $obj){

     foreach($obj as $objinner)
     {
     array_push($arrayofpids, $objinner->pid);
     }

}
$profile2s = profile2_load_multiple($arrayofpids, FALSE);
foreach($profile2s as $obj){dpm($obj);
    foreach($obj as $objinner){
            if(is_array($objinner)){
           foreach($objinner as $i)
           {dpm($i);
                   foreach($i as $n)
                         {

                        }
           }}
    }
}

I want to compare for each value in array field_project_resources result with the profile2 array field of field_resources for each user and then return an array of users that have matching fields.
I am quite new to this and I would appreciate some help.

Yes, definitely something with rules together with http://drupal.org/project/mimemail (I would also recommend http://drupal.org/project/phpmailer together with mimemail), if you want to mail them, or use the https://drupal.org/project/messaging framework and notifications or similar.

You can use rules scheduler to do this on a schedule or use rules events such as "After saving a new term" to trigger the lookup when a term is saved. The tricky part is the conditions/actions of looking up.

You can use the data comparison condition together with a php evaluation to lookup the user profile/term and then generate an action of sending a mail.

Or you may need to use fetch entity by id/property depending on what you have available to the situation to load the node and the same for the user profile, and then compare those results in a php custom action.

The last option is to use views bulk operations to do the lookup for you and then load the list in the rule using the views bulk operations action.


shorten input text size and maxlength with exposed filters I use Drupal-7.14 and Omega sub theme.
I have a view of my content type with exposed filters.
When focusing input tags, HTML output is like this:

  <form action="/searchedlist" method="get" id="views-exposed-form-searchedlist-page-1" accept-charset="UTF-8">

               BANGO

                    <input type="text" id="edit-field-bango-value-min" name="field_bango_value[min]" value="" size="30" maxlength="128" class="form-text" />

                    And
                    <input type="text" id="edit-field-bango-value-max" name="field_bango_value[max]" value="" size="30" maxlength="128" class="form-text" />

Please show me how to change the input text size from 30 to 10 and its maxlength from 128 to 20.

for other startup people

I've reached the solution.

# mkdir sites/all/modules/mymodule
# cd sites/all/modules/mymodule
# vi mymodule.info
# cat mymodule.info
name = mymodule
description = mymodule for dummy
package = mymodule
files[] = mymodule.module
version = "7.x-1.0"
core = "7.x"
# vi mymodule.module
# cat mymodule.module
<?php
function mymodule_form_alter(&$form, &$form_state, $form_id){
  if($form_id == "views_exposed_form"){
    //dsm($form); // print $form array on the top of the page
    if (isset($form['field_bango_value']['min']) && isset($form['field_bango_value']['max'])) {
      $form['field_bango_value']['min']['#size'] = '10';
      $form['field_bango_value']['max']['#size'] = '10';
      $form['field_bango_value']['min']['#maxlength'] = '20';
      $form['field_bango_value']['max']['#maxlength'] = '20';
    }
  }
}
# wget http://ftp.drupal.org/files/projects/devel-7.x-1.3.tar.gz
# tar xzf devel-7.x-1.3.tar.gz
# mv devel modules

Admin > Modules

Check the boxes on mymodule and Devel,then Save.

Admin > config > development > performance

Clear caches.

Browse hostname/myview

Finally, HTML input tags says:

<input type="text" id="edit-field-bango-value-min" name="field_bango_value[min]" value="" size="10" maxlength="20" class="form-text" />
<input type="text" id="edit-field-bango-value-max" name="field_bango_value[max]" value="" size="10" maxlength="20" class="form-text" />

You should be able to use a regular hook_form_alter and has a great answer already, check it out and it should answer your question.


Where is the Rules Evaluation Log? Where is the Rules Evaluation Log?  I need to view it but I can't find it.

There are typically 2 ways of Rules debugging, as further detailed below.

1. Rules Evaluation Log

Within the Rules settings (located at admin/config/workflow/rules/settings in your site), experiment a bit with the debugging facilities that come with the Rules module. More specifically, within the "debugging" section of that page, you should change the value of "Show debug information" to "Always". Be aware also of what's mentioned at the end of that same debugging section, i.e.:

  Debug information is only shown when rules are evaluated and is visible for users having the permission Access the Rules debug log.

So double check (at admin/people/permissions#module-rules) that for the userid you're using you've granted the required permission.

Example of a Rules evaluation log

Here is an example of such Rules Evaluation Log:

URL to view the Rules Evaluation Log

There is not really "an" URL you can go find this log. Such Rules Evaluation log only gets displayed whenever "some Rules event happens" (for a rule that is enabled, disabled doesn't count ...). Like in my sample screenprint: that log is shown right after some user performed a login (because in this site there was an enabled rule that used event "User logged in"). Also, assume you just have 1 enabled rule, using a Rules Event X, then you need to "make something happen" in your site that triggers that Rules Event (if the event is not triggered, then you wouldn't see any logging data).

2. Rules Action to display a value (using devel)

You may also want to (temporary) enable the Devel module, so that you can (temporary) add a Rules Action like "Display a value". That's not within Rules Conditions (as in your question), but if you add that as your first Rules Action, then you can be sure that the values displayed are identical to the value of these variables at the end of the Rules Conditions.

Obviously, make sure that there are no Rules Conditions that would prevent the rules Action(s) from being executed (if needed temporary remove such Rules Conditions).

3. Resources

Community documentation: Tools for testing & debugging Rules contains the official community documentation about Rules debugging.
Video tutorial: Refer to the (great!) video "Debugging rules configuration" for way more details about these 2 debugging variations.

PS: I'm assuming this question is about D7.


How to update payment status inside an order? I am trying to update order status and payment status depending upon the value we get in a variable called $payment_status.  I am able to update order status but I am unable to update payment status inside that order. I am getting an error "The website encountered an unexpected error. Please try again later.
Error: Class 'Drupal\commerce_order\Payment\Payment' not found" The code I used is as follows:-

//update order status based on payment status
  $order = \Drupal\commerce_order\Entity\Order::load($order_id);
  // dpm($order);
  if($payment_status === 'payment.captured' ){
    $order->set('state', 'completed' );
    $order->save();
    $payments = \Drupal\commerce_order\Payment\Payment::loadByProperties(['order_id' => $order_id]);
      foreach ($payments as $payment)
      {
        $payment->setState('completed')->save();
      }
  }
  else{
    $order->set('state', 'pending' );
    $order->save();
  }

How to solve this?

Please change the code from

 \Drupal\commerce_order\Payment\Payment::loadByProperties(['order_id' => $order_id]);
        TO
 \Drupal::entityTypeManager() ->getStorage('commerce_payment') ->loadByProperties([ 'order_id' => [$orderid], ]);


Drupal 7 same token showing twice in token available admin page I have a simple question to understand if I made a mistake (during my migration from Drupal 6 or so ...).

In admin page, when I can use token in fields, in "Browse available tokens." popup I'm seeing same token twice, once with "_", once with "-"

Eg :

Nom [current-user:field_last_name]  Texte field.
Nom [current-user:field-last-name]  Field "field_last_name".

(here the real field machine name is "field_last_name")

Did I miss something ? Tokens are working good but I don't know is this behaviour is normal ?

Regards.

This is normal behavior and nothing wrong.

The token with '_' gets generated by 'token' module, and
the second with '-' gets generated by 'Entity API' module (entity tokens).

Any one can be used.


formBuilder()->submitForm() not working In Drupal 8, I'm getting an exception 'InvalidArgumentException' with message 'The form argument system_theme_settings is not a valid form.'

The story is: I can't add custom colors to my installation profile because of the color module not setting the configuration until a form submit on the theme's settings is called, so I got the form_id with hook_form_alter(), added a custom form_submit handler and serialized the form_state variable into a file (because form_state was gigantic and I had no idea how to find the useful values in there) and loaded it with unserialize() in my installation profile.
(Kind of reminiscent of this issue:
https://www.drupal.org/node/1963922)

Then, I ran:
\Drupal::formBuilder()->submitForm('system_theme_settings', $form_state_variable);

And was told by Drupal that 'system_theme_settings' isn't a valid form.  But, how can this be true, if I already added a custom form submit handler to this form using this very form_id?

If I'm not supposed to use a form_id, but rather a specific function or something like that, where should I look to find this function?

The api documentation for FormBuilder::submitForm is not exactly correct. The $form_arg argument no longer can be a function, but it refers to the class name or form object of the form. In this case ThemeSettingsForm is the class corresponding to system_theme_settings per its getFormId() method return value.

However I am not sure that calling FormBuilder::submitForm will work from your question because form state may not be valid for the system theme settings form. It may be better to track down what specifically color module is requiring in order to set/save the necessary configuration instead of trying to mock form submission.