Set a value from one text field from one content type to another text field in another content type using set data value in rules

Here is example

Content type Article: field_product - Product reference
Content type Basic page: field_product2 - Product reference

Article creation triggers next actions:

{ "rules_on_article_create" : {
    "LABEL" : "On Article create",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "ON" : { "node_insert--article" : { "bundle" : "article" } },
    "DO" : [
      { "entity_create" : {
          "USING" : {
            "type" : "node",
            "param_type" : "page",
            "param_title" : [ "node:title" ],
            "param_author" : [ "node:author" ]
          },
          "PROVIDE" : { "entity_created" : { "entity_created" : "Created entity" } }
        }
      },
      { "data_set" : {
          "data" : [ "entity-created:field-product2" ],
          "value" : [ "node:field-product" ]
        }
      }
    ]
  }
}

I think you r trying to operate with non existing object. When you r creating node of type B there is no link to any another node in rules.


Drupal 7 - field template - $item - img tag

I usually use Devel module to figure out things like this. Install and enable Devel, then add something like this to your field template file:

<?php kpr($item); ?>

This will show you all the contents of $item (arrays and objects). Then you can just print the part that you want (the img tag in this case), wrapped in the extra class.


You need to pass the variable by reference like this using &

function themename_preprocess_comment(&$variables) {


field template for a specific content type

Try "-" in the contact type name like field--field-description--festivals-events.tpl.php

[Edit]
You may also need a template suggestion in your theme.

function mytheme_preprocess_field(&$variables) {
    if($variables['type'] == 'festivals-events'){
        if($variables['element']['#field_name'] == 'field_description') {
            $variables['theme_hook_suggestions'][] = 'field__field_description__festivals_events';
        }
    }
}


open node-reference links title in popup

You can use a theme_preprocess() function to add attributes to that link, or you can create a custom field template that adds classes or specifies a target.

For a new window/tab, you'd add target="_blank" or if you want to use an overlay you would add classes as specified in the module that provides that functionality, such as Lightbox or Colorbox.


What is the variable format to reference Views field data in a Global PHP that resides in a footer/header?

To reference a Views field result here's the format of the variable when using a PHP Global in the footer/header in a Views display:

$results[0]->field_**<FIELD NAME>**[0]['raw']['**<VARIES DEPENDING ON TYPE OF FIELD>**']

This is in reference to a taxonomy id (tid) reference:

$results[0]->field_field_device_type[0]['raw']['tid']

This is in reference to a text field called full_name:

$results[0]->field_field_full_name[0]['raw']['value']

The [0] represents each result row and the last array value usually changes depending on the field type (text,reference,image, etc.) So its better to dsm or print_r() if you really need to reference something that your not sure of.

Here's a sample output of the array structure so you can get an idea of how its laid out:

Here's a better view of the array output of a view's result when you do a print_r() within the header. I had to apply this to another view and forgot how to reference the variables. So here's the full output when you do a print_r($result[0]->field_field_machine_type): (keep in mind it has to be "field_field" when you reference a field.

     Array
(
    [0] => Array
        (
            [rendered] => Array
                (
                    [#markup] => Tablet
                    [#access] => 1
                )

            [raw] => Array
                (
                    [tid] => 105
                    [taxonomy_term] => stdClass Object
                        (
                            [tid] => 105
                            [vid] => 9
                            [name] => Tablet
                            [description] =>
                            [format] => plain_text
                            [weight] => 0
                            [vocabulary_machine_name] => machine_type
                            [rdf_mapping] => Array
                                (
                                    [rdftype] => Array
                                        (
                                            [0] => skos:Concept
                                        )

                                    [name] => Array
                                        (
                                            [predicates] => Array
                                                (
                                                    [0] => rdfs:label
                                                    [1] => skos:prefLabel
                                                )

                                        )

                                    [description] => Array
                                        (
                                            [predicates] => Array
                                                (
                                                    [0] => skos:definition
                                                )

                                        )

                                    [vid] => Array
                                        (
                                            [predicates] => Array
                                                (
                                                    [0] => skos:inScheme
                                                )

                                            [type] => rel
                                        )

                                    [parent] => Array
                                        (
                                            [predicates] => Array
                                                (
                                                    [0] => skos:broader
                                                )

                                            [type] => rel
                                        )

                                )

                        )

                )

        )

)


How can I avoid broken filenames in cached content?

You might attach a cache_clear_all() at the end of your import task.

So every time Feeds updates your content, your cache will be reset.

Your cache will be handled right when it's needed. It's not safe in my opinion to rely on "coincidence" between import time and cache lifetime.


JavaScript errors with 'Add collection', 'Select media' (Media, Field Collection)

OK, this was sort of entertaining.

The trail begins with this silliness in media.popups.js:

dialogOptions.buttons[ok] = function () {
  alert('hell yeah');
  return "poo";

Just as it stuck out for @DeveloperWeeks, it stuck out for me because I'm familiar with the work of Media module's primary maintainer, and I know him (by reputation) to be pretty meticulous. So in checking it out I discovered that it was removed long ago (like, in 2013) in this commit: Removed inappropriate JS code.

(I am sure he would be thrilled, by the way, to know that this bit of code will now live forever after on StackExchange. :-P)

Since the OP lists as part of his installation the latest production release  of Media (7.x-1.5), this didn't mesh. The errors were originating from a two-year-old file.

With this compelling clue in hand, @DeveloperWeeks was able to locate an extra copy of the Media module hidden away in his installation. That's when the sun rose, the flowers bloomed, and things just generally started to make more sense.

As for those pesky errors, well...

  "This is why "duplication of data" is such a horrible thing." -
  @DeveloperWeeks

Hell, yeah. ;-)


Uploading images into separate directories for every new content

Why you would want to do that, I don't know. However, you can use Filefield Paths module with tokens. If you use the timestamp token you can have each directory created named based on timestamp. That will make them unique.


search in node-with-comments plus in unpublished nodes

You can use
hook_searchapi_entity_property_info_alter:

function mymodule_searchapi_entity_property_info_alter(&$info) {
    if (isset($info['node']['bundles'])) {
        // For each content type.
        foreach ($info['node']['bundles'] as $bundle_type => $bundle) {
                $info['node']['bundles'][$bundle_type]['properties']['comments'] = array(
                    'label' => 'node comments',
                    'description' => 'the comments of the node',
                    'type' => 'text', // or whatever you want here
                    'getter callback' => 'mymodule_searchapi_get_whatever', // name me whatever you want

                );
            }
        }
    }
}

and your callback

function mymodule_searchapi_get_whatever($entity, $options, $name, $entity_type, &$info) {
    // return the comments here, as you have everything in the function variables - i.e. use return.
}

Look at example implemntations of this hook and it should be enough to get your started.


Change the title of date_popup filed in custom form

Just use the following code:

'#date_label_position' => 'none',

your code :

$form['filter']['start_date'] = array(
    '#type' => 'date_popup',
    '#date_format' => 'd-m-Y',
    '#title' => t('Start date'),
    '#date_label_position' => 'none',
  );

  $form['filter']['end_date'] = array(
    '#type' => 'date_popup',
    '#date_format' => 'd-m-Y',
    '#title' => t('End date'),
    '#date_label_position' => 'none',
  );


New to Drupal and views, how do I change the order of my fields?

In the View edit page, click the little cog icon in the top-right of the "Fields" pane, there's a rearrange option there.


How to show a view of content types on another content type

I would take a look at the "Panels" module, which allows you to create custom pages that can display multiple Views displays in one page.

-

Alternatively, instead of creating multiple content types, consider utilizing taxonomy terms to differentiate your classes and lessons.

For instance, create a list of terms for a new vocabulary "Class", which differentiates the different types of class.

Then, for each of your "Lesson" content type nodes, apply the specific class taxonomy term which applies.

Finally, you can create a View which displays Lessons content nodes, and have it filter the results to those Lessons which are tagged with a specific "Class" taxonomy term.


Site's settings file return blank screen

This is the intended functionality - your web/server user should be able to access the file and serve it over http but the file by itself doesn't do anything unless its included in the rest of the Drupal bootstrap.

The core concern of this security notice  is that there is a vulnerability if the settings.php file is writable or owned by the webserver.


Update new user's profile with rules, based on his webform submitted data

You need to create and force-save both the User and the User's Profile before you set your data values.  Your rules actions should look like the following:

Create Entity - User
Save Entity - User, Force Save
Create Entity - Profile, choose profile type.
Save Entity - Profile, Force Save
Set Data Value(s)


Additional fields for Ubercart uc_order_product

First of all, if you want alter the meta information of an entity, the hook_entity_info_alter in your custom module is the right way. More information in official page: hook_entity_info_alter

In this particular case, attributte 'fieldable' is not defined, so the function responsable to call the hook_entity_info and hook_entity_info_alter is the entity_get_info() in common.inc file. This function provide default values and the default value to 'fieldable' is FALSE. You only need change this value implementing hook_entity_info_alter.

 function YOUR_MODULE_entity_info_alter(&$entity_info){
   if(isset($entity_info['uc_order_product'])){
     $entity_info['uc_order_product']['fieldable'] = TRUE;
   }
 }

Second issue, This is a link to a previous question about how create fields programatically. The best answer suggests field_create_fieldand 'field_create_instance', but if you have a defined field (for example, an image type field created through the UI), you could use field_update_field and 'field_update_instance'. You can find more information about these functions in field.crud.inc in the field module folder.


how to get all the values in an edit form

The form_state->getValues() only works during the validation and submit process. Instead you need to look to the $form variable for values. Unfortunately you cannot get all the values easily you must dig into the form itself:

$form['title']['widget'][0]['value']['default_value'];

EDIT
I was looking into this more and there may be a cleaner way.

First you must get the form object from the $form_state variable. From there you can use the function getEntity() to actually get the entity that the form is editing. Then if you want to get a value you can use the get('field_name') method or if you want all the values use toArray()

// Get the entire node as an array and will include all values
$node = $form_state->getFormObject()->getEntity()->toArray();

or

// Get the entity object
$node = $form_state->getFormObject()->getEntity();

// Get the field
$node->get('field_my_field');

// Get the field as a string (returns value)
$node->get('field_my_field')->getString();


The Migrate module will help you to export all your image fields, and import them into one unified field; then, you can delete your obsolete fields.


Drupal 7 has lost all "safe" values and summaries

I found out that the problem was caused by Facebook album fetcher module and its text format filter.


Notify user by email when matching content is uploaded

Take a look at subscriptions module also and especially at this tutorial. I think this is a much simpler approach.


Drupal 8 Looking for an elegant alternative of rowCount in a query

According to the Drupal API, "in D8 rowCount() is the number of rows affected by the last DELETE, INSERT, or UPDATE statement executed or throws \Drupal\Core\Database\RowCountException if the last executed statement was SELECT."

If you need to select count of rows you can use $query->addExpression('COUNT(*)');

   $query = \Drupal::database()->select('table', 't');
   $query->addExpression('COUNT(*)');
   $count = $query->execute()->fetchField();


The References module provides autocomplete text fields for user and node references.


How to print an image field on all the basic pages only?

I suggest you to use template_preprocess_page and save your image to a variable. You can refer the below code.

function mytheme_preprocess_page(&$vars) {
     $node = $vars['node'];
     $field = field_get_items('node', $node, 'field_page_cover_image');
      if($field){
         $theme_img = file_create_url($node->field_page_cover_image[$node->language][0]['uri']); //origional image path
         if(isset($theme_img)) {
            //print styled image
            $imagevariable = theme('image_style', array('path' => $node->field_page_cover_image[$node->language][0]['uri'], 'style_name' => 'page_theme'));
           $vars['myImage'] = $imagevariable;
        }
      }
}

You can use $myImage variable to print the image in the tpl file :)


search-api solr is nor performing OR search

You can implement the hook :

hook_search_api_solr_query_alter(array &$call_args, SearchApiQueryInterface $query)

Have a look to your query & params and see if the solr query is what you were expected, if it's not you can alter it.


https://www.drupal.org/project/wysiwyg_mediaembed
Might be what you're looking for and it has a useful issue board if you run into trouble...


Customize days that can be clicked on a Calendar popup

You can pass some Datepicker options from php to the date_popup element through the '#datepicker_options' key:

<?php
$form['date'] = array(
  '#title' => t('Pick the desired date'),
  '#type' => 'date_popup',
  '#datepicker_options' => array(
    'minDate' => 0,
  ),
);

With this method you can pass almost any option but those that accept a function as value, as beforeShowDay, the one needed to restrict weekends or holidays according to the answer referenced by Nikit: https://stackoverflow.com/questions/501943/can-the-jquery-ui-datepicker-be-made-to-disable-saturdays-and-sundays-and-holid

Hence, javascript is required. First you need to include a custom js file from your module code:

<?php
drupal_add_js(drupal_get_path('module', 'FOO') . '/FOO.js');

and provide some code in FOO.js to extend the settings set by date_popup module with our own options.

Here's an example that add the basic option to disable weekends for all datepicker widgets in the page:

(function ($) {
Drupal.behaviors.FOO = {
  attach: function (context) {
    for (var id in Drupal.settings.datePopup) {
      Drupal.settings.datePopup[id].settings.beforeShowDay = $.datepicker.noWeekends;
    }
  }
};
})(jQuery);

Extend to holidays is left as an exercise to the reader :)

Note: the three occurences of FOO in my examples doesn't need to be the same literal, ie: you can provide a BAZ behaviour in BAR.js from FOO.module.

Update: to extend the above for custom days availability, just add a function returning true/false for the day received by parameters.

(function ($) {
Drupal.behaviors.FOO = {
  attach: function (context) {
    for (var id in Drupal.settings.datePopup) {
      Drupal.settings.datePopup[id].settings.beforeShowDay = checkDate;
    }
  }
};

function checkDate(date) {
  if ((date.getDate() % 2) == 0) {
    return [false, 'Even days not available'];
  }
  else {
    return [true, 'Odd days are fine'];
  }
}
})(jQuery);

You can find a more complete example in Date Restrictions module.


How to alter the output of a file-field as a custom field-widget

The file field for uploading is defined in the render callback of ManagedFile:

public static function processManagedFile(&$element, FormStateInterface $form_state, &$complete_form) {
  ...

  // The file upload field itself.
  $element['upload'] = [
    '#name' => 'files[' . $parents_prefix . ']',
    '#type' => 'file',
    '#title' => t('Choose a file'),
    '#title_display' => 'invisible',
    '#size' => $element['#size'],
    '#multiple' => $element['#multiple'],
    '#theme_wrappers' => [],
    '#weight' => -10,
    '#error_no_message' => TRUE,
  ];

So one way to change the output of the field is to define a custom form element which extends File. The element can be themed as wanted.

And in the process callback of the custom widget the type of the upload element can be overwritten to use the newly defined element:

public static function process($element, FormStateInterface $form_state, $form) {
  $element = parent::process($element, $form_state, $form);
  $element['upload']['#type'] = 'myCustomFileElement';
  return $element;
}


node not listed under create content for panel page

Never really found a solution, just a workaround where I went with a view to display the content.


How to display my block on search results page only if nothing found?

To expose a webform as a block, go to the webform, and under the webform>>form settings tabs go to the bottom, open up the Advanced settings, and check 'Available as block'.

Then go to /admin/structure/block find your block and click on 'Configure'. The url will have the form /admin/structure/block/manage/MODULENAME/BLOCKID/configure (MODULENAME will be 'webform', and the BLOCKID will have the form 'client-block-$nid' where $nid is the node ID of the form). Keep a record of these.

Then copy the core template from the DRUPALROOT/modules/search/search-results.tpl.php to your theme directory, and edit it to look something like:

<?php if ($search_results): ?>

<?php print t('Search results');?>

  <ol class="search-results <?php print $module; ?>-results">
  <?php print $search_results; ?>

  <?php print $pager; ?>
<?php else : ?>

<?php print t('Your search yielded no results');?>

  <?php
    $block = block_load('MODULENAME', 'BLOCKID');
    print drupal_render(_block_get_renderable_array(_block_render_blocks(array($block))))
 ?>
<?php endif; ?>

This will print your block instead of the search help if there are no search results.

Now, so your theme can use this new template, you have to make it aware. Edit the theme's template.php file and look for a function called THEMENAME_preprocess_search_result(&$vars) If it exists, add the following code. If it does not exist, create it and add the following code:

THEMENAME_preprocess_search_results(&$vars) {

  // ..... Existing code

  $vars['template_files'][] = 'search-results-' . $vars['module'];
}

Hope this helps.


How do I get a list of nodes that have a reference to a given user?

You can use an entity query:

$nids = \Drupal::entityQuery('node')
  ->condition('type', 'article')
  ->condition('field_allowed_editors', $userid)
  ->execute();

This will result in an array with all node id's that match the conditions.


I have no fields available for sorting with Search API sorts module

Search API Sorts only lists the fields of supported types. Make sure the fields you want to sort on are single value strings or numbers.

If the fields are mutli-value you can use Search API Ranges to give you max/min value fields that you can use.

If a field is full-text, one trick is to create an aggregated field containing just that field and assign it a string type.


form_set_error() redirects to raw ajax response page

The API page for form_set_error() says (emphasis added):

  When a validation error is detected, the validator calls form_set_error() to indicate which element needs to be changed and provide an error message. This causes the Form API to not execute the form submit handlers, and instead to re-display the form to the user with the corresponding elements rendered with an 'error' CSS class (shown as red by default).

I reckon that's probably where your problem lies.  Further down the same page is this:

  Multistep forms not wanting to validate the whole form can set #limit_validation_errors on buttons to limit validation errors to only certain elements.

This looks like it might help.


CAVEAT : This commentary is solely based on MySQL not Drupal.

I have personally worked with Percona Server and MySQL, not with MariaDB as of yet. Percona provides support for MariaDB, Drizzle, Amazon RDS, and other MySQL products.

I learned at Percona Live NYC that Percona gets the latest version of MySQL and injects 30,000 lines of C/C++ that is unique to its Performance Enhancements. MySQL (eh, Oracle) tries to keep up with its own enhancements of InnoDB.

Unless your Drupal website is very heavily trafficked, there is no decent performance difference you can feel or see. However, if you do have high traffic and you want to compare MySQL, Percona, and MariaDB, I have posted an article in the DBA StackExchange on how to go about doing this.


How do I add a meta tag when creating a node via REST API?

I copy/paste the following snippets from the readme file of the metatag module.
I can see that you are missing the serialize function in your solution.
Hopefully that helps you.

Programmatically assign meta tags to an entity
--------------------------------------------------------------------------------
There are two ways to assign an entity's meta tags in custom module. Both
scenarios require a "Metatag" field be added to the entity's field settings, the
field name "field_meta_tags" is used but this is completely arbitrary.

Option 1:

  $entity_type = 'node';
  $values = [
    'nid' => NULL,
    'type' => 'article',
    'title' => 'Testing metatag creation',
    'uid' => 1,
    'status' => TRUE,
    'field_meta_tags' => serialize([
      'title' => 'Some title',
      'description' => 'Some description.',
      'keywords' => 'Some,Keywords',
    ]),
  ];
  $node = \Drupal::entityTypeManager()->getStorage($entity_type)->create($values);
  $node->save();

Option 2:

  $node = Node::create(array(
    'type' => article,
    'langcode' => 'en',
    'status' => 1,
    'uid' => 1,
  ));
  $node->set('title', 'Testing metatag creation');
  $node->set('field_meta_tags', serialize([
    'title' => 'Some title',
    'description' => 'Some description.',
    'keywords' => 'Some,Keywords',
  ]));
  $node->save();

In both examples, the custom meta tag values will still be merged with the
values defined via the global defaults prior to being output - it is not
necessary to copy each value to the new record.


How can I force a view page not to be cached?

This is probably not related to caching inside of views, more likely on page level. You can disable page caching with the route option no_cache. Use a RouteSubscriber to alter the routes of views:

/src/Routing/RouteSubscriber.php

<?php

namespace Drupal\mymodule\Routing;

use Drupal\Core\Routing\RouteSubscriberBase;
use Symfony\Component\Routing\RouteCollection;

class RouteSubscriber extends RouteSubscriberBase {

  protected function alterRoutes(RouteCollection $collection) {

    // no_cache for a specific view
    if ($route = $collection->get('view.testview.page_1')) {
      $route->setOption('no_cache', TRUE);
    }

    // or for all view displays of a specific type
    foreach ($collection->all() as $route) {
      if ($route->getOption('_view_display_plugin_id') == 'rest_export') {
        $route->setOption('no_cache', TRUE);
      }
    }

  }
}

mymodule.services.yml

services:
  mymodule.route_subscriber:
    class: Drupal\mymodule\Routing\RouteSubscriber
    tags:
      - { name: event_subscriber }

This would not be necessary, if the view set the correct cache tags for the content it serves, so that the render cache could be invalidated if the content is changed.


Webform: get field value from the Entity select option

I was able to get all three of the below tokens to pull the single first email address for the group node's field_email.

[webform_submission:values:groups:entity:field_email]
[webform_submission:values:groups:0:entity:field_email]
[webform_submission:values:groups:0:entity:field_email:value]

Only [webform_submission:values:groups] returns 'Node Title (NID)'.


How do I output the link to the content?

This works for me in views-view-fields.html.twig

{{ fields.view_node.content }}

The code above will directly display the value of "Content: Link to Content".

Hope this helps.


Sorry for the late response, your question escaped my mind.

(function ($) {
   (function Forever(){ // we create a function called Forever
     var grabval = $('#edit-title').val();
     $('.vertical-tab-button').each(function(){
       if ($(this).children().children('strong').text() == 'Content Limit'){
         if (grabval == 0 && $(this).children().children('span') == null){
           $(this).children().children('strong').after('Not Limited');
         }
         else if (grabval == 0 && $(this).children().children('span') != null){
           $(this).children().children('span').html('Not Limited');
         }
         else if (grabval != 0 && $(this).children().children('span') == null){
           $(this).children().children('strong').after('Limited');
         }
         else if (grabval != 0 && $(this).children().children('span') != null){
           $(this).children().children('span').html('Limited');
         }
       }
     });
   setTimeout(Forever, 1);
   })();
})(jQuery)

I used the node title for mine, so if you change the title to 0 or 1 or 2 ..etc, it will change.

So all you have to do is change the var grabtext = $('#edit-title').val(); more specifically the #edit-title part, and put the ID or Class name of your Maximum per time period box.


How call a block named Poll Recent from template?

In D7, you will need:

$block = module_invoke('module_name', 'block_view', 'block_delta');
print render($block['content']);

In the case of recent poll:

<?php
  $block = module_invoke('poll', 'block_view', 'recent');
  print render($block['content']);
?>

Curiously, although defined in poll_block_info the delta is actually ignored in poll_block_view, perhaps as the poll module only provides a single block.


Can I set a cron for deleting and re-indexing Search API daily?

If you have Drush on your server, you can use the drush search-api-reindex command. This way you don't need to invoke a cron, but can force a reindex.

Note: You'll need to run drush search-api-list first to get the numeric identifier for the index when you run the re-index command.

Reference more info here: http://drushcommands.com/drush-6x/search-api/search-api-reindex


Drupal mail problem - Greylisting in action

In your setup PHP mail() sends mail, but it's your mailserver who gets "false rejection" notification - possibly a different machine, and even if the same machine, it's totally separate system. PHP mail() never receives anything, so it can't resend. And your mailserver never sent it, so it can't resend, either.

Simplest way to fix it is to use SMTP module

  This module allows Drupal to bypass the PHP mail() function and send email directly to an SMTP server. The module supports SMTP authentication and can even connect to servers using SSL if supported by PHP.

PHPmailer module

  The main differences to the SMTP module are:

  Integration with Mime Mail module
  Improved bulk-mail performance through SMTP keep-alive connections (if supported by the mail server)
  Built-in e-mail rerouting option (useful during site building and development)

or similar solutions, there are a few more.

That way your Drupal will only need to send mail once, and your outgoing mail server will take care about graylists - most of them are configured in a way that works with graylist receiving servers out of the box.


If you don't require a password from your users, then you should:

Make the password form field not visible to the users (it is enough to set #access to FALSE)
Remove the form validation handlers that are not necessary

The form validation handlers that the user login block uses are the following:

user_login_name_validate() just checks the user account matching the username is not blocked
user_login_authenticate_validate() checks the entered password matches the one set for the user account using that username
user_login_final_validate() checks the user didn't enter too much times the wrong password

What you need to do is removing 'user_login_authenticate_validate' and 'user_login_final_validate' from the array $form['#validate'].

Remember also that your form validation handler needs to set $form_state['uid'], since that is the value used from user_login_submit() to load the user object from the database.

As additional notes:

Your code is making assumptions about where/how the field data are saved; in particular, it is assuming the field data are saved in the database currently used by the Drupal site, which is not necessary true, since field data could be saved in MongoDB. I would rather use the following code.

$uid = db_query("SELECT uid FROM {users} WHERE name = :account_name", array(':account_name' => $usuario_nombre))->fetchField();
if (!empty($uid)) {
  $account = user_load($uid);
  if ($countries = field_get_items('user', $account, 'field_paises')) {
    // I assume users can just select a single country.
    $country = array_shift($countries);
    if ($country != $usuario_pais_seleccionado) {
      // Show the error message.
    }
  }
}

You cannot use user_authenticate(), since that requires the account password, which is not saved in the database. The database contains the password hash.
The string passed to t() should contain words in English, since the function is used to translate from English to the language currently set for the site. (Pais is not an English word; probably you meant Country.)
Instead of WHERE name IN ('$usuario_nombre'), you should use WHERE name = :username. Input from users should not be used directly in SQL queries, as that is a security issue. (See SQL injection.)
Functions implemented by a module should always have their names prefixed by the module name.

Talking of security issues, I hope you are using the authentication method you described in a very restricted, controlled environment. I would not use it in a public site where everybody can create an account, especially if the username and the country selected from users are visible to everybody. Even in the case the country is not visible, getting the right username/country combination is much easier than finding the right username/password combination that allows you to log in.


How do I update core in commerce 2.x distribution?

Simple solution found in the end. Before running a composer command I had to add paths in my Windows Environment path variable to both the Git.exe file and the ssh-agent file.

I then ran a slightly different composer command from the one above:
composer update drupal/core --with-dependencies
I did this from the root of my site.

I had to make sure that drupal/core is in the require part of the composer.json file and not the replace part.


Limit Change to Read More Link in Node Teaser to One Content Type

Add following to your THEMENAME.theme file

/**
 * Implements hook_preprocess_HOOK() for node.html.twig.
 */
function THEMENAME_preprocess_node(&$variables) {
    // ...
    if ($variables['teaser']) {
    $node_type = &drupal_static('node_type');
    $node_type = $variables['node']->getType();
  }
}

/**
 * Implements hook_preprocess_links().
 */
function THEMENAME_preprocess_links(&$variables) {
  $node_type = &drupal_static('node_type');
    if (isset($variables['links']['node-readmore'])) {
        // Change link title according to machine name of node_type
        if ($node_type == 'article') {
            $variables['links']['node-readmore']['link']['#title'] = t('Custom Text');
        }
    }
}

Clear Cache.


How to use a variable in script tag of template file?

You can simply embed php in javascript, however the way you are adding your js is not recommended, please look around drupal way of adding js and sending values from php to javascript.

Having said that, the following code might help you-

<script type="text/javascript">
     var job_title = <?php echo $node->title; ?>;
     var container_id = "#footer";
     Springest.getTrainings(job_title, container_id);
  </script>


How to add Google recaptcha to a custom form?

You can use recaptcha module (https://www.drupal.org/project/recaptcha)
and in captcha settings(admin/config/people/captcha) you can add your custom form's form_id and select the challenge type reCAPTCHA(from module recaptcha). This should work.


Module version is not available in the list of the installed modules

On admin/modules, I can see the version of Drupal core modules, and third-party modules.

For third-party modules, Drupal will show the version only if it finds the necessary information in the .info.yml file of the module. In the case of the Honeypot module, this is what Drupal finds.

# Information added by Drupal.org packaging script on 2016-03-11
version: '8.x-1.23'
core: '8.x'
project: 'honeypot'
datestamp: 1457671749

Without that, Drupal doesn't show the module version. For example, this is what Drupal shows for my custom module, which is not hosted on drupal.org.

If you are using modules that aren't hosted on drupal.org, or you don't use Drush to download the modules, you will not see the module version. This also happens if you clone the module repository with Git instead of downloading the module archive from drupal.org.


You need to have 2 views:

First view: Author's content:

View should be a page.
Add all the required field.
set path to be like author/%/content.
Add a contextual filter for the content taxonomy term field (author).

Second view: Authors list

View should be a block.
Add field with term ID (author ID) and mark it to be excluded.
Add field with term name (author name).
Mark the term name output field to be overridden as a link.
Set author name as link text
Set author/[tid]/content as link path. (You can find correct value for term id in token replacements)

P.S. If you use panels it will be a bit different.

P.P.S. You can use standard taxonomy/term/% for the "First view: Author's content" view.


Update module issue - version_major in update_calculate_project_update_status()

If you put:

if(!isset($release['version_major'])) {
    die('<pre>'.print_r($project, TRUE).'</pre>');
}

On line 625 of update.compare.inc then when the version_major is not set it will print out details of the problem module and die.

Once you know what module is causing the problem then remove this code again as otherwise kittens may die.

When you know what module is causing the issue then you can raise the problem in their issue queue.


How can I set up a Drupal rules action to play a specific sound?

I would redirect to the node with the audiofield and set it to autoplay. This way you can have only one audio field per node of course.


Extra sorting criterium in case of ex aequo with Views

Add a new sort criteria, Posting date, set it to descending and make sure the order of your sort criterias are correct, first points, then date.


Modify Drupal's search to show custom fields

Try the Display Suite module. There you can change the appereance of a content type in different view modes. One of these view modes is for example the search result.


share users or nodes across multiple sites without sharing database

I tried almost every possible scenarios,

The best thing for me was use of Oauth2 server module for master site to act as authentication server and OpenID Connect module for other sites which use out-of-box authentication.

This solution can be done without needing to merge databases, or host sites on same server, or periodic synchronization. the only challenge I have is that authentication server must use https, and I'm going to buy certificate for my host.


Render a region e.g page.sidebar_first in views-view.html.twig

Not the region itself, but you can render the blocks with Twig Tweak, so simply add the blocks that are in that region to your template file.

  Twig Tweak module provides a Twig extension with some useful functions
  and filters that can improve development experience.

{# The block with this ID should be configured on "admin/structure/block" page. #}

Block:

{{ drupal_block('bartik_powered') }}


How do I add a custom field token to a default value?

I know this was asked years ago, but if someone comes across this, here's the solution:

https://www.drupal.org/node/919760#comment-9973163

Node tokens in a Webform block refer to the Webform node, not the current node which the block is placed on. Currently, the Token module does not expose node tokens to the Webform block.

There is a patch in this thread which exposes tokens to the Webform block, and should do just what you need. Hopefully it will get committed to the Token module soon. :-)

As an alternative, you could also use https://www.drupal.org/project/token_custom and create a custom token that exposes the field you need.


How do I find (or create) a File Template override in Panels 3?

As Adam Friedman points out, there is Page manager existing pages, which can do part of what "real" Page manager support can do, but it will not have the same capabilities as say the node/%node template has.

There are two issues that work on "full" support for this. First, and Second.


Get access to node titles and nid's only

Yes you can, with  field_permissions module  you can set permissions according to the fields.


Search API and Domain Access: Filter user per domain

I think your approach is just fine, but you forgot to index your field. You've to check the field you created on the field page (admin/config/search/search_api/index/**your_index**/fields)

Once checked, you'll be able to index your extra field and by so, filter on domain.


Organic groups content propagation direction

That screenshot is from Drupal 6.

In Drupal 7 the organic groups module works much differently in that it now uses fields to store its settings.

With Drupal 7 organic groups you need to go the the "OG field settings" administration page (admin/config/group/fields) and configure which fields appear on which content types.

The way that admin page works can be a little confusing but it's fairly straight forward once you get used to it.

The fields provided by the Subgroups for Organic groups module are:

Group user inheritance
Group user permission inheritance

On that admin page add those fields to your sub-group content types, then you can go to the content type field settings for those content types (in the admin/structure/types section) and you can configure default for those fields that will be used whenever sub-groups are created.

If you want to stop content administrators from being able to change the value of that field you can then use the field permissions module to restrict access to those 2 fields.

This is the same way you have to manage the fields from the base OG module (Group and Groups audience) and the fields in the OG access sub-module (Group visibility and Group content visibility).


If the enable full html does not work try using Feeds Image Grabber


Open Public Distribution on IIS 8.0 and SQL Server 2012 R2

I have solved, the issue is at this file on this location:

C:\inetpub\wwwroot\profiles\openpublic\modules\contrib\comment_notify\comment_notify.install

the statement on line 24

$comments_select->addExpression("MD5(CONCAT(:salt,c.mail,COALESCE(u.mail, u.init), c.uid,c.name,c.nid,c.hostname, c.cid))", 'notify_hash', array(':salt' => $salt));

should be replaced with

$comments_select->addExpression("MD5(CONCAT(CONCAT( CONCAT(:salt, c.mail) , CONCAT(COALESCE(u.mail, u.init), c.uid) ),CONCAT( CONCAT(c.name, c.nid) , CONCAT(c.hostname, c.cid) )))", 'notify_hash', array(':salt' => $salt));

because "Drupal 7 driver for SQL Server and SQL Azure" drops the SQL Server stored procedure CONCAT and creates a new one with only 2 parameters.


If I had a penny for every time I've done this...

You've forgotten to return $schema from your email_form_schema() function.

You'll need to reinstall the module (not just disable then re-enable) for the changes to take effect.

There's also a problem with the "last" column. It's a "varchar" and you're using the "unsigned" property which isn't compatible with that type.

You also need to provide the "length" property for all of the "varchar" type columns, including "first" and "last".


You can with Flag + Rules

In /admin/structure/flags/add add flag of "Content" and call it something like "use coupon" flag.

I presume your Nodes teasers are listed in view. So in Views:

In Relationships add "Content flag"

Uncheck include only flagged content
Flag: Slect your flag
By: Current User

In Filter Criteria add "Flagging" and select not flagged.

To prevent from viewing node directly by typing the url, in Rules:

In /admin/config/workflow/rules create Rule with action of "Flagging is viewed".
Add Action of "Page redirect" and send them to some custom /url that says you already redeemed this coupon. (Create a basic page for this)


How to add default text that clears on focus with jQuery to a search form text field in Drupal

You can do this by implementing hook_form_alter() in a custom module.

function custom_form_alter(&$form, &$form_state, $form_id) {
    if ($form['#id'] == 'search-block-form') {
        $search_text = 'Your search text here';
        $form['search_block_form']['#default_value'] = $search_text;
        $form['search_block_form']['#attributes'] = array(
        'onfocus' => "if (this.value == '$search_text') {this.value = '';}",
        'onblur' => "if (this.value == '') {this.value = '$search_text';}");
    }
}


drupal_redirect_form not working with entity

If you want to redirect a form submit you should use the redirect parameter:

function app_contact_form_submit_message_alter(&$form, &$form_state) {
  drupal_get_messages($type = NULL);
  drupal_set_message('Thanks for your feedback we will contact soon.');
  $form_state['redirect'] = 'node/23'; // The path you want to go
}

This will call drupal_redirect_form($form_state) byt its self, if you call it directly you are skipping the save step.

More info: https://api.drupal.org/comment/18139#comment-18139


The Features module can export content types, fields, views and allow you to import into another Drupal site.

The features module enables the capture and management of features in Drupal. A feature is a collection of Drupal entities which taken together satisfy a certain use-case.
Features provides a UI and API for taking different site building components from modules with exportables and bundling them together in a single feature module. A feature module is like any other Drupal module except that it declares its components (e.g. views, contexts, CCK fields, etc.) in its .info file so that it can be checked, updated, or reverted programmatically.


You can add this (*) in field label with field name or can use with style also.


Can I reference field item & label in node.html.twig?

If you can't find the label somewhere inside of content, then the code, which will prepare the label for rendering did not run at this point.

If you are inside the node twig, then there is a fully loaded node object. You can use this to get the field definition and the label:

{{ node.field_myfield.fieldDefinition.label }}

Or the first field item:

{{ node.field_myfield.0.value }}


How do I overwrite the controller for admin/content?

Check a namespace in your RouteSubscriber.php

You have

namespace Drupal\content\Routing

Should be

namespace Drupal\mcontent\Routing

Because your custom module is mcontent (not content)


How to close comments with just 1 click?

You can achieve this by following steps given below:

Create a flag on nodes for administrator only
Add new rule using Rules module
Set React on in Event "A node has been flagged, under
Add action "Set a data value"
Select Data "flagged-node:comment"
Click Continue and set value as 0

Please check Rule given below(exported):

{ "rules_disable_comments" : {
    "LABEL" : "Disable comments",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules", "flag" ],
    "ON" : { "flag_flagged_disable_comments" : [] },
    "DO" : [
      { "data_set" : { "data" : [ "flagged-node:comment" ], "value" : "0" } },
      { "drupal_message" : { "message" : "Comments closed" } }
    ]
  }
}

& Flag given below(exported):

$flags = array();
// Exported flag: "Disable comments".
$flags['disable_comments'] = array (
  'entity_type' => 'node',
  'title' => 'Disable comments',
  'global' => '0',
  'types' =>
  array (
    0 => 'article',
  ),
  'flag_short' => 'Disable comments',
  'flag_long' => '',
  'flag_message' => '',
  'unflag_short' => 'Enable comments',
  'unflag_long' => '',
  'unflag_message' => '',
  'unflag_denied_text' => 'Disabled comments',
  'link_type' => 'toggle',
  'weight' => 0,
  'show_in_links' =>
  array (
    'full' => 'full',
    'teaser' => 'teaser',
    'rss' => 0,
    'search_index' => 0,
    'search_result' => 0,
    'token' => 0,
  ),
  'show_as_field' => 0,
  'show_on_form' => 0,
  'access_author' => '',
  'show_contextual_link' => 0,
  'i18n' => 0,
  'api_version' => 3,
);
return $flags;


Getting a 403 error in REST & 8.2.3 has no permission set for REST for GET of content

This is a known issue with the REST UI module. REST UI has issues with Drupal 8.2 and up. There is an open issue specifically regarding this, and a much longer discussion to look into. I'd post this as a comment, rather than an answer, but I'm a new user here. Best of luck. I'm having the same problem.

UPDATE:

I think REST UI is just a no-go for 8.2.3. Bear with me. I don't have enough reputation to post links :-/

Here is what I did to get some requests to work:

Setting up the REST configurations

In the place of step 2 above, it seems that you need to edit the yml for the entity type you're trying to change the rest configurations for. For example, the node entity would use rest.resource.entity.node.yml (look here for some help: https://www.drupal.org/docs/8/api/restful-web-services-api/restful-web-services-api-overview#practical). I've been given the impression that RESTUI really just isn't useful with 8.2+, so you gotta do it by hand. Once you've created this file to your liking, you need to import it to your site.

I still can't figure out how to do this "correctly"; I don't know if you need to use the configuration importer (which will throw a UUID error) or include it in a theme or in /default/site or what. I did get it to work. I ended up using the Features Module to create a feature package for  REST Resource Configuration (admin/config/development/features/edit), downloaded, unzipped, and installed the module created by the changes.

I then manually edited the config files in the created module's directory (DRUPAL_ROOT/modules/MODULE_NAME/config/install/rest.resource.entity.node.yml) to have the settings I wanted. Finally, I implemented the changes by updating the feature from the features config page (admin/config/development/features/ click on the "changed" next to the module you created, click on the checkbox next to the changes, and click "Import Changes").

There HAS to be a simpler way to handle the import, but it works for me on 8.2.3.

User Permissions

Once your REST configurations are set up, the entity types should follow the permissions you have set in /admin/people/permissions/. So, if anonymous users can view published nodes, they should be able to GET published nodes as well, etc. (At least, according to [the documentation][1].)

If you're still having problems, you need to make sure to include the token header usually.

The csrfToken

A GET request to the endpoint YOUR_SITE.DOMAIN/rest/session/token will provide you with a token which you can set as the X-CSRF-Token' header on your GET or POST request. A typical and simple example using jQuery to GET the first entry might look like this:

function getFirstNode() {
  jQuery
    .get('YOURSITE/rest/session/token')
    .done(function (data) {
      var csrfToken = data;
      jQuery.ajax({
        url: 'YOURSITE/web/node/1?_format=hal_json',
        method: 'GET',
        headers: {
          'Content-Type': 'application/hal+json',
          'X-CSRF-Token': csrfToken,
        },
        success: function (node) {
          console.log(node);
        }
      });
  });
}

If all else fails

I've also had success setting up GET endpoints using the Views Module. This article does a pretty good job explaining the process: http://redcrackle.com/blog/rest-export-views-drupal-8. It won't work for POST requests, but it should help.

I hope this helps. It's a really sticky problem for what should be a simple request, and the documentation does NOT do a great job of making this accessible. Good luck!


Looking for a good Mini - Panels tutorial

I have not found a tutorial specifically for mini-panels, but it works similarly to page panels.  nodeone.se has an excellent tutorial on using Page Panels (Page Manager & Panels modules enabled).

Mini Panels are closely related , but behave more like blocks.  When you define a mini-panel it will be available in the panels UI for placement as well as in the admin/structures/blocks form.  The major difference from blocks is that mini-panels are smart.  They can take context from the node, user and other sources and display accordingly.  They also connect to a View.

There is one thing to observe when defining a mini-panel.  The UI is slightly different from Page Panels and the first time I used them, I could not figure out how to add content to one.  To access the "content" and other setting forms select the Panels breadcrumb  menu at the top.


Accessing $language inside node content in drupal 7

If I understand your question:

global $language_content;

This will return a language object with the current language.


Assuming D7, you can add a field to the vocabulary entity to group the vocabularies together.

For example, you could add another vocabulary "Group" that contains your vocabulary group terms. You could then add it either as a select or free-tagging style term reference field on your other vocabularies and link them that way.

Admin > Structure > Taxonomy > Edit Vocabulary > Manage Fields

You may also want to consider using a single hierarchical vocabulary where the terms are nested under a parent term, e.g 'Vehicle' (recommended)


Newly created fields are not being displayed

Adding a default value doesn’t actually set any value in the field. To do that you must either edit the nodes you want the field on and click save, or write an update hook that sets the field value on all the nodes.

An update hook must be placed in a custom module’s .install file, in your case it would be something like:

function MY_MODULE_update_N() {
  $nodes = \Drupal::entityTypeManager()->getStorage('node')->loadByProperties('type' => 'article');
  foreach ($nodes as $node) {
    $node->set('field_name', $value);
    $node->save();
  }
}

As @4k4 mentioned if you have to update too many nodes as you have memory to, you can create batch updates using the &$sandbox, click here for more information


In Edit Profile link append destination parameter like:

if(user_is_anonymous()){
  $editlink = l(t('Edit Profile'), 'user/login', array('query' => array('destination' => 'user/UID/edit')));
}

Then after login, it will redirect to profile edit page.


Move uploaded content automatically from one node to another

Content in Drupal is organized in "nodes":

  A node is any piece of individual content, such as a page, poll, article, forum topic, or a blog entry. Comments are not stored as nodes but are always connected to one.

So you'll always have a "page" or whatever your content type is named, to store and edit the content. But you don't need to show these pages necessarily to the visitors or users of that site.

You should take a look into Views module, which will enable you to create (another sort of) "pages" that automatically collect content from "nodes" according to the rules and filters that you have definded for it.


Translation table: How do I restore a deleted metatag string?

Here are the steps to reproduce:

Enable Metatags, Entity Translation and Inline Entity Forms.
Make a node type translateable (using Entity Translation) and add an entity reference field that uses the inline_entity_form widget (it doesn't matter what it points to).
Create a node of that type, with custom meta tags and add one referenced entity, save it.
Add a translation in another language, translate the meta tags and save the translation (you can also translate the referenced entity, this isn't relevant for this bug though). At this point we have all content as it should be.
Now edit the translation again, leave the meta tags as they are (everything still looks fine) and make a modification to the referenced entity using the inline entity form widget, then save the entire form. The translated meta tags are gone and have been reset to the default values.

The cause of this issue is the following code in metatag_field_attach_form():

<?php
// Entity_Translation will trigger this hook again, skip it.
if (!empty($form_state['entity_translation']['is_translation'])) {
     return;
}
?>

This code works as intended when adding a translation, but not when editing a translation, because in that case $form_state['entity_translation']['is_translation'] is not defined (it gets defined later, only after the code above has already been executed). However, even though the logic is broken, the resulting behavior is correct, because when editing a translation metatag_field_attach_form() doesn't actually get called twice as mentioned in the code comment, so we really don't want to return yet.

The problem arises when using the inline_entity_form widget, which reloads part of the form using Drupal's standard ajax mechanism. This causes the form to be rebuilt, and the code above from metatag_field_attach_form() is run again, but this time after Entity Translation has set $form_state['entity_translation']['is_translation']. The code is now running as intended, but the resulting functionality is broken. Now the function returns prematurely, $form['#metatags'] doesn't get set, metatags' hook_form_alter() gets skipped and the form submit handler doesn't get set in metatag_metatags_form(), so meta tag information gets lost and is replaced with the default value.

The solution is to fix the code above to only return when a new translation is being added, not anytime a translation is edited:

<?php
// Entity_Translation will trigger this hook again when adding a new     translation, skip it.
if (isset($form_state['entity_translation']['is_translation']) &&     !empty($form_state['entity_translation']['is_translation'])) {
  return;
}
?>


How do I get a list of all CSS and JS that are attached to a page?

You cannot get a list of css/js files because it is constructed very late in the render process.

However, since you want to use an iframe to achieve that goal, you can get it through the normal loading order of a drupal page.

The following is a proof of concept controller method you can use to display a block in a simplified html mode.

public function preview($block_id) {
  /** @var BlockInterface $block */
  $block = Block::load($block_id);

  /** @var BareHtmlPageRendererInterface $bare_html_page_renderer */
  $bare_html_page_renderer = \Drupal::service('bare_html_page_renderer');
  $content = [
    'preview-child' => \Drupal::entityTypeManager()->getViewBuilder('block')->view($block)
  ];

  return $bare_html_page_renderer->renderBarePage($content, 'preview-title', 'preview-theme');
}


I was able to solve it using Views PHP Using some custom PHP to show the "link" only if the user has permission. Not sure if thats the most elegant way.

I would like to know if there is a better approach to solving this. Thanks!


Fetch customer profile in a component rule

Which module you using for customer profile. Are you using user profile like profile_load_profile($account);


create tabs with hook_menu() for custom module

You need to define a 'root' path which is a normal menu item, and then add another item for each of the tabs. The first of these will inherit the properties of the root item, and the second will define its own callbacks.

Combined with the MENU_LOCAL_TASK and MENU_DEFAULT_LOCAL_TASK type constants, you should get the tabs you expect:

function social_links_menu() {
  $items['admin/config/system/social_links'] = array(
    'title' => 'social_links',
    'description' => 'Configure to fit clients needs',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('social_links_settings'),
    'access arguments' => array('administer site configuration'),
    'file' => 'social_links.admin.inc',
  );

  $items['admin/config/system/social_links/tab1'] = array(
    'title' => 'Tab 1',
    'type' => MENU_DEFAULT_LOCAL_TASK,
    'weight' => -10
  );

  $items['admin/config/system/social_links/tab2'] = array(
    'title' => 'Tab 2',
    'type' => MENU_LOCAL_TASK,
    'page callback' => 'some_callback',
    'access arguments' => array('some permission')
  );

  return $items;
}


How to render a block provided by a contrib module in a node template

Go for Twig Tweak.

  Twig Tweak is a small module which provides a Twig extension with some
  useful functions and filters that can improve development experience.

Then it's just

{{ drupal_block('better_social_sharing_buttons_block') }}

Read the docs about Rendering blocks with Twig Tweak.

  This subject is rather confusing because too many things in Drupal are
  referred to as "Blocks". So it is essential to understand what kind of
  block you are going to render. This guide covers three main cases you
  may deal when rendering blocks in a Twig template.


Displaying fields from an entity reference of another entity's field

You can use custom Displays to daisy-chain entity reference fields in this fashion (unless I misunderstand your requirements).

To do this...

Install the Entity View Mode module.
Then in configuration - system - entity view modes, create a new display for the entity in question and make sure it is attached to the recording type. Give your new display a self-explanatory name such as "embedded recording" to avoid confusion later.
Next, go to your recording entity's display mode settings, (eg 'manage display') and in the new "embedded recording" display make sure the Recording Artist entity reference field is visible.
Finally, go to your Composition entity's display mode settings (its 'manage display'), and for the Recording entity reference field, choose rendered entity as its format and pick "embedded recording" as its view mode (this option becomes available if you click on the little gear icon on the right hand side).

(Of course this would be far easier if you could add new display modes from the manage display setting! One day perhaps...)


Multistep registration form for two roles

These modules might help you:

Profile2 for creating different user profiles based on role
Profile2 registration path to have separate registration pages
Formflow to connect multiple forms in a single "workflow"


There are a number of ways you can handle this. The three best that come to mind are:

Use a theme hook template file to modify the output. You can do this at either the field level or the content type level.
Use Display Suite to create a field template.
Create a custom field formatter with Custom Formatters module. This plays nicely with display suite.

In your case Display Suite is probably overkill unless you wanted to use it for managing all your output. It’s an extremely powerful module that if implemented correctly allows you to not have to manipulate template files.

In either case I would suggest taking a good look at Display Suite as it really speeds up the theming process.


Got it fixed on my local environment by putting the base theme name in quotes and then clearing the cache.
Changed base theme: classy to base theme: "classy".
Also, check for a single quote on your theme's description. If you find it, make sure you put the whole description in quotes.


the module ImageCache Actions suit your need. one of the effects that it provide is :

  Watermarking - a much requested addition that enables you to place any
  image anywhere over a source picture, with alpha transparency


Payment Information on hook_commerce_checkout_complete

You can see the payment method the customer selected in the $order->data array, and to determine if the order was paid in full you'd use commerce_payment_order_balance(). Any additional information would have to come from payment transaction entities whose order_id match $order->order_id.


Configuration > Regional and Language > Date and Time

Check what your default Short time format is. If its being printed with spaces, it could be part of the problem.
You could add a new date type, and see if that fixes anything.

The easy way around this, is when managing the image and file upload CCK fields, just specify a directory for those images in the field settings there.


When offloading a hook implementation to another function, which function should be documented as "Implements..."?

TL;DR: Yes, it's fine and widespread too!

It might look kinda unorthodox but it's just offloading the bulk of the hook implementation to an include to keep the main .module file smaller.  Here's where it's happening: menu_block.module (view source at the bottom).

A lot of other contribs do this too, for example: Display Suite (see line 48 onwards) and I'm pretty sure Views and a bunch of others too.


Order quantity increment condition for payment method

Per OP's comment, updated solution:
 public function evaluate(EntityInterface $entity) {
    $this->assertEntity($entity);
    /** @var \Drupal\commerce_order\Entity\OrderInterface $order */
    $order = $entity;
    $increment = $this->configuration['increment'];
    $total = 0;

    foreach ($order->getItems() as $order_item) {
      $total += $order_item->getQuantity();
    }
    if ($total % $increment !== 0) {  return FALSE;  }

    return TRUE;
  }


For a multilingual Drupal 7 site you could enable the Locale and Content translation modules, they are both included in the Drupal Core.

Also, you might want to check the Internationlization module and the Entity translation module.

Basically you start of by adding languages to your site, you can do this in the administration area (/admin/config/regional/language). After that you can allow content types to be translated (/admin/structure/types). When you add a node you will then be able to choose between the enabled languages.

As for SEO: you could check the Drupal SEO Tools, it has a huge list of modules that you can use.


How to fix missing php extensions problems in custom Docker image?

I resolved this by removing the drush and composer services from the docker-compose file and updating my Dockerfile for drupal as follows:

FROM drupal

RUN apt-get update -y && apt-get install -y wget vim git mysql-client

RUN php -r "copy('https://getcomposer.org/installer', 'composer-setup.php');" && \
    php composer-setup.php && \
    mv composer.phar /usr/local/bin/composer && \
    php -r "unlink('composer-setup.php');"

RUN wget -O drush.phar https://github.com/drush-ops/drush-launcher/releases/download/0.4.2/drush.phar && \
    chmod +x drush.phar && \
    mv drush.phar /usr/local/bin/drush


How to retrieve "profile_" only filelds?

The condition should be preg_match("/^profile_/", $profile). Have look at preg_match.


Will Views RSS do what you want?  It typically throws articles/nodes out as RSS(XML),  and you can modify it to produced more structured output if you wish.


There's a "quick dirty workaround" to making profile2 entities work with tokens/pathauto properly if you're interested.

It doesn't work for bulk generation, but does for individual saves of an entity.

It seems there is an ongoing effort to get this solved (http://drupal.org/node/1330546), but nothing's been added in a couple of months. It might be worth checking the issue queue/recent release notes to see if you can find out where they are with this.


I found a solution here. Based on @djayp34's answer, this is how I achieved what I wanted.

Basically the idea is:
Drupal does not support adding a JS snippet through drupal_add_js() or any other function at AJAX callback. So what we are doing here is:

Step 1: We register/load that particular JS code during normal page load.
In template.php:

function MYTHEME_preprocess_html(&$vars) {
  drupal_add_js(
    'Drupal.ajax.prototype.commands.myFunction = function(ajax, response, status){
       //The JS code that needs to be called after completion of ajax
      }',
      'inline'
     );
}

Step 2: We call that JS code when we want it. Here we want it to be called during AJAX callback.

In module file.

function MYMODULE_views_ajax_data_alter(&$commands, $view){
  if($view->name == 'MY_VIEW'){
    $commands[] = array("command" => 'myFunction');
  }
}


Does yoursitename.something/update.php runs after you put it your browser location.
I can only guess maybe your site hosting space is full or you might not have given update permission to the role by which you are updating the site.


ajax callback add more on a select field

After an AJAX submit by a select or some similar not submit element the Form API rebuilds de form if no validate errors are found. See drupal_process_form() where this is stated in the inline comments:

// However, for forms that have not been fully executed (e.g., Ajax
// submissions triggered by non-buttons), there is no submit handler to set
// $form_state['rebuild']. It would not make sense to redisplay the
// identical form without an error for the user to correct, so we also
// rebuild error-free non-executed forms, regardless of
// $form_state['rebuild'].

Your code is not working because you update your number of elements in the callback function in this line:

$form_state['num_names'] = $form_state['values']['myfield'];

The callback function is executed after all form processing so your modifications are done too late. In fact, callback function should only return the response, no modifications on the form should be done here.

Try something like this:

$form['myfield'] = array(
    '#type' => 'select',
    '#options' => $optionsServer,
    '#ajax' => array(
        'callback' => 'ajax_select_change',
        'wrapper' => 'names-fieldset-wrapper',
        'method' => 'replace',
        'effect' => 'fade',
    ),
);

$form['#tree'] = TRUE;
if (empty($form_state['num_names'])) {
   $form_state['num_names'] = 1;
}
else {
  // If there's is value in myfield update number of available names elems.
  $form_state['num_names'] = $form_state['values']['myfield'];
}

$form['myfieldset'] = array(
        '#type' => 'fieldset',
        '#title' => t('myfieldset'),
        '#prefix' => '
',
        '#suffix' => '
',
    );
for ($i = 0; $i < $form_state['num_names']; $i++) {
   $form['myfieldset']['field'.$i] = array(
       '#type' => 'textfield',
       '#title' => t('field'),
       '#size' => 60,
       '#required' => TRUE,
   );
}

function ajax_select_change($form, &$form_state){
    return $form['myfieldset'];
}


The calendar_style style requires a Date argument error when Using CCK as a date argument

When building a calendar in Drupal 6, you should clone the default calendar views in order to create a new on instead of trying to make it from scratch (Error when changin Date argument).

Have a look at these tutorials if you need some extra help:
- Drupal Calendar Setup
- How To: Create a Drupal Calendar


The issue ended up being my CSS. I was using styles from the sample page that had a height of 100%. Once I added some height and width to my naa-map div, my map showed up fine.


Adding custom html and css to views header and footer

It isn't good practice to intermix HTML and CSS (embed CSS or use inline styles). As a rule CSS is kept separate in files in your theme, and some in modules.

Views allows you to define CSS classes for certain parts of the output, but you still have to keep the CSS rules and declarations in your theme.

If you don't have access to your subtheme for some reason or only want to apply tiny changes you can try CSS Editor. It gives you a place where to enter new CSS rules that will apply throughout your theme.

You still have to edit your Views output to include the custom HTML classes to elements you want to style, you can do that through Global Text area as you already found.

Many themes already assign a lot of classes to various Views parts, so maybe you already have classes relevant to your design and you can use them in custom CSS without adding new classes in HTML.


How to debug: How Can I see the form arrays with its components (fields) in a loaded page?

Debugging in Drupal can be a bit frustrating when you first start out but you'll get the hang of it quickly :)

Debug is a really convenient Drupal function to output your form array (or any array/object) from any custom module/template.

In the case of your form, you can invoke hook_form_alter in you custom module to call the debug of your form. (You can find the form ID by looking at the page code and replacing the - with _. For example "user-login-form" would be "user_login_form" here)

 function YOUR_MODULE_NAME_form_alter(&$form, $form_state, $form_id) {
   if($form_id == 'your_form_id') {
     debug($form,'form',TRUE);
   }
 }

Then (after clearing caches) once you visit the page with the form, Drupal will output the $form array as an entry in your watchdog log (admin/reports/dblog).


How to implement a trial membership using Organic groups?

Sounds like a perfect job to accomplish with the Rules module. Below are the headlines of how you could get this to work ...

Rule 1 (When user account is created)

Event: When a new user account is created
Action:

Grant access to role Trial member.
Set some Date field value = expiration date (cfr. your "limited time").
Set some State field value = Active.

Rule 2 (When expired)

Event: When user logs in
Condition: if the date indicated in field with expiration date is passed.
Action: Set your State field value = Pending.

Recommended video tutorials

Rules

If you're not familiar (enough/yet) with Rules, checkout the 32 (!!!) great, and free, video tutorials Learn the Rules framework.

Organic Groups

If you're not familiar (enough/yet) with Organic Groups, then reviewing the amazing set of videos to Learn Organic Groups might help.

Other variations

There are other variations to make this work with the Rules module. E.g. by using 'Rules Scheduler' (= sub-module of Rules) to schedule a variation of "Rule 2", to be executed on your expiration date.


Updating drupal/core using composer: "[RuntimeException] Could not delete web/core" (using Lando)

OK - so composer does not have read/write access to the folder. I've also seen some people mentioning composer timeouts being the problem.
In my case I am using Lando for my dev environment ands listed web/core as one of the excludes:
excludes:
  - web/core

This meant the core files were not available to the container. If I remove core from the excludes then it works fine.


How to attach a single node multiple times to an entity (e.g. badges)?

Somehow it kept slipping my attention, I was probably focussed too much on specific ideas, but as it turns out, there is already a module for that, it's simply called Relation.

It's not that straight forward to use (imho), but it essentially creates relations between entities. The created relations are also entities and thus fieldable. By creating a relation type (A [owns] B / B [is owned by] A), I can add a custom field "amount" which holds the information how many Bs are owned by A.

The result (one custom view block added plus a single line of CSS) looks like this.


First, use the -dev version of Rules.

Second, always use the "Show a message on the site" action for testing. This is a LOT easier to debug than "Send email". You can use tokens in the message to test that the values are what you expect them to be, then when you get the right values you can use the email action with those same tokens in your email.

Third, always clear your caches after making changes to a rule.

Fourth, the issue queue contains many complete examples you can use. For instance, here is an example of how to show a system message when an "article" type node is created (from https://www.drupal.org/project/rules/issues/2852342). Try this you will see that "Node is of Type" DOES work to restrict the type - the message will never be shown if you create a node that is not an article:

uuid: c1b8486c-a96b-4f53-903a-8a08cb85355d
langcode: en
status: true
dependencies: {  }
id: test_rule
label: 'Test rule'
events:
  -
    event_name: 'rules_entity_insert:node'
description: ''
tags: {  }
config_version: '3'
expression:
  id: rules_rule
  uuid: f8e466d6-51d6-41ea-93f1-34436470f3c3
  conditions:
    id: rules_and
    uuid: 7776a869-e0c6-4499-b09e-da727722213e
    conditions:
      -
        id: rules_condition
        uuid: 6bf893f5-7bcf-420c-9a62-7e1cb9a884f6
        context_values:
          types:
            - article
        context_mapping:
          node: node
        context_processors:
          types:
            rules_tokens: {  }
        provides_mapping: {  }
        condition_id: rules_node_is_of_type
        negate: false
  actions:
    id: rules_action_set
    uuid: f0bcccfd-685f-4a74-a4fd-0d36b540037a
    actions:
      -
        id: rules_action
        uuid: ec599dbc-cb40-448b-b37b-129d956c2eb7
        context_values:
          message: '<b>Test rule triggered</b> {{ node.title }}'
          type: status
          repeat: false
        context_mapping: {  }
        context_processors:
          message:
            rules_tokens: {  }
          type:
            rules_tokens: {  }
          repeat:
            rules_tokens: {  }
        provides_mapping: {  }
        action_id: rules_system_message

And finally, here's a complete example for how to send e-mail to an address contained in a field value. This example assumes you have a node content type with machine name "email" which has a single-valued required field of type "email" named "field_email".

uuid: bc3fb7fd-0cbd-416c-8b71-9d6b710eb0ce
langcode: en
status: true
dependencies: {  }
id: send_email_when_content_of_type_email_is_created
label: 'Send email when content of type "email" is created'
events:
  -
    event_name: 'rules_entity_insert:node'
description: ''
tags: {  }
config_version: '3'
expression:
  id: rules_rule
  uuid: 265d153c-9ce9-4250-a1b7-b8670be7826c
  conditions:
    id: rules_and
    uuid: 4f570c4e-3558-4628-96dc-aebb7b6d9e65
    conditions:
      -
        id: rules_condition
        uuid: 8014e5b0-680d-46c3-94fc-0785022447ca
        context_values:
          types:
            - email
        context_mapping:
          node: node
        context_processors:
          types:
            rules_tokens: {  }
        provides_mapping: {  }
        condition_id: rules_node_is_of_type
        negate: false
  actions:
    id: rules_action_set
    uuid: 25127564-6ab9-4587-b1b9-9336781aab9e
    actions:
      -
        id: rules_action
        uuid: 16f51441-39e8-4872-a3c2-e4e12a339f1e
        context_values:
          message: 'Email is {{ node.field_email.value }}'
          type: status
          repeat: false
        context_mapping: {  }
        context_processors:
          message:
            rules_tokens: {  }
          type:
            rules_tokens: {  }
          repeat:
            rules_tokens: {  }
        provides_mapping: {  }
        action_id: rules_system_message
      -
        id: rules_action
        uuid: 2c636fe9-9b9a-46b8-b930-81b9730f5ac2
        context_values:
          to:
            - '{{ node.field_email.value }}'
          subject: 'An Email node was created'
          message: 'An Email node was created'
          reply: ''
          language: ''
        context_mapping: {  }
        context_processors:
          to:
            rules_tokens: {  }
          subject:
            rules_tokens: {  }
          message:
            rules_tokens: {  }
          reply:
            rules_tokens: {  }
          language:
            rules_tokens: {  }
        provides_mapping: {  }
        action_id: rules_send_email

If you import these Rules onto your site and inspect how they're constructed they will help you learn how to do this yourself.


How to add order status to commerce_line_item_table view in same way as in the commerce_user_orders view?

Well, you can add the Commerce Order: Order ID relationship to the view and then add the Commerce Order: Order status field and it'll provide the line item's order's status in the view.

Add the relationship:

Then, add the field:

Now, your view will have order status on the line items:


getting uploaded file name at node title

I also battled with this; this is my solution:

Use the Automatic Nodetitles Module as described by the others, and in the Pattern for the title text box load up the filefield and extract the filename that way. Example:

<?php
//Load the file
$file = file_load($node->field_document['und'][0]['fid']);

// Filename
return $file->filename;
?>

Obviously you need to check the Evaluate PHP in pattern. checkbox at the bottom for this to work, and replace "field_document" with the name of your own file field.

Hope this helps somebody!


It could be that there's a bug in the parser's reporting progress. As long as the parser doesn't tell Feeds parsing is done, Feeds will keep calling the parser over and over again.

Workflow of Feeds

Fetch data.
Parse 50 first items of data.
Process 50 items.
Feeds checks if the parser's progress is complete. If not, the next 50 items of data are parsed.
Process 50 items.

When there's nothing more to parse, Feeds checks if there's more to fetch. If so, above steps are repeated. If not, import finishes.


Scald: themable atom reference – where to find image path etc.?

Found the answer to my question one of scald's issue pages – and it's not really complicated. Either it's just not well documented, or I just didn't see it:

This gets the SID from the node's array:

$img = $vars['node']->field_teaser_image['und'][0]['sid'];

And this fetches the atom reference's object:

$atom = scald_atom_load($img);

This is how I then load the title of the atom reference image inside template.php:

$vars['img_title'] = $atom->title;

And the actual filename is inside another object base_entity:

$vars['img_filename'] = $atom->base_entity->filename;

Hope this may help somebody some day.


Additional old_XXXXXXtaxonomy_term__field_XXX Tables after upgrading

Not sure there is an automatic way to do this, a manual way would be to use:

echo "Show tables;" | drush @alias sql-cli | grep old > drop_tables.sql

Edit the tables.txt file and add drop table and a ; after each table name.  Each line should look like:

drop table old_XXXXXXXtaxonomy_term__field_XXXX;

Backup you database in case Murphy come's around and do:

drush @alias sql-cli < drop_tables.sql

That will remove them from the DB.

Alternative way to do it via a GUI would be to use MySQL Workbench and drop them thru the interface.


How to make the Charts module use the Highcharts legend option "useHTML" (required for RTL)?

You should be able to get this to work using the approach as described in the issue about Pass library-specific options via existing #raw_options, AFTER you apply the patch in comment nr 4 of this issue.

Disclosure: I'm a (co-)maintainer of this module.

PS 1: Would be nice/great if you could confirm that this patch also worked for you.

PS 2: after a similar patch becomes available to Google charts also, both patches will be committed.


You can use view mode of all content types where you want to show in searching. Best things are

Create views modes for all content type
assign or enable view mode for that content type
create views and use render as the entity with that view mode.
Theme based on need or UI/UX
Custom form or create a template for search form so you can change the submit template with different UI.


View's row style output is NULL, template file not found in ./

After creating a new tpl file for views to pick up you need to hit the button called " rescan template files" at the bottom of the window. So that your new tpl gets highlighted.


New Relic performance monitoring and the Features Module

By design, Features shouldn't induce any performance hit besides what is inherent to any Drupal module.  It doesn't implement hook_init() or hook_boot(), nor does it implement any hook_form_alter()s or Node API hooks, so there should literally be no Features activity on most page loads.

However, every time caches are cleared, Features does some heavy work — it interrogates all Feature modules and rebuilds Faux-Exportables.

There are two kinds of Features Components: Exportables and Faux-Exportables.

Exportables

Anything that is a CTools Exportable is also a Features Exportable, such as Views, Contexts and Panels.

On this issue thread, one of the Features maintainers says:

  Generally speaking a View in the database and a View in code perform exactly the same. There are some slight differences in loading methodology (it helps to have a good PHP code cache like xcache or APC when using exportables as the data lives in code), but other than that you shouldn't see any differences.

Faux-Exportables

Faux-Exportables include content types, CCK fields, taxonomy, roles, and permissions.

Faux-Exportables are by definition stored in the database, so they do not require any intervention from Features.  Features only touches Faux-Exportables when rebuilding (as mentioned above).


Fatal error: Class name must be a valid object or a string in /home/dsmedia/blog/public_html/includes/common.inc on line 7749

I had a similar issue today (same error message) and I just solved it. It concerns my personal case, but if the description can help anyone :
the problem was the fact that I had created a few items with a content type that I deleted since. So these non published items had an invalid class, because the content type was not existing anymore.
I found these 3 items in the list of content with a blank space instead of the content type name.
Deleting these 3 items, and then extracting/importing the database again to the customer made it work.

The stange thing is that my version of the site was still working since I deleted the content type, so I couldn't understand why suddenly this problem when migrating the site.


How to autoexpand everything on a view translation edit form?

It's set to closed at
https://git.drupalcode.org/project/drupal/-/blob/8.9.x/core/modules/config_translation/src/FormElement/ListElement.php#L70
by
            '#open' => empty($base_key),

so I'll just add a patch to composer to change it to
            '#open' => true,


How to run drush with cron (elysia cron)?

It would probably be easier to use --root and --uri instead of @main.  Drush loads aliases on a per-user basis; the user you are testing drush @main elysia-cron probably has the @main alias defined in an alias file in ~/.drush.  You'd need to either move your aliases to a global location, or perhaps copy your alias file to the www-data user's .drush folder.


Correct way to create Departments/Categories cck selectors in Drupal 7?

Your concern is true. Anyone that tried to build an eshop with multiple categories had the same question in the beggining.

  1) how I should structure my data in taxonomies or other structures (menus?)

You can create a large taxonomy tree the way I see it on the screenshot. Use taxonomy_manager for better UI. Also to display the taxonomy trees as mega menus you can search for "mega menu" in the drupalmodules.com you will find many such modules.

  2) how to create the cck fields for the manufacturer to add multiple department / categories to his product

You can use the Hierarchical_select module. It is a must for such functionality.

  3) how he can add a brand to his product or create and add a new brand to his product

Create a new Vocabulary for Brands and add a field with autocomplete. You can use Hierarchical Select also. It has an option (with proper permissions) to add a term if it does not exist.


How to redirect views of entity types (bean) for user roles?

From quick view of RabbitHole I would suspect that it doesnt support blocks. One way to prevent this could be to use hook_block_view_alter and drop the data when comparing the url. Something like

function MYMODULE_block_view_alter(&$data, $block) {
  // Remove the data if some page view, possibly
  // this would also disable the data on bean/123/delete... :/
  // mayby instead dpm($block) with devel for better targeting?
  if (arg(0)=='bean' && arg(2) !='edit') {
    unset($data['content']);
    //or redirect
    //drupal_goto('somepage');
  }
}


Technically, you could add a reference field to field config entities. But you can't limit the options there and I'm sure you don't want to allow all the fields, and you need custom theming logic for this anyway. That would just allow you to select the field name.

You can't link to a field value, the combination of entity and field doesn't have its own identifier.

If I understand you correctly, then the simplest option is to make a custom list field with allowed values like this:

field_name_a|Field A
field_name_b|Field B

With as many fields as you need. You could also register a allowed options callback and try to dynamically limit the options based the current page/node type, but that's a bit tricky.

Then you need custom logic in preprocess/twig templates for that paragraph type that gets the value for the selected field from the parent of the paragraph and renders it


Get node's view mode within template_preprocess_page

I needed to put a class based on view mode onto my pages.  I seem to remember that view mode is handled separately from the node data.  My solution was actually based on using the Display Suite submodule Switch View Mode (was already using DS).  This module creates a new base field in the entity and sets the view mode to it.

This let me use the following code to create the class:

$view_mode = $node->ds_switch->value;
if (!empty($view_mode)) {
   $variables['page_class'] .= " node-view-{$view_mode}";
}

This solution won't work with out the module.  A bit of tracing on how this works shows that it is based on using hook_entity_view_mode_alter() to get the view mode and add it to the ds_switch field on the node.

This field seems to be added by using the hook_entity_base_field_info().  See the ds_switch_view_mode.module file in the Display Suite code for details on this.


Image Captcha Refresh not displaying refresh link

I have tried recreating your problem and i saw that after you enable the refresh module for the image recaptcha, a link is added below the image in all the forms where captcha is enabled.

But there is no configuration page specific to this refresh module. The link works fine in reloading the image.

I suggest that you add your form via configuration page of the captcha module instead of adding it in the code.

just include your form machine name and captcha in the captcha module configuration page.


How do I change cardinality (delta) of nodes?

You can use form_alter hook to do it:

/**
 * Implements hook_form_alter().
 */
function your_module_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'article_node_form') {
    // Alter your field here:
    // $form['field_collection'][LANGUAGE_NONE][0]['value'];
  }
}

To debug form output, you can install Devel module and use dpm() function.

/**
 * Implements hook_form_alter().
 */
function your_module_form_alter(&$form, &$form_state, $form_id) {
  dpm($form);
}


How do I prevent CKEditor 4 from stripping Google AdSense asynchronous tags?

Have you read this blogpost (not by me) Drupal WYSYWG Module Custom CkEditor Configuration by Philip Norton.

Your <script> tags are not being stripped out, but the funky <ins> tag is. From that blog post you should be able to add a protectedSource to the AFC rules so that those elements are not stripped. This is untested but deriving from the blogpost:

// Allow Google Adsense <ins> tags, I'm being more specific
// than allowing any raw <ins> tag here. This may be too specific, but
// play with it.
config.protectedSource.push( /<ins class=\"adsbygoogle\"\>.*?<\/ins\>/g );

In order for this configuration to work you may have to install the WYSIWYG module (or append to your own ckeditor javascript profile directly).


Module for Integrating jQuery UI Multiselect Widget

Not quite what you are requesting but thinking that chosen might be a good alternative to what your searching for.


How to redirect certain requests to use https://www.example.com in pantheon?

That's because the $redirect_location doesn't get updated for https://example.com. See updated code below.

$domain = 'www.example.com';
if(isset($_SERVER['PANTHEON_ENVIRONMENT']) && $_SERVER['PANTHEON_ENVIRONMENT'] == 'live') {
  $location = '';

  if(in_array($_SERVER['REQUEST_URI'], array('/node/524'))) {
    if (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on') {
      $location = 'http://' . $domain . $_SERVER['REQUEST_URI'];
    }
  }
  else {
    if($_SERVER['HTTP_HOST'] != 'www.example.com') {
      $location = 'https://' . $domain . $_SERVER['REQUEST_URI'];
    }
    if (!isset($_SERVER['HTTPS']) || $_SERVER['HTTPS'] != 'on') {
      $location = 'https://' . $domain . $_SERVER['REQUEST_URI'];
    }
  }

  // Redirect
  if ($location) {
    header('HTTP/1.0 301 Moved Permanently');
    header('Location: ' . $location);
    exit;
  }
}


What filter should be used for date field in views

You need to activate the date_views module to see the filters appearing in the Views module interface.


Triage / decision tree / simple guided entry / expert system for Drupal 8?

This is not a common need of most websites. But, the building blocks exist within the Drupal API to create such business logic at the end of a webform or custom form.


Inserting based on the results of a select query


In theme_preprocess_page hook

    // CIsSharp, 07/23/2013: For 'projects' page, only display year as title
    if (isset($variables['node'])) {
        if (isset($variables['node']->type) && $variables['node']->type == 'projects' &&
            isset($variables['node']->field_pub_year)) {
          $date = strtotime($variables['node']->field_pub_year[LANGUAGE_NONE][0]['value']);
          $year = date('Y', $date);
          $title = $year . ' Project';
          drupal_set_title($title);

          // Because breadcrumb creation executes before preprocess
          // Fix breadcrumbs title also
          $crumbs = drupal_get_breadcrumb();
          if (count($crumbs) > 0) {
             $crumbs[count($crumbs) - 1] = $title;
             drupal_set_breadcrumb($crumbs);
          }
      }
   }


What are the main difference between panels and paragraphs?

They are not the same and you can't do the same thing with them.

Panels

  The Panels module allows a site administrator to create customized
  layouts for multiple uses.

Paragraphs

  Paragraphs module comes with a new "paragraphs" field type that works
  like Entity Reference's.

With Paragraphs you can create collections of items, like you can do with Field collection, as they are fields that you can attach to your content types, you can't do this with Panels.

In the other hand if you want to modify your layout in a simple and easy way you can use Panels, and if you have a collection of items maybe you have used Paragraphs in the content that you're showing.


How to find out the terms which are not being used for some duration

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

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

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

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


You will need custom coding to provide the argument to the view, but you could use the following modules for the geolocation functionality:

Feature-rich, server-side solution:
Smart IP

Simpler, ip-based server/client-side solution:
geoPlugin


Multiple field value amount based on role

I would take a look at this question: Specific number of values in field setting per role. The hook_form_alter method is the way I would approach it.


Assuming I understand the question: To the best of my knowledge, you cannot. For a file in the private file system, the file URL must be rendered on a page in order to be accessed. Redirects and rewrites won't work.


Forum and Gallery taxonomies are used to maintain the information structure of their respective content types. They should not be mixed.

A tagging taxonomy, on the other hand, is generally freestyle, and allows a user to give keywords describing the content. There is no reason to restrict it to a single content type. Why not use your tags on all content types.


Override Commerce Kickstart Features ( and Features Override module error)

I've found that Features Override works nicely in simple scenarios, but I've been unable to get it working in more complex scenarios, such as modifying Drupal Commerce.

One alternative — instead of modifying the Features Components provided by Drupal Commerce — is to clone them, make your changes to the cloned components, and then featurize the cloned components.


Remove the "Advanced search" form on the result page?

You need to go to:

admin/people/permissions

and uncheck the checkboxes for the users that don't need to use the Advanced Search.


How to force the display of an empty field in panels for an editable field?

In your /sites/all/theme/YourTheme/template.php file, you could try using

function YourThemeName_preprocess_content_field(&$variables) {

    if (!isset($variables['field_name']) {
    $variables['field_name'] = ' ';
  }
}

but I don't know if the empty ' ' will show.


I currently use Boost and Cloudflare together on a medium sized site, I don't have any current performance figures to show you but there is a substantial improvement in performance and scalability by using the boost module with the cloudflare service. I don't use the cloudflare module itself as it only allows you to submit Spam reports & ban/whitelist IP addresses.

I use the boost module and have then setup my account on cloudflare.com to cache static assets like images etc
Boost on its own does a great job of serving more pages faster. However as my site has a lot of static assets and that is primarily why i use the cloudflare service.


Implementing callback function in hook_menu()

The simple answer is it is for ajax items. In drupal 6 you had to declare a path and direct your ahah to it with ['#ahah']['path']. In drupal 7 it is handled automatically and you now use ['#ajax']['callback'] to call the function without having to declare a path.


How to change "Save Draft" value on Webform?

Code to change the text for Save Draft button is:

function customisations_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'webform_client_form_88') {
    $form['actions']['draft']['#value'] = 'Save';
  }
}

This would change only for Save to Draft button. In order to change the submit button text of the webform, we can use the configuration of the Webform to change it. URL for the same is node/88/webform/configure.

Hope that this helps.


How do I change the machine name of a field once it's been created

My procedure is to use drush to clone the field first, then copy the field data with DB queries into the new field table. After I verify the contents of the cloned field, I delete the original field.

I do it this ways because I think the drush method of cloning fields will always be at least as reliable as any cloning code I might craft myself, the data copy query is pretty simple, and I get to check the new field before deleting the original.

drush field-clone field_my_field field_my_field_clone
Insert rows into field_my_field_clone, e.g., INSERT field_my_field_clone SELECT * FROM field_my_field;
Verify the contents of field_my_field_clone.
Delete the field using the UI, e.g., admin/structure/types/manage/my-content-type/fields