How to filter by two fields using a single exposed filter in Views? I have a view listing nodes. I added 2 exposed filters. One is Content: title and the other is Content:Body. Then I have 2 input fields to enter some keyword to do searchs.

I need to have just one field and do the search in both fields: title and body. Can I do this?

I think you could either:

Use the Global: Combine fields filter which allows you to choose two fields (out of those already added to the display as a normal field) to filter on. The filter can be exposed, its operator changed, etc. like normal. Views warns This filter doesn't work for very special field handlers.
Use the Search: Search Terms filter. This uses search.module's data to do the query (check out the search index build mode).


Calculate tax before discount I have created a rule in Drupal with the following conditions/actions.

With this rule, I give 10% discount on a specific product type, but the tax (21% in The Netherlands) is still calculated on the old price (without the discount).

For example, without discount I get the following.

Sub total €28.93
Tax €6.07
Total price €35,00

With the discount, I get the following.

Sub total €25.43
Tx €6.07
Total price €31.50

I tried to change the weight of the rule, but it didn't help.

I used the default tax module of Drupal Commerce and all the default settings. Is there something I can do about it?

I tried also the Commerce Discount module, but with the same behavior.

PS: Prices on this website are shown included of taxes.

After the patch, it is still not working. The Tax should be the following. (The product price is €0.90 with 10% discount; normally the price is €1.00 without the discount.)

€0.74 (excluded tax)
€0.16 (tax)
€0.90 (total)

I think it is not possible, because Drupal Commerce calculate the prices/taxes before the discount. I had the same issue a while ago.


How to limit edit permission to individual values on a multi value field? If I have an image field with multiple values, for example, how could I let users create edit and delete only their own images (i.e. that they upload and not anyone else)? I tried the field permissions module but it does not limit individual values of nodes.

I think your goal is to create a gallery which different people can upload their own images into it and then modify those images. Reaching this goal you can create a gallery content type with multiple images and a taxonomy or a referenced field so you can relate two galleries owned by two different people and in this case any user can modify, create or delete his/her own gallery. At the end you can create a global view for all images using Views module so all images posted by all users are listed inside and can be categorized using the reference field you have added.

If you want all images being uploaded to same content then you must use another approach which needs the ability of drupal module development, first of all you must create a new field type using drupal Field API. This field type must contain a image subfield and a user reference so you can have both image and its uploader in a same place. Then you can use hook_field_access to restrict access to field values in different operations.


Migrating files from local source are not found I am migrating from Drupal 7 to Drupal 8 (8.6.9).
Both the Drupal 7 and the Drupal 8 site currently run on my local machine.
The migration of the public files goes well using:

source:
  plugin: d7_file
  scheme: public
  constants:
    source_base_path: 'http://www.oldsite.com/'
process:
  fid:
    -
      plugin: get
      source: fid
  filename:
    -
      plugin: get
      source: filename
  source_full_path:
    -
      plugin: concat
      delimiter: /
      source:
        - constants/source_base_path
        - filepath
    -
      plugin: urlencode
  uri:
    -
      plugin: file_copy
      source:
        - '@source_full_path'
        - uri
...
destination:
  plugin: 'entity:file'
migration_dependencies:
  required: {  }
  optional: {  }

The private files are not found using the site URL as source_base_path  so I switched it to /absolute/path/to/private. However, the files are still not found.

When I check the migration messages it says File '/absolute/path/to/private/filename.png' not found for each private file. However, if I copy the path and search for the file in the terminal, it's there so the path is correct.

At first I thought it was due to spaces in the filename but it also happens with files without spaces. For completeness: there are no spaces in the path to the private directory.

Note: not all files are images, many are PDFs.

When searching for this problem I find configurations like above, so I'm out of options.

Turns out the problem was not in the Drupal code but simply a path issue. I run the Drupal 8 site inside a DrupalVM server and the migration is done relative to THAT root. So '/absolute/path/to/private/filename.png' is not with respect to the root of my computer, but with respect to the root of the DrupalVM.

The problem is solved by adding an extra synced folder to the DrupalVM that points to the Drupal 7 root:

vagrant_synced_folders:
  - local_path: /path/to/drupal8/root
    destination: /var/www/drupalvm
    type: nfs
    create: true
  - local_path: /path/to/drupal7/root
    destination: /var/www/drupal7
    type: nfs
    create: true

Then restart the server:

vagrant halt
vagrant up

In the migration file the source path becomes:

constants:
    source_base_path: '/var/www/drupal7'

Now the files are found.


Running a customized cron task very often I have a custom cron task that needs to be run every ten minutes.
The task connects to remote servers to retrieve some data and update the drupal db.

In order to achieve that I have to execute drupal cron at least every 10 minutes (I do it via crontab on a GNU/Linux system), so my questions are :

Is it overkill to run drupal cron so frequently ?
What are the main tasks that drupal cron is executing ?
I understand that every task run within cron must check the last time it was executed so it is not run too frequently, is it generally understood this way ?

Is it overkill to run drupal cron so frequently ?

The answer to that is...it depends. If your cron task needs to run every 10 minutes, then no, it's not overkill. If it doesn't, then it is overkill. What you probably need is something like Elysia Cron, which lets you schedule cron jobs for specific modules on a an individual basis. That way you can run your custom labour-intense function as often as you need to without invoking the rest of the system's cron hooks.

  What are the main tasks that drupal cron is executing ?

There's a list of core hooks that will be invoked on a cron run here, I don't think listing each one of those here would be prudent (there are 16 of them) - suffice say to say quite a lot happens; the caches are flushed which is probably a point of interest.

Bear in mind that many contrib modules also implement hook_cron(), so if you want an exhaustive list of functions that are invoked on cron you'll need to go through those files manually.

  I understand that every task run within cron must check the last time it was executed so it is not run too frequently,

The must part of that is not true, there's no 'rule' for whether a task run on cron needs to check its last run time. There are plenty of situations where such a mechanism would be advantageous, but you absolutely don't need to do it. Again it depends on what each task is actually doing.


How do I create a ruleset component? I would like to create a custom ruleset component like the one described in  How to automatically generate multiple aliases for one node?

That answer is for Drupal 7, and I am using Drupal 8. When I go to Rules/Components, none of the plugin options that I see in screenshots of Drupal 7 appear to be available (e.g. rule set, condition set, action set). Basically, the Components tab looks nothing like the one found in Drupal 7, so it's unclear to me how to create a ruleset. I'm not a module developer, but when I look through the module folder, I see a folder named Plugins/RulesExpression which contains files that seem to correspond to these component plugin types. Is there something I have to do to enable them to be available in the administration pages?

The documentation for Drupal 8 Rules is basically empty. The only documentation I found is for contributing developers; it doesn't seem there is any updated documentation for administrator users of the module, and I have searched far and wide for any insight on this and found nothing.

While Rules components may successfully be created and used programmatically, as of Rules 8.x-3.0-alpha4 there is only minimal support for doing this in the UI. Adding these UI features is part of the last meta task needed to be completed before a beta version of Rules is released. You can discover the current status of these UI porting issues by reading the Rules issue queue at https://www.drupal.org/project/issues/rules


Contextual filters in Views - Filter by taxonomy I have a View with contextual filters. I filter by Content Has Taxonomy ID. The problem is that the website is multilanguage, and the name of the taxonomy may change, have commas, non-common characters (cyrillic, for example), be too long and could be, in fact, different from the friendly URL.

My idea (which I have used in other projects) is to have the URL in this way:

www.example.com/en/products/sport-shoes

or

www.example.com/ru/продукты/спортивная-обувь

and from the URL, retrieve the parameters with

$url_arr = explode("/", $_SERVER['REQUEST_URI']);

In this case, $url_arr[2] would contain the taxonomy description(sport-shoes or спортивная-обувь in Russian), which is what I look for. The taxonomy name could be completely different, for example: "Sport shoes, complements, and other wearables".

Then I make a query to the database with db_query() searching by description field ( or better use a EntityFieldQuery), get the ID (the product will be associated to both taxonomy terms and I only need one), and pass the ID to the contextual filter, instead of letting the module Views to guess the ID from the URL (Term name converted to Term ID).

Is this procedure (which works) too convoluted? Is there a simpler and elegant way of doing this?

Retrieving the term ID by name has one considerable downside: If term names change, links may become invalid.

A safer option would be the use of aliases. For each of your terms, generate a URL alias per language that points to the internal view path (containing the term IDs). That way your view won't require custom logic to retrieve the term ID.

You could then expand on that approach and use e.g. the Redirect module to keep track of alias changes.

If you still want to stick to your approach, keep in mind that Drupal provides various functions to deal with paths and arguments. In your case, that one-liner can be simplified to:

$url_arr = arg();


Search API Saved Search tokens output [search-api-saved-search-result:url] has cron.php in urls I'm using Drupal 7 : with Search API

In this I'm using the token [search-api-saved-search-result:url] which I take it should output the Url of the relevant nodes.  The Urls are correct except the have 'cron.php' text in them .  ie 'www.example.com/cron.php/node/1234' ; making them not work.

this is the code in the Search API module.

case 'search-api-saved-search-result':
  $d = $data['search_api_saved_search_result_info'];
  if (!empty($d['search']) && !empty($d['entity'])) {
    $search = $d['search'];
    $index = $search->index();
    $item = $d['entity'];
    foreach ($tokens as $name => $original) {
      if ($name == 'id' && ($id = $index->datasource()->getItemId($item))) {
        $replacements[$original] = $id;
      }
      elseif ($name == 'label' && ($label = $index->datasource()->getItemLabel($item))) {
        $replacements[$original] = $label;
      }
      elseif ($name == 'url' && ($url = $index->datasource()->getItemUrl($item))) {
        $url['options'] += $url_options;
       $replacements[$original] = url($url['path'], $url['options']); // $replacements[$original] = url('http://www.rcnbulletins.com/', $url['options']);
      }
    }
    if (($url_tokens = token_find_with_prefix($tokens, 'url')) && ($url = $index->datasource()->getItemUrl($item))) {
      $replacements += token_generate('url', $url_tokens, $url, $options);
              }
  }
  break;

I'm wondering if this is a bug or something i've missed in admin.

Here is the solution .  thanks to these answers Formatting output of token

/**
* Implements hook_tokens_alter().
*/
function rcn_tokens_alter(&$replacements,  $context){
  // fix urls being outputted with cron.php in the link.
  if(isset($replacements['[search-api-saved-search-result:url]'])){
  $url = $replacements['[search-api-saved-search-result:url]'];
  $newurl = str_replace("cron.php/", "", $url);
  $replacements['[search-api-saved-search-result:url]']  =   check_plain($newurl);
  }

}


Site looks different under SSL I have a strange problem... I just uploaded our new Drupal site. Everything looks great - until we enabled SSL. When SSL is enabled, the look-and-feel of the sight changes slightly. The fonts change in a few places and the width is off on the main pane. It's as if something in CSS is getting messed up. But I can see that the CSS files are being loaded.

I disabled caching and Page Speed, thinking perhaps that was the issue.. but disabling that didn't fix the problem.

I'm really at a loss here. Does anyone have any suggestions on how to tackle this issue?

I'm running Drupal 7.24 on an Apache web server.

Thanks!

If you have enabled SSL, it may happen that some browsers may block the resources that are not using https:// in their URLs. While Chrome and Firefox manage to work fine in some cases, Internet Explorer has a strange behaviour.

I would suggest you to check if external scripts, images, or CSS styles  you are using in you website use http:// in their URLs, and change them if they don't use https://.


How to tell Drupal to use tpl file from my module? I have a custom module and placed comment.tpl.php here:

/sites/all/modules/mymodule/comment.tpl.php

But Drupal is not looking for that file in my custom module directory. How can i make it work?

You need to use hook_theme:

/**
 * Implements hook_theme().
 */
function MY_MODULE_theme($existing, $type, $theme, $path) {

  if($type != 'module') {
    return [];
  }

  // If you want to put your templates in a templates directory
  // in your module directory add .'/templates' to the end.
  $module_path = drupal_get_path('module', 'MY_MODULE');

  return [
    'comment' => [
      'template' => 'comment',
      'path'     => $module_path,
    ],
    'other_template' => [
      'template' => 'comment',
      'path'    => '/my/custom/path/here',
    ],
  ];
}

This has set up our custom theme, then when you want to use it you can:

$tpl_data = [
  'param1' => $foo,
  'param2' => $bar,
];

return theme('comment', $tpl_data);

Now $param1 and $param2 will be available in your template file too.

If you don't need any custom data in your template then $tpl_data can be omitted.

Happy days.


How to reset 'new' and 'updated' flags without visiting a node page? In my drupal site I have a content type that has its nodes visible only in a view and they have always the 'new' (or 'updated') flag up for all users.

How can I reset the flags without visiting the node page?
Is there a function to tell drupal "this user has seen this node"?

You can use node_tag_new() for that

  Updates the 'last viewed' timestamp of the specified node for current user.

e.g.

node_tag_new($node);


How to get notified when a user is blocked? Is there a way to get notified when a user is blocked ? like a hook in user module or ? or there are another way ?

There is hook_user_update() for this. Below is an example on how you can use it for your purpose:

/**
 * Implements hook_user_update().
 */
function my_module_user_update(&$edit, $account, $category) {
  // Check if the user was blocked
  if ($account->original->status != $account->status && $account->status == 0) {
    // Handle notification here
  }
}

To send an email programmatically from Drupal, you can check out this question.

Another way to do this, would be by using the Rules module and following the steps below:

Create a new rule that reacts on the user event "After updating an existing user account".
Add a condition of type "User is blocked" and save it with the defaults.
Add another condition of type "User is blocked", but this time use "account-unchanged" for the Data Selector and check the Negate checkbox.
Add an action of type System > "Send mail" and play with it.


Upload Image with comments under forums In drupal 7 Forums under some topic I want to add a upload image field with the comment field. How can i achive this?

Install CKEditor

This module will allow Drupal to replace textarea fields with the CKEditor - a visual HTML editor, usually called a WYSIWYG editor. This HTML text editor brings many of the powerful WYSIWYG editing functions of known desktop editors like Word to the web. It's very fast and doesn't require any kind of installation on the client computer.

As mentioned by darol100, for Upload Install IMCE

IMCE is an image/file uploader and browser that supports personal
directories and quota.

Here is a nice video tutorial: Installing and Using CKEditor and IMCE


Drupal 8: Class not found from module Controller, but works fine from module EventSubscriber I created a custom D8 module in:

<root>/modules/custom/mymodule

In that custom module are
src/Controller/MyController.php and src/EventSubscriber/MySubscriber.php.

I wrote some custom code in my custom theme in <root>/themes/mytheme/src/MyClass.php.

My namespaces are: Drupal\mymodule and Drupal\mytheme.

I can add/use MyClass in MySubscriber.php (use Drupal\mytheme\MyClass) and it works fine.

However, when trying to add MyClass to MyController.php, it creates a PHP error claiming that it cannot find MyClass. The MyClass code is identical between the two module files.

Why won't it work in MyController.php while working fine in MySubscriber.php?

I've tried a lot of testing, resetting the cache, etc., but cannot find a reason for this. I can use Drupal core classes in myController.php, but nothing from the themes directory (I tried to include custom code from another custom theme).

Any hints? Any best-practice work-arounds?

I never tried accessing theme classes from within any module classes. The reason is simple: The best practice you asked for is not doing so.

Whereas you can add classes to a theme for theming using object-oriented code, you should limit the operations performed by the theme to manipulating output generated by Drupal core and modules.

This should happen in a manner that allows for easily replacing your theme by another theme which is not featuring these classes.

Making a module dependent in a theme class will break this functionality.

Without having screened the core of Drupal, I could imagine that autoloading theme classes won't take place before theme negotiation happened.

Consider moving whatever your theme class does and is required by your module to a custom service provided by your module instead of the theme.

EDIT:

According to your comment, your original theme class had the use of creating a data table that should be themed for output.

The "Drupal way" then would be to moving your class to your custom module and making it a service by creating an according mymodule.services.yml (read more about creating a custom service here or here):

services:
  mymodule.myclass:
    class: Drupal\mymodule\MyClass

Then you can create an instance of your service by either using dependency injection (within the scope of other classes as your controller and/or event subscribers), or the static \Drupal::service('mymodule.myclass') getter within procedural *.module and *.theme files.

Your service could either have a method that returns the data table only, or even have a method for returning a themed version of the data table (render array with a #theme wrapper), whereas you implement a custom hook_theme() with a template and/or pre-processing from within your module.


How download images from ftp I imported products with the help of feeds via commerce product processor. The images from http://example.com/image.jpg downloaded successfully.  But why does not loading the images from ftp://account:123@xx.xxx.xxx.xxx/image.jpg ?

Because the image actually does not below at /image.jpg. You need to investigate where you are storing your files at admin/config/media/file-system. And from there you might find where is your files locate.

The default file path is going to be /sites/default/files so it might be ftp://account:123@xx.xxx.xxx.xxx/sites/default/filesimage.jpg.


I cannot change the temporary Directory I cannot change the temporary directory under file settings.  Everytime I change it, it says the changes have been made, but it reverts back to the setting it previously had.

I even went as far as deleting the 'dbo.variable.file_temporary_path' value in the database, but it is still not working.

Do you have an idea about where this is being stored?

It was hard coded in the settings.php file. This will override any settings you do in the UI.


How can I add an article to a region? How can I add a content (let's say content of Article type)' to ANY region (not only in content region), or how to add a region to a node view page?

By default drupal don't let you do this , you should achieve it with this two solution

use nodeblock

  This module allows you to specify content type(s) as being a block.
  This allows the content managers of the site to edit the block text
  and title without having to access the block administration page.
  Users only need edit access to that node in order to edit it.

  We advice you to use this module together with Node Level Blocks or
  Block Reference module.

  It is very handy to create a simple block content type and enable this
  content type for blocks and use these in place of the normal 'add
  block' functionality.

Achieve it by views block,I mean create a view, get result of it with what you want ,then save it as block ( I mean create block view), then put the block in the region you want.


using the hook_nodeapi in the view mode I am trying to add a form when I view my node; for that I am using the following code.

function review_m_nodeapi(&$node, $op, $a3 = NULL, $a4 = NULL){
    switch($op){
        case view:

In this case I would like to call drupal_get_form().

I would like to add the following code.

function review_m_form($node) {
    $form = array();
    $form['mark'] = array(
        '#type' => 'textfield',
        '#title' => 'Give a mark to the content type(1 to 10)!',
        '#size' => 60,
        '#maxlength' => 2,
    );
    $form['text'] = array(
        '#type' => 'textarea',
        '#title' => 'leave a feedback!',
        '#cols' => 60,
        '#resizable' => FALSE,
        '#rows' => 5,
    );
    $form['created'] = array(
        '#type' => 'textfield',
        '#title' => 'Enter the date!',
        '#size' => 60,
        '#maxlength' => 10,
    );
    $form['submit'] = array(
        '#type' => 'submit',
        '#value' => t('Send review'),
        '#weight' => 10,
    );
    return $form;
}

How can I pass this in the view case, so that it works good for me?

I am trying something like the following code.

case view:
            $node->content['form'] = array(
                drupal_get_form('review_m_form'),
              );

You're missing the first required variable in the signature of your form declaration so things will never work quite as you're expecting.

The function signature should be:

function review_m_form(&$form_state, $node) {

Then you would attach it to your node content like so, remembering to pass the node as a parameter:

$node->content['form'] = drupal_get_form('review_m_form', $node);


Custom fields added via form api not working as expected I'm having a whole mess of issues adding text fields to a form in Drupal 6. I want to add a text field with an autocomplete. I tried adding the field in hook_form_alter() like so:

$form['my_field_name'] = array(
  '#type' => 'textfield',
  '#title' => 'My Title',
  '#required' => true,
  '#default_value' => 'my_default_value',
  '#autocomplete_path' => 'url/to/autocomplete'
);
$output .= drupal_render($form['my_field_name']);

When I output this, the field output to html does not have an id or name attribute, and the autocomplete doesn't work (presumably because the id is missing. Additionally, the default value is not populated in the field.

I can overcome some of these issues by adding in a custom #id, #name, and #value, like so:

$form['my_field_name'] = array(
  '#type' => 'textfield',
  '#title' => 'My Title',
  '#id' => 'my_field_id',
  '#name' => 'my_field_name',
  '#required' => true,
  '#value' => 'my_default_value',
  '#autocomplete_path' => 'url/to/autocomplete'
);
$output .= drupal_render($form['my_field_name']);

This gets the autocomplete working as expected, gives a name and id attribute, and fills in the default value, but unfortunately now the autocomplete does not actually change the value of the field, so I can't enter and submit a new value.

How can I overcome these problems with form_alter?

AFAIK, hook_form_alter() does not require you to perform a drupal_render() in it. And I suspect that is why you are not getting a proper rendered for item.

Also, each custom field needs to processed (by you) on form submit.
Thus, you need to add $form['#submit'][] = 'my_submit_function_submit';, where my_submit_function_submit() handles the database inserts.


How to display specific forms in drupal 7? I need to display the system login form and the system registration form on the same page but different panels (not tabbed like the default). I don't want to build a form from scratch using the forms api. I want to pull the accrual forms from the system and use them. The result should be much like the home page of facebook before you login, on the same page you can either login or sign up. I want to do all this from code, not from a module but from the page.tpl.php file. I have a special function that will display a completely different page for the home page.

I would recommend using blocks with conditional views instead of hard coding this into your template file, but if that's really what you want to do, you basically just need to use drupal_render and drupal_get_form in the appropriate places in your template file i.e.:

Login:
<?php print drupal_render(drupal_get_form('user_login')); ?>
 - OR -
Register:
<?php print drupal_render(drupal_get_form('user_register_form')); ?>


Add a "autocomplete" field in a buildForm How do I add an autocomplete field in a class that extends FormBase?

I created a custom module, which uses a class that extends FormBase. I want to  programmatically create a form field that autocompletes the username from the user registered in the site.

You use entity_autocomplete as #type for the form field. CommentForm::form() contains such a form field, for the administrator users to be able to change the author of a comment. This is the code it uses.

  // The uid field is only displayed when a user with the permission
  // 'administer comments' is editing an existing comment from an
  // authenticated user.
  $owner = $comment->getOwner();
  $form['author']['uid'] = [
    '#type' => 'entity_autocomplete',
    '#target_type' => 'user',
    '#default_value' => $owner->isAnonymous() ? NULL : $owner,
    // A comment can be made anonymous by leaving this field empty therefore
    // there is no need to list them in the autocomplete.
    '#selection_settings' => ['include_anonymous' => FALSE],
    '#title' => $this->t('Authored by'),
    '#description' => $this->t('Leave blank for %anonymous.', ['%anonymous' => $config->get('anonymous')]),
    '#access' => $is_admin,
  ];

As you can see from the code, you can also choose to include the anonymous user.

The result is shown in the following screenshot.


Creating a rule to display Terms Of Service upon Ubercart checkout I have a small web store running Ubercart and with one of the items I must display a terms of service agreement. I have it displayed upon checkout as a requirement to proceed. Some of my other items do not need this service agreement to be purchased.

Question: Is it possible to set up a rule to display the Terms Of Service up check when only certain items are in the cart?

So after a lot of failed methods and frustration I found a solution.

You will need the following modules:

Ubercart Terms of Service (https://drupal.org/project/uc_termsofservice)
Ubercart Product Checkout Pane (https://drupal.org/project/uc_product_panes)

First install the Terms of Service module and set up your terms accordingly. Then install the Ubercart Product Checkout Pane and set the TOS to appear at checkout with the specified product(s).

This allows you to display the terms for each product that requires them.


Drush won't clear uploaded temporary files So, working on a unix system, it's common that /tmp has the sticky bit set (i.e. only the owner of the temporary file can write/delete it). This is an issue when running drush cron.

If I upload a file, and the file gets stored in /tmp, then the owner is _www (I'm on a MacOS machine). When I run drush, I'm running it as my own user, so if I run drush cron then my user is attempting to delete the temporary file(s) that was uploaded, and I get a permission denied.

Can anyone think of a simple workaround for this problem?

Simply make CRON run drush as _www user. /etc/cron.d suppotys it, it's format is:

#<timing>   <user> <command>

Just make entry for your drush:

11 * * * *    _www   drush

Details, of course, may vary a little.

I used this answer.


Form submition don't work I will build a form for register new team on drupal 7 website.

In my custom module i use this code :

tournament.module :

function tournament_menu() {
    $items['tournament/newteam'] = array(
        'title' => 'Créer une nouvelle équipe',
        'page callback' => 'form_newteam',
        'access callback' => TRUE,
        'file' => 'form_tournament.inc',
    );
}

form_tournament.inc :

function form_newteam ($form, &$form_state) {
    $form['description'] = array(
        '#type' => 'item',
        '#title' => 'Créer une nouvelle équipe'
    );

    $form['name'] = array(
        '#type' => 'fieldset',
        '#title' => t('Name'),
        '#collapsible' => TRUE,
        '#collapsed' => FALSE,
    );
    $form['name']['name_team'] = array(
        '#type' => 'textfield',
        '#title' => 'Nom de l\'équipe',
        '#required' => TRUE,
        '#description' => "Entrez le nom de votre équipe.",
        '#size' => 20,
        '#maxlength' => 25,
    );
    $form['name']['tag_team'] = array(
        '#type' => 'textfield',
        '#title' => 'Tag de l\'équipe',
        '#required' => TRUE,
        '#description' => "Entrez le tag de votre équipe (version courte du nom de votre     équipe ex : 'FrR').",
        '#size' => 4,
        '#maxlength' => 4,
    );

    $form['submit'] = array(
        '#type' => 'submit',
        '#value' => 'Créer',
    );

    $form['contact'] = array(
        '#type' => 'fieldset',
        '#title' => t('Contact'),
        '#collapsible' => TRUE,
        '#collapsed' => FALSE,
    );
    $form['contact']['contact_email_team'] = array(
        '#type' => 'textfield',
        '#title' => 'Email de contact de l\'équipe',
        '#required' => TRUE,
        '#description' => "Entrez l'email de contact de la team.",
        '#size' => 20,
    );
    $form['contact']['contact_name_team'] = array(
        '#type' => 'textfield',
        '#title' => 'Nom du contact',
        '#required' => TRUE,
        '#description' => "Entrez le nom du contact de l'équipe.",
        '#size' => 20,
        '#maxlength' => 64,
   );

    [...]

    return $form;
}

function form_newteam_validate($form, &$form_state) {
    $syntaxe_email = '#^[\w.-]+@[\w.-]+\.[a-zA-Z]{2,6}$#';

    if (!preg_match($syntaxe_email, $email)) {
        form_set_error('contact_email_team', "Entrez une adresse email valide !");
    }
}

function form_newteam_submit($form, &$form_state) {

    drupal_set_message('OK : team : @team, tag : @tag, email : @email, contact : @contact, site_web : @site, logo : @filename. ',
        array(
            '@team' => $form_state['name']['name_team'],
            '@tag' => $form_state['name']['tag_team'],
            '@email' => $form_state['contact']['contact_email_team'],
        )
    );
}

This form appears correctly, but when i submit it, nothing is happening...

Any idea ?

Thank !

drupal_get_form has to be called to render a correct form.

Alter the hook_menu definition to this:

function tournament_menu() {
    $items['tournament/newteam'] = array(
        'title' => t('Créer une nouvelle équipe'),
        'page callback' => 'drupal_get_form',
        'page arguments' => array('form_newteam')
        'access callback' => TRUE,
        'file' => 'form_tournament.inc',
    );
}


How to conditionally update and import nodes using Migrate? I need to migrate new nodes and update others in the same time. 2 installations of the same project are out of sync, which means, that the same nid may not indicate the same node on both sides. But I'm sure they're the same if their titles are equal. So I think, that I need a conditional field mapping, as illustrated in the following pseudocode:

if source_nid = destination_nid
  if source_title = destination_title
    addFieldMapping('nid', 'nid')
else
  continue

I have only one idea, how can I do this - split migrations into two different parts with filters managed by prepareRow() method (one of the for node updating, the other for import of new nodes). Is this the only way? I would appreciate something more elegant.

OK, at least now I know, that splitting migration into two with filtered rows works just fine. prepareRow function looks like this:

public function prepareRow($row) {
  // If node exists on destination
  if ($node = node_load($row->nid)) {
    // Use the metatdata wrapper to pull values
    $node_wrapper = entity_metadata_wrapper('node', $node);
    // If destination title is the same as source title
    if ($node_wrapper->label() == $row->title) {
      return TRUE;
    }
    else {
      return FALSE;
    }
  }
  else {
    return FALSE;
  }
}


EntityFieldQuery gives error on adding propertyCondition I have to list down taxonomy term ids which should be greater than a specific tid.
Below is the code I am using:-

$query = new EntityFieldQuery();

$tid = variable_get('last_player_update'); //last index of player update

$query->entityCondition('entity_type', 'taxonomy_term')
  ->propertyCondition( 'tid',  'value', $tid, '>=')
  ->propertyCondition('vid', 3)
  ->propertyOrderBy('tid', 'ASC')
  ->range(0, 1000);

$result = $query->execute();

On executing the script I am getting the following error:-

PDOException: SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '9174 'value') AND (taxonomy_term_data.vid = '3') ORDER BY taxonomy_term_data.ti' at line 1: SELECT taxonomy_term_data.tid AS entity_id, :entity_type AS entity_type, NULL AS revision_id FROM {taxonomy_term_data} taxonomy_term_data WHERE (taxonomy_term_data.tid 9174 :db_condition_placeholder_0) AND (taxonomy_term_data.vid = :db_condition_placeholder_1) ORDER BY taxonomy_term_data.tid ASC LIMIT 1000 OFFSET 0; Array ( [:db_condition_placeholder_0] => value [:db_condition_placeholder_1] => 3 [:entity_type] => taxonomy_term ) in EntityFieldQuery->execute()

What I am missing in the above code snippet?

Fields have columns. Properties do not. You want:

$query->entityCondition('entity_type', 'taxonomy_term')
  ->propertyCondition( 'tid',  $tid, '>=')
  ->propertyCondition('vid', 3)
  ->propertyOrderBy('tid', 'ASC')
  ->range(0, 1000);


Hide results of drupal view when filter value is empty after search Help needed, how to hide all results of a view when filter value is empty, after search button pressed.
(I have this: Set Advanced | Exposed Form | Exposed Form Style to input required. Not working well. When open view OK, but for empty search field, and search button pressed all appear)
I know there are lot of solutions  here: (5 years old) https://www.drupal.org/node/358546 but I can't find those options in views in Drupal 7.
Can somone provide a working solution for Drupal 7 and Views version 7.x-3.x?

Explain question, end the operator for VIN and kod sterownika set to: "is equal to"

Edit your view and then set the "Exposed form style" to basic.

Hope that helps!


Where is the Migrate UI page? In Drupal 8.2.x there is the new migration UI tool. I've enabled it, but I can't find any link going to any UI page. Back in Drupal 7 when you enabled a module, it would have a configure link next to the module name in the modules page, but Drupal 8 doesn't. How would one find these configure links to the module pages?

modules -> migrate UI -> configure.

Press on the gear and you will enter the migration process.


How to uncheck url path settings in node form alter for existing content? Here I wonder how to uncheck url path settings in node form alter for existing content?

Here is your answer two ways of doing it

Method 1:

function module_node_update($node) {
  if($node->type == "blog"){
        $node->path['pathauto'] = TRUE;//to be checked
        $node->path['pathauto'] = FALSE;//To be unchecked
  }
}

or either you can do it in node_presave

Method 2:

function module_node_presave($node){
 if($node->type == "blog"){
            $node->path['pathauto'] = TRUE;//to be checked
            $node->path['pathauto'] = FALSE;//To be unchecked
      }
}

Try and let me know hope it helps
:)


How to build and organize menus with rich taxonomies and complex view-based menus I would like to hear your insights about strategies on organizing menus. I mean two main approaches: having each menu header as an individual Drupal menu vs. having all menus grouped as one big menu, perhaps named "Main menu".

I built quite a large site where I had to use such modules as OM Maximenu, Taxonomy menu/Taxonomy menu trails, Menu Block, Sitemap, DHTML Menu. Without much knowledge about Drupal and the consequences of my choice, just to keep my progress on, I took my liberty to sometimes put a group of menu items as individual menus, sometimes I grouped them together (this was the case of Taxonomy menu and Menu Block where I could define the level at which menu starts).

Then, when I installed Sitemap I saw that my menu organization revealed to public. This was also a lesson.

Although everything works OK, I don't feel alright with this kind of mess. Especially, after some time I know I will have to do a repetitive research on how a particular menu is built, rather than have it intuitively solved right away.

My question: What is your preferred way to build and organize menus with rich taxonomies and complex view-based menus (OM Maximenu)?

Typically, we put all of the site sections in the main menu.

Each site section will get its own Drupal menu.  How items get into menus varies widely project-to-project, but we will rely on path-alias define section organization as much as possible.

Each section will have its own Panels pages, where the site section gets used as the context / selection rule (typically by path matching), and the menu is placed in a content area.

Occasionally, we will have a site section taxonomy, which gets used inside a custom block to display the proper menu.


Views + Search API not properly sorting by Commerce Price (seems random) I have a search index View of product variations. The commerce_price field is indexed and exposed as sort option. However, when sorting by the price it appears mostly in order (Asc or Desc) but some items are not in the proper order (see screenshot)
I've tried indexing the price field as an integer, decimal, and string but it always has the same effect.
There are no additional sort items.
There are not any price adjustments or custom calculations.
There is no custom code affecting the Views or pricing.
I've tried wiping and rebuilding the index multiple times.
The View is using Better Exposed Filters.
Any ideas how I can get the products to sort by price correctly?

Resolved. Not sure exactly what is/was going on but the price sorting is now working. There was another identically named commerce price field in Views. Adding that field and removing the first one fixed the issue. I know, something unusual appears to be going on but at least the sorting is working now.


Webform add data along with submitted values I'm using Webform 6x 3.11 and have passed a nodeID into a hidden field called hidden_key. I have created a custom module to implement hook_form_alter() whereby I am trying to add additional data (along with the data that is being submitted) to the submission results.

This additional data is based on some calculations performed on the value in the hidden field, ie: getting some details about the node based on the nodeID. Here's what I currently have:

<?php
    function custom_form_proc_form_alter(&$form, &$form_state, $form_id) {
        if ($form_id == 'webform_client_form_33') {
            $form['#submit'][] = 'custom_form_proc_submit';
        }
    }

    function custom_form_proc_submit($form, &$form_state) {
        $node = node_load($form_state['values']['hidden_key']);
        $pool_title = $node->title;
        $pool_category = $node->field_category[0]['value'];

        // ?????
    }
?>

Where you see my ????? is where I am stuck. Along with whatever data gets submitted with the form, I would like to add these 2 custom fields to the submission results so that it looks like:

Fullname: Mr So-and-So
Email Address: someone@test.com
Pool Category: $pool_category
Pool Title: $pool_title
Availability: Yes

I would really appreciate your help! Thank you!

For webform submission it is best to use hook_webform_submission_insert($node, $submission).
$submission->data will contain all the submitted values arranged against form components ids.

See my implementation how I arranged a webform as user register form.

function user_register_webform_submission_insert($node, $submission){
// Load information about form components
$comps = $node->webform['components'];
$fields = array();

//Extract the component info to get form_key=>cid to resolve relation
foreach($comps as $cid => $comp_info){
    $fields[$comp_info['form_key']] = $cid;
}

// Load the submitted data (field values)
$data = $submission->data;

//Prepare a user info
$user = array(
    'mail' => $data[$fields['mail']]['value'][0],
    'name' => $data[$fields['name']]['value'][0],
    'pass' => user_password(8),
    'status' => 1,
    'init' => $data[$fields['mail']]['value'][0],
    'roles' => array(2, 3),
);

$account = user_save(null, $user);
}


How to check whether content entered by a user in a custom form is valid HTML? I am trying to write a custom form in Drupal 6 which will check whether the content submitted by a user is valid HTML.

If the content is valid I need to generate a txt file with HTML markup based on the content without a DTD.

You can probably do that with PHPTidy (PHP Module) and tidy_get_error_count


Using ImageWidget as form element I would like to have a multi image upload in my form with an option to sort images and provide optional title/alt. This functoonality is present in the image widget field widget plugin and so instead of writing a lot of new code I am wondering if there is a simple way to use it as form element somehow?

I agree with @mradcliffe, that there is probably no simple way to reuse field widgets for normal form fields. The code of field widgets heavily depend on an underlying entity field.

I think the best solution is to create a mock custom entity. As you obviously don't need to store the result, otherwise you would already use an entity, you can set

"storage" = "Drupal\Core\Entity\ContentEntityNullStorage",

in the entity. Example for this is the core Contact Form, which needs very little code to implement fully customizable forms by reusing the form API for entity forms.


Save checkboxes value into another checkbox field I'd like to save the value of a checkboxes field which is link to a product once I save my content type.

I've created the code needed to create the product and the node. When the node is in creation mode everything appear as it should and my node get's save, the product created but I struggle to save the value into the field field_permission that I've added to the product type.

Permission field.

Label: Permissions
Machine Name: field_permission
Field Type: List(text)
Widget: Check boxes/radio buttons

The values inside this field are:

permission1|Permission1
permission2|Permission2
permission3|Permission3

I've selected the number of value to 3. I got my check-boxes field created. Great !

Then, I've created a content type and alter form to save a custom node. I had this form element which appear on the form.

    $options = array(
      permission1|Permission1
      permission2|Permission2
      permission3|Permission3
    );

    $form['permission'] = array(
      '#type' => 'checkboxes',
      '#options' => $options,
      '#title' => t('Select permissions:'),
    );

Then when I save the new node using a custom submit, I create a product and it works fine,
But:

I want to save the value selected inside $form[permission] and copy those values to the field_permission I've create onto the product type. I've read that I have to use the wrapper and call the newly created product. Fine. It works but the value aren't still save into my new field. Any idea How to save checkboxes values ?

Thanks.

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

$node = new stdClass();
// Set content type
    $node->type = 'event';
    // Prepare defaults
    node_object_prepare($node);

    $node->title  = $form_state['values']['title'];

    $node->language = LANGUAGE_NONE;

    //create path with pathauto
    $path = 'mycontent' . date('YmdHis');
    $node->path = array('alias' => $path);
    $node->uid = $user->uid;

    //create new product type
    $price = $form_state['values']['field_cost']['und'][0]['value'];
    $extra = array(
    'sku' => 'event-' . drupal_hash_base64(microtime()),
    'title' => $node->title,
    'uid' => $node->uid,
    'status' => TRUE,
    );
$reg_id = _create_product('event_product', $price, $extra);

//add permissions value to the product
$product = commerce_product_load($reg_id);
$wrapper = entity_metadata_wrapper('commerce_product', $product);

$permissions = $form_state['values']['permission'];

    --- HERE IS THE PROBLEM --- How to copy those values ???

   foreach ($permissions as $key => $value){
      $wrapper->field_event_permission['#default_value'] = $permissions;
   }

$wrapper->save();

dsm($wrapper->getPropertyInfo());

   //save the field attached to the node
.....
   node_save($node);
}

Yes, it's solved.

I don't need to add the permission to the product. I just check the permission that are check on the field_permission related to this node and then I display the Add to cart button only if the user meet the required permission.

Thanks


How to load all field values from multiple entities? I have an EFQ that finds the users whose field values match a given array of values:

  $users_query = new EntityFieldQuery();

  $users_query->entityCondition('entity_type', 'user')
    ->fieldCondition('field_my_field', 'value', $array_of_values);

  $users_query_result = $users_query->execute();

This will create a list of uid's but I need to know which uid goes with which value in the array.

EFQ will return an entity stub, if you want the fully loaded entities, you can try something like:

// Build query
$query = new EntityFieldQuery();
$query->entityCondition('entity_type', 'user');
$query->fieldCondition('field_my_field', 'value', $values);
// Execute for result
$result = $query->execute();
// If has data
if (!empty($result['user'])) {
  // Load users
  $accounts = entity_load('user', array_keys($result['user']));
  // If using devel
  // dpm($accounts);
}else{
  // No results
}


user hook node update to attach files to a node? im using the following code to upload an array of files when a node gets saved.

function mymodule_node_update($node){
 $result = $query;

 foreach ($result as $record) {
$url = ($record['src']);
$name_arr = explode('/', $url );
$filename = end($name_arr);
$filepath = system_retrieve_file($url, 'public://my_files/');

$file = new StdClass();
$file->uid = 1;
$file->uri = $filepath;
$file->filename = $filename;
$file->filemime = file_get_mimetype($file->uri);
$file->status = 1;

$dest = file_default_scheme() . '://'.$filename;
$file = file_copy($file, $dest);
$file->display = 1;
$file->description = "";
 }
}

This uploads the files to my public directory, and creates an entry into files_managed in my database.

But now how do I link those files to a filefield on the node im updating?
I've tried variations of

  $node->field_file = (array)$file;

but nothing is working.

Thanks for any help

The field data has already been committed by the time hook_node_update() is called, so you won't be able to make any persistent alterations to field data in there.

Instead you could use hook_node_presave(), which is run before any data is written to the backend.

function mymodule_node_presave($node) {
  // Build up file object

  // Then add it to the node.
  $node->field_files[$node->language][] = (array)$file;
}


How to add large number of pages to a content type? I created a content type "cities", with
Fields: Title, body, location(text field)

I would like to create about 200 pages for this content type.

I can create manually one by one. It will take a lot of time to do that. Is there faster way I can add the pages by using some bulk load methods?

Use the Devel module, and its devel_generate submodule.

Using this submodule, you can perfectly create 200 nodes (with randomly generated content) of any content type.


How to disable watchdog table entry? My drupal 8 watchdog entry running very vastly. I want to stop the watchdog entry for few times immediate basis and resolve the issues. Please suggest.

The Database Logging (dblog) is responsible for logging to the Watchdog table. Uninstall the module and it will remove the table and logging to it.


Changing site:mode throws Twig memory error I am trying to toggle the site mode for a new Drupal 8 development site. When I run the command drupal site:mode dev I get the following error:

PHP Fatal error:  Allowed memory size of 1073741824 bytes exhausted (tried to allocate 1038876672 bytes) in phar:///usr/local/bin/drupal/vendor/twig/twig/lib/Twig/Extension/Debug.php on line 56

Increasing the memory (even to something huge) doesn't resolve this. Is Twig trying to throw an error, or output loads of data? How can I fix this please?

You're debugging an entity or other object somewhere that has recursive references and debug gets into an endless recursion until all memory is used up.

Instead of debug(node) or similar, use debug(node.toArray()), that gives you the raw value instead of huge object structures.


How to use Views on custom route? Views require "Use AJAX" in order to display exposed filters when using Block display. I think this is necessary to avoid submitting/influencing other form elements on the current page.

I have a page that is a View but my page has to have a certain route name because my app relies on it. So I've used Block display for the Views instead of the Page display.

But I want the user to see the filtering arguments in URL so he can save the search or link to it. So obviously I will have to use the Page display for my view. But how can I use the Views with mine route?

Is is a good idea to create a Page view with some dummy path and load the View's route and get it's content and display it via mine route controller?

At first I've used the config option mentioned by Daniel Wehner but I ended up with using a custom filtering form + query tag. This gave me much better flexibility and customization options than Views' exposed filters.

There are a couple of things you can try out:

Write a display plugin for views which extends the  page one and allows you to specficy the route name in the UI. Note: views already uses a option in the view yml file 'route_name' if it is available:

display:
 page_1:
   display_options:
     path: node
     route_name: hallo_world

So you could just hack your yml file and be done.
Use the route alter event and simply rename the route generated by views:

protected function alterRoutes(RouteCollection $collection) {
  if ($route = $collection->get("view.$view_id.$display_id")) {
    $collection->remove("view.$view_id.$display_id"); // not sure about the method name.
    $collection->add('hey.this.is.my.cystom.route.name', $route);
  }
}

Be okay with the name views generates, as it won't change over time.


How should I deal with Views URL parameter "page" in Google web master tool? I have node view which has pager with URL parameter "page". I want Google bot crawls all the pages ( page=1 page=2 page=3... ) but regard all of them as just one and only the first page (without parameter "page") should appear on the search result.

On the webmaster setting page I have set URL parameter for "page" as below but now I'm getting duplicated title and description.

  How does this parameter affect page content: Paginates
  Which URLs with this parameter should Googlebot crawl: Every URL

What's the best way to configure URL parameter for Views "page" on Google Webmaster Tools?

Try Nodewords module for Drupal 6 or Meta tags for Drupal 7.
These modules will allow you configure the NOINDEX and NOFOLLOW parameters for listing pages in order to get only 1st page in SERP.


Why are links missing when using the Notify module? I use the Notify module. When I select for Mail System (admin/config/system/mailsystem)
the choice DefaultMailSystem, the mail is sent but change line in a small border like this

But when I select HtmlMailSystem, it sent in a line (like what I want) but the links disappear and it looks something like this:

The links only appear in Gmail. In the other mails (hotmail,yahoo) they do not.

Why does this happen?

How could it be correct? In a line with links?

Your question is pretty incomplete, so let me start with adding some crucial information that I think is missing in it:

Relative path admin/config/system/mailsystem is not something that gets added to a site by the Notify module. Instead that path is what gets added after you enable the Mail System module, at least for the 7.x-2.34 version of it, which is what the rest of my answer assumes you're using.
After you enable the Mail System module you can navigate to the admin/config/system/mailsystem path.

After you do so, within the settings for "Site-wide default MailSystemInterface class", you'll be able to select either DefaultMailSystem or TestingMailSystem. However you can not, repeat not, select HtmlMailSystem (as in your question).

In order to be able to select HtmlMailSystem, you first have to enable the HTML Mail module. Which is what I did, I enabled the 7.x-2.65 version of it, which is what the rest of my answer assumes you're using.

With the above crucial additions, I think that the actual answer to your question can be found within relative path admin/config/system/htmlmail, where you can configure the settings for the HTML Mail module. I'm not sure if it's the only solution to answer your question, but pretty sure that you should select some other text filter within Post-filtering (located near the bottom within Step 3): by default it uses unfiltered, so check the results you get if you use any of the other filters you have available (or define a new filter to make it work as you want).


Is there a token I can use to display a node's view mode? I am trying to use Rules to send an email with the results of the submission of a node. Is there any way to place the entire contents of the node using a token?

e.g. [node:teaser]

Look at the Advanced Entity Tokens module.

  Advanced Entity Tokens (AET) Creates a Token for each of your entity
  items.

  Through AET you can query the DB for entities using Tokens.

  Examples

  [aet:node:1] will return the 1st node with the token view mode (or
  full if token is not available).
  [aet:file:1:view-original] will
  return the 1st file entity with the original view mode.
  [aet:taxonomy_term:1:name] will return the 1st node title field (note
  that this level of chaining is done by the formal token implementation
  of the node entity in token/token.tokens.inc -> token_token_info()).

  Real World Examples

  Displaying a node inside a block: This could be done using Node Block
  OR you could insert a token inside a block you create through the
  Blocks interface that retrieves a certain node (or a property inside a
  node, [aet:node:] or [aet:node::body]) with no extra code.
  Displaying a File Entity (image) inside a title field: I'm not sure
  how this could have been done without custom code, BUT with AET you
  could easily insert the Token for a specific File Entity
  ([aet:file:]) and your entity will be displayed. AET defaults to
  the Token view mode if available (full otherwise), but you could just
  as easily specify a view mode of your own
  ([aet:file::view-teaser]).
  I'm saving this spot for real life
  examples other Drupal users had (or thought of having) for this
  module.


How to change the behaviour or display of the language switcher? On translated pages the language switcher shows links to translated languages, but for untranslated languages there is no link, but the name of the language without a link. In the case, that there is no corresponding node in a given language, i would like the language switcher to show a link to the front page instead.

How can i accomplish this behaviour? Thank you very much!

Add next into template.php file of your theme:

<?php
  function YOURTHEMENAME_links__locale_block($variables) {
    foreach($variables['links'] as $key => $lang) {
      if (isset($lang['attributes']['class']) && in_array('locale-untranslated', $lang['attributes']['class'])) {
        // Set here any page link.
        $variables['links'][$key]['href'] = '<front>';
      }
    }
    return theme_links($variables);
  }


How to get node content in an sql query? I see that in D6 the node table has only the title of the node. How to query database to get  the body (content) of a particular node?

Update: I figured out the content bodies are stored in node_revisions table.

Drupal 7

In Drupal 7 body content is saved in field_data_body and field_revision_body tables.

So example query to fetch title and body would be:

SELECT title, r.body_value, n.changed FROM node n LEFT JOIN field_data_body r ON n.nid = r.entity_id AND n.vid = r.revision_id

To query via drush, run drush sqlq following by above query.


is it possible to declare an user group for the remote user in aliases.drushrc.php I have a different user group for apache on my remote server clould i specify a group for drush sync like remote-user user adds the user or in some similar way
?

No; in unix, the group ownership is attached to the user.  Use usermod -a -G to add the desired group permanently to your remote user.  See man usermod for more information.


node_load() Performance and alternatives I created a custom module which lists the last X nodes from a certain content type, with the following query:

SELECT n.title, r.teaser, r.timestamp
FROM node n
INNER JOIN node_revisions r ON r.vid = n.vid
INNER JOIN term_node tn ON tn.nid = n.nid
INNER JOIN term_data t ON t.tid = tn.tid
WHERE t.name= 'breaking_news'
AND n.status = 1
ORDER BY n.nid DESC LIMIT 25

Then I do a node_load($nid) to check if there is a image and an audio file inside, for example

$mynode = node_load($queryresutl->nid);
if ($mynode->field_efe_audio[0]['filepath']) {
  $audio = 'yep, has audio';
}

But I've read that node_load() could be a performance killer, so I wonder if this is true and if there's is an alternative to check fields in my module?

First i would make sure that using node_load() does slower your script. If you are sure it really does you can either:

1- Create an index_audio  table with a nid and use_audio columns.
You could update this table on node creation/update/delete. Then
you can just query this table to make sure a specific node does have
audio attached to it. I would use that solution only if i you have to
intensively make such a check
2- Directly query your field table with your nid as etid, in your
instance : field_data_field_efe_audio table see if it returns
FALSE or some actual data


Setting up video for Drupal- to play in popup I've set up a Drupal website and would like to have video box that pops up when a user clicks a picture graphic. Sounds simple enough, but it turns out it is not straightforward in the land of Drupal, flash, codecs, and iphone... Here's what I'd like:

User clicks a link on my Drupal website, a video box player pops up as a mini-box player for the user to watch in a PC or Mac.
For iphone users, want the ability for them to view video on iPhone (which means it can't be flash).
Here's where I am so far. I recorded a screencast using both Camtasia for Mac and Screenflow. But I don't know which format to encode the video- or how to.

I've read that JW player (long tail video) is a good player because it will play both flash and HTML (good for iPhone), but then also read that Drupal and JWplayer does do a popup video window from a link. Is that true?

So before embarking further, I'd love some input on how to proceed? Which encoding format, how to achieve pop-up video player, and have ability to play on iPhone. Of course all through a Drupal site. Btw- I would be hosting the video on Vimeo, or Amazon's cloudfront.

Video is hard. One thing to think about is that if you are going to use Vimeo then you don't need to worry about formats since Vimeo will handle that on upload (and the player, and the HTML5). My personal preference would be to use embedded media field, and the media:vimeo module.

Then you end up with the video as a cck field and you can use something like colorbox to give you your popup.


Weird appearances in a node For some reasons I have too weird appearances in a node.

A "Read more" button appearing near to my "Tags" list (even though my display settings dictate only "Full page" appearance, and I've disabled any other option.
An RSS button, that appears there although I never installed the Aggregator module.

How can you explain these phenomena?

It seems that the problem was some kind of data mixing made by mistake at the page.tpl.php.

I think it's fixed now.


views field php condition I use drupal6 and UC2. I am working on a view which exports order details into an excel file such as - address and total order amount. Total amount field is crucial for me - Would it be possible to use views php and check if payment method is COD then get total amount. If payment method is different than COD then result would be nothing or 0?

Thank you

You can certainly do that. If you setup a view and tell it to grab Ubercart Order data it will allow you to access information on orders such as the payment type, amount, order id, etc.

So if you grab the following information you'll be set to feed it into the Views PHP field.

Payment Method
Order Total (Exclude this from the display)

Then if you add the Global: PHP field you need to put the following into the Value code field:

if ($data->uc_orders_payment_method == "cod") {
  return number_format($data->uc_orders_order_total, 2, '.', ',');
} else {
  return number_format(0, 2, '.', ',');
}

And this in the output code field:

<?php
  print $value;
?>


How to add a javascript field to custom content type I have a custom content type called 'Visualisation'. I would like a user to be able to upload their own javascript file for each instance of the content type. I would then like to load this script on the page in which the content is displayed.

I have tried adding a custom field 'file', however Drupal doesn't allow javascript files and appends the file with 'txt'. How can I add a javascript file and then load when the content is displayed?

EDIT

As it seems unsafe to achieve this the way I've mentioned above I'll try and elaborate on what I'm trying to do.

The content type is for HTML5 canvas visualisations. Each visualisation will use a custom created script file. The whole content will consist of a title, canvas element, javascript file and description. I therefore need to attach a script to each visualisation.

Would it be better to have a field with just the name of the file and load it in the page template?

Many thanks for any help.

First things first: a warning.
This sounds like an extremely dangerous idea. If you do this, please at least make sure that you're only opening this up to trusted users (as allowing people to place javascript on your page could lead to some very, very bad things, much like the php filter.)

That being said, if your sure you want to do this, your gonna need to add the js to your page programmaticly. You could easily do this through your theme functions of template_preprocess_node.

Find that function in your template.php file. You'll want to add a condition to check for the content type, then grab the js file and use drupal_add_js to grab the attached js file and attach it to the head.


How do I limit a normalizer to a given class or interface? I'm creating a custom normalizer for node entities.

I want to restrict the normalizer to normalize Node entities only. It seems like there are two ways this can be done:

protected $supportedInterfaceOrClass = NodeInterface::class;
public function supportsNormalization($data, $format = NULL) {
  return (bool) $data instanceof NodeInterface;
}

Is there a difference between the two? Do I need both, or only one of them?

It seems like I don't need the $supportedInterfaceOrClass, but what is it used for? Can I just remove it and only use supportsNormalization()?

UPDATE: My class extends the NormalizerBase class.

You didn't explicitly state that your class is extending NormalizerBase, but I assume that's the case. My reply is based on that assumption.

If you look in the code for NormalizerBase, there are two spots where $supportedInterfaceOrClass is accessed, in supportsNormalization() and supportsDenormalization(). If you override supportsNormalization() as option #2 from the original post suggests, your normalizer will be restricted to nodes. However, it overrides the base method, bypassing a check to see if the given normalization format is even supported, which is not good. If someone were to try to normalize an unsupported format, the overridden method would incorrectly return TRUE. Therefore, it is better to set supportedInterfaceOrClass according option #1 from the original post, as that will also cover the denormalization option, as well as allow the base API to do its work.

Verdict: Do NOT use method #2. Do use method #1. I would implement __construct() and set the node class upon instantiation:

public function __construct() {
  this->supportedInterfaceOrClass = NodeInterface::class;
}


D8: render block in node? We're migrating some code to D8 and in some of our nodes' body field we used to call PHP code directly with the now defunct module_invoke to render a block in the node before the content.

All the examples I can find explain how to do that in D8 with themes or templates, but I need to render the block inside the node body using PHP code, is there a way to do that?

We already tried:

\Drupal::moduleHandler()->invoke($module, $hook, $args = array())

but it doesn't show the block, presumably because it only takes modules?

From this answer we also tried:

$block = \Drupal\block_content\Entity\BlockContent::load($bid);
$render = \Drupal::entityTypeManager()->getViewBuilder('block_content')->view($block);

Trying to print or render $render either doesn't show anything or literally prints out an array.

You can do the following:

In hook_preprocess_page() add the following code.

$block_entity = Drupal\block_content\Entity\BlockContent::load(BLOCK_ID);// BLOCK_ID
$block_view = \Drupal::entityTypeManager()->getViewBuilder('block_content')->view($block_entity, 'DISPLAY_VIEW_NAME');
if ($block_view) {
    $variables['page']['my_block'] = $block_view;
}

In your Twig template, print the block with the following code.

{% if page.my_block %}
  {{ page.my_block }}
{% endif %}


How to organize content via taxonomy, blocks, panels, views? I am new to Drupal. I have a guitar lessons site that I want to convert to drupal. Guitar lessons are a container that contain exercises, and lessons are categorized - I set up taxonomy). Exercises contain text, and media: audio, video, an image or two. Main image (tab) will automatically be displayed, audio will have link, and video would appear in tab, as would secondary image (fretboard diagram). So the media could be imagined as having its own mini horizontal panel or something below the image. Some audio/video will be designated as accessible to registered users only. On left there would be block that lists exercises in the current lesson. In lesson page there would be navigation (next exercise, etc, as well as a show all exercises option).

Not sure how to create this container-exercises relationship. And since I want people to be able search on exercises by themselves, apart from a lesson, I need a way for exercises to not only be attached to a lesson, but to be categorized and accessed on their own. I suspect taxonomy is the key here.

I have been reading about Panels as a way to control layout without editing themes. Also read about Views and understand the query function they play as well as perhaps display of results. So I understand these will be key. I have set up the exercise content type, adding custom fields. But now I am at a dead end. I don't know the process flow to make Drupal display the content the way I am seeing it in my head. And I don't know to what extent the tools will get the job done vs me having to code. I know PHP very well, CSS so-so, and Javascript so-so. I am trying to avoid coding if possible, except for minor tweaks. From building my site in postnuke some years back and doing an insane amount of coding, I know I don't want to repeat that!

Any tips on how you would go about this design with taxonomy, panels and views (or other tools) will be very appreciated. I would even be willing to hire someone to help me get started (apology if that is against the posting rules!).

This is a very broad question Brian, but I think it boils down to 'how should I handle relationships between entities'.

Take a look at the Entity Reference module.  With that you can create links between your various nodes so that you can display them on the same page.

For instance let's say your main content type is exercise, on each exercise node you could use the module to create links to a video and a fingering diagram (or several).  Then for each other thing you wanted to display on the page, you create a view with a contextual filter that looks for the node id of the exercise which is being displayed.

I highly recommend finding some reading or videos on how contextual filters in views works.

Panels makes the handling of contexts a little bit easier in the long run.  There's an excellent tutorial on Page Manager.


Template file not loading for block view I have a block view in the header. The suggested tpl files are block__mens_header (block--mens-header.tpl) as well as node--mens-header.tpl For some reason the more general tpl files are working but I need to get specific here. Is there a preprocess function I need before these will be seen?

I seem to remember, in drupal 6 at least, that you need to have block.tpl.php there, even if you don't modify it at all, in order for the specific block templates to be seen.

ADD:  If it's in there, you might try a preprocess_block() hook with something like:

$variables['template_files'][] = 'block--mens-header';

stuck in it.  This should point it to block--mens-header.tpl.php in your theme directory.  Obviously, wrap that in some logic so it's only set for the block in question.


Image style is not working for larger size image I am working on a drupal 7 site http://imgmart.com where I have defined multiple image styles. I have a content type called gallery with image cck field. Everything works fine if I upload image of lower resolution like 800px (around 1 MB) file. When I upload larger resolution image, image style won't work but image file is getting uploaded successfully. I don't see any error reported in log file or log messages page.

What could be the issue?

If you allow users to upload large images, you might run into this problem even after upping the PHP memory limit. If this happens, I strongly recommend installing this module: Max Image Size.

Suppose you allow users to upload 10mb image files straight from their digital camera, without forcing them to use image editing software.

Without Max Image Size module, the uncompressed image data for that massive file is held in memory and manipulated multiple times for each image style. That consumes a huge amount of memory. For many-megabyte "straight from camera" images that'll often exceed any memory limit you could or would want to place on a web server for one user's process.
With Max Image Size, there's a step before that honking great image reaches GD, cleanly scaling it down once to a large-but-reasonable size (2560x1600 by default, this setting can be changed). All the image style manipulations are then done to that image using much less memory.

This also has the effect of capping the largest possible size another user would get if they click an "original image" link. Very occasionally this might be a problem  (e.g. if you're selling professional stock images and need the original monster-sized file - though even then it might be better to upload a raw or tiff file as an untouched plain download alongside the JPG), but usually it's a good thing too. If a user is on mobile data and clicks a full-size image link, they'll normally expect something like a high-quality 2560x1600 wallpaper, not some beast that takes minutes to load and wipes out a substantial chunk of their data allowance.


What is Drupal caching based on? What does Drupal use for caching? Is this something like APC or memcache? Where does it store cache files?

Out of the box, it's stored in the database, in a number of tables names cache_[name_of_bin].

There are lots of other options if one wants to configure it differently.

Memcache
MongoDB A nice feature is that mongo supports replication across multiple databases
APC
Varnish Doesn't replace normal caching, but integrates with Varnish so Varnish can invalidate cache when Drupal does
Boost Can generate static HTML files from content.

Also see Lullabots Beginners guide to caching data in drupal 7 (Thanks  Chapabu!).


Views PDF CSS file not being applied on generated PDF I've created a pdf display with views_pdf module in views, and under the PDF SETTINGS i've included a CSS File (eg. sites/all/themes/custom/mytheme/css/mytheme.css).

When viewing the page display of the view, the css is being applied, but when viewing the generated pdf, all of the css is missing.
I have tried putting inline css as well but it's not working.

Can someone tell me what is the workaround for this?

What worked for me is to rewrite the field. For the title field it would be something like:

[title]

And then use this custom class in my CSS file.


What is the correct way to save checkboxes values on form submission? The FAPI documentation gives the following instruction and example:

  checkboxes

  Description: Format a set of checkboxes. #options is an associative
  array, where the key is the #return_value of the checkbox and the
  value is displayed. The #options array cannot have a 0 key, as it
  would not be possible to discern checked and unchecked states.

$form['high_school']['tests_taken'] = array(
  '#type' => 'checkboxes',
  '#options' => drupal_map_assoc(array(t('SAT'), t('ACT'))),
  '#title' => t('What standardized tests did you take?'),
  ...
),

I have the following element in my form constructor:

'audio_options' => array(
  '#type' => 'checkboxes',
  '#title' => t('Options'),
  '#options' => drupal_map_assoc(array(
    t('Controls'),
    t('Autoplay'),
    t('Loop'),
    t('Buffer'),
  )),
  '#attributes' => array('class' => array('container-inline')),
),

and the following in my submit handler:

$node->field_audio_options[LANGUAGE_NONE] = $form_state['values']['audio_options'];

On submission the error thrown is:

  PDOException: SQLSTATE[HY000]: General error: 1366 Incorrect integer
  value: 'Controls' for column 'delta' at row 1

Why does the documentation say that you can use a string as the options key, when presumably it is saved in the delta column of the field's table, which requires an integer?

What is the correct way to save checkboxes values on form submission?

Thanks.

The arrays aren't of compatible formats, you need to prepare them yourself:

foreach (array_filter($form_state['values']['audio_options']) as $selection) {
  $node->field_audio_options[LANGUAGE_NONE][]['value'] = $selection;
}


How do I prevent a form from being cached for anonymous users? I have a form that is pre-populated with information specific to an anonymous user's session information. However, the form appears to get cached for all anonymous users by default.
'Internal Dynamic Page Cache' is enabled, 'Internal Page Cache' is not.

How do I disable caching of this form? It should be rebuilt fresh every time it is displayed.

To update:

In order to prevent a form from caching at all, you can include the following #cache key in your form:

$form['#cache'] = ['max-age' => 0];


Drupal 7 - How to show an upcoming event from site 1 on site 2? For Drupal 7, Is it possible to show an upcoming event from site A on site B's block?

Also, is it possible to show an upcoming event by category? For example, I wanna have an upcoming event for swimming class and an upcoming event for hiking group. However, they are all in one same calendar.

Thanks,
HL

You can use Shared Blocks, it has both drupal 6 and 7 stable releases:

If you have a main site with blocks that you want to syndicate across several
other websites, you need this module!

Features:

Allows publishing and subscribing of Drupal blocks
Changes to published blocks are updated on sites with subscription blocks
Published blocks provides a JSON endpoint at sharedblocks/{module}/{delta}
Block subscriptions are updated on cron with an adjustable refresh interval


content administration page not found, and user manager page not found I don't know what did this...but now when I try and go to my content manager or my user manager I get a 'page not found' in the admin overlay.

.htaccess is ok and nothing has changed in the php.ini

Where do I look next?

also to note:  admin/people/people is giving me Permission denied?!   I am UID 1 obviously...

updated:  the add content button is still there..  so im guessing this is some broken core module?  I have tried replacing the core and it still is giving me the same thing.
attached is a screeen

Admin_views was turned on and not functioning causing the overridden admin url aliases it uses to throw this error.

After disabling, the admin screens returned to normal function.


How do I insert HTML just before the body closing tag? I am looking for the best way to insert arbitrary HTML content into a page before the closing body tag, similar to the way drupal_add_js() adds JavaScript to the bottom of a page.

I am coming from a Wordpress background, and in Wordpress this could be accomplished by using the wp_footer() hook.

I have looked into using hook_page_alter(), but I was wondering if this was the correct way to do this or if there is a better way of accomplishing this task.

The equivalent of hook_footer() that was used in Drupal 6 is to implement hook_page_build(), and alter the content of $page['page_bottom'], using code similar to the following one:

function mymodule_page_build(&$page) {
  $page['page_bottom']['devel'] = array(
    '#weight' => 25,
    '#markup' => '
' . devel_query_table() . '
',
  );
}

The content of $page['page_bottom'] is output from html.tpl.php, using the following code:

  <?php print $page_top; ?>
  <?php print $page; ?>
  <?php print $page_bottom; ?>

The value of $page_bottom is initialized from template_process_html() using the following code:

  // Render page_top and page_bottom into top level variables.
  $variables['page_top'] = drupal_render($variables['page']['page_top']);
  $variables['page_bottom'] = drupal_render($variables['page']['page_bottom']);
  // Place the rendered HTML for the page body into a top level variable.
  $variables['page'] = $variables['page']['#children'];
  $variables['page_bottom'] .= drupal_get_js('footer');

The difference between hook_page_alter() and hook_page_build() is that hook_page_alter() is executed after hook_page_build() and should be used to alter, or remove content added by another module, while hook_page_build() should be used to add new content to the page.


Add html markup to Drupal Webform I want to extend the simple text the Webform module allows for radio buttons to include HTML markup.

The Drupal Options Markup module purports to add markup to the text for radio buttons. It does, but it also seems to be very buggy and causes missing index errors in the Webform module.

Hand coding seems to be a better option. Digging into hook_form_alter, I can see where the array is built.

Here is the question: How do add markup to the plain text of the #options array. From the forms api reference, the t function is used. Can I insert HTML into that?

   '#title' => t('Selected'),
   '#options' => array(
      0 => t('No'),
     1 => t('Yes'),

The result I want can be seen in the Illustration from webform options markup.

You can't add html to the t() function.
A quick (and maybe dirty way) is to just do something like this:

   '#title' => t('Selected'),
   '#options' => array(
      0 => t('No') . 'Markup',
     1 => t('Yes') . '

Markup

',


Invalidate cache on a REST endpoint I have an endpoint that returns an array of Order entities, but it's caching the results so when a new order is placed the cache has to be cleared.

The code within the endpoint is:

// Tried this also.
// $this->orderManager->resetCache()
$orders = $this->orderManager->loadByProperties([
  'uid' => $this->customer->id(),
]);
$response = new ResourceResponse($orders);
// maybe this doesn't work because it's an \Drupal\Entity\commerce\Order[]
$response->addCacheableDependency($orders);

return new ResourceResponse($orders);

What am I missing?

See the comment from @Clive, you can only add single objects as dependency. But you need to add a list tag as well, because the entity query may change because of entities added or modified that are not in the cached list.

$list_tags = \Drupal::entityTypeManager()->getDefinition('entity_type')->getListCacheTags();
$response->getCacheableMetadata()->addCacheTags($list_tags);


Media theme missing from the file system? Not really sure about this error, I wasn't aware there was a media theme but could anyone help me understand this please?

  User warning: The following theme is missing from the file system: media in drupal_get_filename() (line 268 of core/includes/bootstrap.inc).
  drupal_get_filename('theme', 'media') (Line: 291)
  drupal_get_path('theme', 'media') (Line: 394)
  Drupal\Core\Asset\LibraryDiscoveryParser->drupalGetPath('theme', 'media') (Line: 85)
  Drupal\Core\Asset\LibraryDiscoveryParser->buildByExtension('media') (Line: 87)
  Drupal\Core\Asset\LibraryDiscoveryCollector->getLibraryDefinitions('media') (Line: 66)
  Drupal\Core\Asset\LibraryDiscoveryCollector->resolveCacheMiss('media') (Line: 149)
  Drupal\Core\Cache\CacheCollector->get('media') (Line: 44)
  Drupal\Core\Asset\LibraryDiscovery->getLibrariesByExtension('media') (Line: 58)
  Drupal\Core\Asset\LibraryDiscovery->getLibraryByName('media', 'form') (Line: 54)
  Drupal\Core\Asset\LibraryDependencyResolver->doGetDependencies(Array, Array) (Line: 56)
  Drupal\Core\Asset\LibraryDependencyResolver->doGetDependencies(Array) (Line: 31)
  Drupal\Core\Asset\LibraryDependencyResolver->getLibrariesWithDependencies(Array) (Line: 104)
  Drupal\Core\Asset\AssetResolver->getLibrariesToLoad(Object) (Line: 116)
  Drupal\Core\Asset\AssetResolver->getCssAssets(Object, ) (Line: 291)
  Drupal\Core\Render\HtmlResponseAttachmentsProcessor->processAssetLibraries(Object, Array) (Line: 161)
  Drupal\Core\Render\HtmlResponseAttachmentsProcessor->processAttachments(Object) (Line: 45)
  Drupal\Core\EventSubscriber\HtmlResponseSubscriber->onRespond(Object, 'kernel.response', Object)
  call_user_func(Array, Object, 'kernel.response', Object) (Line: 111)
  Drupal\Component\EventDispatcher\ContainerAwareEventDispatcher->dispatch('kernel.response', Object) (Line: 191)
  Symfony\Component\HttpKernel\HttpKernel->filterResponse(Object, Object, 1) (Line: 173)
  Symfony\Component\HttpKernel\HttpKernel->handleRaw(Object, 1) (Line: 68)
  Symfony\Component\HttpKernel\HttpKernel->handle(Object, 1, 1) (Line: 57)
  Drupal\Core\StackMiddleware\Session->handle(Object, 1, 1) (Line: 47)
  Drupal\Core\StackMiddleware\KernelPreHandle->handle(Object, 1, 1) (Line: 99)
  Drupal\page_cache\StackMiddleware\PageCache->pass(Object, 1, 1) (Line: 78)
  Drupal\page_cache\StackMiddleware\PageCache->handle(Object, 1, 1) (Line: 47)
  Drupal\Core\StackMiddleware\ReverseProxyMiddleware->handle(Object, 1, 1) (Line: 50)
  Drupal\Core\StackMiddleware\NegotiationMiddleware->handle(Object, 1, 1) (Line: 23)
  Stack\StackedHttpKernel->handle(Object, 1, 1) (Line: 664)
  Drupal\Core\DrupalKernel->handle(Object) (Line: 19)

This warning generally occurs if Drupal can't find the folder of the related module or theme. There is a manual page on how to get rid of this error: How to fix "The following module is missing from the file system..." warning messages

But looking at the date of the question, there is a big chance this is happening because of version conflict in media_entity module and source provider modules. If your media_entity module is installed and its version is 1.x, then your core media module is not installed. And if you are using 2.x versions of media source provider modules like media_entity_video or video_embed_field, they are probably looking for the core media module. If you're building a new website you should start over with the core media module. If you're upgrading your existing site, you should follow the upgrade path. Instructions for both are at the media_entity module page.


How to check if page exists using page alias in D7? In D7, how do I check whether a page exists by page alias? I've found some guy asking the same very question but I have problems with using menu_valid_path() (or drupal_valid_path() in D7) function. It always returns TRUE, no matter how weird a path I pass to it. Here is a sample code:

if(drupal_valid_path($GLOBALS['base_url'] . '/contacts')) //this exists
{
    print_r('Exists!');
}
if(drupal_valid_path($GLOBALS['base_url'] . '/weird_alias')) //this doesn't exist
{
    print_r('Exists!');
}

I get two "exists" despite the fact that /weird_alias page doesn't exist and returns a "page not found" error. I'm extremely reluctant to use drupal_http_request() because there are a lot of unnecessary things like headers, timeouts etc. Shouldn't there be an easier way to check internal paths?

If you look at the code for drupal_valid_path() it passes the alias through url_is_external(), which considers paths with a http:// prefix to be external. The function defaults to allow access to these sorts of paths and simply returns that fact; it does not check whether the 'external' url exists.

Since you're adding $GLOBALS['base_url'] to the alias it will appear to be external; you just need to pass the alias into the function without the base URL attached:

if(drupal_valid_path('weird_alias')) {
  // This code is never run
  print_r('Exists!');

}


Unable to add WHERE conditions as OR to query object I'm attempting to override the query method for a node migration in the migrate_d2d module by adding two where conditions with "OR", and the first one is being added as AND instead of OR for some reason.  In this case, there is already one WHERE condition of node type, so I am adding two more, which means I'm trying to change

SELECT blah from {node} WHERE type = 'type1';

to

SELECT blah FROM {node} WHERE type IN ('type1', 'type2', 'type3');

It doesn't look like it is possible to override an existing WHERE condition without completely overriding the entire query method, so it seems that my next best bet is to add the WHERE conditions with OR so that the resulting query is

SELECT blah FROM {node} WHERE (type = 'type1') OR (type = 'type2') OR (type = 'type3');

To accomplish this, based on what I've found searching around (such as here), I used db_or():

$db_or = db_or();
$db_or->condition('type', 'type2')
  ->condition('type', 'type3');
$query->condition($db_or);

However, when I print out the resulting query what I actually get is

SELECT blah FROM {node} WHERE (type = 'type1') AND (type = 'type2') OR (type = 'type3');

and this is verified by the migration results, since the migration doesn't bring across any nodes (which makes sense, since one node can't be of two types).

I also tried it with separate additions to $db_or:

$db_or->condition('type', 'type2')
$db_or->condition('type', 'type3');

and even tried adding as one condition:

$db_or->condition('type', array('type2', 'type3'), 'IN');

but the result is still the same.

What it looks like to me is that no matter how you add a WHERE condition when there already is one, it automatically adds the next one as AND, even if you specify that it should be OR.

So my questions are:

Am I adding these conditions to the query object correctly (assuming I want them as OR)?
Is there a way to remove the initial condition so that I could just add my own WHERE condition from scratch?
Is there a better way to do this?

Thanks.

Am I adding these conditions to the query object correctly (assuming I want them as OR)?

Not quite; all components of the the OR need to be added to the condition object, so you need to do something like this:

$query = db_select('node')->fields('node', array('nid'));

$db_or = db_or();
$db_or->condition('type', 'type1')
  ->condition('type', 'type2')
  ->condition('type', 'type3');

$query->condition($db_or);

That'll give you this query string:

SELECT  node.nid AS nid
FROM
{node} node
WHERE ( (type = :db_condition_placeholder_0) OR (type = :db_condition_placeholder_1) OR (type = :db_condition_placeholder_2) )

  Is there a way to remove the initial condition so that I could just add my own WHERE condition from scratch?

Yes you can use SelectQuery::where(), but there's really no need. You can use the above, or preferably...

  Is there a better way to do this?

Yes, by using IN as you originally planned:

$query = db_select('node')
  ->fields('node', array('nid'))
  ->condition('type', array('type1', 'type2', 'type3'), 'IN');

That gives:

SELECT  node.nid AS nid
FROM
{node} node
WHERE  (type IN  (:db_condition_placeholder_0, :db_condition_placeholder_1, :db_condition_placeholder_2))

Note that the third parameter of "IN" to condition() isn't strictly necessary, as the DB class automatically assumes "IN" if an array is passed.


How can I manually change image orientation? I manage a website with Drupal 7 where users can upload pictures from their mobile or from their desktop. I have configured Image Style with "autorotate" effect and most of the pictures are well displayed after styling.

But some are misoriented and I'd like to be able to manually change the picture orientation (or let the user do it).

Do you know a solution for this ?

1 Read an image in JS from attached file https://developer.mozilla.org/ru/docs/Web/API/URL/createObjectURL

2 Use Lib for reading Exif data from jpg for autorotation as default option https://github.com/exif-js/exif-js

3 Create controls for manual rotate image on canvas as manual tool https://stackoverflow.com/questions/17411991/html5-canvas-rotate-image

4 Send on server additional param with rotation value (for apply rotation to orig image on server side)
    OR
  Apply rotation on original size image on JS and send result on server as base64 code. Decode to binary data in server side and put it on disk.

sorry for my english


Ctools modal_form not working with webforms i have been trying all morning to get my webform to open up within ctools modal_forms popup window. i’ve tried everything, but nothing has worked so far.

the module is working no problem. this form window displays as expected.

mywebsite.com/modal_forms/nojs/register

and my webform is published and working

mywebsite.com/webform/free-trial

but when viewing docs and tuts on the module,  the URL would seem to be

mywebsite.com/modal_forms/nojs/webform_free-trial

i’ve also manually created links such as this

Modal Login

Modal Login

even went to the config page and set,

PAGE ACTIVATION SETTINGS/Only the listed pages

webform/free-trial

Mondo Aggro! any help would be greatly appreciated, thank you

The issue is your modal link path isn't correct. When using Webforms the link needs to use the Node ID (nid), not the form clean-url (/modal_forms/nojs/webform/[nid]) Here's how the link would look considering your example above:

Free Trial


Getting the workflow associated to a node type How do i get the workflow entity associated to a certain node bundle? So far my approach has been to use EntityTypeManager to load the workflow config entity storage and trying to load the right workflow using loadByProperties() function,

$workflow = $this->entityTypeManager->getStorage('workflow')->loadByProperties();

except I don't know what properties I should be specifying or If I'm approaching this the right way.

Workflows are configuration entities so you can load them using their id:

$workflow = $this->entityTypeManager->getStorage('workflow')->load('workflow_machine_name');

Or "query" them using the Entity Query (check the Drupal 8 example shown here):

$query = $this->entityTypeManager->getStorage('workflow')->getQuery();
$query->condition('type_settings.entity_types.node', 'article', 'IN');
$workflows = $query->execute();

The condition is a proof-of-concept drawn from another config entity query but is the right path you need to test it agains the workflow entity schema.


How to add an exposed filter to a view programatically? How would one go about adding an exposed filter item to any given view programatically?

EDIT 1: This needs to happen during the request. So, I'm guessing some views hook needs to be used.

Depends on the filter you need, but, let's say you want to filter by Node type, then you would use the following in a views.inc file included into your module within a hook_views_default_views() function.

$handler->display->display_options['filters']['type']['id'] = 'type';
$handler->display->display_options['filters']['type']['table'] = 'node';
$handler->display->display_options['filters']['type']['field'] = 'type';
$handler->display->display_options['filters']['type']['value'] = array(
    'news' => 'news',
);
$handler->display->display_options['filters']['type']['expose']['operator'] = TRUE;

For a sample of what this file may look like, pull up the node.views_default.inc file in the views module. You can also create a view and choose to look at what the code behind it if you need the particular syntax for a filter. The option to export is found at the top right of the view within the edit screen. I would search hook_views_default_views() for additional information.


Drupal Commerce "let me know when the price goes down" I've been trying to create a price alert for products of which price dropped (let users flag that product and e-mail them when that product's price drops). For this purpose, I installed Flag and have been trying to make such a thing with it and Rules. Am I on the right track? If not, what can I do?

Regards,

In product content type add a new radio field "Would you like to receive an email if the product price change?" with options Yes and No.

Install Token module and Rules module

You can write a rule to send an email whenever the product node price field is updated to only users who has selected Yes option. you can do this by adding a standard available condition or you can execute a custom php code and use Token to access the radio button value.


"Uncaught TypeError: Cannot call method 'call' of undefined at 507 jquery.validate.js" I am trying to implement clientside validation using the clientside validation model. I have been following the documentation located here. Specifically the Form API Section for Drupal 7. I believe I have followed the instructions faithfully but when I try it out I get the following error:

Uncaught TypeError: Cannot call method 'call' of undefined at 507 jquery.validate.js

Here is my slightly modified jquery script I am using:

(function ($) {
  //Define a Drupal behaviour with a custom name
  Drupal.behaviors.dynamicTextfieldValidator = {
    attach: function (context, settings) {
      //Add an eventlistener to the document reacting on the
      //'clientsideValidationAddCustomRules' event.
      $(document).bind('clientsideValidationAddCustomRules', function(event){
          //Add your custom method with the 'addMethod' function of jQuery.validator
          //http://docs.jquery.com/Plugins/Validation/Validator/addMethod#namemethodmessage
          jQuery.validator.addMethod("validInputType", function(value, element, param) {
              return value !== '';
          }, jQuery.format('Field can not be empty'));
      });
    }
  }
})(jQuery);

The code looks right to me but I am no javascript expert. Any ideas what I could be doing wrong?

Thanks.

Try closing Drupal.behaviors.dynamicTextfieldValidator with a semicolon

  };
})(jQuery);