how to overwrite the views output? I used Views with 6 fields. I want to overwrite the output for 4 fields, and add "more >>" under one fields output, and make the "more" link to the node. I know that creating 4 template files will get that, but creating 4 template files is too boring.

Is there a way to overwrite the 4 fields in one file? If I can, could you make me an example?

or you can simply add a views field 'Node:Link' - you can set the text in the options of that field.

If you want to add this field to other fields, choose the 'rewrite output' option of those fields, and place the token of that current field + the token of the 'node:link' field in the output area.

Make sure you check the 'exclude from display' option for the 'node:link' field and set the field first in the field order, so the token is made available


How would I use entity wrapper to insert new values into an entity property list? bundle? I would like to save a list of values into a entity property.

foreach ($results as $result)
{
   $wrapper->title->set(value);
}

Can an entity property hold an array of values or would I use an entity reference defined as a field for each of my values?

Thanks

A field can only hold multiple values if it's been explicitly set to hold more than one value (this is an option when creating the field - see "How many values the field will store" at http://drupal.org/documentation/modules/field-ui ). In that case, the correct syntax using the entity metadata wrapper is to use array operator [] as follow:

$tids = array(....);
$wrapper = entity_metadata_wrapper('node', node_load(1));
foreach ($tids as $tid) {
  $wrapper->field_taxonomy[] = $tid;
}

Please note that in your original example you use the field 'title' - however that is a special drupal field, and it cannot be made to be multi-valued.


How to do a date range entityQuery with a Date only field in Drupal 8? In Drupal 8, the Date only field stores data in a varchar column in a CCYY-MM-DD format, e.g., 2016-04-18.

As such, you can't simply do a greater than (>=), less than (<=) or similar timestamp based entityQuery anymore.

Is there a simple solution on how to deal with this? Specifically I am attempting to do two queries, one where the date field is between 14 and 21 days old, and one where the date field is 21 and over days old.

I'm doing lots of conditions like that in entity queries, I haven't encountered a problem yet.

The main thing you have to be aware of is the timezone the data is stored, which is UTC. You need to convert it to the storage timezone (there's a constant for that), or your query will be off by a few hours.

Here's an example based on something I'm doing, if you only store days, then there is a constant for formatting that too.

$date = new DrupalDateTime('21 days ago');
$date->setTimezone(new \DateTimezone(DATETIME_STORAGE_TIMEZONE));
$formatted = $date->format(DATETIME_DATETIME_STORAGE_FORMAT);

$nids = \Drupal::entityQuery('node')
  ->condition('your_date_field.value', $formatted, '<=')
  ->range(0, 50)
  ->execute();


Is there a way to change content in 1 master node and have it changed in hundreds of others? I have searched for quite a while but with no success. Using D7.41, Views 3.

I have a lot of nodes of the same content type (~50 nodes) and all of these nodes have images and some text, plus 4-6 blocks of views in each (different text, different images and in some cases different blocks).

Task: to let the content manager edit this master template (change text, images, change blocks for all these 50 nodes), but the changes would then be replicated 20 times - I have exactly same structure replicated for 20 different regions - the same content, different paths. So that would be some kind of "Master template".

I do understand, that all of this could be managed with blocks, when all the content of the page is done via blocks, but maybe there is some other more clever way to achieve this?

Updated: one of the ways to reduce the amount of blocks used, I guess (as per user comment below), would be solution to have fieldable blocks. But in that case there is another question - how to do that?

If you have so many blocks, then you should try to find ways/techniques to reduce the amount of them. Below are some possible modules to help you on that.
BEAN
You should have a look at the Bean module, which potentially can help you to answer this question. Here is a quote about its project page:

Think of a Bean as a method to provide new types (compared to node this would be a content type) which then provides an add content interface to create as many blocks as you require (see screenshot below). The bean content can then be placed around the site just like any other block.

This module also works great in combination with the UUID and UUID Features Integration modules. And after you become familiar with the Bean module, you might find other cases in your site where you also want to use this module (which somehow compensates the fact that you need to add another module).
The video tutorial Drupal Bean module tutorial - using Bean Admin UI provides a great introduction to really understand the power of this module, and the kind of things you can do with it (by only using site building techniques, no custom coding involved). It also shows how the Bean module transforms Drupal blocks into fieldable entities.
Remark: this module (a raising star!) has been moved to core in D8 ...
Rules and Rules block visibility
Another module to have a look at (to help reduce the number of your blocks), is the Rules block visibility module. Here is a quote from its project page:

The Rules block visibility module allows Rules components to be used to control block visibility. This provides Drupal administrators and developers extreme flexibility in controlling when blocks should be displayed on their websites, in addition to the default visibility options provided by Drupal.
The general idea is that if you can do it with Rules, you can use it to control block visibility, so the possibilities are limitless:

Need to show a block only for users registered more than a month ago?

Perhaps you have a block that must be shown only between 8am-5pm on weekdays?

What about displaying or hiding a block based on current weather conditions?

All of this can be done by using Rules block visibility.


Customize Search Result Snippet to use Teaser I would like to customize the output of each search result item printed on the search result page. Right now it automatically prints a portion of the content of each item, but I'd like more control. I would like to specify what fields to display in the search result. For example I'd like to output field_image followed by field_mytextfield. Rather than whatever Drupal is doing to output the trimmed content of the result.

I'm using a template to customize the output already

{{ title_prefix }}

        {{ title }}

{{ title_suffix }}
{% if snippet %}

{{ snippet }}

{% endif %}

However I don't seem to have access to what is inside snippet, and I'm not sure how to directly access the fields of the result. I'd like to use the content type's teaser as the result display but I'm not sure how to use that.

You can take control on which content the snippet is based by modifying the view mode "search_result". If you want to hide information from a field, then simply remove it there. But you can't change the behavior, how the snippet is composed out of this content. This is hard coded. And it will be text only with all tags removed.

If you want to provide additional elements for the search result, beside the snippet, you can do this by implementing template_preprocess_search_result in your module/theme file:

function [MODULE_NAME]_preprocess_search_result(&$variables) {
  $node = $variables['result']['node'];
  if (isset($node)) {
    $variables['teaser'] = \Drupal::entityTypeManager()->getViewBuilder('node')->view($node,'teaser');
  }
};

And use it in twig:

{{ teaser }}


Filefield with IMCE browse server I am having rather strange issue. I have created custom CCK with image upload field. To browse a server folders I've installed a CCK Filefield and configured it to work with IMCE , however I can't see images (uploaded with FTP), unless I upload them through IMCE itself. The strange thing is that in Description field I have also IMCE file browser wich "see" correctly all images. What am I missing? Thanks

To overcome the above problem, I have installed the IMCE for FileField module; everything started working.


How can I get the Contact Form "Manage Display" Settings programmatically? I am trying to use hook_mail_alter to create a custom contact mail.

I want to get the display setting of the contact form.

(example path: http://mysite/admin/structure/contact/manage/my_contact_form/display/mail)

The things I want to know are:

Field Label
If its disabled or not
Field order
Field ID

How can I get this information in the PHP script?

EDIT:

I was able to get most of the information I wanted. but I couldn't get the field weight to display in the right order. I have a display mode called 'mail' and I want to get the weight of each field in this mode.

for now the code looks like this:

/**
 * Implements hook_mail_alter().
 */
function contact_plus_mail_alter(&$message) {
    if (isset($message['id']) && $message['id'] == 'contact_page_mail') {

        $siteName = \Drupal::config('system.site')->get('name');
        $siteMail = \Drupal::config('system.site')->get('mail');
        /** @var \Drupal\contact\Entity\Message $contactMessage */
        $contactMessage = $message['params']['contact_message'];
        $entityType = $contactMessage->getEntityType()->id();
        $bundle = $contactMessage->bundle();

        $contactForm = $contactMessage->getContactForm();
        $form_title = $contactForm->label();
        $recipients = implode(',', $contactForm->getRecipients());
        /** @var \Drupal\Core\Field\FieldItemListInterface[] $fields */
        $fields = $contactMessage->getFields();
        $data = [
            'title' => $form_title,
            'fields' => [],
        ];
        foreach ($fields as $key => $field) {
            $fieldDefinition = $field->getFieldDefinition();
            $data['fields'][] = [
                'label' => $fieldDefinition->getLabel(),
                'info' => $field->getValue(),
                'display_options' => $fieldDefinition->getDisplayOptions(),
                'weight' => '', // I want to get the field weight for the 'mail' display mode.
            ];
        }
        // TODO: order the data by weight

        // ... send the email
    }
}

I was able to retrieve the order of the 'mail' display.
The secret was in the ->getComponets() function in this part:

$display = \Drupal::entityTypeManager()
    ->getStorage('entity_view_display')
    ->load($entityType . '.' . $bundle . '.' . $displayMode);
$displayFields = $display->getComponents();

the final code looks like this:

/**
 * Implements hook_mail_alter().
 */
function contact_plus_mail_alter(&$message) {
    if (isset($message['id']) && $message['id'] == 'contact_page_mail') {
        $message['send'] = false;

        $siteName = \Drupal::config('system.site')->get('name');
        $siteMail = \Drupal::config('system.site')->get('mail');

        /** @var \Drupal\contact\Entity\Message $contactMessage */
        $contactMessage = $message['params']['contact_message'];
        $entityType = $contactMessage->getEntityType()->id();
        $bundle = $contactMessage->bundle();
        $contactForm = $contactMessage->getContactForm();
        $form_title = $contactForm->label();
        $recipients = implode(',', $contactForm->getRecipients());
        // Data for the email
        $data = [
            'title' => $form_title,
            'today' => (new \DateTime('now', new \DateTimeZone('UTC')))->format('m/d/Y'),
            'fields' => [],
        ];
        // get the 'mail' display mode if defined
        $viewModes = \Drupal::service('entity_display.repository')
            ->getViewModeOptionsByBundle(
                $entityType, $bundle
            );
        $displayMode = array_key_exists('mail', $viewModes) ? 'mail' : 'default';

        // get display field settings (weight, id, etc...)
        /** @var \Drupal\Core\Entity\Entity\EntityViewDisplay $display */
        $display = \Drupal::entityTypeManager()
            ->getStorage('entity_view_display')
            ->load($entityType . '.' . $bundle . '.' . $displayMode);
        $displayFields = $display->getComponents();

        // put the fields info in the email data
        foreach ($displayFields as $key => $fieldConfig) {
            $field = $contactMessage->get($key);
            $fieldDefinition = $field->getFieldDefinition();
            $data['fields'][$key] = [
                'label' => $fieldDefinition->getLabel(),
                'info' => $field->getValue(),
                'display_options' => $fieldDefinition->getDisplayOptions(),
                'weight' => $fieldConfig['weight'],
            ];
        }

        // order by weight
        function compare_weight($a, $b) {
            return strnatcmp($a['weight'], $b['weight']);
        }
        uasort($data['fields'], 'compare_weight');

        // send the email for the responsible
        $emailSender = new EmailSender($siteName . '<' . $siteMail . '>', $recipients, $form_title, 'my_theme', $data);
        $emailSender->createAndSendEmail();

        // send a copy to the person who filed the form
        if (isset($data['fields']['field_email'])) {
            $email = $data['fields']['field_email']['info'][0]['value'];
            $emailSender->to = $email;
        }
        $emailSender->createAndSendEmail();
    }
}

Hope it helps someone.


How can I upgrade to core 9? I have Drupal 8.8.* and I would like to migrate to Drupal 9 using Drush 8. I know, we can use composer however I just wanted to confirm, whether we can do by using Drush command?

I tried using Drush but it's showing no updates available.

$ drush pm-update drupal-9.0.0
Update information last refreshed: Thu, 06/11/2020 - 11:42
 Name    Installed Version  Proposed version  Message
 Drupal  8.9.0              8.9.0             Specified version not found

No code updates available.

No, you can't. drush pm-update has been deprecated for a while. The command is still available in the Drush 8.x branch but in later revisions it only exists as a signpost to inform the user how to move to Composer:

  The pm-updatecode command was removed. Please see composer update --dry-run and composer update.

Noting that Drush 8 isn't supporting revisions past 8.3.x or 9.x, you should look into upgrading Drush and moving to a Composer-driven upgrade process.


How to alter Fields of Field Collection? I have a field collection in a custom Content Type.

I wanted to do form alter.

I'm unable to locate the fields of field collection in hook_form_alter(), do we have any other way ?

try to use
$form['YOUR_field_collection']['und']['0']['sub_field']['und']['0']['value']
for ex : to add ['#autocomplete_path'] would :
$form['YOUR_field_collection']['und']['0']['sub_field']['und']['0']['value']'#autocomplete_path']=''


How to allow user login only once at a time? I want to allow a user login to the site only once at a time. User should not be able to login at other machine/place while he is logged in.
I want to user password should get destroyed once used and should promt user to "request new password".
I also want to show user login time,logout time, number of visits, last visit time...etc in a block for user.

How can i get these in Drupal?

You can get what you're looking for with a combination of existing modules:

Session limit module
Password policy module
User stats module + Views module

You shouldn't have to write a single bit of code using those 3 modules.

You don't mention which version of Drupal you're using but each of those modules have D6 and D7 releases (albeit a dev release for one of them).


Query String and hook_page_alter() Is it possible to read the query string and it's values from the &$page param in the hook_page_alter function?

If not, is it possible at all?

I'm not sure why you'd need to get it from the $page variable, you can get the query string from the $_SERVER superglobal at any point in the page execution, and convert it into an array with PHP's parse_str():

function MYMODULE_page_alter(&$page) {
  // Convert the query string to an associative array named $qs
  parse_str($_SERVER['QUERY_STRING'], $qs);

  // For the string name=jeff&foo=bar:
  //
  // $qs['name'] = 'jeff';
  // $qs['foo'] = 'bar';
}


User profile private public toggle I'm searching for a way to let users chose if they want their user profile to be public or to be private (just the owner and admin). I'm not picky if this can se set for the whole profile or for every profile field.

I already looked at User Field Privacy but this one conflicts with Field Permissions (this site needs fields permissions).
And I'd rather not use Profile2 for this functionality since I'm only using the standard profile fields.

I thought about using Field Conditional Formatters but this seams rather complicated to set up for every field.

Any ideas?

Easiest way would be to change the access callback to the user page (user/%user) via hook_menu_alter.
The new access callback would use the value of a user field to determine or the page is accessible or not.

Code to give you an idea of the structure, not a fully functioning example

YOUR_MODULE_menu_alter(&$items){
  $items['user/%user']['access callback'] = 'user_profile_is_private';
}

function user_profile_is_private($user){
  // Check the content of the user field here and return true/false.
}

This tells drupal to use the user_profile_is_private function to determine or people can access the user page or not. This function should return true/false.
The user object is passed to this function via the core user module already.

You'll need to add the core user access function user_view_accessin there somehow to prevent this change to override all other access settings.


Zen Theme Outputting Term Desc in Node - How To Add To Views Hello i am using a zen based them Plain Grail. I nitice that on nodes it shows the term description on hover in nodes. I would like to achieve this effect in some of my views.

I have seen this question asked on here before but because my theme is already outputting this i thought it best to ask a new question.

I cannot see any reference to this in Plain Grail or Zens template.tpl

Does anyone know how i can show the term description in Views? thanks

Drupal 6 and Views 3

See source of term:

term01

So term's descrtiption here just title attribute.
So for Views you can add field with link (or rewrite output), and put in Title some placeholder name.


How Print individual fields in a view row by row I have so much fields in a content like "title", "field_image", "field_description", and i use a view for create a block and put it on my front page...

I will make a slider with a jquery plugin (jssor slider), i need use the structure of jssor slider. then in my view, i use "views-view-fields--[name_machine]--block.html.twig" for print individual fields. but the file "views-view-fields..." print for each content, run all code on this file,and i need to put the initial containers of this plugin only once, and the code of the images several times.

I try to put the initial containers of the plugin in the "page.html.twig" but when i print the block with the "views-view-fields..." inside
he puts a lot of code and many labels and containers that I do not need and the plugin stops working. let me show the files.

my page.html.twig
          {# Header #}
      {% if page.banner_front %}

        {% block banner_front %}
            {{ page.banner_front }}
        {% endblock %}

then my views-view-fields--banner--block.html.twig:

                        {% if fields.title.content %}
                            {{ fields.title.content }}
                        {% endif %}

                        {% if fields.banner_description.content %}
                            {{ fields.banner_description.content }}
                        {% endif %}

                    {% if fields.field_url.content %}

Ver más

                    {% endif %}

to work correctly, the label
 must be left of the label
, but when the region is printed the system prints many labels and containers that damage the structure of the slider.

On Drupal 7 i used inside of the foreach the code of the images, and outside the inicial structure, and works well but now, i dont know how to this.

Thanks a lot.

If you work with Format:Unformatted list try to override the views-view-unformatted.html.twig, you will have the ability to add class to parent or inside each row.


Importing dates TO and FROM using Feeds module I'm wanting to import some content to my drupal site. One of the fields for this new content type is a date field. The date actually has both to and from fields and in fact the nodes I will be importing have a start and end date...I've read about importing using the Feeds module (here for example: How to import date fields using CSV file? I haven't been able to find any material on importing a date range (for example, an event. The event begins on August 4, 2015 and ends on August 6). What would be the format for that?

I'm imagining something like MM/DD/YYYY - MM/DD/YYYY. Does anyone know the preferred format?

Nevermind, I discovered these can be handled by specifying the Date: Start and Date: End fields in the Feeds importer itself; sweet.


Custom VBO Action only works when enqueued (Adding User Role and Organic Group) I wrote a custom module to add a VBO action that allows an Admin of a group to search the sites users, add them to their list (adds a role to the select users to get them on the list) and then allows the Admin to optionally add the user to an organic group they also may admin. The role is added just fine, but the organic group won't 'stick' unless I enqueue the operation. When I don't enqueue the operation, I dpm'ed the call to og_group and it's returning a membership object and claims it was successful, but it clearly didn't save. I don't have any errors or notices in the logs either.
Here's my setup for saving the group/user relationship:

$values = array(
        'entity_type' => 'user',
        'entity' => $user,
        );

og_group('node', $group->nid, $values);

$user is a fully loaded user account and $group is the group node. I tried adding name_field and the group audience to the values array, but this made no difference.

Here's the hook for the VBO:

function vbo_users_to_groups_action_info() {
 return array(
   'vbo_users_to_groups_my_custom_action' => array(
   'type' => 'user',
   'label' => t('Add users to Pro List and optional Group'),
   'behavior' => array('changes_property'),
   'configurable' => TRUE,
   'vbo_configurable' => FALSE,
   'triggers' => array('any'),
   ),
  );
}

Is there anything else you need to see that may be causing this?

If anybody runs into this in the future, I had to pass the group id into the og_user_node field and save the user after calling og_group():

$values = array(
    'entity_type' => 'user',
    'entity' => $user,
    );

og_group('node', $group->nid, $values);
$data['og_user_node']['und'][0]['target_id'] = $groupid;
user_save($user, $data);

You should check for any other groups the user is in and create an array of groups along with the new group id and save that into og_user_node, but in my situation, users are only allowed in 1 group, so this takes care of putting them in the new group and removing the old one.


How do I define the default cache and cache settings programmically in a Kernel test? A user provided a set of site caching configuration settings that cause some errors. For example:

$settings['cache']['bins']['dynamic_page_cache'] = 'cache.backend.memcache';
$settings['cache']['bins']['discovery'] = 'cache.backend.memcache';

On top of that, the memcache module states that users must include the following in their site configuration:

$settings['cache']['default'] = 'cache.backend.memcache';

I would like to extend some core Kernel tests to run with the memcache module configured the way the user described. I can easily enable the module by adding it to the $modules array in the MyTest class. What else do I need to add to ensure the “site configuration settings” are the way the user recommends. I was hoping I could add something to the MyTest::setUp() function to change the settings, or better yet, have a dataProvider to supply a variety of settings to the test function to test against. I thought there would be something obvious in the system.performance configuration item, but it looks like cache.default is a service. Do I need to redefine this service programmically? How do I do that? The memcache module does not automatically override the cache.default service in its services.yml file.

Take a look the Memcache module.
The module has tests, and seems you need write

  protected function setUp() {
    $this->config = [
      'memcache' => [
        'servers' => ['127.0.0.2:12345' => 'default'],
        'bin' => ['default' => 'default'],
      ],
      'hash_salt' => $this->randomMachineName(),
    ];
    $settings = new Settings($this->config);
    $this->settings = new MemcacheSettings($settings);
  }


drupal_render() and drupal_get_form() In the following snippet, the form returned has only the hidden values. No name, email, or comment.

require_once drupal_get_path('module', 'contact') .'/contact.pages.inc';
$elements = drupal_get_form(array('contact_site_form'));
$form = drupal_render($elements);

Can anyone say why $form is not returning an HTML form?


How to display different image on hover and content in pop-up? I am displaying a list of images using Views. I would like a different image to display on hover, and then text/content to be displayed in the pop-up. I am trying to use Colorbox module, but can't figure out how to display a different image on hover, or how to display text/content in the pop-up.

Any help would be greatly appreciated.

This is the html that the Colorbox trigger field (set to Image) produces with "Enable Colorbox load" and "Enable Colorbox inline" options both UNTICKED:

What am I missing/doing wrong? The popup is still not working.

The Beautytips module provides ballon-help style tooltips for any page element and you can also use it in views.

Currently i am using this module with views to display the text(for field) in bottom of my page , when mouse hover of image. For more information check this video

  It provides an API for adding custom beautytips as well as some
  built-in features. Admins can enable rollover balloon-help style
  tooltips for text fields within forms. It also supplies hover tips for
  Drupal help links and advanced help links.


Help with debugging and fixing errors with SalesForce Mapping Module For Drupal SalesForce Suite I am having the follwoing Errors show up in my log messages

When I select from the Drupal Entity Type , Drupal Entity Bundle, and Salesforce Object I get these errors

Notice: Undefined index: salesforce_record_type_default in salesforce_mapping_form_validate() (line 520 of /x/x/x/x/x/x/web/sites/all/modules/salesforce/modules/salesforce_mapping/includes/salesforce_mapping.admin.inc).

Notice: Undefined index: salesforce_record_types_allowed in salesforce_mapping_form_validate() (line 520 of /x/x/x/x/x/x/web/sites/all/modules/salesforce/modules/salesforce_mapping/includes/salesforce_mapping.admin.inc).

Warning: in_array() expects parameter 2 to be array, null given in salesforce_mapping_form_validate() (line 520 of /x/x/x/x/x/x/web/sites/all/modules/salesforce/modules/salesforce_mapping/includes/salesforce_mapping.admin.inc).

For just SalesForce Object I get this additional error

Warning: Invalid argument supplied for foreach() in form_type_checkboxes_value() (line 2337 of /x/x/x/x/x/x/web/includes/form.inc).

In the UI I am unable to add more then the initial field, when I click the button to add additional mapping and select my field type, the second row of fields disappears and it logs this error in watchdog

Notice: Undefined offset: 1 in salesforce_mapping_form_field_callback() (line 428 of /x/x/x/x/x/x/web/sites/all/modules/salesforce/modules/salesforce_mapping/includes/salesforce_mapping.admin.inc).

Local Environment on XAMPP Mac OS Yosemite/ Drupal 7.34/ SalesForce Module 7.x-3.0-Dev/PHP 5.6

To further update this issue, it will allow me to create a mapping but with only the first row in the mapping table. If I save it and then go back in to edit, when I click "add another field mapping" I get a popup with this error.

An AJAX HTTP error occurred.
HTTP Result Code: 200
Debugging information follows.
Path: /system/ajax
StatusText: OK
ResponseText:
Fatal error:  Call to undefined function salesforce_mapping_form_validate() in /x/x/x/x/x/x/web/includes/form.inc on line 1513

Without being able to find an answer to the issues I was having, I did finally get the mapping module to work by downgrading XAMPP and instead of using PHP 5.6 used PHP 5.3, which enabled the Mapping module to begin functioning properly.


How to display a button with “markup”? I created a custom module and in the code below the button is not rendered, there is only the text :

$form = ['#markup' => '<button type="button" class="btn btn-success" disabled="disabled">Product unavailable</button>'];

How to display the button?

<?php

/**
 * @file
 * Hook implementations of commerce_add_to_cart_access module.
 */

use Drupal\commerce_product\Entity\ProductType;
use Drupal\commerce_product\Entity\ProductVariationType;
use Drupal\Core\Entity\Display\EntityViewDisplayInterface;
use Drupal\Core\Entity\EntityInterface;
use Drupal\Core\Url;

function commerce_add_to_cart_access_form_commerce_order_item_add_to_cart_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {
  // Your original code to get store owner.
  $current_store = \Drupal::service('commerce_store.current_store');
  $owner = $current_store->getStore()->getOwner();
  if (!$owner->hasRole('marchand_premium')) {
    // Overwrite the whole form markup!
    $form = ['#markup' => '<button type="button" class="btn btn-success" disabled="disabled">Product unavailable</button>'];
  }
}

You can use the inline_template to solve the problem:

// Delete the other button.
unset($form);
$form['submit'] = [
  '#type' => 'inline_template',
  '#template' => '<button type="button" class="btn btn-success" disabled="disabled">Product unavailable</button>',
];


Same tax for all territories and tax-free products We're selling registrations to a congress through Drupal Commerce 2 and have been informed by the government of the country where the conference takes place that we have to charge their local tax to all attendees. Our attendees come from all over the world.

Is there a way to configure the Commerce 2 tax module to have it charge the same tax rate to all orders, regardless of where the customer is, other than creating a custom tax type and adding all territories one by one?

We also sell other products and do not want this local tax applied to those products. How would we go about configuring those products so they are not included in the tax calculation?

(Answering my own question.)

I ended up not using Commerce's Tax module but coding my own.  I added a "Taxable" field to products and created an Order Processor plugin to calculate the tax amount and add it to orders as an adjustment.

It took much longer to figure out how to do it than to actually do it.


Can a site be put in maintenance mode without a database? I'm trying to handle a planned database outage and want Drupal to show the maintenance page during that time.

$conf['maintenance_theme'] = 'exampletheme' and a suitable $conf['_message'] are set in my sites/sitename.com/settings.php
I have a maintenace-page--offline.tpl.php and maintenance-page.tpl.php in sites/all/themes/exampletheme/templates/
I set $conf['maintenance_mode'] = TRUE in sites/sitename.com/settings.php

I hope that Drupal that does not have a database can still bootstrap and display the contents of maintenance-page--offline-tpl.php in this configuration, but in my testing it seems that's not the case. Should this work? Anything I should look into?

What you're describing should work: the maintenance-page--offline.tpl.php template should be called when the database is unavailable.

Drupal does not bootstrap completely when there is no database, but does so partially. When the bootstrap process fails to contact the database, it calls _drupal_log_error() in include/errors.inc, which (indirectly) calls _drupal_maintenance_theme() in includes/theme.maintenance.inc. This is enough to allow hook invocations to work, and to load the theme specified in your $conf['maintenance_theme'] setting.

First, I would verify that _drupal_maintenance_theme() is being called and that it's finding your theme. If you're using a debugger, set a breakpoint there. If not, add this line at the end of the function:

  echo "
Custom theme: $custom_theme
";

If all is ok up to this point, try starting off with the simplest possible maintenance page in maintenance-page--offline.tpl.php, e.g.

Hello world

If that works, and your maintenance page does not, perhaps your maintenance page contains something that attempts to access the database, or invokes a hook that attempts to access the database? Can you post your template and any errors you are seeing?

If the simple maintenance page doesn't work, more debugging would be needed.


How to get work Internationalization module with l function? I am using Internationalization module to translate content.
How to get work this module with l function?

for example, when I create programatically link to content:

l(t('About us'), 'node/22');

I would like to achieve, that path 'node/22' will change when I switch website to another language. With Internationalization module, each translation of node creates another node, so I need to change paths in links on website.

For this time,
I can create just if-else condition:

<?php
if ($language->language == 'en')
$output = l(t('About us'), 'node/22');
elseif (($language->language == 'de')
$output = l(t('About us'), 'node/23');
?>

IS it possible to use l function in that way, that I don't need to write else-if condition?

There's no easy way to do this, but you can do something like this:

$nid = 22;
$node = node_load($nid);
if ($node) {
  $translations = translation_node_get_translations($node->tnid);
  $nid = isset($translations[$language->language]) ? $translations[$language->language]->nid : $nid;
}

Or use the Entity translation module, which relies on the ability of fields to have values in multiple languages and then the node id doesn't change.


link field template syntax / display link field as an image / devel dpm (D7) My link field is currently displaying as a URL as you can see here (yellow border). I have added dpm($items) to my link field template file. How do I read the dpm output or more specifically how do I edit my template file to say "display this field as the specified image"?

The following example works in a different situation where the field is an uploaded file but in this case the field is a link.

<?php $path = $items[0]['#file']->uri; ?>
<a href="<?php print file_create_url($path); ?>">

I dont really understand what the problem is, If you are already outputting the link URL, and you want to display that as an image, surely you can just wrap it in an img tag?

<?php $path = $items[0]['#file']->uri; ?>

<img src="<?php print file_create_url($path); ?>" />

OR, with an mp3 file like in your example...

<?php $path = $items[0]['#file']->uri; ?>
<audio controls>
  <source src="<?php print file_create_url($path); ?>" type="audio/mpeg">
</audio>


Where to render? Preprocess or template? We are constantly improving our coding performance and we are monitoring every page load to optimize loading en rendering times in our websites.
Above statement in mind, I stumbled upon the question where should we render the renderable arrays?

If you render them in your preprocessor, the template keeps pretty neat since you're only printing variables.

Preprocessor:

function template_preprocess_node__faq(&$variables) {
    $node = node_load($variables['nid']);
    $node_style = node_view($node, $variables['view_mode']);

    $faq_sets = array(
      '#theme'  => 'my_module_faq_set',
      '#sets'   => $variables['field_faq_set'],
    );

    $variables['faq_image']   = render($node_style['field_faq_image']);
}

Template:

<div class="faq_image">
     <?php print $faq_image; ?>
</div>

However, I'm not sure it this is the proper/fastest/neatest way to preprocess and print variables.

Drupal isn't consisting in this matter either I guess... In the default node.tpl.php variables are rendered while in other default templates (like html.php.php), variables are just printed.

Does anyone have a rule and/or some tips and advices on how to tackle this issue the cleanest and fastest way?

Drupal isn't consisting in this matter either I guess... In the default node.tpl.php variables are rendered while in other default templates (like html.php.php), variables are just printed.

That's not quite right. If you look at template_preprocess_html() you can see that nothing is run through render()/drupal_render(). So quite simply the variables in html.tpl.php are printed rather than rendered because they don't need to be rendered. All the vars are already strings, and no render arrays were used to build the template.

Conversely, the node content in node.tpl.php is a render array. So any parts of it that need to be rendered have to be run through render() and not just printed.

I would be tempted to follow core's example of using render() in templates, not in preprocess functions, unless you have a specific reason to do it differently.

From a performance point of view the difference would surely be negligible, but profiling the code in the context of your site and hardware is the only way to be certain.


varnish + multiple webheads = files/(css/*.css|js/*.js) missing I have this weird issue and I'm not sure if it's me who's doing something wrong or I'm just missing something but maybe some of you can guide me a little bit here...

i setup a varnish server, within varnish itself i created 2 backends and using director i'm able to do round robin to my webheads. That parts seems to be working fine as I'm able to bring one of my webheads down and the other one can serve content to varnish and vice verse.

but here is a kicker... i noticed that sometimes page doesn't load properly so i start looking into why and I noticed some of the files are 304 or 404, so turns out somehow some of files in (files/css/.css or files/js/.js are missing), so I rsync them so now they all appears to have same content in those directories, but when i go to another page it seems like drupal generates more of those and since varnish goes to a round robin for any hit it serves some of page from one webhead and another part from another, so even though css,js file has been generated on first webhead it not generated on second and hence shows 304 or 404.

please advise

This is happening when you have optimization for CSS/JS turned on. These files are generated regarding the context (the page visited by the browser) and so the visitor won't be served some files when the round robin changed the targeted server.

You can configure the round robin to stay on the same server on a per-session basis (see: Pure VCL cookie-based sticky sessions in Varnish 2.1), but generally you should set up a NFS share between your server where you'll put the sites/default/files folder.

Source: Drupal's optimize CSS and JavaScript setting causing problems in multiple server environments.


ajax form submit multiple times I have a form which consists of one submit button (Add to cart). I made it submit via AJAX but the problem is that when I press the button the second or third (and so on) times, the submit handler doesn't execute. I think this happens because the form_build_id and form_token fields should be rebuilt.

Do you have any idea on how I can achieve this functionality?

This is the code I am using.

function mymodule_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'my_form_id') {
    $form['submit']['#ajax'] = array(
      'callback' => 'mymodule_ajax_form_callback',
      'wrapper' => 'my_form_wrapper',
    );

    $form['#prefix'] = '
';
    $form['#suffix'] = '
';
  }
}

function mymodule_ajax_form_callback($form, &$form_state){
  return $form;
}

As reported on drupalcommerce.org, the trick is to clear the form and form state caches in your AJAX callback.

The following is a working code example taken from that post:

function ajax_cart_form_alter(&$form, &$form_state, $form_id) {
  // Add ajax property to Add to Cart button
  if (strstr($form_id, 'commerce_cart_add_to_cart_form')) {
    $form['submit'] = array(
      '#value' => t('Add to Cart'),
      '#type' => 'submit',
      '#ajax' => array(
        'callback' => 'ajax_cart_form',
        'wrapper' => 'block-commerce-cart-cart',
        'effect' => 'fade',
        'progress' => array('type' => 'throbber', 'message' => ''),
      ),
    );
  }
}

function ajax_cart_form($form, &$form_state){
  global $user;
  $order_id = commerce_cart_order_id($user->uid);
  $cart =  commerce_embed_view('commerce_cart_block', 'default', array($order_id));
  $commands = array();

  // The next line allows different quantities
  // to be submitted each time
  unset($form['quantity']['#value']);

  // Clear form and form state cache
  $form_state = form_state_defaults();
  $form_build_id = $_POST['form_build_id'];
  form_set_cache($form_build_id, $form, $form_state);

  $commands[] = ajax_command_replace('#block-commerce-cart-cart .view-commerce-cart-block', $cart);
  $commands[] = ajax_command_replace('#block-commerce-cart-cart .cart-empty-block', $cart);
  return array('#type' => 'ajax', '#commands' => $commands);
}


Disabling reply link for comments not working I would like to disable reply to comment for anonymous user.

I saw on sereval topics that you have to unset

  $variables['content']['links']['comment']['#links']['comment-reply']

So I ended up adding a preprocess to the .theme file (bartik.theme since I'm using Bartik. Btw I'm using Drupal 8.5.3)

function bartik_preprocess_comment(&$variables) {
  if (\Drupal::currentUser()->isAnonymous()) {
    unset($variables['content']['links']['comment']['#links']['comment-reply']);
  }
}

Despite that preprocess, I still have the reply link when I'm anonymous. Does anyone has an idea about what's going on ?

You can use hook_comment_links_alter() rather than THEME_preprocess_comment() .Where as hook_comment_links_alter() will render all the comments links before build:

function YOURMODULE_comment_links_alter(array &$links, Drupal\comment\CommentInterface $entity, array &$context) {
  if (\Drupal::currentUser()->isAnonymous()) {
    unset($links['comment']['#links']['comment-reply']);
  }
}


How to create a Views user page? I'd like to create a users page (author page) where Articles by that user will be displayed.
For example mysite/users/John needs to return teasers of articles that wrote the Author John.

I don't know how to make this when I have names in the URL. I can make the list of recent articles of a user only on paths like mysite/users/1.

This is how my configuration in Views looks like:

In Content: Author uid I have selected Provide default value --> User ID from URL. From that it only looks for ID and can't recognize a name in the URL (i'm using pathauto).

In your contextual filter settings select "provide default value" -> "user id from url" and it will work.


Solution to migrate a field collection My requirement is to migrate  content nodes in xml format to drupal 7 content type fields.The xml contains a node which has to be field collection in drupal.I know how to migrate field which are enity references and term references.But i am new to field collection migration.I am using drupal migrate contrib module for migration.
The field collection node in my xml file.

<myphotos_grid grid="true"><![CDATA[<rows>
  <row rowID="1">
    <rowAttribute>
      <theName>photo-name</theName>
      <value>photname1</value>
    </rowAttribute>
    <rowAttribute>
      <theName>photo-credit</theName>
      <value>my credit</value>
    </rowAttribute>
    <rowAttribute>
      <theName>photo</theName>
      <value>
      <attachment id="1009343343"/>
      </value>
    </rowAttribute>
  </row>
  <row rowID="2">
    <rowAttribute>
      <theName>photo-name</theName>
      <value/>
    </rowAttribute>
    <rowAttribute>
      <theName>photo-credit</theName>
      <value/>
    </rowAttribute>
    <rowAttribute>
      <theName>photo</theName>
      <value>
      <attachment id="4432434344"/>
      </value>
    </rowAttribute>
  </row>
</rows>]]></myphotos_grid>

I am writing a base class for my content types migration by extending XMLMigration class and it defines the migration source files and destination.Also i am writing corresponding classes for each content type which defines the field mapping by extending base class.

Above xml grid node in xml which has to be migrated to to field collection in my content type X in drupal 7 site.

My queries

Whether i need to write a seperate class for field collection extending my custom content type X migration class or adding the field mappings for field collection in the custom content type X migration class?
Whcih is the best standard to migrate field collection in drupal?

I am new to this field collection migration,please help,Also very sorry for my english.

I think you're on the right track. If I'm understanding your question, you won't need to add an extra class.  Instead, you'll want to use your existing Migration class's complete() method, which is called after the node has been created.  Within complete(), you can then use entity_create to create your field collection and entity_metadata_wrapper around your newly migrated node to set a reference to your field collection entity.

In psuedocode,

public function complete($entity, stdClass $row) {
  fc_entity = entity_create(...)
  $ewrapper = entity_metadata_wrapper('node', $entity);
  $ewrapper->fc_ref_field->set( $fc_entity->nid );
  $ewrapper->save();
}

Or something thereabouts. When in doubt, "whatever works" is the correct standard for migration code. Hope that helps get you started!


Can we use double quotes for strings inside t()? Is it correct what said in the comment #7 for Usernames allow @ symbol?

  t() value should write in single quotes not in double quotes.

A string is a string... PhP allows strings to be defined four ways, but the two that apply here are 'xxx' and "xxx"... both are valid strings that will be passed to the t() function.  The function cannot determine how the string variable was created, it only gets the content between the delimiters.  So you can use either one.

That said, some people like the convention of using single quotes for straight constant strings since '$foo' = $foo... while "$foo" = value of $foo.  AFAIK, Drupal coding standards do not specify what can be used for a string.

Adendum:  Note that the string being passed to the t() function should be a static string in order to be translatable.  E.g. if you use "$foo", this would be impossible to translate.  That's what the placeholders are for.


Create duplicate registration form with extra fields I have a site built using Drupal 7. The site has a registration form now. There is a new requirement to add a couple of new fields in the registration form and put it in a new page.

http://example.com/register is the existing registration form and user submitting this form will be registered. http://example.com/newpage is a new page with some content and registration form with two extra fields. When users submit this page, a new user account will be created along with saving the new fields to the user profile.

How can I implement this?

Use the LoginToboggan module

  The LoginToboggan module offers several modifications of the Drupal login system in an external module by offering the following features and usability improvements:

Allow users to login using either their username OR their e-mail
address.
Allow users to login immediately.
Provide a login form on Access Denied pages for non-logged-in
(anonymous) users.
The module provides two login block options: One uses JavaScript to
display the form within the block immediately upon clicking "log
in". The other brings the user to a separate page, but returns the
user to their original page upon login.
Customize the registration form with two e-mail fields to ensure
accuracy.
Optionally redirect the user to a specific page when using the
'immediate login' feature.
Optionally redirect the user to a specific page upon validation of
their e-mail address.
Optionally display a user message indicating a successful login.
Optionally combine both the login and registration form on one page.
Optionally have unvalidated users purged from the system at a
 pre-defined interval (please read the CAVEATS section of
 INSTALL.txt for important information on configuring this
 feature!).
Integrates with Rules module to do various tasks when a user
 validates via email validation process (see
 http://drupal.org/node/880904 for an example)

Demo is here http://doaproject.org/user/register


Create a list field linking to PDFs I'm relatively new to Drupal 7 and I'm a little lost on this one.

I have an "event" Content Type that contains a list field type that displays about five "location" options. Here they are, in key|label form:

Main Entrance|Main Entrance

School Entrance|School Entrance

Park Entrance|Park Entrance

Staff Entrance|Staff Entrance

What I'd like to do is directly link each label to a PDF file containing a map of the entrance location; e.g., Staff Entrance|Staff Entrance.

When I try to customize the field settings, Drupal tells me that the following tags are allowed in labels:   <big>
 <q>      <tt>

 . But in spite of my efforts to add tags to labels, Drupal changes them to HTML entities and ignores them; e.g., &lt;Staff Entrance&gt;. This is the case for all HTML tags.

Is there a reason HTML is not rendering in my labels?

Thanks!

My guess is that a label can't be an anchor (because of XSS).
You may want to use theme_preprocess_field or theme_preprocess_node to wrap the label with an anchor.


Add class to column in a table I have a table in a form such as the 'user_admin_account' form. In one of the TD's I want to add a class, how do I do this the most convenient way?

This is what I currently have, it doesn't seem to work

$row = array(
  'title' => array(
    'data' => array(
      '#title' => $name . ' ' . $surname,
      '#attributes' => array(
        'class' => array(
          'myClass',
        ),
      ),
    ),
  ),
  'date' => date('Y-m-d', $account->created),
  'name' => $name . ' ' . $surname,
);

The variables for theme_table() are structured differently to a standard render array, so you need to format your array slightly differently:

$row = array(
  'title' => array(
    'data' => $name . ' ' . $surname,
    'class' => array('myClass')
  ),
  'date' => date('Y-m-d', $account->created),
  'name' => $name . ' ' . $surname,
);

The above produces:

      1970-01-01

The first and last column are only empty as my test environment doesn't have the same variables defined as in your code.


Populate dropdown with data from database in Drupal7 using jQuery Error is seen when i made a drop down list to populate data from Database.
Database : dtable
File in the template of hook_theme named : myModueForm_theme.tpl.php
<?php
$sel = "<select  name=\"select1\" id=\"select1\">
        <option value=\"\">Select...</option>
        <option value=\"data1\">data1</option>
        <option value=\"data2\">data2</option>
        <option value=\"data3\">data3</option>
        <option value=\"data4\">data4</option>
    </select>";
echo "$sel";

?>
Script :
jQuery("#select1").change( function(){
if( jQuery(this).val() == "data1" ) {
jQuery.ajax({
    type: "POST",
    url: "<?php echo $base_url;?>?q=search/data1",
    error: function(returnval) {
        alert("Failure");
    },
    success: function (returnval) {
        alert(returnval);
        alert("Sucess");
    }
})
}
});

The Module file which handles the database connection named: myModule.module
$items['search/data1'] = array()
'title' => 'Add data', //page title
'description' => 'form',
'page callback' => 'search_data1',
'page arguments' => array('access content'),
'access callback' => TRUE

);
// In the search_data function
function search_data1(){

$options="<select  name=\"select2\" id=\"select2\">";
$result = db_select('dtable', 'c')
    ->fields('c')
    ->execute()
    ->fetchAll();
foreach ($result as $record) {
$name = ($record->dt1);
    $options.="<option value=\"$name\">".$name."</option>";
    //alert(node);

}
$options.= "</SELECT>";
return $options;

}
What I want is

please tell me where is the error & how to solve

I want to return the page back to the theme PHP page with the query result, but when I display back the return value from the module file, I get the whole HTML.
Please help & treat me as a beginner.Thanks in advance...

By default, hook_menu's delivery callback is set to drupal_deliver_html_page(), therefore it delivers content wrapped in a page template. You will need to modify the delivery callback.

To output page content in ajax

function MYMODULE_menu() {
  $items['search/data1'] = array()
  'title' => 'Add data', //page title
  'description' => 'form',
  'page callback' => 'search_data1',
  'page arguments' => array('access content'),
  'delivery callback' => 'MYMODULE_ajax_deliver',
  'access callback' => TRUE
}

function MYMODULE_ajax_deliver() {
  if ($page_callback_result) echo drupal_json_output($page_callback_result);
}

To output naked page content

function MYMODULE_menu() {
  $items['search/data1'] = array()
  'title' => 'Add data', //page title
  'description' => 'form',
  'page callback' => 'search_data1',
  'page arguments' => array('access content'),
  'delivery callback' => 'MYMODULE_custom_deliver',
  'access callback' => TRUE
}

function MYMODULE_custom_deliver($page_callback_result) {
  if ($page_callback_result) echo $page_callback_result;
}

To learn more about a custom delivery callback function, see my other answer.


Is there way to create regions for view modes programmatically? So I have programmatically created a view mode and I need to theme it. The view mode will be rendered via views modules for different content types and The structure requires that I separate fields into to separate regions. A image region and content region. The different content types will be able to choose the fields they want for each region. So event may use featured image, while news article can use hero image field.

I really don't wan't to use display suite if there is some programmatic way of doing this.

You should be able to theme the fields behaving like a css-grid-system, maybe provided by your theme. Name view field templates like this:

views-view-field--foobar--page--field_name.tpl.php

And

Make sure they have the correct order in the view.
Empty fields wont be displayed.

If they have different names for the different content types, just include all field-names in your selectors ..

Maybe also have a look in the docs, and views have name suggestions under Advanced -> Theme: Click on Information


Should drush configuration export automatically update core.extension.yml? The Drupal 8 documentation seems to be lacking in regards to the core.extension.yml file, so I'm a little confused on the right way of updating it.

Should drush be populating it on config export, or are you supposed to manually update it?
Do I need to move it from core to my config/sync folder, or leave it in core?

My file's contents are this, even though I have a handful of modules enabled on the site and have exported my config numerous times:

module: {}
theme: {}
profile: ''

On the site I am exporting from (site a) I am using composer to download modules and drush en to enable them, then drush cex to export the configuration to my sync folder. When I copy the sync folder contents over site b and import via drush cim I run into errors that the modules are not installed / enabled. Manually enabling each module then re-importing was successful.

Both sites are 8.3.7.

I think that the problem comes from where you have the config files, to be sure that they are really in the config/sync folder go to check if you have this following line in the settings.php file:

$config_directories = array(CONFIG_SYNC_DIRECTORY => 'config/sync');

Keep in mind that this line will have the location of the site configuration files.

Each time you use the drush cex or drush cex sync command the core.extension.yml file will be updated (if needed) with the actual modules (and others) configuration.


How to create an end date field in a hook_form_alter I've succeeded creating a simple date_popup field with the following code :

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

Now, is there any way to directly create the "End date" field without having to create a second field declaration ? Is there any bundled widget I can use ? I've seen something about date_combo but I'm not sure to understand it well.

Thanks for help !

there is no way to do it with the standard field widgets, you have to craft your own, the examples module may help you


Table 'main_semaphore' doesn't exist I have imported an outdated production Drupal 6.9 site to my development machine. Then, I upgraded all modules to 6.24. After a while, I imported the database of the production site (to have new nodes). The site appears to work properly on the front end. But now it does not update neither form drush, nor by calling update.php from browser. At drush I get:

    An error occurred at function : drush_pm_post_pm_update            [error]
    WD php: Table 'mysitedb.semaphore' doesn't exist              [error]
    query: DELETE FROM main_semaphore WHERE value =
    '31092233150575fa189b4d9.09364052' in /path/to/mysite/includes/lock.inc
    on line 224.

On Google Chrome, I get just a "Server error" page.

Update: I created semaphore table using this answer but it did not resolve the problem.

From main_ one would think you have a prefix set up on your production site or the development site and perhaps not or werent at the time of upgrade. It's quite confusing what you see, but one thing for sure: compare prefix settings and check MySQL for SHOW TABLES LIKE '%semaphore%' and go from there.


Try to add in different views to a single page, keep getting "Error" message? I have a panel where I'm pulling in 7 different views pages in different regions, and when I try and save it, I keep getting the same message-- "The website encountered an unexpected error. Please try again later."

So, I went to the specifics of the error and this is what it says:

PDOException: SQLSTATE[22001]: String data, right truncated: 1406 Data too long for column 'panel' at row 1: INSERT INTO {panels_pane} (did, panel, type, subtype, shown, access, configuration, cache, style, css, extras, position, locks, uuid) VALUES (:db_insert_placeholder_0, :db_insert_placeholder_1, :db_insert_placeholder_2, :db_insert_placeholder_3, :db_insert_placeholder_4, :db_insert_placeholder_5, :db_insert_placeholder_6, :db_insert_placeholder_7, :db_insert_placeholder_8, :db_insert_placeholder_9, :db_insert_placeholder_10, :db_insert_placeholder_11, :db_insert_placeholder_12, :db_insert_placeholder_13); Array ( [:db_insert_placeholder_0] => 41 [:db_insert_placeholder_1] => block_layout_row_2_col_2_row_1_region_1_ [:db_insert_placeholder_2] => views [:db_insert_placeholder_3] => review_entries [:db_insert_placeholder_4] => 1 [:db_insert_placeholder_5] => a:0:{} [:db_insert_placeholder_6] => a:15:{s:23:"override_pager_settings";i:1;s:9:"use_pager";i:0;s:14:"nodes_per_page";s:1:"5";s:8:"pager_id";s:1:"0";s:6:"offset";s:1:"0";s:9:"more_link";i:1;s:10:"feed_icons";i:0;s:10:"panel_args";i:0;s:12:"link_to_view";i:1;s:4:"args";s:0:"";s:3:"url";s:0:"";s:7:"display";s:7:"block_6";s:14:"override_title";i:0;s:19:"override_title_text";s:0:"";s:22:"override_title_heading";s:2:"h2";} [:db_insert_placeholder_7] => a:0:{} [:db_insert_placeholder_8] => a:1:{s:8:"settings";N;} [:db_insert_placeholder_9] => a:0:{} [:db_insert_placeholder_10] => a:0:{} [:db_insert_placeholder_11] => 0 [:db_insert_placeholder_12] => a:0:{} [:db_insert_placeholder_13] => cc38c8a0-a223-4b16-91ca-7426f802c8f8 ) in drupal_write_record() (line 7308 of /srv/bindings/2ed870ecae69481598cc782d3c4e9589/code/includes/common.inc).

Does anyone have any idea how to fix this?? Thanks!

As the error says the data for some columns is too long. I had the same problem in some where else, so I simply opened the phpmyadmin, found the column and change it's type to something else with more capacity. In my case the type was blob and I changed it to the long blob and it worked.

Try this and I guess it will work


Run drush cron for a single module Is it possible to run drush cron over a single module, something similar to "drush cron my_module"?

You can do

drush php-eval 'my_module_cron();'

and it should run.


Why is the token in my custom module not replaced? I want to use the token [user:name] in my module. This module contains a sample  ControllerBase class

In my class I test this:

class Page_test_Controller extends ControllerBase {

    /**
     * {@inheritdoc}
     */
    public function token() {
        $build = array(
            '#type' => 'markup',
            '#markup' => t('[user:name] hello'),
        );
        return $build;
    }

}

When I load my page the token isn't replaced as shown here:

What am I missing or doing wrong?

Translatable strings don't use tokens, but placeholders, see for example https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Component%21Render%21FormattableMarkup.php/function/FormattableMarkup%3A%3AplaceholderFormat/8 for some documentation, or https://www.drupal.org/node/322729 (more 7.x, but conceptually still mostly OK).

Tokens are when you have user configurable text like the user register/confirmation mails. It doesn't make sense to have token in a text that is hardcoded since tokens are only useful if that text can be customized by the user. For documentation on how to use the token API, see https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Utility%21Token.php/class/Token/8


Print comment form inside node's page instead of a link to comment page How can I print comment form inside node's page instead of a link to comment page (Drupal 6) ?

You can set that under "Comment settings" on the edit page of your content type.


Using Rules to create an Entity Reference if two fields in different entities match? I'm attempting to use a "registration code" entered during a user's registration to create an entity reference to a node with a corresponding code.

Any help is greatly appreciated.

Specific use case:

"Professor" (users) have "Classes" (nodes) that contain a text-field with a unique 5-digit code (created with Computed Field).

"Students" have a "Registration Code" field on their registration & user profile page (aka a text field on the user entity) for manually entering a 5-digit code that should "assign" them to a "Class" that has the same registration code.

I'm not a programmer, but this might make more sense:

if [Student user's 5-digit registration code] = ["Class" node's 5-digit registration code] then an entity reference is created between [student user] and ["class" node]

I'd like the rule to trigger when a user updates the registration code field.

Essentially, I'm attempting to avoid displaying Entity Reference's autocomplete widget to users.

I don't think I would start with Rules, especially from a performance standpoint. I would first try something like this:

in the Student content type, create an Entity Reference field for the reference, making sure it has a default value, say 0 for ease of access later
Using Field Permissions, hide that field to everyone but admin

  The Field Permissions module allows site administrators to set
  field-level permissions to edit, view and create fields on any entity.

create a custom module
using hook_node_validate(), check the list of Classes for the existence of the correct code
using hook_node_presave(), update the hidden reference field once it is validated

Now you have something that allows the Student to enter a value, have it validated, and then copy that value into a proper reference field for later use

EDIT

I was curious if I was correct in my initial answer, so I figured it out to check, and it worked - for this example:

Create a content type Class, using the title field as the Class Code
Create a content type Student
Add field to Student content type: field_student_class_code, entity reference to Class content type
use Field Permissions to hide field_student_class_code to everyone but Admin
Add field to Student content type: field_student_visible_class_code, text field
Create a new module called custom_node_reference, and include this code:

function custom_node_reference_node_validate($node, $form, &$form_state)
{
  if($node->type == 'student')
  {
    $lang = $form['field_student_visible_class_code']['#language'];
    $class_value = check_plain($form['field_student_visible_class_code'][$lang][0]['value']['#value']);

    $result = db_select('node', 'table_alias')
        ->condition('type', 'class', '=')
        ->condition('title', $class_value, '=')
        ->fields('table_alias')
        ->execute();

    if($result->rowCount() <= 0)
    {
      form_set_error('field_student_visible_class_code', 'That class code does not exist, please re-enter a valid class code');
    }
  }
}

function custom_node_reference_node_presave($node)
{
  if($node->type == 'student')
  {
    $lang = $node->language;

    // get entity_id for current class code
    $val = db_select('node', 'n')
      ->fields('n', array('nid'))
      ->condition('type', 'class', '=')
      ->condition('title', $node->field_student_visible_class_code[$lang][0]['value'], '=')
      ->execute()
      ->fetchField();

      $node->field_student_class_code[$lang][0]['target_id'] = $val;
    }
  }

If you change the machine names of the fields, you will need to adjust the code to suit


Auto fill content field with random values I have field_x with values "A" or "B".

They must be assigned randomly by the system between A or B at every node added ( must not be changed on "node edit" by the node author).
The total numbers of nodes will be "30" and the assignment must be symmetrical ( after all 30 nodes will be added: 15 nodes must have "A" value and 15 nodes "B" value)

I've tried an solution with RULES but I didn't find an random function to use. Anyone has an better solution ? Thank you!

More rational explanation of the problem:

Insurance company "X" has 5 workers who upload client files (nodes), every worker must upload 30 files per month to the system. Every file has an field named "file_inspector" that has the name of the inspector who will check the insurance problem from that respective file. The field "file_inspector" can have "inspector1" or "inspector2" values that will not be completed by the worker but will be assigned by Drupal randomly based on the fact that at the end of the month total number of nodes will be 30 for every worker and "inspector1" and "inspector2" must be assigned equally 15 / 15.
The assignment must happen in real time (when the node is added) not at the end of the month. (Hope this makes more sense now)

This should be done in a custom module by creating a custom field type

Good starting points would be either one of serial or unique_field modules and changing the logic of how the number is generated to match the logic described in your post


HTML showing as text i am using below code to show content in admincontroller of my module but $filelink is show as text instead of html

i tried to show href link in $filelink but it renders and text content like below:

Resume

but i want it as

Resume

  function content() {
    $url = Url::fromRoute('bd_career_add');
    //$add_link = ;
    $add_link = '
' . \Drupal::l(t('New Submission'), $url) . '
';

    $text = array(
      '#type' => 'markup',
      '#markup' => $add_link,
    );

    // Table header.
    $header = array(
      'id' => t('Id'),
      'name' => t('Name'),
      'number' => t('Number'),
      'email' => t('Email'),
      'email' => t('Resume'),
      'operations' => t('Delete'),
    );
    $rows = array();
    foreach (BdCareerStorage::getAll() as $id => $content) {
      // Row with attributes on the row and some of its cells.
      $editUrl = Url::fromRoute('bd_career_edit', array('id' => $id));
      $deleteUrl = Url::fromRoute('bd_career_delete', array('id' => $id));

    $file = \Drupal\file\Entity\File::load($content->resumefid);
    $filelink ="getFileUri())."' target='_blank'>Resume";

      $rows[] = array(
        'data' => array(
          \Drupal::l($id, $editUrl),
          $content->name.' '.$content->lname,$content->number,$filelink,
          \Drupal::l('Delete', $deleteUrl)
        ),
      );
    }
    $table = array(
      '#type' => 'table',
      '#header' => $header,
      '#rows' => $rows,
      '#attributes' => array(
        'id' => 'bd-career-table',
      ),
    );
    //return $add_link . ($table);
    return array(
      $text,
      $table,
    );
  }

solved it using below code:

$file = \Drupal\file\Entity\File::load($content->resumefid);
$filelink = file_create_url($file->getFileUri());

$url = Url::fromUri($filelink);
$external_link = \Drupal::l(t('Download Resume'), $url);

  $rows[] = array(
    'data' => array(
      \Drupal::l($id, $editUrl),
      $content->name.' '.$content->lname,$content->number,$external_link,
      \Drupal::l('Delete', $deleteUrl)
    ),


How can I remove content from the front page? Made page--front.tpl.php. Created the view for content-type: news for example. Then put the view block in a block region. View block - only display news type limit at 1 or 2.

But when viewing the front page, all content types' content shows up on the front page along with the view block. I checked that it was managed by Display Suite but it shouldn't show show all contents on front page.

Why does this happen?

Update

Uncheck "promoted to front page" checkbox on all entries and it worked.

Other question:

"No front page content has been created yet.
Add new content"

How can I remove this text above on front page? I am using blocks most of the time, so text shouldn't be there.

It sounds like you have your content type to "Publish to front page".  Edit your content and un-check "Promote to front page":


When to use a module vs. writing own code? At the risk of asking a "too open ended question" I'm giving it a try:

I'm running into more and more situations where I have to decide to either use a module that does a lot more than what I need or just writing my own code or template mod.

For example, the password policy has features that I need, but also has a lot that I don't. The 47kb zip file size tells me that it's a lot of code for my small problem. I implemented my own password policy with less than 20 lines of code in a hook.

I'm trying to limit the total amount of modules installed to a max of around 100. However, since signups don't happen that frequently this module probably won't affect the overall site performance.

Does anyone have specific recommendations on when to use a module vs. writing own code? Especially when better runtime performance and reduced overall complexity are the main goals.

The way I go about deciding whether to use a module or write my own code is roughly the following:

If the functionality I need can be written with a couple of lines of code I don't even start looking for a module to do it. Using a module for every little thing often gets you a good portion of extra code and other data that you don't need. All the unnecessary extras could:

negatively affect performance
make the site more complex and harder to maintain
result in more bugs

If there would be a considerable amount of code to write I'll look for possibly existing modules to make the task easier. Good reasons to use a existing module in my book:

it fits the requirements fairly well: using the module (and altering it with hooks, adding extra functionality via a custom module where needed) to get exactly what's needed is easier/faster than writing everything from scratch.
the site administrator needs to be able to change specific settings via the GUI and the module already offers that.


Commerce - Hide Add-to-Cart form from Anonymous users I am constructing a site that will serve mainly agents (authenticated users), but should still show all of the products (without prices) for anonymous users. When logged in, only agents should see the Add-to-Cart form on the product display page, and anonymous users should instead see a link to an "Ask a Question" page.

Is this possible? I looked through the permissions table and could not find a way to prevent access to the cart form by anonymous users.

The only thing I can think of doing is customizing my node--product-display.tpl.php file:

<?php
    if ($logged_in) {
      print render($page['content']);
  } else {
      // something else
  }
?>

I'll have to print the rest of my fields out manually, but as far as I know, this is the only way to print the Add to Cart form. I'm a bit uneasy about this, so I'm humbly looking here for another solution.  thanks

From the link : http://www.drupalcommerce.org/node/2528 with an condition for anonymous user added.

  It's taken me a while but I've finally cracked it! I've used
  hook_form_FORM_ID_alter() (that took me some learning and meant I had
  to create my own, admittedly trivial, module!). So in my module I've
  got the following which sets #access for the submit form to false
  which stops it being rendered (see
  http://api.drupal.org/api/drupal/developer%21topics%21forms_api_referenc...).

  In the future, I'll be able to extend this to disable the button on
  certain conditions (say when there's no stock but I want to show what
  combinations are possible). It would also presumably be an easy way of
  changing, say, the text for the button, such as "Buy" instead of "Add
  to cart".

  function mymodule_form_commerce_cart_add_to_cart_form_alter (&$form, &$form_state, $form_id) {
global $user;
    if ($user->uid == 0) {
    // Disable the Add to Cart submit button

  $form['submit'] = array('#access' => FALSE);
        }
    }


Exposing webform submissions for Views, but not giving anonymous users permission to view all submissions I have a webform set up in Drupal 8 and am trying to create a View that displays certain fields from form submissions. The webform and the view seem to be set up fine and are working.

The problem comes in when I want the view to be visible for anonymous users. I seem to be stuck with two options, neither of which are ideal:

Option 1: Anonymous users can see the page created in Views, but there are no fields on it.
Option 2: Anonymous users can see the page with the fields, but I have to grant the "View any webform submissions" permission, which then gives them access to view (and download) on the webform page itself.

Can anyone help me with an option 3, where the fields are visible in this View, but without granting the "View any webform submissions" permission to anonymous users?

You will have to give following permissions to anonymous users from permissions page. admin/people/permissions

View any webform submissions

Allows viewing all webforms and submissions.


Major module update with Composer I have some modules in 8.8.5 that need an major update.
What is the best practice without loosing data or settings?

For example:
drupal/admin_toolbar          1.27.0          2.2.0

Do I need to uninstall the module in de admin backoffice Drupal?
If so, I first need to uninstall both modules: Required by: admin_toolbar_tools, adminimal_admin_toolbar
Finally uninstall admin_toolbar
Composer remove drupal/admin_toolbar
Composer require drupal/admin_toobar
Drush updatedb
Drush cr

Is that the correct way?
Or can I simply remove the old version with composer and require the new one?

No you don't uninstall the module first. You want to have the module enabled when updating to let possible database updates kick in. Which may be performed to update existing data/entities. If you already have the latest 1.x version installed you could simply do

$ composer require drupal/admin_toolbar to upgrade the module.
$ drush cr && drush -y updb to perform database updates.
And finally $ drush -y cex to export any eventually updated config.

If you don't have the latest 1.x version installed yet, it's better to upgrade incrementally. And to play really safe to also do two consecutive releases for that.

$ composer update drupal/admin_toolbar --with-dependencies && drush cr && drush -y updb && drush -y cex to first update to the latest 1.x version, followed by a release.
And then $ composer require drupal/admin_toolbar && drush cr && drush -y updb && drush -y cex to get the latest major upgrade, followed by another release.


Panels problem with changing the width of columns or regions Some times when I try to change the width of columns or regions with Fluid Width the panels displays the NAN% and it doesn't change the width

Using Firebug I got the following error

What should I do?

UPDATE

It only displays this javascript error in console in flexible-admin.js file

splitter.parent.css('padding-right', (splitter.right_padding + moved) + 'px');

I found it. when the current language of the site is rtl such error reported. it must be ltr


Book page appears in one language (of four) only I run a Drupal 7 site with 4 languages installed: English (for me as admin) and 3 balkan languages (I don't speak them actually): Serbian, Croatian, Slovenian.

I have added a book there (url shortcut should be: help) and have added 3 book pages: Imprint (in German, url shortcut imprint), Privacy and Terms of Services (both pages have English content and url shortcuts privacy and tos).

All 3 book pages should be visible in all languages - i.e. in English, Serbian, Croatian, Slovenian.

However for some reason they are only visible in the Croatian view of my web site and also only /hr/shortcuts work.

And when I look at http://balkan-preferans.de/en/node/1#overlay=en/admin/content they have Croatian as language:

Can I somehow change the language to be All?

Ok, found that setting under

Home » Administration » Configuration » Search and metadata » URL aliases

Or go to Modules and configure Path module settings

Setting the language to All languages has solved my problem


How to remove submitted & author information on Entityform submission view? I'm trying to remove the author/submitted information from an entityform submission view and I don't seem to find the right way to do so.

I'm using Display Suite to manage the view of the email that is being sent to the user with the values of the submission, also in the regular view submission page. The submission is for anonymous users, so it's useless to add the following prepended information:

  Submitted by Anonymous on thu, 06/12/2014 - 14:18

Which obviously doesn't make any sense in the way my form is working.

Does anyone knows how to achieve the removal of this information?

Thanks!

That value is a t() function call here http://cgit.drupalcode.org/entityform/tree/entityform.module#n1092

This is used by the custom EntityClass provided by the EntityForms module in the buildContent function:
http://cgit.drupalcode.org/entityform/tree/entityform.module#n1226

This is PHP class. You have many options:

See if there is a TPL file defined for this submission and alter the default output with your own.
Try to use String Overrides to and set the t() string to "" in the Admin interface for String Overrides. The string you'd look to replace is "Submitted by !name on !date". This may have un-desired affects for other content types and non-Anonymous users ...
Your other option is to replace the custom EntityForms class with 1 of your own using a database query to change the system table's entry for the EntityForms class to 1 you copy-paste of the same name and change the 1 line of code in it :/ (I don't really recommend this.
Lastly you can use hook_page_alter to scan for the string in the content array of the Node on the page and remove the text out.
Or really lastly, you can hide the text using CSS rules.


Why is the page content always rendered after blocks displayed on the same page? I have a Static Page node at, say, /my-page. It has a title and body. I have also placed a block (pointing to a View) in the "Main content" region, at the very bottom of the list.

However, when viewing /my-page, the block is displayed above the <article> element that contains the page content. An example can be seen below.

Why is this the case? What can I do to always show the page content above everything else that is placed in the same region?

You need to adjust the display order of the blocks through configuration. Navigate to Manage >> Structure >> Block layout (relative path: /admin/structure/block), click the handle icon next to the "Main page content" block and use it to drag the block to the top of the "Content" region.


Get enabled content types machine name I'm trying to get the enabled content type machine names for a given group.

I wrote the following code, but to get the machine name I should cut the strings to group_node:.

    /** @var \Drupal\group\Entity\GroupType $group */
    $group = GroupType::load($groupKey);
    $plugins = $group->getInstalledContentPlugins();
    foreach ($plugins->getConfiguration() as $key => $plugin) {
      // Cut key here.
    }

Okay, I don't know how I missed this.

/** @var \Drupal\group\Entity\GroupType $group */
$group = GroupType::load($groupKey);
$plugins = $group->getInstalledContentPlugins();
foreach ($plugins as $key => $plugin) {
  $bundle = $plugin->getEntityBundle();
}


drupal not detecting function in custom module's inc file I have a custom module, in my module call commerce_discount_add_line_item() function, it exists in commerce_discount.rules.inc,
this modules is installed correctly and status is enabled but when I call it returns:

  ( ! ) Fatal error: Call to undefined function
  commerce_discount_add_line_item().

It is strange, why has this happened?

By default inc files are not included(only module files are included). They should be called explicitly like below before making a call to a function in that file.

module_load_include('inc', 'commerce_discount', 'commerce_discount.rules');

Further Reading on inc files and how they differ from .module files : https://drupal.stackexchange.com/a/54069/4876


How do I update customers cart prices and add discount and then let them checkout? I'm using Drupal 7 Commerce and Commerce discount, amongst many others.

So the use case is this. We often get enquiries for bulk orders containing many products. We want our customer to go to the website and add what they want into their cart. As admin I want to open that unpaid cart, edit product prices and apply a Fixed Price Discount. Then when the customer refreshes their cart they will see our amendments and continue with payment. Is this possible? Am I missing something obvious?

At present I can edit a order that is in the cart but when the customer refreshes their cart the order is reverted back to prior my changes. I can't edit product prices at all whilst the order isn't completed. Once in Completed status, I can tweak product prices and add the discount.

To get the Fixed price discount feature to work I had to switch from the Line Item Manager widget over to Multiple Inline Entity References. For the line items field on orders that is. Before that I couldn't use the Fixed price discount feature at all.

Any help would be greatly appreciated. I must be performing the wrong searches or something.

There aren't many good solutions here, because you're hitting up against the limitations of the pricing system. You have two basic options: custom line item fields that contain special pricing paired with a pricing rule that overrides the default product price or some combination of discounts that adjust product prices solely for that user. The former may be a challenge, because I can't remember if we ever fully got Inline Entity Form to manage line items, and the latter would be a pain for orders with a lot of different products.

The Commerce Price List module was ultimately developed to handle situations like this, where price lists can be assigned on a per user / quantity basis. It appears the same feature set works in D7 as in D8, but it would give the customer access to that pricing on any order while the price list was active, not just a single one. If that's no problem, then that's probably your solution.


My hosting provider ask me to use xCache instead of the built in Drupal cache system Just that I have a problem with a website (Drupal 7), the server falls down every night.
My hosting provider ask me use xCache instead of built in Drupal cache system.
Does it make any sense?

It makes perfect sense to use PHP opcode cache, you should be using one if not already using. I'd recommend APC for PHP version 5.4 and less.

xCache is somewhat similar in the way it handles caching like APC, but the mechanism is different. You have to do quick research which one suits your needs and hosting compatibility.

If you are using PHP 5.5+ then it comes with in-house OPcache. Personally I haven't tested but when the package is bundled with software core it certainly grabs attention. You should check the use case for you.

eAccelerator is also nice one, I used to use it few years ago, but, when I got to play with more RAM, APC is beast.

The later part of your question says about

  use xCache instead of built in Drupal cache system

which is completely false, xCache or any other opcode cache is not replacement of Drupal Cache, it should be used together. Opcode cache is for PHP, it doesn't have anything to do with Drupal.

As for the part of replacement concerns, you can use Memcached instead of Drupal cache that is stored in database.


Show related nodes of category selected in current node (using static select list) I created a content type containing a select list field (ie Fruit, Food, Jewelery etc).

I am not using any node reference nor any taxonomy vocabulary.

I have added a static select list. I want to show related nodes under the current node. I.e if I visit a node containing the fruit category, then all the other nodes containing fruit category should be shown below the current node.

I recommend converting your select list field to Taxonomy and use a module like Similar By Terms.

  This Drupal module attempts to provide context for content items by
  displaying a block with links to other similar content. Similarity is
  based on the taxonomy terms assigned to content. Blocks are available
  based on similarity within each of the defined vocabularies for a site
  as well as a block for similarity within all vocabularies.


Using Pathauto URL alias in link fields In a view, I have several fields that I would like to link to the original content. The title field's default behaviour is like this, but I want to have the trimmed body and the image fields to behave the same way too.

For this, using the content:path field and then rewriting the other fields using this one as a token has been recommended here. But this gives me the Drupal path, not the URL alias.

Another idea is to use Global Redirect module and to set it to always use URL aliases. But this obviously requires to install yet antoher module. I am hoping to manage without it.

The content pages behave according to the URLs so I need to have the aliased ones.

Is there a way to get the URL aliases in views link fields?

(I am using Drupal 7.23, Views 7.x-3.7 and Pathauto 7.x-1.2)

I do not see any problem here. You can do it like this:

Add the view
Add the fields
Add NID, exclude it from display, and move it to top of list
Open the field setting which you want to change, expand the Rewrite results fieldset, and check "Output this field as link"
As link path input, enter node/[nid] (this is the token)


broken handler for custom handlers I'm using Drupal 7 with views 3.

I have defined a custom handler for a field and is working on my development machine. When I revert same view in live environment I am getting issue of broken handler, even the handler class s present.

Thanks in advance for your help.

I have fixed this issue by using hook_views_data_alter(). Earlier the custom handler for the select field was defined in hook_views_data().


Taxonomy field not visible for anonymous users with content create permission When creating a new node, anonymous users can't see taxonomy field but administer can see it.anonymous users have permission to create nodes.

How can I show it to anonymous users?

You just have to give anonymous user the permission of administer taxonomy.


When adding media to content, how can I search for the media by tag or term? In Drupal 8, I created a new Media type "PDF Files." I have imported almost 30,000 of them, each complete with Title (Name), file, and the taxonomy that categorizes them.

On the content type (Let's say the default Article, for example) I've added an entity reference field and the ability to locate a file via the Entity File Browser project (https://www.drupal.org/project/entity_browser).

This is working well enough, but it searched via the Name field only by default.

How can I accomplish the same thing but searching by comma separated tags?

So, each file has a tag structure TAG1, TAG2, TAG3.

In the search field for the file while in the content type, if I type in TAG1, TAG3 then all the files with that combination of tags should come up.

Before I dive into a custom script or extending the entity browser, wanted to make sure this isn't something simple I'm overlooking. (Just now getting into D8 after a long D7 background).

UPDATES:

So as has been suggested in the comments, use a view as a reference. It seems that choosing a view reference requires that the view be an Entity Reference (instead of type Page, Block, etc.) But, it seems that Media doesn't have the ability to search by tag. This Drupal project seems to try to address that - https://www.drupal.org/project/media_taxonomy_filter but no luck.

Also, another hurdle I seem to have hit is that when creating a View of type Media, there is no taxonomy field filter. This seems odd in that Media now can be categorized with taxonomy. Is that right? Like, for the admin media page which is powered by a view, can I not filter that by taxonomy?

As Kevin said, you need to install the Entity browser module

Optional module: I personally also use Entity Browser Enhance(d|r) for a much better usability when selecting media.

Go to /admin/structure/views/add and create a view showing Media items. On the next screen add a display type Entity browser to your view. You must add the special Entity browser bulk select form field to this view. Configure the view with additional fields and filters of your own choice. E.g. if you need taxonomy tags, add an exposed filter for your tags field.

Under Configurarion > Content Authoring > Entity browsers, create a new entity browser for your media. Configure as you need, and in the last step add the previously created view as widget plugin.
(Beyond the selection view you could add multiple widgets here like DropZoneJs for in-place uploading or Inline Entity form for in-place creating of new nodes).

Go to Structure > Content Types, and edit the form display of your node. Change the widget of the media field to Entity browser and select your previously created browser.

There are quite a lot of configuration options on the way, but this is a basic outline to get a media browser like this:
(The search part can contain any/multiple exposed filter like a "normal" view)

I recommend this tutorial for additional information
https://www.electriccitizen.com/blog/media-libraries-drupal-8
(but I personally would not use Inline entity forms for media, better stick with Entity browser for selection and DropZoneJS for in-place uploading)


Load custom form into contents of a specific content type I have created a custom form through Drupal form API. Also i have added various content pages of a Content Type called "Search Pages". Those pages contain only Metadata which they are hidden. What i actually want is to show my custom form into those pages (Search Pages). How can i implement that programmaticaly?

You can output form as block, then output this block in region and set block's visibility options to show only on specific content types:

/**
 * Implements hook_block_info().
 */
function mymodule_block_info() {
  $blocks = array();
  $blocks['my_block'] = array(
    'info' => t('Block with form'),
  );
  return $blocks;
}
/**
 * Implements hook_block_view().
 */
function mymodule_block_view($delta = '') {
  $block = array();
  switch($delta) {
    case 'my_block' :
      $block['content'] = drupal_get_form('mymodule_custom_form');
      break;
  }
  return $block;
}
/**
 * Form example.
 */
function mymodule_custom_form($form, &$form_state) {
  $form = array();
  $form['text'] = array(
    '#type' => 'textfield',
    '#title' => t('Place your form fields here'),
  );
  return $form;
}

Clear cache, go to blocks page (/admin/structure/block), assign your block to region. Go to your block configuration page and define Visibility settings on Content types tab.


How do I allow a free product into a cart, but only if cart net value is above $10? I'm interested in running a promotion ...

I'd like to make a product free if the customer's cart total is $10.

I was able to do that with this module: http://drupal.org/project/uc_discounts_alt

Everything is working great, but I don't want my customer to be able to add the product to their cart unless they are buying $10 worth of regular products.

The products I'm giving away could be placed in another ubercart class, but I can't find a module that will allow me to prevent the node from being sold unless the cart total is $10 or more.

Any ideas or help would be greatly appreciated.

I've already explored the "free" checkout options; I'm really simply looking how to make a product not sellable unless the cart total has a minimum of $10.

Take a look at the Ubercart Restrictions module.

  This module will do its best to prevent the wrong sort of people from
  ordering the wrong sort of goods, or to ship them to the wrong kinds
  of places.

  For example, some products cannot be ordered by minors, or some
  products cannot be shipped to certain states


How do I add onclick Google Analtyics custom event "add to cart" to add to cart button in Drupal Commerce? I want to fire a Google Analytics custom event called "add to cart" when someone adds a product to the cart.

I am using classic Google Analytics, not Universal.

I tried adding this to the commmerce_add_to_cart_confirmation.js:

_gaq.push(['_trackEvent', 'Button', 'Add to Cart']);

Didn't work.

Then I found the module that builds the add to cart form, commmerce_cart.module, and updated it to go from this:

else {
  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Add to cart'),
    '#weight' => 50,
  );

to this:

else {
  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Add to cart'),
    '#onclick' => "_gaq.push(['_trackEvent', 'Button', 'Add to Cart']);"
    '#weight' => 50,
  );

That didn't work either. I would have preferred the former because the confirmation overlay only is presented when the add to cart is successful, whereas the latter would fire the custom event every time the add to cart button is clicked, even if there was an error.

Any help would be appreciated.

Sorry for updating, but you can easily add code before sending form!

It's in sites/all/modules/uc_ajax_cart/js/uc_ajax_cart.js:70

Just put your request after

beforeSubmit : function () {