Generically detecting changed fields in a custom form prior to saving a node

This, at long last, should work as a generic solution. Thanks to Clive and morbiD for all the input.

Pass both versions of the node to the following function. It will:

Pull all of the detected content type's editable fields and their editable columns (i.e. items that could possibly appear on the custom form) from the database in a single query.
Ignore fields and columns that are completely empty in both versions.
Treat a field that has a different number of values between the two versions as a change.
Iterate through every field, value, and column and compare the two versions.
Compare items non-identically (!=) if they are numeric and identically (!==) if they are anything else.
Immediately return TRUE on the first change it detects (since one change is enough to know we need to resave the node).
Return FALSE if no change is detected after all the values are compared.
Recursively compare field collections by loading them and their schema and passing the results to itself. This SHOULD even allow it to compare nested field collections. The code should NOT have any dependency on the Field Collection module.

Let me know if there are any more bugs or typos in this code.

/*
 * Pass both versions of the node to this function. Returns TRUE if it detects any changes and FALSE if not.
 * Pass field collections as an array keyed by field collection ID.
 *
 * @param object $old_entity
 *   The original (stored in the database) node object.
 *   This function may also pass itself a FieldCollectionItemEntity object to compare field collections.
 * @param object $new_entity
 *   The prepared node object for comparison.
 *   This function may also pass itself a FieldCollectionItemEntity object to compare field collections.
 */
function _fields_changed($old_entity, $new_entity) {
  // Check for node or field collection.
  $entity_is_field_collection = (get_class($old_entity) == 'FieldCollectionItemEntity');

  $bundle = ($entity_is_field_collection ? $old_entity->field_name : $old_entity->type);

  // Sanity check. Exit and throw an error if the content types don't match.
  if($bundle !== ($entity_is_field_collection ? $new_entity->field_name : $new_entity->type)) {
    drupal_set_message('Content type mismatch. Unable to save changes.', 'error');
    return FALSE;
  }

  // Get field info.
  $field_read_params = array(
    'entity_type' => ($entity_is_field_collection ? 'field_collection_item' : 'node'),
    'bundle' => $bundle
  );
  $fields_info = field_read_fields($field_read_params);

  foreach($fields_info as $field_name => $field_info) {
    $old_field = $old_entity->$field_name;
    $new_field = $new_entity->$field_name;

    // Check the number of values for each field, or if they are populated at all.
    $old_field_count = (isset($old_field[LANGUAGE_NONE]) ? count($old_field[LANGUAGE_NONE]) : 0);
    $new_field_count = (isset($new_field[LANGUAGE_NONE]) ? count($new_field[LANGUAGE_NONE]) : 0);

    if ($old_field_count != $new_field_count) {
      // The two versions have a different number of values. Something has changed.
      return TRUE;
    } elseif ($old_field_count > 0 && $new_field_count > 0) {
      // Both versions have an equal number of values. Time to compare.

      // See if this field is a field collection.
      if ($field_info['type'] == 'field_collection') {

        foreach ($new_field[LANGUAGE_NONE] as $delta => $values) {
          $old_field_collection = entity_load_unchanged('field_collection_item', $values['entity']->item_id);
          $new_field_collection = $values['entity'];

          if (_fields_changed($old_field_collection, $new_field_collection)) {
            return TRUE;
          }
        }
        unset($delta, $values);

      } else {
        foreach($old_field[LANGUAGE_NONE] as $delta => $value) {
          foreach($field_info['columns'] as $field_column_name => $field_column_info) {
            $old_value = $old_field[LANGUAGE_NONE][$delta][$field_column_name];
            $new_value = $new_field[LANGUAGE_NONE][$delta][$field_column_name];
            $field_column_type = $field_column_info['type'];

            // As with the overall field, exit if one version has a value and the other doesn't.
            if (isset($old_value) != isset($new_value)) {
              return TRUE;
            } elseif (isset($old_value) && isset($new_value)) {
              // The column stores numeric data so compare values non-identically.
              if (in_array($field_column_type, array('int', 'float', 'numeric'))) {
                if ($new_value != $old_value) {
                  return TRUE;
                }
              }
              // The column stores non-numeric data so compare values identically,
              elseif ($new_value !== $old_value) {
                return TRUE;
              }
            } else {
              // Included for clarity. Both values are empty so there was obviously no change.
            }
          }
          unset($field_column_name, $field_column_info);
        }
        unset($delta, $value);
      }
    } else {
      // Included for clarity. Both values are empty so there was obviously no change.
    }
  }
  unset($field_name, $field_info);
  // End of field comparison loop.

  // We didn't find any changes. Don't resave the node.
  return FALSE;
}

Sometimes you are interested in knowing which fields have changed.
In order to know that, you can use this version of the function:

/*
 * Pass both versions of the node to this function. Returns an array of
 * fields that were changed or an empty array if none were changed.
 * Pass field collections as an array keyed by field collection ID.
 *
 * @param object $old_entity
 *   The original (stored in the database) node object.
 *   This function may also pass itself a FieldCollectionItemEntity object to compare field collections.
 * @param object $new_entity
 *   The prepared node object for comparison.
 *   This function may also pass itself a FieldCollectionItemEntity object to compare field collections.
 */
function _fields_changed($old_entity, $new_entity) {
  // Check for node or field collection.
  $entity_is_field_collection = (get_class($old_entity) == 'FieldCollectionItemEntity');

  $bundle = ($entity_is_field_collection ? $old_entity->field_name : $old_entity->type);

  // Sanity check. Exit and throw an error if the content types don't match.
  if ($bundle !== ($entity_is_field_collection ? $new_entity->field_name : $new_entity->type)) {
    drupal_set_message('Content type mismatch. Unable to save changes.', 'error');
    return FALSE;
  }

  // Get field info.
  $field_read_params = array(
    'entity_type' => ($entity_is_field_collection ? 'field_collection_item' : 'node'),
    'bundle' => $bundle
  );
  $fields_info = field_read_fields($field_read_params);

  $fields_changed = array();

  foreach ($fields_info as $field_name => $field_info) {
    $old_field = $old_entity->$field_name;
    $new_field = $new_entity->$field_name;

    // Check the number of values for each field, or if they are populated at all.
    $old_field_count = (isset($old_field[LANGUAGE_NONE]) ? count($old_field[LANGUAGE_NONE]) : 0);
    $new_field_count = (isset($new_field[LANGUAGE_NONE]) ? count($new_field[LANGUAGE_NONE]) : 0);

    if ($old_field_count != $new_field_count) {
      // The two versions have a different number of values. Something has changed.
      $fields_changed[] = $field_name;
    }
    elseif ($old_field_count > 0 && $new_field_count > 0) {
      // Both versions have an equal number of values. Time to compare.

      // See if this field is a field collection.
      if ($field_info['type'] == 'field_collection') {

        foreach ($new_field[LANGUAGE_NONE] as $delta => $values) {
          $old_field_collection = entity_load_unchanged('field_collection_item', $values['entity']->item_id);
          $new_field_collection = $values['entity'];

          $fields_changed = array_merge($fields_changed, _fields_changed($old_field_collection, $new_field_collection));
        }
        unset($delta, $values);

      }
      else {
        foreach ($old_field[LANGUAGE_NONE] as $delta => $value) {
          foreach ($field_info['columns'] as $field_column_name => $field_column_info) {
            $old_value = $old_field[LANGUAGE_NONE][$delta][$field_column_name];
            $new_value = $new_field[LANGUAGE_NONE][$delta][$field_column_name];
            $field_column_type = $field_column_info['type'];

            // As with the overall field, exit if one version has a value and the other doesn't.
            if (isset($old_value) != isset($new_value)) {
              $fields_changed[] = $old_field;
            }
            elseif (isset($old_value) && isset($new_value)) {
              // The column stores numeric data so compare values non-identically.
              if (in_array($field_column_type, array(
                'int',
                'float',
                'numeric'
              ))) {
                if ($new_value != $old_value) {
                  $fields_changed[] = $field_name;
                }
              }
              // The column stores non-numeric data so compare values identically,
              elseif ($new_value !== $old_value) {
                $fields_changed[] = $field_name;
              }
            }
            else {
              // Included for clarity. Both values are empty so there was obviously no change.
            }
          }
          unset($field_column_name, $field_column_info);
        }
        unset($delta, $value);
      }
    }
    else {
      // Included for clarity. Both values are empty so there was obviously no change.
    }
  }
  unset($field_name, $field_info);
  // End of field comparison loop.

  return $fields_changed;
}

Sometimes you may want to make it so that changing certain fields of a node do not cause that node's "changed" timestamp to be updated. This could be implemented like as follows:

/**
 * Implements hook_node_presave().
 */
function mymodule_node_presave($node) {
  $fields_changed = _fields_changed($node->original, $node);
  $no_update_timestamp_fields = array('field_subject', 'field_keywords');
  if (!empty($fields_changed) &&
    empty(array_diff($fields_changed, $no_update_timestamp_fields))) {
    // Don't change the $node->changed timestamp if one of the fields has
    // been changed that should not affect the timestamp.
    $node->changed = $node->original->changed;
  }
}

EDIT (7/30/2013) Tightened up field collection support. Added support for fields with multiple values.

EDIT (7/31/2015) Added version of function which returns which fields have changed, and example use case.


RedHen Registration: where is the display settings?

Well after a break and with my mind a bit clearer.
The display settings don't depend of the registration type, they can be found in "manage display" of the content type (in my case "Event"). Only that no matter what display one choose it will always appear a tab for "registration", but I think this can be manage with the css.


How to get view by tag sorting the same as main view sort criteria

You can add another argument/contextual filter (surename). And in the contextual filter settings you could specify the sort criteria when the filter is not in URL. You can choose the sort criteria numeric or alphabetical as in the screen shots

Then

Edit: If you have a content type called directory, and the content type has taxonomy term reference and a field called surname you can replicate the config in the screen shot below and it should work. Note contextual filter and sort criteria settings:
 1. Page View config note:

 2. Contextual filter taxonomy tag settings
 3. How the it will display the summary:
 4. How it will display the content, note how it is sorted by surname


How to use TinyMCE 4.5 with the WYSIWYG module?

The previous version of the WYSIWYG module didn't support TinyMCE, but it does now.


How can I download specific dev version of Drupal module?

For the easiest way to do it:

Go into the repository
Select a version there and click on it
There will be hash of commit (example)

So, you know the hash of commit - just clone this module from repository and switch to required hash of commit.

How to clone module via git

How to checkout the specific commit

Example:

git clone --branch 7.x-1.x https://git.drupal.org/project/geocoder.git
cd geocoder
git checkout c994066d58bc7518bc9796c60d4d43f98ae477cd


I'm using Webform. How can I use JavaScript in it?

You should try Webform conditional module.

  This modules enhances the existing Conditional Rules of the Webform
  Module. It adds the ability to make components dependent on select
  components(i.e. listboxes, radio buttons, and checkboxes) that appear
  on the same page.

Screencast Demo

View a demonstration form


How can i load a table on changing a select option using AHAH callback

Try to add some wrapper to your table:

function list_user_form(){
   $form['howmany'] = array(
      '#title' => t('List all the users in a group'),
      '#type' => 'select',
      '#options' => select_usergroup_dropdown_options(),
      '#default_value' => $default,
      '#ahah' => array(
         'path' => 'mailusers/listuserstable',
         'effect' => 'fade',
         'wrapper' => 'mytable'
      )
   );

   $form['mytable'] = array(
      '#title' => t("Generated table"),
      '#prefix' => '
',
      '#suffix' => '
',
      '#type' => 'fieldset',
      '#description' => t('This is where we get automatically generated table')
   );

   $form['submit'] = array(
      '#type' => 'submit',
      '#value' => t('Click Me')
   );
   return $form;
}

function listuserstable(){
   // make html for the table and rendering it
}


Mobile Tools detects mobile and iPad, not Android tablet

Have you looked at ThemeKey? It has OS based redirection rules. Here is a quote about it (from the module's project page):

... allows you to define simple or sophisticated theme-switching rules which allow automatic selection of a theme depending on current path, taxonomy terms, language, node-type, and many, many other properties. It can also be easily extended to support additional properties exposed by other modules. In combination with Drupal's theme inheritance you can easily achieve features like:

individually-styled channels
a front-page / "splash" screen
a date/time-selected Christmas theme
mobile themes for different auto-detected mobile devices
special themes for "limited" or "old" browsers
content, user, or role -specific themes
indicating your environment (production, staging, testing, sandbox, … )
testing your redesign safely on a live server


Get nodes by content type when type key is not in root of nodes array

With an EntityFieldQuery:

$query = new \EntityFieldQuery();
$query->entityCondition('entity_type', 'node')
  ->propertyCondition('type', 'page')
  ->fieldCondition('field_worktype', 'value', 'foo');

$result = $query->execute();
if (!empty($result['node'])) {
  $nodes = node_load_multiple(array_keys($result['node']));
}

As an aside, the method in your OP (using the $conditions array) is deprecated in favour of EntityFieldQuery anyway, which can perform the same filters.


How to alter search query to include custom fields?

For the normal Drupal search you can do so by defining a custom search type in a module.

Use hook_search_info() to define your custom search type & hook_search_execute($keys = NULL, $conditions = NULL) to create or extend your search query.

More available hooks can be found at the Drupal's Search interface or by looking up the search contrib module under yourdrupal\modules\search\search.api.php


Generate image styles with a rule on "node save"?

There seems to be a third module that has this ability already, however it doesn't seem to be compatible with Rules just yet. It is compatible with Trigger however (I don't know if this allows it to be automatically compatible with Rules...let me know if you find out how). Here is the module: http://drupal.org/project/ispreg


Old site migration and keeping links (as aliases)

There's no real need to escape the URI string.

Here's one way to handle this:

In a custom module, implement hook_menu(), creating an item for the path 'faculty.php'
In your php function callback for the above path, look at the PID value, look up the new path (you do have a database table mapping old content to new content, right? :) ), and do a 301 redirect.

Another approach is to do this lookup on all 404 pages with something like the following code in a hook_init():

function hook_init() {
  if (!menu_get_item($_GET['q'])) {
    $pid = isset($_GET['PID']) ? $_GET['PID'] : FALSE;

    if ($pid) {
      // lookup new path and 301 to it
    }
  }
}


To list content owned by a user you can:

Create a View that lists content
Create a Page Display within that view
Configure a "Contextual filter" for "Content: Author UID" and set its "When the filter value is NOT in the URL" setting to "Provide a default value", then select "User ID from URL" for the "Type".


How do I download drupal from my webhost so I can run on my home server?

Answer courtesy of Dipen:

"You need to adjust the username/password value in settings.php. You need to put valid username/pwd applicable on home server mysql instance."


Views: How to show titles of nodes but hide link based on role

I found it. I added a boolean field with Yes as the value for access, No for no access. This requires some careful management, as the value of this field has to equal the given access control.
But in Views everything is very easy, using the extra boolean field.
I added both Titles (Title1 being the one without a link, Title2 with link) and the boolean field. Both titles excluded from display, the boolean included.
In its settings rewrite i input [Title2], and in the empty behaviour [Title1]. That's all.


Admin Config page for my module is empty

'page_callback' => 'drupal_get_form',
'page_arguments' => array('casabaca_s3s_admin'),

needs to be

'page callback' => 'drupal_get_form',
'page arguments' => array('casabaca_s3s_admin'),

(underscores removed from array keys)


content_extra_field_weight() function in Drupal 7

Invoke hook_field_extra_fields(), pass the result to  hook_field_extra_fields_alter() and look for weight keys in the result.


Notice: Array to string conversion in token_replace() (line 102 of /var/www/html/includes/token.inc)

Check Notice: Array to string conversion in token_replace() (line 102 of /.../includes/token.inc).

  This is a dirty fix that excludes wrong values passed into the
  token_replace(). Use it only as a last resort, this does not solve the
  issue but only disables the message !

  Open token.inc and change the content of token_replace()

return str_replace($tokens, $values, $text);

  Change to:

 foreach ($replacements as $value => $replacement) {
   if ((!is_array($value)) && (!is_array($replacement))&& (!is_array($text))) {
     $text = str_replace($value, $replacement, $text);
   }
 }
 return $text;


You have multiple options:

You can use code that iterates over all nodes and changes the value of the field (you will need some module to execute the code, for example devel).
Other option is to use the Views Bulk Operations module, build a view which shows a list of nodes of that type, and add a views bulk operations field which has the option to edit a node, and this will allow you to select all the nodes in a view and modify a field with the same value.


Looks like you're mistaking the function definition for an implementation example.

The function definition describes the arguments to use, but it's not a literal example of how to call it.

So when you want to use the drupal_goto() function, instead of this:

drupal_goto($path, array $options = array(), $http_response_code = 302);

It should look more like this:

drupal_goto($path, array(), 301);


Change the submit handler of a form of a module

I think that it solves the problem to do like this

$form['#submit'] = array("my_module_form_submit_handler");

Here's the whole function:

function my_theme_form_alter(&$form, $form_state, $form_id) {
  $form['#submit'] = array("my_module_form_submit_handler");
}

function my_theme_form_submit_handler($form, &$form_state) {
  drupal_set_message("The form is being submitted, do some extra stuff now...");
}


CSS Not Displaying Correct Via .info File (ok on page.tpl)

I suspect it's because, when it's ross.css, your css gets applied before another .css file; while, when it's in .tpl it gets applied after.

Ex: if h1 exists with the same command, it uses the last h1 (which is in some other .css file).

JS FIDDLE EXAMPLE

So try adding !important; to your css. ex: h1 { border: solid red !important; }

JS FIDDLE EXAMPLE 2


How do I send an email containing the user password?

First thing, you cannot send the password. You can only send a reset/one-time-login link. Passwords in Drupal are a one-way street, they can never be retrieved. To send the link is pretty easy. Use _user_mail_notify()

_user_mail_notify('password_reset', $account);


This should do it:

function MYTHEME_preprocess_page(&$vars) {
  if (drupal_is_front_page()) {
    drupal_add_js(drupal_get_path('theme', 'MYTHEME') . '/MYSCRIPTS/myscript.js');
    $vars['scripts'] = drupal_get_js();
  }
}

FYI:  You'd use drupal_get_js in case any modules are also using hook_preprocess_page and setting new scripts themselves.

Also, I wouldn't just add a newer version of jQuery in willy nilly.  Try either jQuery Update or jQuery Multi


In a twig, how do I access different fields of a specific content type in a taxonomy term page

When you display a taxonomy term the output is produced by this View:

admin/structure/views/view/taxonomy_term

The taxonomy term itself is in the header

HEADER
Global: Rendered entity - Taxonomy term (Global: Rendered entity - Taxonomy term)

and uses the taxonomy term template shown in your question, where you have only access to the fields of the term, not the content.

The format of the content is configured in the main part of the View. Default is to display the content as Teaser:

FORMAT
Format:Unformatted list | Settings
Show:Content | Teaser

If you want to change the fields, you can customize the Teaser in UI:

admin/structure/types/manage/article/display/teaser

Or in this node template (this targets the View, so it would also work, if you changed the view mode):

node--view--taxonomy-term.html.twig

Or switch to a field based View and configure the fields inside of the View.


Drupal doesn't have a way to generally replace a function in a module with a function implemented by another module.

In the case of hooks, you could alter the output of a hook with another hook, but in your case you don't even need this. Just implement hook_node_insert(), hook_node_update(), and hook_node_delete(), and add the code necessary for counting the tags used by nodes.

As said from Jaypan, you don't say in which way querying the taxonomy_index table would be too expensive. I am not sure it would be that expensive, since the table saves the taxonomy term IDs and the node IDs: You just need to count the table rows with a specific value for tid.


Why can't I reinstall my module after uninstall?

This is not so easy right now.

One way to do it is to put a forced dependency in those configurations, then they will be uninstalled together with a module. Core might even switch to doing that automatically, as I just discussed with @alexpott.

I'm not really sure how you are using that module. I have a feeling that is not what you want.

  How share my site configuration (block, field, view, etc.) without this problem please ?

Share how? With whom? Multiple separate sites, or dev/staging/production of the same site?

If the second, then do not use a module for this. Use the configuration staging folder and the configuration sync API/UI, that is designed to deal with updated default configuration.

If the first, keep in mind that default configuration is only designed for one use case: Initial default configuration when a module is installed for the first time. Modules are not meant to be re-installled to install updated configuration, the only way to do it like that would be first remove all the configuration and then create it again. That will not work for things like fields, because you will lose your data.


How to Move Tooltip Away from Checkbox in Bootstrap Theme?

If you open up the settings for your theme under the appearance tab there should be a javascript tab. If you click that the tooltips and popover settings are displayed. You can either turn them off or make them appear below the field.


how to bypass video conversion for mp4 files?

If you haven't already, look at these options under admin/config/media/video

Bypass video conversion

(Bypass video conversion when creating videos.)
Video convert on node submit

(Convert videos on node submit will enable by default for all users.)


I'm sorry to say but, you are doing it wrong.

In some very few cases it could be worth not to write a module for an ajax request. The reason would be that you want to do something simple, not related to Drupal that needs to be very fast. I did this once for a site where I needed to look up if a domain name was registered or not.

In this case you are not isolated from Drupal. You need to know the context of your script (The node id) and you need to use the Drupal API's entity_load, so instead  of creating a custom PHP file and writing code in there, why not create a module which is a PHP file, only it's named foo.module, use the drupal API's to in make the ajax callback hook_menu, and add the javascript with context drupal_add_js and you will save yourself a lot of work, by doing things the Drupal way. Drupal is made it make it easy to develop stuff by creating modules, instead of adding custom PHP files, which makes things a lot more difficult to manage.

If you really wanted to do this without creating a module, you would need to bootstrap Drupal in your custom PHP file (making it pointless to use a custom php file), and add the node id in the preprocess_node hook in your theme.


How can I strip out default markup for a text field?

Several ways to skin this cat. You can use a custom tpl.php as suggested, or, you can also explore some contrib modules such as display suite or fences.


Webform default validation message altering

For Drupal 8, Webform uses Drupal's default Email Form Element. You'll have to override this element info and add your own validation message there.

See https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Render%21theme.api.php/function/hook_element_info_alter/8.5.x


Price formatter for range of variation products

Commerce Pricing Attributes

  This module provides some enhancements to the Commerce Product Option
  and Commerce Product Attributes handling by applying pricing rules to
  custom product attributes. So, you can add attributes to products that
  affect the final product price.

Dynamic price calculation based on selected operators.
Cart combination based on product attributes.
Support for multi currency.
Multilingual attributes.
Different attributes and settings per product.
Price adjustments either per item or per order.
Rules integration.
Easy UI for editing and reordering attributes


How to pass an extra argument to an entity form?

Have a look at https://www.drupal.org/node/2310425

This should explaine everything needed.

Here is an example how it would look like:

mymodule.entityB_add:
  path: '/admin/config/mymodule/{entityA}/{entityB}/add'
  defaults:
    _entity_form: 'mymodule_entityA_entityB.default'
    _title: 'EntityB'
  requirements:
    _entity_create_access: 'mymodule_entityA'
  options:
    parameters:
      entityA:
        type: entity:entity_type_a
      entityB:
        type: entity:entity_type_b


Is it possible to avoid using Views PHP?

A possible solution that might help to simplify the challenge in your question, is to use the fairly new Math Field module (for D7). Some more details about this module (from its project page):

  The Math Field module defines a new field type to dynamically calculate values on entity forms. This is an alternative to Computed Field
  that does not require the use of PHP Filter.

  Math expression fields are dynamically updated via ajax on the entity form as soon as all necessary fields are populated. If JavaScript is disabled, the field will be evaluated when the form is submitted. The result is stored in the database when the form is submitted.

By creating some auxiliary field(s) (calculated via the Math field), you may be able to complete your puzzle. Possibly via some additional logic implemented via the Rules module, to implement logic that is similar to what I described in my answer to "How to set the values of some fields depending on the value of a list box?".

For more details (step-by-step instructions) about Math Field, refer to either of these links:

the (amazing!) Community documentation about the Math Field module.
the interesting article about Introducing the Math Field module, which also includes some screenprints to see it at work (such as the the add/edit form example).


Take a look Commerce File & its dependency Commerce License. These module enable a licensing product functionality tied to some sort of digital file. This will get you a good way there, but you'll probably add extra features for your particular use (e.g. some sort serial code validation before displaying the download link).


How to pass required arguments to a custom content type with services?

1) Firstly you will create your custom resource for POST request.
Add Below Code to your module file.

function Your_Module_Name_services_resources() {
     $resources = array();
     //$_SERVER['REQUEST_METHOD'] = 'POST';
     //Include the necessary inc files.
    module_load_include('inc', 'Your_Module_Name', 'includes/Your_Module_Name.services');

   //Service Apis for contents.
    $resources += Your_Module_Name_resource();
    return $resources;
}

2) Create Your_Module_Name.services.inc file and write below code for your custom callback as given below.

function Your_Module_Name_resource() {
  $api = array(
'applicant_validate' => array( // Resource Name
 'operations' => array(
    'create' => array(
    'help' => 'Validate Applicant',
    'file' => array(
        'type' => 'inc',
        'module' => 'your_module_name',
        'name' => 'includes/your_module_name.services',
    ),
    'callback' => 'your_callback_function_name',
    'access callback' => 'user_access',
    'access arguments' => array('access content'),
    'access arguments append' => FALSE,
    'args' => array(
        array(
        'name' => 'body',
        'type' => 'string',
        'description' => 'Function to perform',
        'source' => 'data',
        'optional' => FALSE,
        'default' => '0',
        ),
    ),
    ),
    ),
  ));
   return $api;
 }

// variable name $body as you mentioned above in args part with name      parameter

function your_callback_function_name($body)
{
  // It's called when you will hit to your web service url from your from submission.

}

Validate Web Service

 <form id="frm" method="post" action="http://example.com/api/endpoint/applicant_validate">
 <input type="text" placeholder="Application Id" name="appno" id="appno"/>
 <input type="text" placeholder="Email Id" name="emailid" id="emailid"/>
<input type="text" placeholder="Mobile Number" name="mobno" id="mobno"/>
<input type="text" name="userpwd" placeholder="Password" id="userpwd"/>
<input  type="submit" value="submit"/>

</form>


This is not a Drupal related problem.

Your 'next' and 'prev' selectors are not specific enough. You should write also the parent block id.

Every block in a page has a unique id attribute in HTML. You should find stuff like

<div id="block-3" class="block">

wrapping your slideshow.

Just declare a more specific jQuery selector, adding the block id.

Here's a modification for your code, assuming that the block has a "block-3" id:

drupal_add_js("jQuery(document).ready(function() {
    // change slideshow with your view name
    jQuery('.view-slideshow .view-content').cycle({
        fx: 'fade',
        speed:  'fast',
        timeout: 3000,
        next:   '#block-3 .views-field-view-node-1', // added a 'parent child' jquery selector
        prev:   '#block-3 .views-field-view-node'
    });
});", 'inline');


Views: add (link to file field) to image field

First add the "Content:File" field
Check "Exclude from display" (hidden)
Under "Formatter" select "URL to file"
Then add your Image field and uncheck "Link this field to the original piece of content" or something similar
Click on "Rewrite Results" and check "Output this field as a link"
In the "Link path" textbox add "Replacement Pattern" from the file field ([field_file] == Content: File, for example)


Returning a db query for select options in webform

If you're creating a select list then you only need two fields from the database, so you can use the excellent fetchAllKeyed() method of the database query. This will let you get your results in a single line of code:

function _MY_MODULE_get_rate_options() {
  return db_query('SELECT id, name FROM {my_table}')->fetchAllKeyed();
}

The result is an array keyed by the first field (id) with values from the second field (name).


Flag the inappropriate content and not allowing people to add a content?

I would look into using rules again.

You are going to need a way of identifying users who should not be able to post. Set a rule to apply a flag to the users account once one of their nodes has been flagged 3 times.

Then use this flag in another rule as an IF to only apply it to said user, then maybe either redirect the users who access node/add pages to a page with a custom warning message or try another form of disabling the node creation. Please see below

  Event:
  Content going to be saved / Accessing a page

  Conditions:
  User is flagged with "suspended user"

  Actions:
  Page Redirect
  Show a message on the site

EDIT: Am I correct in assuming you are wanting users to flag a node inappropriate? You should be able to use something like the rule you have already created to do so, just also flag the node author when you flag the content...


Display of hierarchical Taxonomy in views along with the related content

1-
Use Hierarchical Select module. it may help you.

2- by using the Taxonomy menu module

3- use Views Tree and Views Field View


Can I attach a javascript function to a Drupal.behaviors javascript function?

Yes you can. You can attach as many event handlers to any DOM element as you want.

So you have to write your own module that alters the output (is a form? some form_alter function. Is a page? some ouptut alter function or theme function) adding your custom JavaScript.

In your custom JavaScript add the code using behaviors that attachs your event handlers for the click event.

The tricky part is how you locate the next and prev buttons. You can start from the code snippet you posted. It seems that prev and next buttons are located here:

 var multipageControl = new Drupal.multipageControl({
      title: $('> .multipage-pane-title', this).text(),
      wrapper: $(this),
      has_next: $(this).next().length,
      has_previous: $(this).prev().length
    });

See the has_next and has_previous entries.

Looking at the previous lines you can see:

// Transform each div.multipage-pane into a multipage with controls.

It seems that the $(this) code referes to a div.multipage-pane, so the buttons seem to be:

$prev_buttons = jQuery('div.multipage-pane').prev();
$next_buttons = jQuery('div.multipage-pane').next();

Disclaimer: I don't know that module so I am shooting blindly but I think this approach will work.


Custom form set error for user login validate

you cant submit your form because you have set the error.

the form set error should be applied inside some condition

 function user_information_user_login_form_validate(&$form, &$form_state) {
    //print_r($form_state);
    //set some condition
     if($form_state["some_field"] != "somevalue")// only when the condition satisfies the form set error should display. if not all the time your from set error will be called
      form_set_error('name', t('Password invalid'));
    }

above condition is a sample condition you have to replace it with your own condition for validating your password.


You can try Node View Count module.

  Node View Count module allows to count node views. Unlike statistics module, this module records each view of node with user uid and timestamp. So now you can know how many times a user viewed node by day, week, month and etc.

To print the count in teasers.

Implement hook_node_view()
Check the $node->type and $view_mode
Call nodeviewcount_db_count_node_views($node, $user = NULL, $distinct_users = FALSE) to get the count
Add the count to $node->content
In your template file print the count that you added.

Update:

You cannot rely on IP for uniqueness,  but if you want to count unique views based on IP then follow one of the below steps.

The accesslog table will contain all the access logs with IP details, you can query this table for path like node/nid and group by IP to get the count, One thing to note is that accesslog will be cleared periodically, if you are going to use this table then you have to make sure that it won't be cleared by selecting never in Discard access logs older than. I will not suggest doing this way because this table will contain access log for all pages, though there is a moule Better Statistics using which you can restrict statistics to log access details only for node pages.
Or, you can create a custom module and create a custom table somewhat similar to accesslog and then implement hook_node_view() to populate the table, later you can query the table to get the count.


Problem: users are logged out automatically without any reason, while navigating to the website

There are some settings regarding cookie session lifetime in the settings.php file. These settings might not be allowed for overwriting and your server might have its own rules.

 ini_set('session.cookie_lifetime', 2000000);
 ini_set('session.gc_maxlifetime', 200000);

Check admin/reports/status/php.


Set fields in uc_addresses checkout pane to disabled

It must be a form and You can alter via hook_form_alter.
But in function you should must check the form_id and after that print_r or dpr or dsm (whatever you like ) the $form. And search for the address field and unset it.


Search and display node by scanning a barcode image

How to transfer the code from the barcode image to the text field on the webform upon scanning?

AFAIK most of the scanners place value into focused form element (the one with the cursor in it). So make sure that field is focused when you load the page and that should cover your first question. You can probably use contrib modules (eg. https://www.drupal.org/project/focus) to achieve it without any custom Javascript.

  and what is the best approach for performing the search among all nodes and pull out/display only the node related to the card being scanned.

I think the easiest approach is to create a View with exposed filter (barcode). Then after scanning the barcode on the plastic card, you'll be one click away from a node for an existing card.


401 Unauthorized : Missing required argument node

You put comma on last parameter "type": "discussion", that doesn't required at the end. javascript, jquery, json doesn't allow comma at end of array. It returns invalid argument.


How can I enable search on parts of a word and autocomplete suggestions?

Click in "Edit" this Database server, and navigate to the end of that page:


How do I redirect to a route with POST method?

Normally, you cannot redirect through a HTTP "POST" response. A normal Drupal RedirectResponse (or whatever redirect response you send) will be a 302 or 301 redirect, which is done through the GET method.

Basically, you can do a subrequest, as suggested by Eyal, or you can add some server validation to grant a "200 OK" response through your "hidden" route, such as a CSRF token. To keep alive some posted information, you can use your Session service to flash them for the next request, then flush them in your hidden route after your validation


Getting "--> ;" on front page after editing custom html.tpl file

it is probably stemming from this line:

 is a commenting system for HTML, but the item you are trying to comment out is php, which uses a different method for commenting.

you would use the html commenting around html elements:

whereas for php:

<?php //print $scripts; ?>

or

<?php /*print $scripts;*/ ?>

would be appropriate.


There is a bug in the Date module.  Found this in the Issues queue:
Group Multiple Value functionality is broken, patch for review
in http://drupal.org/node/1086100
The patch in #2 there worked for me.  Hope it gets rolled in, but in the meantime hope this saves someone else some time.


Aegir is a powerful tool to manage hosting environments, deploy new versions of your site, clone a live site to a testing environment... Stuff like that. I don't know which kind of users you're talking about, but I would only give access to experienced Drupal developers. If you want 'normal' end users of a site to be able to setup their own subsite, maybe http://drupal.org/project/subdomain is right for you.


Use this code in a preprocess hook:

$node = \Drupal::entityManager()->getStorage('node')->load($nid);
$view_builder = \Drupal::entityManager()->getViewBuilder('node');
$variables['node_full'] = $view_builder->view($node, 'full');
$variables['node_teaser'] = $view_builder->view($node, 'teaser');
$variables['body_full'] = $node->body->view('full');
$variables['body_teaser'] = $node->body->view('teaser');

And in twig

{{ node_full }}
{{ node_teaser }}
{{ body_full }}
{{ body_teaser }}

Use the rendered node and configure the view modes full, teaser or a custom view mode. The single rendered field does not work well with other code.


Adding a temporary column to a db_select query

You just need to use an expression, e.g.

$query = db_select('people', 'p')
  ->fields('p', array('id', 'date'));

$query->addExpression(':val', 'type', array(':val' => 'thing'));

Gives:

SELECT p.id AS id, p.date AS date, :val AS type
FROM
{people} p

The replacement for :val will be injected when you execute the query.


Form validate & submit functions not firing on form loaded with AJAX

Well im not so sure about exiting...

i would try in my ajax callback:

function MYMODULE_my_ajax_callback() {
  $commands = array();
  $form = drupal_get_form('my_form');
  // im doing a replace command as an example, this could be another command invoked..
  $commands[] = ajax_command_replace('#container-to-append-form', render($form));

  $page = array('#type' => 'ajax', '#commands' => $commands);
  ajax_deliver($page);
}


Getting "Fatal error: Class not found" by bootstrapping external script and executing user_save function

The correct answer could be to also use the necessary namespacing when instantiating the GmapDefaults class:

include_once(DRUPAL_ROOT . base_path() . drupal_get_path('module', 'gmap') . '/lib/Drupal/gmap/GmapDefaults.php');

$macro = !empty($field['settings']['gmap_macro']) ? $field['settings']['gmap_macro'] : '[gmap ]';
$map = array_merge(Drupal\gmap\GmapDefaults::getInstance()->getDefaults(), gmap_parse_macro($macro));

Note that I also converted the original include to an absolute path based include to make sure the path is correct...

I just prepended the necessary namespace before "GmapDefaults::" and it works.


'Views Field' issue in NO RESULTS BEHAVIOR - Hide if empty not working

Your questions does not give much information about your view, but if you want to hide the complete output of a row (when using a table) you can do this:

  You can add filter criteria corresponding to the field on which you
  want to hide  the row . Suppose you want to hide the row if content:
  body is empty then you can add filter criteria as Content:Body not
  equal to "" (where value field should be left empty). This will
  automatically hide the row if the specific field is empty .

source: Hide row in view if any field is empty


How can I add two 'add to cart' ubercart buttons in a product page

I would recommend creating a view:block that displays the product's price and an add to cart button, you can then duplicate the view:block and have in the block admin page, add the two new view blocks to the regions you would like them displayed in.


Multiple Group Managers in Organic Group

OK, so intuition told me that this was a can do... Really, membership and controlling the permissions of members is largely what OG is about.

Anyway, the brief solution that I was looking for is this:

Edit the node containing the group in question from group manager account
Click Group Tab
Click Add people
Add user name
Go back to /admin/people (this is where the magic happens)
Check the box beside the username in update options.
open dropdown box
Select Administrator member click Update

Voilà!

There is much more that can be done (for example adding custom roles). Explore on!


Adding links to $content['links'] in theme layer

You don't have to worry about overwriting what is there, just don't overwrite anything :)

The correct place for altering links is generally hook_node_view_alter(), as you mentioned.

For adding your own links it is hook_node_view()

As an example see http://drupal.org/node/224333#node_links


How to remove a specific term page link?

Little bit tricky but you can achieve without code.

Add a new boolean field to taxonomy term.(eg: show link(field name))

Save for each term show link value either true or false. Depend you wants to show the link or hide the link for that term.

Add three fields like shown in the image in your views.

Taxonomy term: Name [hidden] -- Exclude from display and deselect link to taxonomy term

Taxonomy term: Term ID [hidden]  -- Exclude from display

Taxonomy term: show link


Getting translations programmatically from non-default language

This will work for a node that has a field_animal with translation (in Drupal 8).
First we found the french translation then we compare with the string, second we fetch the english translation.

$myString = 'Chien';
$translation = \Drupal::service('entity.repository')->getTranslationFromContext($node, 'fr');
$animalFr = $translation->get('field_animal')->value;
if ($myString == $animalFr){
  $translation = \Drupal::service('entity.repository')->getTranslationFromContext($node, 'en');
  $animalEn = $translation->get('field_animal')->value;
}


The process list is saying that Mysql is writing to tmp tables.  The issue is the way you configured mysql.  Check the my.cnf configuration, and make sure that the temporary tables are large enough.


Profile picture with a border color depending of the role

Try hook_preprocess_user_picture() in your template.php

function MYTHEME_preprocess_user_picture(&$vars) {
    $account = user_load($vars['account']->uid);

    foreach ($account->roles as $role) {
        $vars['classes_array'][] = 'role-' . strtolower(str_replace(' ', '-', $role));
    }
}

Each user picture should then have the role-rolename classes added to it.
It is similar to Clive's answer you mentioned, but different hook.


You can control how the user is redirected after login using the Rules module.  Create a rule using the event User logs in and action Redirect to page.  You can create as many redirect rules as you need to get the user to go to the appropriate destination.

For example, for my social networking site, I do the following:

redirect users who haven't completed their profiles to a page telling them they need to do that (condition: user doesn't have profile_completed role)
redirect users who have completed their profiles and have new messages (from private message module) to the message inbox (condition: custom PHP condition)
redirect all other users to the search screen

In my implementation, I actually implemented this as a rule set (component) instead of a bunch of individual rules so that I could easily achieve the third option ("redirect all other users").


Displaying article image on full display conditionally

You have to use Field formatter conditions module to achieve this goal.

First thing attach a field on desired content type with boolean value and then use this field value as a condition in field formatter settings to display other fields as you want.

For more information go through the module documentation.


Different redirect page for registration, login and first time login

I have not tested this but from the documentation page:

  There are no separate triggers for login and registration; instead you
  can differentiate them by specifying the pages that a user comes from:

  user - the user login form.
  user/register - the user registration form.
  user/*/edit - one-time login link, after the user has set the password.
  other - the login block or login forms embedded by other    modules.

It looks like you can specify both three options you ask for.


It is possible with just core views.

Create a view that displays terms
enable aggregation
add relationship Content with term
add sort content uuid with aggregation type: count
add field content uuid with aggregation type: count
add field taxonomy term

Your view should look similar to the following


Selecting English from language selector fails

Go to Configuration and choose Languages.
Edit 'English' language
Add 'en' in 'Path prefix language code' filed
save and flush all cache


Select order type and store with hook_form_alter()

You're overthinking it. As with most elements, you just need to set #default_value on the main element definition itself. Here's working example code I tested in my own development environment:

/**
 * Implements hook_form_FORM_ID_alter().
 *
 * Sets default values on the order add form for the order type and store.
 */
function example_form_commerce_order_add_form_alter(&$form, $form_state) {
  $form['type']['#default_value'] = 'default';
  $form['store_id']['#default_value'] = 2;
}

Obviously you'll need to replace the values I've set with your own. : )


Get URL path or node.id in views fields replacement pattern

But if I click on Add field (in my view), nid, or path are not
  available?

Did you create a view of Show: Content ? (re-using pic from other answer, look in view settings)

You probably selected something else, hence why those fields are not available.

So you could add a relationship of node content or create a brand new view again and this time make sure you select Show: content.


Why can't I change values in my cookies?

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

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

setcookie() has a "$path" argument:

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

So in my setcookie() I now do:

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

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


The name of a preprocess function is based on the theme/template that is being processed. To preprocess the html.tpl.php file you'll need to use hook_preprocess_html():

function media_preprocess_html(&$vars) {
  $node = menu_get_object();

  if ($node && $node->nid) {
    $vars['theme_hook_suggestions'][] = 'html__' . $node->type;
  }
}


How to print node embed field in field collection

You are accessing the raw value of the body field in your code. I guess the functionality of replacing [[nid: 2]] comes from a text filter?

Try rendering the field with field_view_field instead. In the example below the label is also hidden by defining $display and passing that variable along to field_view_field.

$display = array('label' => 'hidden');
$section_desc = field_view_field('field_collection', $field_section_content_info[$section_content_id], 'field_section_body', $display);


How do I block a user/cancel a user account in Simpletest?

Once you've got the user object back from drupalCreateUser() you can use standard API methods to make changes (in this case user_save()):

user_save($user, array('status' => 0));


Grouping fields with field group doesn't work on display of Drupal Commerce product in product variation

The Field Group module provides the ability to group on both the edit form and the display independently.

This means to add a field group to the form you have to do so on admin/structure/types/manage/CONTENTTYPE and to add a field group for display you do it on admin/structure/types/manage/CONTENTTYPE/display (this is for nodes, this will be in different places for other entity types).

If you want the group on both the form and the display you have to add it in both places.


D6 to D7 upgrade error Invalid datetime format Incorrect integer value

I should have posted the answer here instead, it may help someone. This is fixed. I had missing images in the /sites/default/files/ folder. This was a upgraded d6 to d7 site with 4000 nodes and many images. I did not have the latest images in my files folder. So saving a node with uploaded cck field images threw this error.


As per template suggestion for Drupal 7, we have a general format as:

  block--[region|[module|--delta]].tpl.php

  base template: block.tpl.php

  Theme hook suggestions are made based on these factors, listed from
  the most specific template to the least. Drupal will use the most
  specific template it finds:

  block--module--delta.tpl.php block--module.tpl.php
  block--region.tpl.php "module" being the name of the module and
  "delta", the internal id assigned to the block by the module.

Now, in order to override and define your own suggestions apart from these, you can provide new template suggestions in your theme template.php file file using template_preprocess_block as:

function mytheme_preprocess_block(&$variables) {
    $variables['theme_hook_suggestions'][] = 'common_block_template';
}

Now you place(create) this common-block-template.tpl.php file in your themes templates folder and it will be default template for all your blocks and don't forget to clear drupal cache.

Note: This templates will be applied to every block present in your Drupal 7 website i.e. user login block, content block etc.. So make sure you do define logic as per your page requirements as for example if you want to limit this template suggestion for just a uri name mypage, then

function mytheme_preprocess_block(&$variables) {
 if (current_path() == 'mypage') {
  $variables['theme_hook_suggestions'][] = 'common_block_template';
 }
}

UPDATE:
To target delta (with numeric values & to avoid custom module block) the were created using Drupal 7 site building block module:

function mytheme_preprocess_block(&$variables) {
    $block = $variables['elements']['#block'];
   if (is_numeric($block->delta)) {
      $variables['theme_hook_suggestions'][] = 'common_block_template';
    }
 }

If you need to target just block which has delta of 1 then:

function mytheme_preprocess_block(&$variables) {
    $block = $variables['elements']['#block'];
   if ($block->delta == 1) {
      $variables['theme_hook_suggestions'][] = 'common_block_template';
    }
 }


How do I export all of my customers (not users) from Drupal into a CSV file?

With the https://www.drupal.org/project/views_data_export module you can create views and export to CSV, Excel, XML, etc.

It also supports exporting in batches (default activated if the views has 1 000 or more rows). So 10 000 clients shouldn't be a problem.


How to filter by month in view using a date field

If you are using the date module, then you can set the granularity to month in the date filter settings.

Then, you can configure the filter like so Operator: "is equal to" and Date: "this month".

If you don't see these filter settings, you would have to enable the date_views module.


Two concerns: Available for security updates / Image captions

No matter which CMS you use this will always be an issue. If you do not have time to be proactive about maintaining your software, you should look into paying someone to do it for you.
This is the result of Drupal's modular design. It's done this way so it can accommodate the wide-spectrum of use cases. It's a simplicity/flexible tradeoff that can be good and bad depending on the circumstances.


Letting only user #1 pass all the validations of required fields when saving content

You could probably use hook_form_alter and check if the current user is uid=1 then make each field not required any more.

That would be easier for most forms than messing with the actual validation functions and it would also make the UI reflect what is actually happening. You could even put a little message at the top of the form letting the user know that the form has been manipulated like that.


How to display a message according to the country of the store?

For commerce-store--online--full.html.twig it should looks like:
  {% if store_entity.address.country_code == FR %}

        ENTREPRISE FRANÇAISE

  {% elseif store_entity.address.country_code == BE %}

        ENTREPRISE BELGE

  {% endif %}


Is there a way to cancel a node deletion using rules?

You should be able to do this via the conditions field in the rules module. Unsure how to create an 'are you sure' option, but you could certainly stop them from doing it with rules.

There might be better solutions, but here's what I'd do if I wanted to achieve what you are doing.

Install Flags and Rules module. Create flag to appear on Content Type 'Phone call' called 'Delete this call'.

In rules create two rules. One called Delete call, the other called 'display message about unable to delete call'.

First rule:

Triggered on action - node is flagged
Conditions - Entity has field call date/time (whatever the field is called)
           - Data comparison - select the date/time field, then is greater than +1 minute.

Then action - unpublish content

For the second rule do the same but change second condition to less than - 1 minute. Then as the action do 'display message on the site' and select message as 'Unable to delete calls that have passed'.

That should work.


The function you are looking for is theme_render_template(), which gets the filename of the template file to render, and an array of variables to pass to the template file.

In Drupal 6, it is called as in the following code.

 $messages = drupal_set_message();
  if (isset($messages['warning'])) {
    $title = count($messages['warning']) > 1 ? 'The following update warnings should be carefully reviewed before continuing' : 'The following update warning should be carefully reviewed before continuing';
    $variables['messages'] .= '<h4>' . $title . ':</h4>';
    $variables['messages'] .= theme('status_messages', 'warning');
  }

  // This was called as a theme hook (not template), so we need to
  // fix path_to_theme() for the template, to point at the actual
  // theme rather than system module as owner of the hook.
  global $theme_path;
  $theme_path = 'themes/garland';

  return theme_render_template('themes/garland/maintenance-page.tpl.php', $variables);

theme_render_template() is still present in Drupal 7, and Drupal 8.

In Drupal 7, although, the function is only used from theme(). There isn't generally any reason to call the function directly; you can define a new theme function that uses a template file, and then call theme() as theme('theme_function', $array). (Replace 'theme_function' with the name of the theme function.)


How to pass field value to referenced node template?

TL,DR: No.

Long version:

Conceptionally entity render arrays are self-contained, cachable units. The Drupal way would be either preprocessing and a custom cache context based on the referencing node, or a views block with a contextual filter.

But IMHO both ways are terrible workarounds, your Twig snippet {% include ... with ... %} is the better technique.


change order of shipping services in checkout

Unfortunately, there's a pending feature request to make these orderable via the user interface, but in the meantime you're dependent on code to change their ordering. The hook to use is hook_commerce_shipping_collect_rates(), and what you need to do is alter the weight value of the line items in the $order->shipping_rates array.


Do tokens work with Rules "Set a data value"?

I have found the answer to my own question and thought I'd share. The solution is to use Token Filter module. Once you have installed this module got to: Admin > Config > Content Authoring > Text Formats. Create a new Text Format or edit an existing one and you will see an option called "Replace Tokens", check this and save your format. Now when your are using "Set Data Value" make sure that the text field has the input format that you just created/changed.

You should now be able to pass tokens successfully using Rules Set Data Value and they will format correctly.


Contextual filters with multiple taxonomy vocabularies

I think you will need the following setup to work. I'd test this extensively, as it seems somewhat fragile.

a) Prefix your city taxonomy path alias pattern to something like 'cities/[term-name]'. You can't create a view page with a path that starts with an argument.

b) Add another view (you may want to disable the default tax term view or alter the default taxonomy term view ) with 2 contextual filters, 1) Content: Has taxonomy term ID set to provide default value (raw path using 2 component and alias) restricted to the city vocab. and 2) Content: Has taxonomy term ID set to provide default value (raw path using 2 component and alias) restricted to the places vocab.

These contextual filters will share these settings: in the validation criteria, Filter value type set to 'Term name converted to Term ID' and tick the 'Transform dashes to URL to spaces in term name filter values' checkbox.

For the second contextual filter, set 'Action to take in filter value does not validate' to "Show all", which will allow you show all results when viewing 'cities/london'.

Note, using this technique can be problematic if you anticipate any of your terms containing apostrophes, b/c the path alias for a term with an apostrophe can be name-s-something and this won't be converted to a term id.

c) Then, you'll need to alter the link generated by your existing unordered list of places view. Not sure how to go about this in the UI alone. If you share your exported view code, I'll take a look. If you can, you could create a view field template file to retrieve arg(0) and arg(1) and then use those results to generate the link in the template file.


How do I show a list of nodes referenced by a field?

The "Entity reference" field has a few options about how to display the referenced entities (Label, entire node, Node ID).

But you're referencing News agencies from News nodes, not the other way around. So you're able to choose how News agencies are listed on News pages through the "Manage display" settings in Content type.

If you want to list nodes on the News agency pages you need to use Views to create "backwards" Relationship:

Create Views listing News, Block display
Add a Contextual filter for the Entity reference field relating to the News agency and configure it
When the filter value is NOT available
Provide default value
Content ID from URL
When the filter value IS available or a default is provided
Specify validation criteria
Content
Related? News agency

Test the configuration by entering one of your News Agency NIDs into the Views Preview field. You should see News nodes that relate to that agency in the view results.
If everything is working as expected place the Block into a region in your theme and configure it to only appear on the News Agency pages, and configure the filter option for the reference.

Now when you visit News Agency pages you'll see a list of all News that relate to that agency.


Possible reasons why status report page is blank

I didn't manage to get the php logging, but I do know now why this report page was blank. I had installed a not complete functioning module named Backup and Migrate Opencloud that needed Libraries 7.x-2.0 or higher. I was still on 7.x-1.0. After I updated to the latest libraries version the status report page showed up again.


How to create a Search API search box that redirects you to the search page

There was a similar question for Drupal 7 Expose a view's filters both in a block, and in the actual view. In Drupal 8 this should be much easier, you can do this in UI:

Place the block Exposed form: search_content-page_1 a second time, now in the region Content above the block Main page content and configure the visibility to show only on pages with the path /search/content.


It's a well known problem of Drupal 7 - every form button is rendered with type="submit".

What you need to do, is to add prevent="click submit mousedown" to your button, to prevent actual submission. Maybe only one of those 3 is really needed, but this combination gave me pretty consistent results.

OK, but the above only prevents form from actual saving data. It still gets validated, and that's not exactly what you want, right? I already got answer on how to omit form's validation at AJAX button click.

Other approach would be to either add custom form element, let's call it real_button, a copy of button but with type="button", or to change type on document ready using jQuery.


Print the query which is built using db_select()

SelectQuery implements SelectQuery::__toString(), which is called in the contexts where a string is required.

Consider the following code.

global $theme_key;

$query = db_select('block')
  ->condition('theme', $theme_key)
  ->condition('status', 1)
  ->fields('block');

print $query;

Its output is the following one.

SELECT block.*
FROM
{block} block
WHERE  (theme = :db_condition_placeholder_0) AND (status = :db_condition_placeholder_1)

To get the array of arguments used for the query, you can call SelectQuery::arguments().

The following code prints the query and its arguments using the functions made available from the Devel module.

global $theme_key;

$query = db_select('block')
  ->condition('theme', $theme_key)
  ->condition('status', 1)
  ->fields('block');

dpm((string) $query);
dpm($query->arguments());

The Devel module is not necessary, though, and you could drupal_set_message() to show the output. For example, you could use the following function to get a  string with the placeholders replaced by their actual values.

function _get_query_string(SelectQueryInterface $query) {
  $string = (string) $query;
  $arguments = $query->arguments();

  if (!empty($arguments) && is_array($arguments)) {
    foreach ($arguments as $placeholder => &$value) {
      if (is_string($value)) {
        $value = "'$value'";
      }
    }

    $string = strtr($string, $arguments);
  }

  return $string;
}

The previous example code I shown would become the following one.

global $theme_key;

$query = db_select('block')
  ->condition('theme', $theme_key)
  ->condition('status', 1)
  ->fields('block');

drupal_set_message(format_string('Query: %query', array('%query' => _get_query_string($query))));

function _get_query_string(SelectQueryInterface $query) {
  $string = (string) $query;
  $arguments = $query->arguments();

  if (!empty($arguments) && is_array($arguments)) {
    foreach ($arguments as $placeholder => &$value) {
      if (is_string($value)) {
        $value = "'$value'";
      }
    }

    $string = strtr($string, $arguments);
  }

  return $string;
}

Notice that SelectQuery::arguments() returns the array of query arguments only when it is called after SelectQuery::__toString(), SelectQuery::compile(), or SelectQuery::execute(); otherwise, SelectQuery::arguments() returns NULL.

You could use a function similar to the following one to get the string query, with the placeholders replaced with the arguments.


How to add a view with contextual filters in a panel

I added %1 to arguments and it seems to be working now. But can someone explain what this is exactly? I don't really understand why its working with this.


Feeds Module Periodic Import not working

If you are using Ultimate Cron, make sure you set the 3 hour cron to the Job Scheduler cron and and also to the Feeds crons (there are like 4 of them).


Different payment methods for different product types

The product's type is a property of the commerce_product entity, so you can use the built-in "Data comparison" condition to test it.

Just add a new condition of type "Data comparison", and make the data selector look like this:

When you continue you'll get a screen like this:

As you can see you get a nice drop down list of product types to choose from. I just tested that and it works a treat.

If that isn't working for whatever reason, it's pretty easy to implement your own rules condition in a custom module:

function MYMODULE_rules_condition_info() {
  return array(
    'commerce_product_is_type' => array(
      'label' => t('Product is a certain type'),
      'parameter' => array(
        'product' => array(
          'label' => t('Product'),
          'type' => 'commerce_product',
        ),
        'type' => array(
          'label' => t('Product Type (Machine Name)'),
          'type' => 'text'
        )
      ),
      'group' => t('Commerce Product'),
      'callbacks' => array(
        'execute' => 'MYMODULE_commerce_product_is_type',
      )
    ),
  );
}

function MYMODULE_commerce_product_is_type($product, $type) {
  return $product->type == $type;
}


How do I update the unit price of an order item on Add to Cart in Commerce 2.x?

I managed to update the price by updating the order item of order rather than the order item in event.

$items = $event->getOrder()->getItems();
foreach ($items as $key => $item) {
    $currencyCode = $item->getUnitPrice()->getCurrencyCode();
    $unit_price = new Price('20.00', $currencyCode);
    $item->setUnitPrice($unit_price,TRUE);
    $item->save();
}


I can't access a provided variable in rule action

I was having this problem with a different module with Rules.  I believe the data types are conflicting.  node:author:name is a string, while the value have calculated is an integer, a decimal or a float.

My Problem:

User Field - Voting Currency (set as integer)

Event:

Vote was cast on entity

Action:

Query database for the value of the vote cast
Calculate the value to add/subtract from the Voting Currency field
Set the new value of Voting Currency field.

I discovered the vote was a decimal data type.
I removed the Voting Currency integer field with a Voting Currency decimal field and everything worked!


Must implement interface > Drupal\Core\Entity\EntityTypeManagerInterface, none given in __construct() function

A bit late but the code from EventSubscriber has three arguments so your services.yml file should read:

services:
  custom_module.order_complete:
    class: Drupal\custom_module\EventSubscriber\PurchaseBuildRegistration
    arguments: ['@entity_type.manager', '@rng.registrant.factory', '@current_user']
tags:
  - { name: event_subscriber }


How to interlace ouput of nodes two content types in views

You could create a view that outputs the two node types and then use hook_views_pre_render() to sort, shuffle, or arrange the $view->result array any way you wanted.  Then when it is rendered in the next steps, it would be printed however you wanted.  You would hook into this like:

function YOURMODULE_views_pre_render(&$view) {

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

    // do whatever you want with $view->result[]

  }

}

MORE INFO:  $view->result[] is an array of "rows" basically, eg $view->result[0] contains all the raw data that makes up the first row, $view->result[1] is the second, etc.


What causes 'Invalid form POST data' when removing an attached file from a node?

I can confirm, increasing 'max_allowed_packet' in our MySQL config solved this problem. MySQL's default of 1 megabyte was too small. Increasing it to 16M, then restarting MySQL has resolved this issue.

Info on our solution was found here:
https://www.shift8web.ca/blog/2014/11/drupal-problem-an-ajax-http-request-terminated-abnormally/


How to add a new webform submission formatter for the webform components

What you have in that list are date formats. You can manage those, including adding new ones, at /admin/config/regional/date-time.


Modifying twig file to show elements side-by-side

It’s likely because field.label_element is a p tag, which makes the new line.

Try to use span instead, like this:

{{ field.label }}{{ field.label_suffix }}

  {{ field.content }}

You can also add a
 tag after the closing a tag to make sure that all label/content sets are shown on separate lines.

Since the above did not work in your case, you can add a div around the two elements and then you can add some simple flexbox styling in your css to get the desired result.


Is there any way to show user profile of authenticated user after loged in?

You can use Author Pane module to display a block of user information.

  Author Pane is a block of information about a given user, like those
  typically found on a forum post, but can be used in other places as
  well. From core, it collects the user picture, name, join date, online
  status, contact link, and profile information. In addition, any module
  or theme can feed it more information via the preprocess system. All
  of this information is then gathered and displayed using a template
  file.

If you do not want to use this module, then you can create a views to display user information.

Go to Administration -> Structure -> Views
Click on "Add new view" link
Set name for views in "View name" field and select "users" from "show" drop down.
Click on "Continue and Edit" button
Create a block display for the views.
Add "User: Picture", "User: E-mail", "User: Name" and "Global: Custom text (Custom text)".
Check check-box "Output this field as a link" under "Rewrite results" section for "Global: Custom text" and set "user/logout" as Link path for the field.
Save the views


Module Structure question from perspective of PHP dev

Content Types and /or entities would be the way to go about this.  Content types you can think of as objects that are fieldable.  So for example your course would have fields that would represent an objects property.  All content types are node and accessed similarly and can be distinguished by a node id (nid).  Content types automatically integrate into views.

Views can be used to display your data on the courses and they can be filtered by using exposed filters, or filtered by using contextual filters (arguments from the URL).  Content types are automatically usable in views along with their fields

Entity references are the backbone of relationships in drupal.  In an object sense you can have a one to one, one to many relationships with other objects or content types.  So your course may have sections and what not so in drupal you would create a content type of both Course and Section and then reference them using the entity references module.  See entity reference module which must have the entity api module

Taxonomy is a way to tag stuff so if you want to tag a course a certain subject you could use a field that is a taxonomy reference.


I'm unable to select and saveany text filters except for "Filtered HTML".

As far as I know, this functionality is "broken" in D7, meaning that the UI is at least misleading. Here's some discussion https://drupal.org/node/1003262

What you can do is change the order of text formats at admin/config/content/formats. The default text format available to users will be according to permissions and the order of text formats.

Also see http://drupal.org/project/better_formats. That will give you more options.

Also see How do you set a default input text format per content type?


hook_field_attach_presave not saving - user profile field

You'll need to implement hook_field_presave(). You can find out from the parameters passed in if it's being invoked for an address field saved to a user account and do the necessary transformation on the 'locality' of the address field value in the $items array.


Illegal choice detected with Unlimited Image field

I had similar issue, fixed it by changing one of my required field from radio buttons to "select list".


How can I make views show 10 items if there are actually less (and add placeholders)?

You can add the empty rows to the view in the View's Style output template. Assuming you are using the unformatted style, the template name would be views-view-unformatted--[view-name].tpl.php.

Using the default views-view-unformatted.tpl.php as a starting point, add the following to the top of your custom template:

<?php
$num = count($rows);
$add = (10 - $num);
for ($i=0;$i<$add;$i++) {
  $rows[] = '
Empty Row
';
  $classes_array[] = 'views-row views-row-' . ($num + $i);
}
?>

If you're worried about the views-row-last classes, etc, the same sort of logic could be applied earlier in the view build process using something like hook_view_pre_render(), but depending on your scenario, the above should suffice.


You can use your theme's template.php to add a theme_password() wrapper to inject your custom vars:

function MYTHEME_password(&$variables) {
  $node = menu_get_object();
  if(isset($node->nid) && $node->nid == 5) { //Check for display on node/5
    //@TODO: Add $variables altercation
  }
  return theme_password($variables);
}


This is not the place to ask for tutorials.  Exactly what you need depends entirely on what exactly you are trying to accomplish.

To answer your question in general, yes Drupal can be used to create any sort of web app you want, with the proper modules.

First, you should look through the modules page to show the expandability of Drupal and determine which modules you need to accomplish the desired effect.  There are over 16000 modules available.


You do not have to include all of that jquery libraries: Drupal core has that libraries. You can just include any jquery.ui library with drupal_add_library('system', 'ui.datepicker') or another library which you want to include. Then, in your JavaScript file, you can write something like this.

(function ($) {
  Drupal.behaviors.custom_js = {
    attach: function(context) {
      $('#YOURID input[type="text"]').datepicker({
        showOn: "button",
        buttonImage: Drupal.settings.basePath + "sites/all/themes/YOURTHEME/images/calendar.png",
        dateFormat: "dd-mm-yy",
        showAnim: "slideDown",
        buttonImageOnly: true
      });
    }
  };
})(jQuery);

If you want to use the datepicker with the form API, you have to change the type element to 'date_popup'.


Drush remote with switching shell users (sudo)

Set 'remote-user' => 'www-data' in your site alias, and Drush will exec the remote Drush as the www-data user.  ssh-copy-id www-data@server.example.com, and you'll be all ready to go.


The setting on the content type's field display settings page allows you to choose image style to display. Drupal only generates styles when they're used somewhere.


OK, I wanted to post that I figured this out. You have to go to the content type and enable "Repeat". For me it was in the vertical tabs of the Events content type. Once I did that and set it to the date field it worked. BUT the Date Repeat section in the Events content type edit form did NOT work. I just ignored this section altogether and once I create the single event and save, a tab appears above the content titled "Repeat." When I click on that, I see basically the same settings as I did when creating the node, but this time they actually work!!! –


Feeds XPath Parser - Update existing content

it doesn't recognized the nid field as unique,

What is  the field associated with the nid value?

If you have a custom field associated with the nid :

You should install https://www.drupal.org/project/field_validation

and add the validation of the field at
http://yourwebsite/admin/structure/field_validation

and set the validator with the value "Unique values".

Sometimes a space in the value of the feed can cause this in this case you can use tamper for trim spaces :
https://www.drupal.org/project/feeds_tamper


Making images go to external sites in Slick carousel

I found the solution. In the Slick settings, I set the Link to the custom text field. For most of the time I've been working on this that field did not show up in the Link dropdown. But suddenly it did.

At first it's misleading because the Views preview shows the original image with the smaller linked image overlaid. However, if you go back to where the block is placed, the images will appear correctly. Whew!


flowplayer - stream from file:///fodler/video.flv possible?

Flash video has problems playing from some local URLs in Windows, but it mainly has to do with network shares.  The workaround is to map the share to a drive letter.

You may also be having problems with local file access versus network resource access.  Google "flash player security restrictions" for an overview.  With the Flowplayer SWF, you are likely out of luck for working around this w/o getting users to change security settings.

The best option is to use a local web server.  With this you may even be able to get Drupal running off of your memory stick.  There are several options, but I have had good luck with Server2Go.  I have never used it with Drupal, though.


Any better popup modal framework in drupal

Could the Colorbox module be useful for you?

  Colorbox is a light-weight, customizable lightbox plugin for jQuery 1.3 through 1.6. This module allows for integration of Colorbox into Drupal.


changing role wen opening a confirmation link but auto login with logintoboggan

If using rules module, then you will have an event: when user account is activated. when rule fires you can define action add role.

For sending email even: when user account is created and then as action send email.

There is more possibilities. I like to do it with custom modules so I can simpletest the code. If so, use hook_user_insert() and hook_user_login(). In hook_user_login() check for user roles.


How do I implement a one page navigation with anchors?

This is the code I'm using on most of my projects

(function ($, Drupal) {
  var wt = window.wt || {}; //just my personal namespace

  wt.getFixedTop = function() {
    /* return pixel height of fixed elements, e.g. Admin Toolbar or a fixed main nav */
  };

  wt.scrollTo = function(uri) {
    if ((uri.indexOf(location.pathname) === 0 || uri.indexOf('#scroll') === 0) && uri.indexOf('#scroll') !== -1) {
      var selector = decodeURIComponent(uri.substring(uri.indexOf('#scroll') + '#scroll'.length));
      var regex = /^=[#\.\[\]a-zA-Z0-9-_]+$/;
      if (selector.search(regex) != -1) {
        selector = selector.substring(1);
        $('html, body').animate({scrollTop: $(selector).offset().top - wt.getFixedTop() }, 1000);
      }
      return false;
    }
  }

  $('body').on('click', 'a[href*="#scroll"]', function () {
    wt.scrollTo($(this).attr('href'));
  });

  $('body').imagesLoaded( function() {
    window.setTimeout( wt.scrollTo(location.pathname + location.hash), 200 );
  });

}(jQuery, Drupal));

It requires ImagesLoaded and works within and across pages, and with responsive images. It also allows linking to IDs and classes by appending the proper CSS selector, e.g. /some-page#scroll=.my_class

It certainly is not a perfect solution, but our internal, HTML-trained editors can quickly create deep links to any section they want by adding #scroll=<CSS_ID_OR_CLASS_SELECTOR> to any link.


how to change value of submit button of comment form?

You're replacing the entire element at the moment (which is why it doesn't show). You can change a specific property in the array like so:

$form['actions']['submit']['#value'] = t('Post Comments');

That way you're just setting the #value property, and not removing the other properties that already exist for the element.


Why can only admin user access the print version of a view?

I have a help at this moment from a friend. The solution is simple, just search the permission Access the PDF version in admin/people/permissions and set the permission to the users. The problem was that the permission page is too long and if you search for print you will never find Access the PDF version` permission


theme_menu_link() did the trick. It contains an array under element of #original_link which has the menu name in it. Using that, I can add pipe delimited links to certain menus.

http://api.drupal.org/api/drupal/includes--menu.inc/function/theme_menu_link/7


Retrive specific deleted nodes and re-import

We had this same problem on one of our sites and the best solution we could come up with was to use Node Export as you mentioned. Like you, we didn't have it or UUID installed at that time, but we installed them just for this purpose, and it worked fine.

The only catch is you need to be able to load the backed-up database into a functioning site (we did it on our test server) before you can export the missing nodes.


How do I make the nodes referenced by organic group content also be OG content?

Here is the solution I've come up with.

It works, but might not be the most elegant solution. I didn't think that this would matter too much, since it's only being called on node save, but I'm open for comments and suggestions.

/**
 * Ensure that referenced nodes belong to the same organic group
 *
 */
function MODULE_node_presave($node) {

  if ($node->type == NODE_TYPE) {

    $og = og_get_entity_groups('node', $node);
    $nids = get_referenced_nodes($node);

    foreach($nids as $nid){

      $child_node = node_load($nid);

      //Set the values
      $values = array(
        'entity_type' => 'node',
        'entity' => $child_node,
        'state' => OG_STATE_ACTIVE,
      );

      //Add this node to the group
      $gid = array_values($og['node']);
      $result = og_group('node', $gid[0], $values);

    }
  }
}

/**
 * Helper function - get all node reference fields of a node
 * @param $master_nid - the node id of the referencing node
 */
function get_referenced_nodes($master_node) {

  $fields = field_info_instances('node', $master_node->type);

  $items = array();

  foreach($fields as $field){

    if($field['widget']['module'] == 'inline_entity_form'){
      // Get the node reference items for this field
      $items[] = field_get_items('node', $master_node, $field['field_name']);

    }

  }

  // Loop through and grab the nids
  foreach ($items as $field) {
    foreach($field as $target){
      $nids[] = $target['target_id'];
    }
  }

  return $nids;

}


The issue here appears to be that you have installed the same module in two directories:

sites/all/modules/contrib/i18n

and

sites/all/modules/i18n

and drupal is picking them both up.  If this is the case, I would disable the module, uninstall it, delete one of the directories above, and then re-enable the module.  That should clear this up.

If you can't access your site's admin UI at all, then you will have to go in and remove one of the directories directly; I would suggest removing sites/all/modules/i18n as the other directory appears to be being searched first.

ADDITION:  From some line number searching, the Drupal 6 version of i18n.module declares i18n_variable_set() from lines 881 to 894 and the Drupal 7 version doesn't even get that long--ending at line 610.  This coupled with the fact that the i18n_variable submodule isn't even included with the Drupal 6 version has me thinking you have a sorts of module mish mash going on here.

ADDITION 2:

I just installed the Drupal 7 i18n module on a clean install in:

sites/all/modules/i18n

and enabled it and the i18n variable module.  ALL good.

I then copied the Drupal 6 i18n module's code into:

sites/all/modules/contrib/i18n

and....

  PHP Fatal error:  Cannot redeclare i18n_variable_set() (previously declared in /Applications/MAMP/htdocs/d7lrfm/sites/all/modules/i18n/i18n_variable/i18n_variable.module:116) in /Applications/MAMP/htdocs/d7lrfm/sites/all/modules/contrib/i18n/i18n.module on line 894

so, I would check to see if the same thing is happening on your site and if so, remove the errant Drupal 6 version.  A quick check of the .info files will show you what core version of Drupal they are for.  (And, oops, yes, here I put the Drupal 6 version in sites/all/modules/contrib/i18n and the Drupal 7 one in sites/all/modules/i18n which appears to be opposite of what's happening on your site, but I tried to be as similar as possible :)


IMO you should only allow voting for users which have at least X user points. Here is a technique to get that to work:

Grant some permission when a user's amount of user points reaches X, and take that permission away again if it gets reduced to some amount below that. The obvious permission to be used for this is by using the role which allows voting.
Monitor changes in user points for a user, by using the Rules module like so:

Use the Rules Event that captures user points being rewarded (whereas such points can be negative also ...).
Use the Rules Event (or Rules Action!) as described in How to access current amount of earned userpoints in a Rules Condition? (be aware that there is no out-of-the-box Rules Condition like "does this user have at least X user points"?).
Perform a Rules Action to grant access to the role that allows voting, when the user's amount of user points is at least X (and revoke that access if it is below X). If you'd also use the Conditional Rules module, you can perform both types of Rules Actions (grant and revoke) in a single rule.

With that, all that's left is to pick a vaue for ... X!

Note: this approach does not require any PHP coding, so "programming experience" is not required (you only need to be a bit familiar with Rules, for which there are lots of free tutorials available.


How to map a taxonomy term into Feeds Importer?

It was simpler than what I thought.

The code is exactly the same, but instead of 'value', we have to use 'tid':

function set_profile_value(FeedsSource $source, $entity, $target, array $values, array $mapping) {
    if (substr($source->id, 0, 7) == 'my_data') {
        if (!empty($mapping['profile'])) {
            $entity->{$target}[$entity->language][0]['tid'] = $mapping['profile'];
        }
    }
}


The database API actually has a preferred way to add expressions of this type, namely the SelectQuery::isNull() and SelectQuery::isNotNull() functions. You can use them like this:

$query->isNull('f.fid');

$query->isNotNull('q.field_question_value');


Redirect to front page after emptying the shopping cart (ubercart)

You can use drupal_goto function.

drupal_goto('<front>');


Drupal 8, The file used in the Image field may not be referenced

Check \Drupal\file\Element\ManagedFile for answer, it appears that your file is being saved as permanent, but there is no entry in file_usage table:

if ($file = File::load($fid)) {
      if ($file->isPermanent()) {
        $references = static::fileUsage()->listUsage($file);
        if (empty($references)) {
          // We expect the field name placeholder value to be wrapped in t()
          // here, so it won't be escaped again as it's already marked safe.
          $form_state->setError($element, t('The file used in the @name field may not be referenced.', ['@name' => $element['#title']]));
        }
      }
    }

If you want to store your files permanently, you need to make sure they've got usage entries, to do so, you can tweak you form submit handler a little bit, here's some quick example:

// get file fid wherever it is
$values = $form_state->getValues();
$fid = $values['my_file_field'];

// call file usage service and load file
$file_usage = \Drupal::service('file.usage');
$file = File::load($fid);

// set file status permanent
if(!$file->isPermanent()){
  $file->setPermanent();
}

// check file usage , if it's empty, add new entry
$usage = $file_usage->listUsage($file);
if(empty($usage)){
  // let's assume it's image
  $file_usage->add($file,'mymodule','image',$fid);
}
$file->save();


Restricting Menu Item visibility for certain nodes

I don't know about any module that does what you need. But you could clone you menu (with Menu Clone), remove the particular items and set the visibility to the seperate menus.


hook_views_data TIMESTAMP field is empty

It appears the API is looking for an integer, particularly Unix timestamp and not the MySql timestamp which is transformed into a string. Looking at how Drupal handles the node table was key to grasping this and the hook_views_data documentation indicates that the field is an integer as well.


There are hundreds of improvements. There are also many API changes, but they would only affect custom code using Views hooks, not the views themselves, which are converted upon update.

Some major features:

Functionality similar to Semantic Views.
Group-by support and aggregate functions: you can do queries like "give me the count of nodes written by each user, sort by the amount of nodes DESC."
Views OR: you can separate different filter conditions by OR.
Pluggable pagers.
Pluggable exposed filters: expose items per page, sort.
Header, Footer, and Empty Text as pluggable areas.
Pluggable caching.
More argument, filter, and sort handlers.
Pluggable backends Flickr API, Apache Solr, RDF, etc.
Displays can now be disabled, renamed, and reordered, cloned.
A new UI in the Drupal 7 version.

Most importantly, it provides a much smoother upgrade to Views 7.x-3.x.

See the CHANGELOG.txt for a complete list of changes.


How to update 8.0.x to 8.1.x with composer?

I see, you directly get drupal/drupal. I don't think that's actually supported, you still get a vendor folder from git and the composer.json isn't properly set up. I'm using composer command from this site:

composer create-project drupal-composer/drupal-project:8.x-dev myproject --stability dev --no-interaction

Regarding update, the trick seems to be the following argument to composer require:

composer require --update-with-dependencies "drupal/core:8.1.*"

That updated drupal/core and all dependencies it has.


Delete from Multiple Tables using db_delete()

You can't I'm afraid.

db_delete() takes a single string parameter to define which table the query is to be run against. There's no scope to provide more than one table at a time.

You can run any SQL statement you like, though, with db_query(), eg.

// Deletes all nodes and related author users...please don't actually run this!!
$sql = 'DELETE u, n FROM {node} n INNER JOIN {users} u ON u.uid = n.uid';
db_query($sql);


If you can login with ssh on the server you could use drush to unset the maintenance mode±

drush vset maintenance_mode 0


Looks like that styling is being driven by the flex display on div.region-we-mega-menu.
Creating a style that overrides justify-content: flex-start; to justify-content: flex-end; should do the trick.


moving a drupal website to another server

check the sites/default/settings.php for $base_url

it might have been set for a sub-directory install, and may still reflect the original server location.

if it wasn't set originally, setting it now may help as well.


help to understand files in sites/all/default/files/js folder

Like you said these are just cached versions of the javascript files. Drupal compresses them so they can be served to the user faster, notice the difference in file size between the version 29.1 KB opposed to 117.4 KB.

Are there any error when you clear cache through drush? Mostly I've found that they stay behind when you run drush as a user that cannot modify the files, e.g. a user not in whatever group owns the files. In this case you need to add your user to whatever group owns the files.


How to get link path in custom block for a view?

In your view, in FIELDS add Content: Path

Then in views-view-fields--phrases-block.tpl.php add:

    <a class="my-link-class" href="<?php print $fields["field_path"]->raw; ?>">Path

if the above doesn't work try:

<a class="my-link-class" href="<?php print $fields["field_path"]->content; ?>">Path

If the 1st and 2nd doesn't work, to make the 2nd one work, get rid off all your html markup, because it's probably printing as href="/yourpath"

Click on your Path field and unchecked add default classes.

In field settings, uncheck add field wrappers.


How to clear cache for config entity after making changes?

Yes, you have to add the cacheable dependencies of the config object, not only to the form, but also to the render array in preprocess, so that the rendered output gets the correct cache data:

function mymodule_preprocess_node(&$variables) {
  $config = \Drupal::config('mymodule.settings');
  $config_value = $config->get('some_field');
  // add the cache tag, so that the output gets invalidated when the config is saved
  \Drupal::service('renderer')->addCacheableDependency($variables, $config);

  $library = 'mymodule/some-library';

  if($config_value == 'some_value') {
    $variables['#attached']['library'][] = $library;
  }
}


Allow user to flag only those node that associated to a particular term of a vocabulary?

Found these links which solved my question
https://www.drupal.org/node/2235353
https://www.drupal.org/node/952114


Migration multibyte images file name issue

The solution is, simply, to compress the folder or files as tar not zip. Tar does not encode file names so it keeps it as it is in the filesystem. This is the Reference


Make email validation message in drupal 7 webform come out in spanish

Try with String Overrides module.

When you go to module settings choose 'Spanish' tab (if you have more than one language enabled), on the left side put "Please enter an email address" (without quotes of course) and on the right side write Spanish translation. (clear cache)

Let me know if this is working.


Adding option to one product in Commerce but not to others of the same product type

You can build your restaurant menu based on views, where you list commerce_products instead of product types(nodes). This will render one row for each variation.
You can also add relationship to your product types(nodes) for rendering/grouping/filtering.

You can also render the view of product variations at the product full page. Then the user will see all the possible variations of current product at once.


Views: how to remove ending zeros from decimal field

I created a file /theme/bartik/templates/views-view-field--open-events--page--field-coefficient.tpl.php:

<?php
print (float) $row->_field_data['id']['entity']->field_coefficient[LANGUAGE_NONE][0]['value'];

And it worked.