How are better exposed filters - checkboxes value - assigned

This has nothing to do with Exposed filter settings, it's to do with what information is stored in the Taxonomy term Entity Reference field on your Content Type, and it's the term ID, not the term name.
So when you add the most ready-available Taxonomy Fields/Filters to your Content Views you will get the term ID.
Other Taxonomy term information (term name included) is stored in another database table and you have to add the Relationship for that particular field in order to pull information from that table into Views.
What you want is to add the Relationship for the Field on your content that stores the Taxonomy term reference. You can require the Relationship if you only want to see nodes in results where that field isn't empty.
After you add that Relationship you will get more options under Fields and Filters, one of those options is the Taxonomy term Name. They will use the Relationship by default since they can't be added to the Views without it.
Add the Name Filter to your Views and expose it. Adjust the Vocabulary settings and other options to your particular need.


You can do one of two things: store the incoming data in the session somehow and alter it into the appropriate fields via hook_form_alter() or immediately create the relevant customer profiles for the session and reference them from the cart order you create. Default rules in Drupal Commerce will handle assigning those customer profiles to any user account that gets created during checkout for your anonymous sessions.


Draggable views module doesn't sort content

Only solution that worked for me was the following:

go to your content type/vocabulary
add a weight field (label: weight | machine name: weight | field type: integer
edit your sorting view and add sort criteria for your newly added weight field
edit your draggable views field and change "Handler" from Native to FieldAPI
under Field select your weight field
go to your content view and add the new weight field as you sort criteria

This is the only thing that worked for me. If it doesn't work immediately, just reorder a few items on your draggable view so that the ordering values are reset.

Hope this works for you too.


See drupal_goto() has been removed.

  Drupal 8 (procedural)

use Symfony\Component\HttpFoundation\RedirectResponse;

function my_menu_callback_foo() {
  //....
  return new RedirectResponse(\Drupal::url('user.page'));
}

  Drupal 8 (properly injected)

use Drupal\Core\Controller\ControllerBase;

class MyControllerClass extends ControllerBase {

  public function foo() {
    //...
    return $this->redirect('user.page');
  }
}

  If the route name is not known use RedirectResponse with a URL. When redirecting to an external location, use TrustedRedirectResponse.

use Drupal\Core\Controller\ControllerBase;

class MyControllerClass extends ControllerBase {

  public function foo() {
    //...
    return new TrustedRedirectResponse('https://example.com/some/path'); // for eg. Url::fromUserInput(\Drupal::destination()->get())->setAbsolute()->toString();
  }
}


How to setup gmap maps on nodes (using location fields)

Using OpenLayers instead of Gmap you can set up different maps for different fields. It's more complicated, but with more options.


Added ajax to a Link but its not working

I did it :
The problem was in my callback function :

function custom_ajaxcallback($type = 'ajax') {
  if($type == 'ajax') {
    $output = t('Hello World!');
    $command = array();
    $commands[] = ajax_command_append('#sayinghello', $output);
    $page = array('#type' => 'ajax', '#commands' => $commands); --> In this line
    ajax_deliver($page);
  }
  else{
    return t("Hello world in new page.");
  }
}


Unable to collect end date after field is saved

When I did this, I created a new date field and set it as hidden on the page. I configured it the way I wanted, then duplicated the existing information in the new field, manipulating the database directly. As you will have two date values (..._value and ..._value2) you should begin by setting them the same.

Once you are sure that the correct values are in place, you must then change all your views, rules etc that use the date field to use the new field.

Then set the new field to display and hide the old field. Make sure everything is working before you delete the old field.

There is no short cut that I am aware of. Best to do all this on a copy, with extensive backups. Good luck.


Use media_entity. End of discussion.

People are actively working on getting it into core and once that happened, there is no reason to use file_entity anymore.

We (as in me and @slashrsm/MD Systems) will continue to minimally maintain it, as we have a number of big sites (a distribution actually) that relies on it, but it will most likely never get out of alpha while media_entity is already stable.

We're actively blogging about the status and progress on getting media into core:

http://www.md-systems.ch/en/blog/md-systems/2017/01/09/current-status-of-media-in-drupal-8-core-and-next-steps
http://www.md-systems.ch/en/blog/md-systems/2017/01/30/media-initiative-is-official-and-we-are-one-of-its-leading-parts


How to filter views "node-changed-day is not node-created-day"

I just found a solution myself. There is  available ”Views PHP Filter” module for Drupal6. After installing I added new filter:  ”Node: Node ID PHP handler” for my Views. I left the filter options as default but filled PHP– textarea vith code below, and it worked.

$nodeids = array();

$result = db_query(db_rewrite_sql('SELECT DISTINCT(c.nid) FROM {node} c  WHERE c.status = 1  AND  c.changed >= c.created + 86400  - c.created % 86400  ORDER BY c.changed DESC'));

while ($node = db_fetch_object($result))  {
$nodeids[] = $node->nid;
};

return $nodeids;


To properly add JS or CSS to a form you use the #attached array key. See this similar question answered already here with links to documentation. Then your JS button should work.

https://drupal.stackexchange.com/a/70036/3279


It needs to be done with PHP. If you use the l() function to generate your links, they will automatically get the active class if you are the page to which the link is linked to.
To do this you would need to enable the PHP filter, but this filter is both recommended against, as well as non-existent in Drupal 8, so it would be better to create a block through code and use that instead of enabling the PHP filter.


This is something you would most likely want to adjust using your style.css file and an inspector program (such as DOM Inspector for Firefox) in the browser.

Another way to do it would be to use a grid-based theme like Omega that lets you choose how many columns wide to make zones and regions. Using Omega Tools you can do that directly in the Appearance admin configuration UI.


You can add your code in a JS file say somescript.js and save it in your theme folder. In the theme.info file add the following line

scripts[] = somescript.js

This will add somescript.js to all pages by default. If you want it for a particular page add a conditional check and use drupal_add_js(PATH_TO_JS)
For more info check out Managing JavaScript in Drupal 7


Try adding some instrumentation by replacing the check_plain function with this version:

function check_plain($text) {
  $plain = htmlspecialchars($text, ENT_QUOTES, 'UTF-8');
  if (empty($plain) && !empty($text)) {
    dpm($text);
    ddebug_backtrace();
  }
}

You will need to have the devel module enabled.  The next time the error is triggered, the offending text will be displayed along with a backtrace that shows what function triggered the error.  With that info, you can search your code and database for the offending text and remove it.


Programmatically add new role to group member

I was eventually able to find the correct process.  The working code follows:

// Get the group owner
$owner = $group->getOwner();

// Get the membership details of the owner
$membership = $group->getMember($owner);

// Get the roles of the owner
$roles = $membership->getRoles();

// Check whether the owner has manager role
if (!isset($roles['client-manager'])) {
  // No, so add the manager role to the membership
  // Get the group_content entity
  $group_content = $membership->getGroupContent();
  // Set target group role
  $group_content->group_roles->target_id = 'client-manager';
  // Save updated entity
  $group_content->save();
}

Thanks for your help.


Loading a jQuery plugin from the Libraries 2.X module in Drupal 7?

Yea using a module that exposes it as a library is totally the way to go.

And you certainly don't want to use drupal_add_js because drupal_add_library  [link] will do it the proper way.

And for your case:

drupal_add_library('jqeasing', 'easing');


Commerce line item views with fields from content node

This isn't easy, because the line item has no direct reference to the node. It does store the node URL in a textfield, but that does not a Views reference make. If you have a store where there's only one product display referencing each product, then you can get away with using a reverse product reference - i.e. starting with the line item, you reference the product, and from the product, you add a reverse reference to the "node referencing the product." Then you should be able to add fields from the product display node.

If you have multiple product displays referencing any given product, this solution might not work (unless of course each node contained the same fields you intend to pull into the View).


User pictures are no longer guaranteed to exist in Drupal 8. It is added by the standard profile, but not added if you use the minimal profile.

The user picture is simply a image field attached to the user bundle, so normal file field API's can be used. To get the file path of the default image for the user picture field attached to the user bundle:

<?php
$field = \Drupal\field\Entity\FieldConfig::loadByName('user', 'user', 'user_picture');
$default_image = $field->getSetting('default_image');
$file = \Drupal::entityManager()->loadEntityByUuid('file', $default_image['uuid']);
$file->getFileUri();
?>

I'm not sure what you are trying to achieve. If you are looking for better default avatars, then I encourage you to look at Avatar Kit for Drupal 8. Disclaimer: I am the developer of Avatar Kit.


Site running from accidental upload of core in subdirectory

I had a similar incident where someone had put a second set of core modules in a second folder called "modules" inside the main modules directory.  As a result Drupal was running off of the system.module located in modules/modules/system.  This made updating the site problematic.

The only way I fixed it was by dumping the database as a text file (.sql), editing the modules/modules file paths in the systems table, then re-importing, overwriting the database.  You may also be able to do this via MySQL commands or using an interface such as phpMyAdmin.  You should also look at my other answer about steps taken when editing the database. (You would almost think that cowboy edits of the database is all I do everyday)

Know that editing the database is not best practice, but sometimes it is the only fix.  Make sure that you should have a backup in case you mess things up, which in most likely happen on our first attempt.


I'm pretty sure that if you go to admin/store/products/classes and add a class where the Class ID is the same as the machine name of the content type that Ubercart will pick it up as a product type.


Get dynamically created image URL in a block with paragraph and media bundle

I wouldn't try to hack the render array content. You might be more successful with the paragraph entity:

{% set uri = paragraph.field_slide_image.0.entity.field_image_upload.entity.uri.value %}

{% set url1 = uri|image_style('style1') %}
{% set url2 = uri|image_style('style2') %}
{% set url3 = uri|image_style('style3') %}

For the filter image_style install the module Twig Tweak.


Add and/or option to Drupal Views' Contextual Filters?

You can achieve your requirement by installing Views Contextual Filters OR module. By default contextual filters are in AND condition.

  The module provides a views plugin which modify query to support OR
  conditions for contextual filters.


drush/drush:dev-master is not Drush 8, it is Drush 9.  To install Drush 8, try composer global require drush/drush, or better yet, use cgr.

For notes on installing Drush 9 via Composer, please see drush dev-master requires codegyre-robo.


Have configuration form use a different theme than the currently set Admin theme

You can control this in the route definition.

If you give non admin users access to the form they will see it in a regular theme:

my_settings:
  path: '/admin/config/system/my_settings'
  defaults:
    _form: 'Drupal\my_settings\Form\SettingsForm'
  requirements:
    _permission: 'access content'

If you want to have admins see the form in a regular theme then move the path outside of /admin:

my_settings:
  path: '/other-path/my_settings'
  defaults:
    _form: 'Drupal\my_settings\Form\SettingsForm'
  requirements:
    _permission: 'administer site configuration'

Or do both at the same time.

Details:

If you give a non admin user permission for an admin route, then the form will be displayed in the regular theme, because the admin theme is only accessible for admin users or users who have the "administration theme" permission.

Whether a route is considered as admin route is controlled by the route option _admin_route. If this option is not set, it is added by AdminRouteSubscriber::alterRoutes to all routes with an admin path:

  protected function alterRoutes(RouteCollection $collection) {
    foreach ($collection->all() as $route) {
      if (strpos($route->getPath(), '/admin') === 0 && !$route->hasOption('_admin_route')) {
        $route->setOption('_admin_route', TRUE);
      }
    }
  }

If you want to override this you can set the option to false:

  options:
    _admin_route: FALSE


Setting up an exposed filter to only filter conditionally

If the district is a term, entity reference, or a list field value, then you should be able to do this. Otherwise, You'll need to do something more involved (and honestly, at that point, you're probably better off just restructuring that data to work with views.

As far as only exposing options that will provide valid results, I'd recommend taking a look at Views Selective Filters (https://www.drupal.org/project/views_selective_filters). Be wary though, as the views_selective_filters module does an additional query, per selective filter as the view is loaded. Not a huge problem for 1 or 2 filters. But can start to cause performance issues if you're not careful.

Edit
The question as I (now) understand it: How do you change the options of a select list exposed filter based on an arbitrary value set against the currently logged in user?

First, hook into the exposed filter form and modify the district filter.

function mymodule_form_FORM_ID_alter(&$form, &$form_state) {
  $district_options = mymodule_get_district_options();

  if (!empty($district_options)) {
    $form['field_district']['#type'] = 'select';
    $form['field_district']['#options'] = $district_options;
  }
}

Next, you need to actually write mymodule_get_district_options().

function mymodule_get_district_options() {
  // Load the current user.
  global $user;
  $account = user_load($user->uid);

  // Default to loading all districts.
  $district_ids = FALSE;

  // Get the districts value from the loaded account.
  if (!empty($account) && !empty($account->field_districts)) {
    $district_values = $account->field_districts;
    foreach ($district_values[LANGUAGE_NONE] as $delta => $value) {
      $district_ids[] = $value['target_id'];
  }

  // Load the districts set on the current user, or ALL districts if none are set.
  $districts = entity_load('district', $district_ids);

  $options = [];
  if (!empty($districts)) {
    foreach ($districts as $district) {
      $options[$district->id] = $district->title;
    }
  }

  return $options;
}

Something along those lines should work. I haven't tested this.


You can add a relationship, "Content" and make it available in fields.

If you can provide more details regarding your content type, I can provide a better answer.


If it is available in theme options at http://example.com/admin/appearance/settings/drupon then you can.
If Drupon provides both "left sidebar" and "right sidebar" regions, you can move blocks from one region to the other at http://example.com/admin/structure/block
If it's compatible with Panels or other fast theming system, see it's documentation
If none above, you need to subtheme to alter CSS or structure.


How can I hide a certain warning message showing to users?

You need to include ini_set( 'display_errors','0'); in your setting.php file in drupal site.

See more about error reporting
http://php.net/manual/en/function.error-reporting.php

// Reporting E_NOTICE can be good too (to report uninitialized
// variables or catch variable name misspellings ...)

ini_set( 'display_errors','0');


Go to previous page (not after form submit)

Create your link this way:

$link = l('Link title', 'your/menu/path', array('query' => drupal_get_destination));

This will add the destination argument to the link URL.

Then, at the end of your page callback, simply call:

drupal_goto();


Filter by field that only exists for some content types shown in view

Yes, that's doable.

I would create a separate view for strict and flexible and then tailor each to suit your needs. You may need to use hook_views_query_alter if you can't get the functionality quite right with just the view UI.

A possible simpler alternative approach is outlined in this answer here.

Essentially this involves clicking on the reduce duplicates checkbox when configuring your join in the views UI.


Updates for custom module not showing in update.php list

The 'system' table in your db contains the current "version" of modules, so I would check there first.

Also, if these modules are dependencies, you can just include them in your module.info (writing module .info files in Drupal 7) by simply adding

dependencies[] = devel
dependencies[] = views

and so on.


Not sure i follow your narrative up there but you might be interested in entity metadata wrapper to help you deal with the objects and their states individually with custom forms.

https://drupal.org/node/1021556

The project page:
https://drupal.org/project/entity


What is the best method for getting vendor files on the server?

You have two options.

Commit the entire project with Git.
Use Acquia BLT.

The first method is not preferred because it makes the repository size massive and unwieldy, but if you have no build server you have no build server. But not having a build server isn't necessarily the end, because...

The second choice would allow you to build locally and deploy to remote using a command BLT provides.

Here is an example. I want to build my develop branch and put it on the server. I can enter the repository url in my project.yml file (provided by BLT), and run this command:

blt deploy -Ddeploy.branch=develop-build -Ddeploy.commitMsg='PROJECT-000: Generating new build for PROJECT.'

This will generate a build artifact (which is not committed into your canonical repository), but instead committed to the remote repository being deployed to as develop-build or whatever you name the branch. You then switch your dev environment to run that branch instead of develop. For instance, my canonical repo lives on GitHub, my remote repo is on Acquia. GitHub won't ever have the -build branches committed to it, and the Acquia repo won't ever have develop or master - it will have the build artifacts of deployed branches. You could use the same repository for both, but its a drag IMO because you (or I, anyway) want the canonical repo to be clean and not be dragging around artifacts of this size.

It is easier with a CI server to automate all of this, but Acquia BLT is a viable option when you don't have a CI service to use because you can run the commands yourself from your machine.

Another option would be to build your own scripts to do this as well, but I'd say you are better off starting with BLT. It can be added to existing projects, and it is straight-forward to configure via project.yml.

So no, you do not need to run Composer on the production server. Most hosting companies would never allow this anyway.


Change page title of a module generated page

The module is using its own menu definition. The title of the menu item is used for displaying the page title of the page in question (which is 'Tags' in English and 'Labels' in your Dutch version):

/**
 * Implements hook_menu().
 */
function tagclouds_menu() {
  $items = array();

  // [...]

  $items['tagclouds/list/%tagclouds_vocs'] = array(
    'title' => 'Tags',
    'page callback' => 'tagclouds_page_list',
    'page arguments' => array(2),
    'access callback' => 'user_access',
    'access arguments' => array('access content'),
    'type' => MENU_CALLBACK,
  );

  // [...]

  return $items;
}

As you are using a localized version of Drupal, you have several options to change the page title.

The first and most easy solution is to change the translation of 'Tags' to your desired string. You can use the localization interface which is located at /admin/config/regional/translate/translate.

However, the above solution will change the translation for 'Tags' within your whole site. Which means that the new translation might appear somewhere else as well, and on an English page the title would still be 'Tags'.

The second solution is changing the menu item's title. You can do so without side-effects as the menu item of question is a menu callback. Its title will not be shown within your menu structure, but as page title only. As you should never touch the sources of a contributed module (for your customizations), writing a small custom module is the way to go here.

Follow this guide to get started with custom modules and create the required files. Within your custom module's MYMODULE.module file you can implement hook_menu_alter(), which allows you to change the menu items of other modules. In this case, we'll change the menu item of the tagclouds tag overview page:

/**
 * Implements hook_menu_alter()
 */
function MYMODULE_menu_alter(&$items) {
  // Whether the tagclouds menu item is defined.
  if (isset($items['tagclouds/list/%tagclouds_vocs'])) {
    // Change the menu item's title.
    $items['tagclouds/list/%tagclouds_vocs']['title'] = 'Your New English Title';
  }

  // For translation extractors, you may also implement
  // this little function call.
  t('Your New English Title');
}

Change MYMODULE to your module's name, activate the module and/or clear your Drupal caches. You might have to visit the page once, so that the translatable string will be known to Drupal's localization system. Afterwards you can head to the translation interface as described within the first solution and add a translation for 'Your New English Title'.

The third solution is to hook into the page pre-processing within your theme. Locate your theme's template.php file. If your theme is implementing the theme hook THEME_preprocess_page() already (which is very likely), you may just add the lines from the following function's body. If your theme does not implement this hook, you may add the whole function, renaming THEME to your theme's name. This little code checks, whether you are at the tagclouds listing page and - if so - changes the page title using drupal_set_title():

/**
 * Implements THEME_preprocess_page()
 */
function THEME_preprocess_page(&$variables) {
  // Load the current path into a variable.
  $current_path = current_path();
  // Whether the current path is the tagclouds listing path.
  if (strpos($current_path, 'tagclouds/list/') === 0) {
    // Set the page title. We use drupal_set_title here, as
    // the static page title will be evaluated within the
    // process_page function, which follows the pre-processing.
    drupal_set_title(t('Your New English Title'));
  }
}

Once again, following Drupal standards you set the English title here, so after you cleared the Drupal caches and visited the page once, you should follow the steps of the first solution to add an appropriate Dutch translation to your localization.

The last solution is suggesting the module maintainer to allow editing the page labels within the module settings. This change however might take a little longer as most module maintainers are contributing to the modules within their spare time.


Way to remove the Override Title form option in Panel component config?

The function responsible for the overriding title:

/**
 * Add the default FAPI elements to the content type configuration form.
 */
function ctools_content_configure_form_defaults($form, &$form_state) {
  $plugin = $form_state['plugin'];
  $subtype = $form_state['subtype'];
  $contexts = isset($form_state['contexts']) ? $form_state['contexts'] : NULL;
  $conf = $form_state['conf'];

  $add_submit = FALSE;
  if (!empty($subtype['required context']) && is_array($contexts)) {
    $form['context'] = ctools_context_selector($contexts, $subtype['required context'], isset($conf['context']) ? $conf['context'] : array());
    $add_submit = TRUE;
  }

  ctools_include('dependent');

  // Unless we're not allowed to override the title on this content type, add this
  // gadget to all panes.
  if (empty($plugin['no title override']) && empty($subtype['no title override'])) {
    $form['aligner_start'] = array(
      '#markup' => '
',
    );
    $form['override_title'] = array(
      '#type' => 'checkbox',
      '#default_value' => isset($conf['override_title']) ? $conf['override_title'] : '',
      '#title' => t('Override title'),
      '#id' => 'override-title-checkbox',
    );
    $form['override_title_text'] = array(
      '#type' => 'textfield',
      '#default_value' => isset($conf['override_title_text']) ? $conf['override_title_text'] : '',
      '#size' => 35,
      '#id' => 'override-title-textfield',
      '#dependency' => array('override-title-checkbox' => array(1)),
      '#dependency_type' => 'hidden',
    );
    $form['override_title_heading'] = array(
      '#type' => 'select',
      '#default_value' => isset($conf['override_title_heading']) ? $conf['override_title_heading'] : 'h2',
      '#options' => array(
        'h1' => t('h1'),
        'h2' => t('h2'),
        'h3' => t('h3'),
        'h4' => t('h4'),
        'h5' => t('h5'),
        'h6' => t('h6'),
        'div' => t('div'),
        'span' => t('span'),
      ),
      '#id' => 'override-title-heading',
      '#dependency' => array('override-title-checkbox' => array(1)),
      '#dependency_type' => 'hidden',
    );

    $form['aligner_stop'] = array(
      '#markup' => '
',
    );
    if (is_array($contexts)) {
      $form['override_title_markup'] = array(
        '#prefix' => '
',
        '#suffix' => '
',
        '#markup' => t('You may use %keywords from contexts, as well as %title to contain the original title.'),
      );
    }
    $add_submit = TRUE;
  }

  if ($add_submit) {
    // '#submit' is already set up due to the wizard.
    $form['#submit'][] = 'ctools_content_configure_form_defaults_submit';
  }
  return $form;
}

states on line 513:

  // Unless we're not allowed to override the title on this content type, add this
  // gadget to all panes.

which means you could just add the following array members to the existing $plugin or $subtype:

  $plugin['no title override'] = TRUE;
  $subtype['no title override'] = TRUE;

and theoretically it should work.


How to manually use Drupal 7's admin Overlay?

You can also use the Overlay Paths module. This is a simple module that enables administrators to use the built-in Overlay for non-admin pages. This means that you can use the overlay for doing popups without adding yet more javascript libraries to your site.


Show workflow transition bar in all states

I worked out what the issue is, you can only see that bar when you're looking at the Latest Version of a node (using the "Latest Version" tab) not when viewing the latest published version of the node (using the "View" tab).

So this is now resolved by checking if they have access to the "Latest Version" tab of a node (basically checking that exists) and sending them to that if it does, otherwise sending them to the "View" tab. The code below does it and is called from hook_node_insert & hook_node_update in my custom module .module file.

function send_user_to_view_page_after_save(NodeInterface $node) {
  $nid = (string) $node->id();

  if (!is_null($nid)) {
    $alias = Drupal::service('path.alias_manager')->getAliasByPath("/node/{$nid}");
    $url_service = new Url("entity.node.latest_version", ["node" => $nid], []);

    if ($url_service->access() === TRUE) {
      $response = new RedirectResponse("/node/{$nid}/latest");
      $response->send();
    }

    $response = new RedirectResponse($alias);
    $response->send();
  }
}


I suggest you implement hook_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) function.

    function hook_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {
      // Check if the $form_id is your node type add form.
             if ($form_id == 'article') {
                // Add a custom validation function. Example:
                $form['#validate'][] = 'custom_form_test';
              }
    }

Then you need to implement the custom function where you will put your logic.

function custom_form_test(&$form, FormStateInterface $form_state) {
  // Get value of the field which use the inline entity form display.
 $tags_value = $form_state->getValue('field_tags');

}

See the screenshot of the $form_state dump and also with the field_tags taxonomy term reference values:

So you can access all the values from the inline form display.
For example to access name value:

$name = $tags_value[0]['inline_entity_form']['name'][0]['value'];

Just looping into arrays. Once you get the value that you want you cand restrict finishing the submision of a node by write a message error. Example:

 $form_state->setErrorByName(
                'field_tags',
                'The name is WRONG!'
              );

Hope to help you!


Use QueryAggregateInterface::execute:

$result = \Drupal::entityQueryAggregate('node')
  ->aggregate('nid', 'sum')
  ->condition('status', NodeInterface::PUBLISHED)
  ->execute();

The result returned is keyed by fieldname and aggregate function:

$sum = $result['0']['nid_sum'];


It sounds like you need to reference the relationship you created down in the filter criteria.
In the example below I have a views where I want to display all documents of the current logged in user.

I created the views showing all documents first. Get your view working the way you want it too first.
Create the relationship - I want documents that are related to who authored them
Filter your view by the author relationship. So in the example below my view is filtered by the current user - and it shows all documents in which the current user is the author.
Once your view is sorted you can work out the user reference part.

Hope this helps


Use VBO to send tokenised email in Drupal 6

The Views Send module solved my issue.

  Views Send enables you to send mass mailing from a View.


highWaterProperty renamed to high_water_property, and moved from the top-level migration plugin configuration into the source plugin configuration.

id: my_migration
source:
  high_water_property:
    name: changed

For more information, see: https://www.drupal.org/node/2795403


sub directory multisite just redirecting to default after first page

Any caching turned on? (varnish/memcache/...)

If using memcache make sure to separate the memory buckets in each site's config.

$conf['memcache_key_prefix'] = 'Example_Memcached_Key';


If deleting any function from a contributed module works for you without giving any issues, then it's totally ok except that the next module update will override your change and you will have to delete the offending lines again. So the best course is to report this to the contributed module's developers, so they fix and commit necessary changes.

By the way, this seems to have already been reported on https://www.drupal.org/project/ckeditor/issues/2957580.


How do I can change the default description of elements?

you can find the descriptions at user.module under user directory (in modules directory)

you can find those descriptions under user_account_form function

Ex, E-mail address field description below.

$form['account']['mail'] = array(
    '#type' => 'textfield',
    '#title' => t('E-mail address'),
    '#maxlength' => EMAIL_MAX_LENGTH,
    '#description' => t('A valid e-mail address. All e-mails from the system will be sent to this address. The e-mail address is not made public and will only be used if you wish to receive a new password or wish to receive certain news or notifications by e-mail.'),
    '#required' => TRUE,
    '#default_value' => (!$register ? $account->mail : ''),
  );

But it's better to  Use hook_form_alter to achieve it


Using a module controller to create a page that is more than just a div from the twig template?

When you generate an entity with drupal console you get a twig template for the content of the entity. This is not a page and not a theme. If you want to use a page template, that is specific to the entity, then you use a template name suggestion, for exampe page--myentity.html.twig. The content from the entity controller will end up like any other content inside of this page in the region content if you use the standard block layout, where the block "Main page content" is placed in this region.

You can remove anything else from the page template what you don't need and replace this with static html.


How do I pre-populate the login/sign up form?

I have already extended the standard Drupal login form

Sounds like you're already using hook_form_alter(), so all you have to do is add the #default_value attribute to your form array.

Ex:

$form['my_field_name'] = array(
    '#type' => 'textfield',
    '#title' => t('something'),
    '#default_value' => t('Hello World'),
);

OR Use the Profile2 module suggested by @Kevin

  Profile2 allows for creating multiple profile types, which may be
  assigned to roles via permissions (e.g. a general profile + a customer
  profile)


condition inside template.php (if logged_in/logged_out and else)

This should help you out. Drupal user login - How to tell if a Drupal user is logged in (authenticated)

You can also use the utility variable $logged_in: Returns TRUE if the user is registered and signed in.

Updated answer.

In template.php, you can use global $user; to check and see if someone is logged in.

global $user;
if (isset($user->roles[1])) {
  //Put code here.
}

Checking against Devel, you can see that $user->roles[1] means it's an anonymous user.


There are several problems with your code:

Your AJAX callback should return a form element. Now it returns plain 33.
All changes should be made inside form building function, in your case rah_cc_generate_form. Simply add condition to test $form_state['triggering_element'] and perform action if it was your AJAX trigger. Do not alter things in AJAX handler, it's not what it is for. I know it's counter-intuitive, but that's the way it is.
Changing default value once there is some user input will have no effect. Maybe you should try to change appropriate entry in $form_state['input']? But that depends on your intentions.


Batch operation keeps looping after completion

I was able to fix it by using the magic send() method for RedirectResponse class and building a full URL (mostly) manually.

  public static function completeImport() {

    $url = $GLOBALS['base_secure_url'];
    $url .= $GLOBALS['base_path'];
    $url .= Url::fromRoute('system.admin_content')->getInternalPath();
    $url .= '?status=All&type=academy_webinar&title=&langcode=All';

    $redirect = new RedirectResponse($url);

    $redirect->send();
  }


Which implementation is better for custom breadcrumb and why?

When you build a module which for example provides a new content or entity type you can include a breadcrumb builder, because you might have data fields that the standard breadcrumb builder doesn't know of and you want to process them in your breadcrumbs. An example for this would be  Drupal\book\BookBreadcrumbBuilder from the core book module.

When you build a theme and want to modify the breadcrumbs already built by the installed core, contrib and custom modules you use a theme based solution in a preprocess hook.

So best practice depends on which level you are working on. Not a good idea would be in this example if the book module would use a preprocess hook.


If you want to change its machine name their option available in advance option of view or want to change its display name that will change form display.


I have enabled Node clone on a Drupal 7 site. The cloning capability appears as an action link at the beginning of the node content on the View tab, not as a separate tab. The link text is "Clone content". The actual HTML is:

Clone content

I'm using a clean Zen subtheme. Perhaps your theme is preventing the action links from appearing?


How to invert a contextual filter which is a taxonomy term ID?

I haven't tested this, but at the bottom of the contextual filter form, under 'More" is a button that reads:
Exclude
If selected, the numbers entered for the filter will be excluded rather than limiting the view.

Have you tried this?  Please follow up with a comment for your results.


No you can't.
The user.flood user_limit config setting feeds into the DatabaseBackend::isAllowed() method as the $threshold arg, which is used to compare the row count for this query:
  $number = $this->connection
      ->select(static::TABLE_NAME, 'f')
      ->condition('event', $name)
      ->condition('identifier', $identifier)
      ->condition('timestamp', REQUEST_TIME - $window, '>')
      ->countQuery()
      ->execute()
      ->fetchField();

It only compares the threshold login count against a unique user ID, $identifier.
You'd have to do some sort of modification to the flood core service to make some sort of per-role flood limit.


How to configure boost for multisite configuration

Boost works out of the box with multi-site. If your cache files are being generated (they appear in /cache/normal/site1.example.org/), but not served (boost comment in the footer of the page, or X-Cached-By in the HTTP headers), then there is an issue with your .htaccess configuration.

You can debug your htaccess rules by enabling the rewrite log:

RewriteLog "/tmp/rewrite.log"
RewriteLogLevel 2

This can generate a lot of logs, use with great care in production.

Also check this post on how to debug htaccess rules:
https://stackoverflow.com/questions/9153262/tips-for-debugging-htaccess-rewrite-rules


Functionality aside, I think the basic structure for D6 would be:

<?php
if(isset($sidebars['left'])):
  foreach($sidebars['left'] as $value):
    if (!empty(${'sidebar_'.$value})): ?>
    <div id="sidebar-<?php echo $value; ?>" class="col-<?php echo $value; ?> sidebar left tb-height-balance tb-region tb-scope tb-sidebar tb-left">
      <?php print ${'sidebar_'.$value}; ?>
    </div>
    <?php
    endif;
  endforeach;
endif; ?>


drush extension installation directory location

This (the incorrect contents in the drush_sup README file) is a drush_sup bug report, and should go in the drush_sup issue queue.  I am the drush_sup maintainer, though, and can make this correction.

If you use Drush to download drush sup (i.e. drush dl drush_sup), then it will automatically be placed in the .drush folder in your home directory.  Drush automatically finds extensions stored in this location.


Hide Authoring info on certain pages/nodes

You could add a checkbox field to the content type, and adjust the node.tpl file. If the box is not checked, don't print submitted by.

Add the field to all content types (sounds like thats what you asked for) and remove it from each display under "Manage Display".

Then, in template.php, implement template_preprocess_node:

mythemename_preprocess_node(&$variables) {
  $node = $variables['node'];

  // here we are creating a brand new variable
  // true, unless otherwise set by editors
  $variables['show_authoring'] = TRUE;

  // the field exists on the node object
  // update our custom variable to this field value
  if (isset($node->field_show_authoring)) {
    $variables['show_authoring'] = $node->field_show_authoring[LANGUAGE_NONE][0]['value'];
  }
}

If you want all nodes have this, you can copy in node.tpl.php to your theme or edit the one in your theme if it exists, and do:

<?php if ($display_submitted && $show_authoring): ?>
  <div class="submitted">
    <?php print $submitted; ?>
  </div>
<?php endif; ?>

You could remove $display_submitted if you wanted to, I left that there in case you wanted control in the future to completely disable showing authoring for certain content types, like Webform for example. My syntax should be correct but I did not have a chance to test this in a sandbox.

See more:

template_preprocess_node
How do I create a variable for my template file?
Preprocessing function for node.tpl.php


How to use lazy_builder to load and replace content asynchronously

Normally placeholders are used for elements that are not cacheable, like a timestamp, so that the rest of the render array no longer depends on the dynamic data and can be cached. On a cache hit the placeholder gets replaced by the result of the lazy builder. This is the asynchronous part.

What you are trying to do looks more like asynchronous loading of web content in the browser. You can use BipPipe for this, but then don't put a sleep command in the lazy builder, try to solve this in javascript.


Go to your-site/admin/appearance page, remove the styles (in Firefox is View/Page Style/No Style) and find the Administration theme form.

Select seven as administration theme and save configuration.


Use FieldDefinitionInterface::getDefaultValueLiteral:

$definitions = \Drupal::service('entity_field.manager')->getFieldDefinitions('node', 'page');
if (isset($definitions['field_example'])) {
  $default_value = $definitions['field_example']->getDefaultValueLiteral();
}


pager_query() - How to fetch only 100 records with a pagination 10 items per page?

You can pass a $count_query argument to pager_query(), which you can use to control the overall count:

e.g.

$sql = 'SELECT * FROM my_table';
$count_sql = 'SELECT COUNT(id) FROM my_table LIMIT 100';

$result = pager_query($sql, 10, 0, $count_sql);


Thanks for your answers.
Already solved the issue.

You have selected a layout Panopoly, I changed it to one of the "Extra laytous panels" and matter settled.


Can't log onto drupal with any email address

Consider editing the eMailId currently stored in the Drupal database, using PhpMyAdmin. And this by replacing that eMail ID with some other eMail ID that is usable for you.

Then use the "request new pasword" feature for that account, which should be mailed now to the eMail Id that you can work with. Use the password reset link and you should be up and running.

Does this help?


You can add more info about the referenced Media in your content Views through a Relationship for that Media field.
Add the Relationship (under Advanced Views settings) called something like Media referenced from field_mixed_media under the Content Category.
You can Require it if you only want to see nodes that have that Field filled in (not empty).
Once you add that Relationship you will see more options when adding new Fields and Filters.
In your case you'll want to add the Filter Media type from the Media Category, it will use the Relationship by default, and Expose it.
The Exposed filter will show as a drop-down select list. If you want it display as checkboxes you can use the Better Exposed Filters module.


D7, AmazonS3, composer_manager and awssdk libraries understanding

In the last days, I have repeated the painful procedure many times on different AWS EC2 instances to be sure to have a precise and repeatable procedure.
I am thus very confident about my understanding of it today.
I have written a step-by-step procedure to deploy amazonS3, with the main encountered problems and how I dealt with them. I believe that such a document would have helped me a lot some days ago (and back then, I didn't found any), so here is my proposal. I would appreciate some real experts validation there !

1) install Drush or update to get 5+ version

2) apply all valid patches from the amazonS3 README (https://www.drupal.org/project/amazons3), mainly to allow S3 generated URI s3:///filename.ext" to be supported by media and fileentity related modules

3) Install composer (goes without saying, but I missed it at first!) with :

curl -sS https://getcomposer.org/installer | php
sudo mv composer.phar /usr/local/bin/composer
alias composer='/usr/local/bin/composer.phar'

composer command should return usage tips

4) Install PHP's cURL extention. On Ubuntu, sudo apt-get install php5-curl is sometimes not enough. (See "cURL library required to enable drupal ...")

sudo apt-get update
sudo apt-get install curl libcurl3 libcurl3-dev php5-curl
sudo /etc/init.d/apache2 restart

5) From the drupal_root folder, launch amazons3 download and install

drush  dl composer_manager
drush  en composer_manager

6) Configure the directory where to put vendor and composer.json files. The default directory are outside of Drupal's directory (vendor : "../vendor", composer: "../")
Once the composer_manager is enabled, I went admin/config/system/composer-manager/settings  and set the fields as follows (again, refer to best practices for RW permissions of Drupal folders).

7) Be sure to give write permissions to www-data to the folder. Especially with the folder being outside of the drupal_root folder.

8) Download and install amazonS3 using Drush and composer, since AWSSDK libraries will be automatically installed with all dependencies.

drush dl amazons3
drush en amazons3

These commands should automatically generate composer.json in the previously indicated folder. You can check that all the dependencies were correctly gathered from amazonS3 and other modules requirements.
In my case, composer.json contains :

{
"require": {
    "aws/aws-sdk-php": "2.8.5-p1",
    "capgemini/drupal_doctrine_cache": "0.0.1-p1",
    "doctrine/cache": "~1.4",
    "php": ">=5.3.0"
},
"config": {
    "autoloader-suffix": "ComposerManager"
},
"require-dev": {
    "phpunit/phpunit": "~4.6",
    "satooshi/php-coveralls": "0.6.*"
},
"repositories": [
    {
        "type": "vcs",
        "url": "https://github.com/deviantintegral/drupal-doctrine-cache.git"
    },
    {
        "type": "vcs",
        "url": "https://github.com/deviantintegral/aws-sdk-php.git"
    }
],
"autoload": {
    "psr-4": {
        "Drupal\\amazons3\\": [
            "../../modules/contrib/amazons3/src/"
        ]
    }
}

}

9) I can't explain why, but the first install generated an incomplete composer.json . You can regenerate the file using by accessing /admin/config/system/composer-manager and click regenerate, or running from drupal_root folder the following drush command :

composer-json-rebuild

9bis) You can also, directly from the composer folder (which location was set previously) and run :
composer install. The command will download all required PHP libraries in composer vendor's folder.

I personally found it very confusing all the locations on my server where composer files where located :

Some docs advise to put composer folder in a ~/.composer/vendor folder in user's home directory. - - Drupal created a .composer in a .drush/composer (to indicate that Drush is required for that user)
I found a ~/.composer in my root folder. It contains users's credentials to access github repository to load the required packages
Most of the docs recommend to store a composer folder just above the drupal_root
I choose to follow these last recommendations to put it in the sites/all/libraries/composer in order to commit the code. But I can't say whether this is the right way to proceed.

10) Finally, retrieve you AWS API KEY and AWS SECRET KEY from console.aws.amazon.com and  configure amazonS3 in /admin/config/media/amazons3, by setting your Security Credentials: Access Key ID and Secret Access Key, and S3 Bucketname. You can also put the values in the settings configuration file, by adding the following lines to your settings.php :

$conf['amazons3_key'] = "<AWS API KEY>";
$conf['amazons3_secret']="<AWS SECRET KEY>";
$conf['amazons3_bucket']="<bucketname>";

11) AmazonS3 should be working : create a file field on a content type, select Amazon S3 as the location to save to. Create a node, attach a file,Save and view the node. The attached file should be displayed as a link to you S3 bucket.

During  my last install, I was able to avoid most of the problems encountered in my previous tries : cURL, read/write permissions, composer unable to parse version requirements, etc.
The last error I was confronted to, was a composer out of memory problem, which I fixed with the following :

sudo /bin/dd if=/dev/zero of=/var/swap.1 bs=1M count=1024
sudo /sbin/mkswap /var/swap.1
sudo /sbin/swapon /var/swap.1

I hope this note will help someone, since S3 really worth a few headaches with the installation. Besides, the last release of the module is only two months old.


function do_search(e) {
  clearTimeout(search_timer);
  search_timer = setTimeout(function() {
    var v = $("#YOUR_INPUT_VAR_ID").val();
    p(v);
    CALL THE AJAX HERE
  }, 500);
}


How to create suggestions conditionally (by block type/bundle) override system templates in Drupal 8

Currently, I have only found a workaround using image-formatter override

Create a file name suggestion hook for theme in themename.theme:

function themename_theme_suggestions_alter(array &$suggestions, array $variables, $hook) {
    switch ($hook) {
        case 'image_formatter':

            /**
             * @var Drupal\url_image\Plugin\Field\FieldType\UrlImageItem $item
             */
            $item = $variables['item'];
            $config = $item->getFieldDefinition();
            switch ($config->getTargetBundle()) {
                case 'b_partner_images':
                    $suggestions[] = 'image_formatter__b_partner_images';
                    break;
            }
            break;
    }
}

Create a template file image-formatter--b-partner-images.html.twig:

It works, but not as beautifully, as I would like.

PS: I used that specific hook_theme_suggestions_alter format, because I have more than one suggestions hook, and I put them inside this single function, so I can add more conditions with ease.


Get value of a field attached to a user entity based on currently logged in user

global $user;
// Only if logged in
if($user->uid) {
  $logged_in_user = user_load($user->uid);
  $field_user_class = field_get_items('user', $logged_in_user, 'field_user_class');
  // Do stuff with array $field_user_class
}


Custom Webform handler not working on Wizard Webform

Hopefully this will help someone out there but this is the code I finally got working.  It takes the serial value from a webform submission and writes a Png barcode for use in emails.  I'm using the Barcodes Module for Drupal 8.
use Com\Tecnick\Barcode\Barcode as BarcodeGenerator;

class BarcodeHandler extends WebformHandlerBase {
  /**
   * {@inheritdoc}
   * Write PNG barcode for registration emails
   */
 public function postSave(WebformSubmissionInterface $webform_submission, $update = TRUE) {
   $regId = $webform_submission->serial();
   $type = 'C39';
   $barcode_file = 'registration/barcodes/' . $regId . '.png';
   $barcode = new BarcodeGenerator();
   $barcode_obj = $barcode->getBarcodeObj($type, $regId, 250, 50, 'black');

   file_put_contents($barcode_file, $barcode_obj->getPngData());

  }
}


I already have a complete HTML/CSS mockup should I use a base theme or start from scratch?

It's a mix of personal preference, familiarity with the theme system and, arguably most importantly, the experience of the end-user admin and how much they'll need to modify layout.

Unless the site layout will need to be extensively modified (by a non-developer, beyond just toggling/placing blocks) I would always choose to start from scratch.


This seems to be an ongoing issue as there are reports of other modules conflicting with the display suite view modes feature. For some it had to do with Panels as seen here:

https://www.drupal.org/node/1919452

  Posted by drupalstrap on February 17, 2013 at 5:57am Greetings,

  The only view mode i am able to use is the default view mode. As long
  as I am using the default view mode, I can switch layouts without any
  problem. If I try to switch to another view mode, it still uses the
  settings of the default view mode. I have tried every way of
  troubleshooting that I can think of including changing themes,
  altering CSS files and tpl.php files etc in order to try to isolate
  the problem. Furthermore, i am not able to apply wrapper or class
  styles via the UI settings. They don't appear in the source code.

  Anyway, I have been battling this for two days now and figured I would
  see if anybody out there has any suggestions. On the server side, I am
  using php 5.3 with apc. I have tried clearing cache hundreds of times
  as well as restarting the server to see if there was something in
  memory that was stuck. I have also tried other browsers so it is
  something related to my development environment I guess. LAMP???
  Please help. Thanks.

  Upload new files Comments  billsdesk’s picture Comment #1billsdesk
  commented 2 years ago I am having the same problem. I created a view
  mode and set it as the view mode to use when I edited the page. Yet,
  the Full Content mode is always used, and not the specified view mode.
  The Manage Display tab always opens the correct view mode. I turned on
  the view mode switcher, and it correctly identifies that the page
  opened in the full content mode. However, it does allow switching to
  the correct mode. I checked the permissions, and all is good. No error
  messages. I am using Drupal 7.22, and Display Suite 7-2.3. report spam
  on user billsdesk  alunyov’s picture Comment #2alunyov commented about
  a year ago Hello, I had same problem. In my case switching off panel
  for node view helped to solve the issue. I think it is something
  related with page manager. If you check settings page:
  admin/structure/ds/list/extras -> Other -> "View mode per node"
  option, in description you will find "Change view modes for individual
  nodes. A new tab 'Display settings' will appear on the content create
  form. You can also pass the name of a view mode through the URL, eg
  node/x?v=full. If you install the Page manager module and override the
  node view, Page manager will win."

  Added: check _ds_extras_menu_alter() in ds_extras.registry.inc. it
  explains a lot report spam on user alunyov  aspilicious’s picture
  Comment #3aspilicious commented about a year ago Status:  Active  »
  Closed (works as designed) Closing this works as designed. If you
  still have this issue and you DON'T have page manager enabled please
  reopen this one. report spam on user aspilicious  Geijutsuka’s picture
  Comment #4Geijutsuka commented about a year ago I'm having this
  problem on a new site I've been developing... The strange thing is
  that it's only happened within the last couple weeks. Something
  triggered this behavior, but I'm not sure what yet (trying to figure
  out STR).

  I set up a brand-new sandbox site with everything up-to-date and it
  seems to work as designed... flawless. I also don't have Page Manager
  or Panels installed, and I definitely don't want to have to resort to
  changing the view mode for every single piece of content. I'm going to
  update the problematic site (ds is up to date, but there are a lot of
  other updates) and see if that fixes it... if not, I'll be back.

In my case it wasn't panels that was causing the issue but it was due to the "revisioning" module that cause the view mode to get stuck on default. There has also been reports here:

https://www.drupal.org/node/2304917#comment-9550067

I updated to the latest revisioning v7.1.9 and it still causes issues with the view mode. The only option is to turn this off if revisioning is really not necessary.


Inside Panelizer, is there a trick to formatting image fields?

Although I could swear that I had done this before, I deleted the image in the panel. This time, when I added the image back into the panel, I got image formatter options. Which I set, and the node behaved correctly.

Despite the frustratingly long time I worked on this, it was a non-problem!

AMENDMENT:
When the panel is first created and saved, all of the fields appear in the panel. If the image field is left as is, there are no formatter options. However, if the image field is deleted from the panel and then re-added, then the formatter options appear. This is noteworthy, I think.


Views related nodes with contextual filters multiple-value handling problem

The answer was very simple but I missed it, you don't miss it if you are in the same situation:

Tick the Allow multiple values below the MORE part in contextual filter.


Programmatically create a node with a menu link

You can save menu link Separately using the below code on node save.

 $menu_link = MenuLinkContent::create(array(
      'title' => 'Menu Title', // Menu title is your title of menu, in this case node title
      'path' => '/path/to/node', // Menu link something like '/node/'.$nid, replace $nid with your node id
      'menu_name' => 'navigation',
      'weight' => 0,
      'bundle' => 'menu_link_content',
 ));

 $menu_link->save();


First thing you need to do is login via Services (unless you allow anonymous users permission to create content), which is a POST call to ?q=[my-endpoint]/user/login.json
Once logged in, you need to retrieve a new CSRF token (this new token should be returned within the login result)
Then make a POST call to ?q=[my-endpoint]/node.json, sending along something like this:

-

{
  title: "Hello world",
  type: "article",
  uid: 123,
  body: {
    und: [
      { value: 'How are you?' }
    ]
  }
}

Attach an X-CSRF-Token header to the request using the new token value generated after logging in.

That should then return something like this to you:

{
  nid: 456,
  uri: /* ... */
}

I have a blog post with examples of most of the Services Resources here: http://tylerfrankenstein.com/code/drupal-services-examples


How to use term id in content paths using path auto?

You likely need the Entity tokens module from http://drupal.org/project/entity for now. We are working on adding the more detailed field tokens into Drupal 7.


Apache solr is not accessible by my server but accessible by my localhost

problem was caused by selinux on my server.

by disabling selinux and rebooting centOs I could connect to my solr apache.

I found the answer here


It turned out to be a 401 error that only occurred when the user was not logged in. Changing the 'access arguments' string in the hook_services_resources array fixed the problem.


Synchronize users strategy for Drupal 7?

I don't know anything about WHMCS but there seem to be a lot of apps around LDAP connectivity that you can get for it.

The LDAP project for Drupal works well for me for authorization, both with Drupal as the host and with Drupal as the client.


The clean solution is template preprocessing: In yourtheme.theme create something like

function yourtheme_preprocess_field(&$variables, $hook) {
  $element = $variables['element'];
  $parentEntity = $element['#object'];
  //might be useful for if-clause: $variables['field_name'] and $variables['field_type']
  if ($parentEntity && $parentEntity->getEntityTypeId() == 'paragraph' ) {
    //whatever logic you need goes here, e.g. something like
    //$variables['attributes']['data-from-parent-paragraph'] = $parentEntity->getYourStuff();
  }
}


I have been working on Drupal for about 2 years and I have found these two modules to be absolutely the best tools to template a node:

Display Suite: https://drupal.org/project/ds
Panelizer: https://drupal.org/project/panelizer


Is it posible to use taxonomy terms in Context module?

Take a look at
Using Block Visibility Groups to Create Conditional Layouts in Drupal 8 about solution,
and the
Term condition module,

it works for me.


How to stop / hijack a infinite redirection loop with a redirecting rule

You might want to consider a simple redirect in .htaccess

To redirect based on user agent, if not already on redirected page.

RewriteEngine On
RewriteCond %{HTTP_USER_AGENT} MSIE [1-7]
RewriteCond %{REQUEST_URI} !^/upgrade/
RewriteRule .? upgrade [L]


How to show taxonomy term image on node creation page drupal?

Instead of term reference field try Entity reference field with Entity Reference view widget. This will help you to specify a view for field. Create an entity reference view that shows your additional image field. Select this view in your entity reference field settings.


If content type with specific field that is not empty has specific taxonomy term attach library

Try the following , and don't forget to clear the cache

function lehigh_preprocess_page(&$variables) {
    $current_route = \Drupal::routeMatch();
    $node = $current_route->getParameter('node');
    $target_taxonomy_id = 123;
    if (isset($node) && $node->getType() == 'standard_content_page'
        && $node->hasField('field_section')
        && !$node->get('field_section')->isEmpty()) {
        if ($node->get('field_section')->referencedEntities()[0]->id() == $target_taxonomy_id) {
            $variables['#attached']['library'][] = 'lehigh/financialaid';
        }
    }
}


Regarding "Menu > Settings" , You can able to select

Source for the Main Links (Primary menu)

  Select what should be displayed as the Main links (typically at the
  top of the page).

Secondary links

  Select the source menu for the Secondary links.

For example, If you created a new menu called Header Menu and added some links, now you would like to display Header Menu as Main Menu on top of page which is nothing but Primary Links. In that case you have to set "Source for the main links to " Header Menu.

Reading these values

Yes, You can able to read these values using below code

$primary_menu = variable_get('menu_main_links_source', 'main-menu')
$secondary_menu = variable_get('menu_secondary_links_source', 'user-menu'),

Regarding menus based on roles

You can try using Menu Item Visibility Module

  This module exposes configurable and extendable visibility settings
  for menu links. For example, if you want to create a 'My account' link
  that points to /user, both anonymous and registered users have access
  to the /user path, so both will see the link, even if anonymous users
  do not technically have an account.


If you are using Panels and Page Manager successfully (they share a common interface for many capabilities) you are well on your way to getting this together. Your question does not indicate if you are using views.  Adding its functionality to your setup in conjunction with Panels/Page Manager is important for gaining the control you need.

First, enable View Content Panes module in the Ctools Suite.  Content panes work similarly to blocks, but are 'smarter' and handle context information passed from Panels/Page Manager.  To define a content pane in views, select the add button in views and the content pane option will be available.  You define a content pane similarly to a views block (you can learn more by viewing 'Taming the Beast'). Once defined, your content panes will show up in Panels/Panel/variant/content/add-content menu just as blocks and other content types do already.

Mini Panels are also similar to blocks plus they accept contexts from Panels/Page Manager and they have the ability to subdivide the content of a block in a specific layout. LIke panel pages, they have access to a large variety opf content types including views and view content panes. They show up in admin/structure blocks for theme layouts and in a Panels/Page-Manager variant's content tab.  If you don't need the additional layout control, you should be able to accomplish what you need using the content panes from views.

Panels Everywhere provides a vehicle for taking control of the entire display layout, not just the content area.  I works the same as Panels for content control so really will not add anything new for your issue here.

For more on panels and mini-panels see this answer.


In views, what is the difference between Normal menu entry, Menu tab and Default menu tab

They correspond to the type parameter of items returned from hook_menu()

Normal menu entry = MENU_NORMAL_ITEM

  Menu type -- A "normal" menu item that's shown in menu and breadcrumbs.

  Normal menu items show up in the menu tree and can be moved/hidden by the administrator. Use this for most menu items. It is the default value if no menu item type is specified.

Menu tab = MENU_LOCAL_TASK

  Menu type -- A task specific to the parent item, usually rendered as a tab.
  Local tasks are menu items that describe actions to be performed on their parent item. An example is the path "node/52/edit", which performs the "edit" task on "node/52".
  Default menu tab = MENU_DEFAULT_LOCAL_TASK

  Menu type -- The "default" local task, which is initially active.

  Every set of local tasks should provide one "default" task, that links to the same path as its parent when clicked.

The best example I can think of are node pages. When you visit a node page, the 'View' tab is provided by a menu item of type MENU_DEFAULT_LOCAL_TASK (see $items['node/%node/view'] in node_menu()).

It doesn't have a path as such (it inherits from the parent menu item), it's only purpose it to allow the node page to have a tab amongst the groups of 'real' tabs, which are defined with MENU_LOCAL_TASK.


Block caching not working for anonymous users despite setting cache contexts

The issue was that I had different render arrays set depending on whether the user was logged in or not, but the cache context only applied to one of the render arrays but not the other. If I have different possible render arrays being returned every single one needs to have the cache settings added.

I resolved the issue by changing my code to

if ($user->hasRole('anonymous')) {
        if ($loginrequired) {
            $content = [
                '#markup' => '
 Login required. Click Here to Login
',
                '#cache'   => [
                     'max-age' => 0,
                     'contexts' => ['url.path']
                 ],
            ];
            return $content;
        }
}
$content = [
    'header'   => [
        '#markup' => $header_text,
    ],
    '#cache'   => [
        'max-age' => 0,
        'contexts' => ['url.path']
    ],
    $webform,
];
return $content;


I consider it generating permissions based on some data within your site.

For instance, I wanted to create permissions based on terms or vocabularies for roles, in regards to if they could use the functionality a contrib module I maintain provides:

http://kevinquillen.com/drupal/2016/02/21/dynamic-permissions-in-drupal-8

If you look at the NodePermissions class, it does something similar.


How to remove the "Close comment thread" button in Open Atrium?

Keep it simple. Just throw a CSS "display:none;" on it.


Organic Groups Create Content Link does not appear

Not sure which permission you mean with the "Permission to create content for content type is set" (consider adding the URL within admin to clarify that, is it /admin/people/permissions?).

However, it could well be that your issue is because you've not yet completed the "OG Permissions" located with something like /admin/config/group/permissions/ (and then select the 'edit' link for the group type your issue is about).


For reference, here is a description on how the map on the D.O homepage was built. https://association.drupal.org/node/784

To achieve what you want, you could use the Views Auto-refresh submodule of the Views Hacks module to auto refresh the openlayers map view in short intervals.


The reason you get an Access denied is because your menu item doesn't have a page callback attribute specified. (You have used callback instead). You can check the documentation of hook_menu() here.

On the same page, you'd notice that it says - when the page callback attribute is omitted for a menu item, the page callback of its parent will be taken.

However, when a parent doesn't exist for the menu item in question, it returns an Access denied. This happens even before the current user's access to your menu item is resolved; so the access callback doesn't really matter. (explains why changing that hasn't helped)


Set default to empty result with views exposed filters

You can use a views preprocessor to achieve this. The 'empty' element behaves similarly to the "No Results Behavior" option in the Views UI. Place this code in template.php and clear the cache:

function mytheme_preprocess_views_view(&$vars) {
  if ($vars['view']->name == 'my_view_name') {
    if (empty($vars['view']->exposed_input)) {
      $vars['rows'] = array();
      $vars['empty'] = '';
    }
  }
}

Tested using Views 7.x-3.0-rc1.


This is a feature provided by Symfony:

  The Request object as a Controller Argument

  What if you need to read query parameters, grab a request header or get access to an uploaded file? All of that information is stored in Symfony's Request object. To get it in your controller, just add it as an argument and type-hint it with the Request class:

use Symfony\Component\HttpFoundation\Request;

public function indexAction(Request $request, $firstName, $lastName)
{
  $page = $request->query->get('page', 1);

  // ...
}


You're using Drush 8, which requires a minimum PHP version of 5.4.5 (http://docs.drush.org/en/master/install/).

Your current version (5.3) doesn't understand short array syntax, hence the error you're seeing.

To fix, either upgrade PHP, or switch to an older branch of Drush.


You have to implement the hook_menu_alter and adjust the links weight property to your will. Here is a sample code that changes the node's default contextual links by placing the delete link over the edit link:

/**
 * Implements hook_menu_alter().
 */
function foo_menu_alter(&$items) {
  $items['node/%node/delete']['weight'] = 0;
  $items['node/%node/edit']['weight'] = 1;
}

Keep in mind that the smallest the weight of a link the more will flow on top, negative numbers may also be used.


You requirement can fulfill Views Field View module

  This module allows you to embed a view as a field in a view. A new
  field handler is made available, so this can also be used in area
  (header/footer/empty) handlers as well as rows.

  This view handler can accept arguments from fields of the parent view
  using tokens and pass them into the child view for each row. Raw or
  rendered token values can be used, as well as static values.


Webform Computed Data Display Grade and Text based on result

Yes, this is possible. Computed elements can trigger condition logic.  In your use case, you could hide/show a text field based on the score.  You might need to trim the computed element's whitespace to get the condition to trigger properly


Make field content as exposed filter dropdown

your question isn't 100% clear but it sounds like you want to display the nodes in a view and want to filter them with an exposed "brand" dropdown?
I also assume your "brand" field is a term reference to a vocabulary.

Create a view for the nodes and add a filter for "Content: Has taxonomy term" and select your "brand" vocabulary, "dropdown" as the filter type and "expose this filter".


How can I make a response cachable by browsers?

FinishResponseSubscriber overwrites the ETag header, unless your response meets certain conditions. That is it has to be cacheable and provides a custom Cache-Control header. When testing the code make sure you have browser caching enabled (in the performance settings).

Example:

  public function view() {
    $response = new CacheableResponse();
    $response->headers->set('Cache-Control', 'public, max-age=60');
    $response->setEtag('123');
    return $response;
  }

Besides browser caching you might also want to set Drupal caching data to invalidate the cached response when the content becomes outdated, see for example Invalidate cache on a REST endpoint.


Bundle fields for entity without type config entity not created

This is not answer to the problem I had but a workable solution nonetheless.
In the end I have created custom entity per each "bundle" that I have initially planned.

It actually resulted in less tables and also it provided option to handle logic that I have initially planned to do via plugins.

The only drawback of this solution are some route handlers where I have to provide the entity type via option parameter in order to be able to use single handler to get a page title, for example, due to the variable name "restriction" in route handlers.

Also in entity references or entity loader I have to use entity type only instead of entity type and bundle but that's totally fine.

I am using single entity base class, the same forms and so on so not that big of a deal(for now).


How to extends %module_x/templates/xyz.html.twig?

As of https://drupal.org/node/2143557 (committed January 24, 2014) you can now do this:

{% extends "@node/node.html.twig" %}

Note that the 'templates' directory is automatically included.


Ubercart - different payment gateway settings per product

There is a sandbox project for multiple gateways. I attempted to contact the developer a few days ago, but haven't heard back.

http://drupal.org/node/1106004

you select the profile in the product edit. Its not complete but close.


How to map Feed Importer with my content type?

How do I map that link with my content type? (note it's NOT the feed's link)

You're right your feed link is NOT a feed link. The URL is simply incorrect and this issue has nothing to do with Feeds module.

http://www.happynews.com/rss/.aspx returns 404 but when you dig a little you can quickly find that http://www.happynews.com/rss/ returns directories and other resources containing XML feeds.

For example https://www.happynews.com/rss/environment.aspx is a correct RSS channel titled "HappyNews - Environment" where you can see <item> XML nodes and each nested <title><description><link><pubDate> data.

To import such single channel you need:

create importer with HTTP Fetcher
and as a parser check Common syndication parser option
in fetcher settings you should provide RSS source channel link, so in Automatically add scheme input simply paste link to the channel you want to import like https://www.happynews.com/rss/environment.aspx
if right address is given Feeds fetcher will be able to"recognize" the scheme and all accessible fields should be visible on mapping tab in "Select a source" select field.

After all steps inluding RSS -> node fields mapping definitions you will be able to import data periodically (when CRON configured) or manually by running http://you-site-address/import

You can also attach importer to specific content type, this way source is imported by creating a node of that content type.
  .


How can i customize the output of "repeat rule" for human readability (german)?

I resolved this by just deleting the phrase by hand from the localized translation set.

I hope this won't trigger any other unwanted stuff.


Is there a way to create field collection table dropbox for added content in form

There's the field collection table module which provides a table-based widget and formatter for field collection fields.

It's not the same as the hierarchical select Dropbox but its worth a look, and would probably serve as a good place to start if you're thinking about coding your own solution.


Unable to retrieve node content with drupalgap

Ok, so with thanks to the advice about it being another module interfering with the retrieval of JSON data, I've identified the culprit through a process of elimination.

When I disable the "Node Registration" module the problem goes away and I can view node content through the mobile app.

Of course, that gives me another problem with how to get the functionality Node Registration was giving me, but I'll save that one for now...


How to recalculate the current User Points?

You should have used the Userpoints admin UI or its API (e.g. userpoints_userpointsapi()) to make changes in the records. That way you can make point adjustments without the problem of database integrity that you've introduced. If possible, I'd restore the DB rows and adjust the point records with the UI/APi.

In absence of that being a possibility, you can see that _userpoints_update_cache(), the function used for maintaining updated userpoints/userpoints_total tables, requires those tables to always be consistent, as they are referenced when transactions are added/updated/removed. Thus, the userpoints code won't be much help here.

You'll have to do an aggregate SQL query on the userpoints_txn table for each impacted user to determine their updated score and use that to update the userpoints/userpoints_total tables accordingly.


The File output (Generic File) is rendered from "file-link.html.twig" template file. To update the Link Text, you can override template_preprocess_file_link() in your theme's themename.theme file. So suppose if my theme name is bartik then function name will be bartik_preprocess_file_link(). Check example below:

use Drupal\Core\Template\Attribute;
use Drupal\file\Entity\File;
use Drupal\Core\Url;

/**
 * Implements hook_preprocess_HOOK() for file-link.html.twig.
 */
function [THEME_NAME]_preprocess_file_link(&$variables) {
  $file = $variables['file'];
  $options = array();

  $file_entity = ($file instanceof File) ? $file : File::load($file->fid);
  // @todo Wrap in file_url_transform_relative(). This is currently
  // impossible. As a work-around, we currently add the 'url.site' cache context
  // to ensure different file URLs are generated for different sites in a
  // multisite setup, including HTTP and HTTPS versions of the same site.
  // Fix in https://www.drupal.org/node/2646744.
  $url = file_create_url($file_entity->getFileUri());
  $variables['#cache']['contexts'][] = 'url.site';

  $mime_type = $file->getMimeType();
  // Set options as per anchor format described at
  // http://microformats.org/wiki/file-format-examples
  $options['attributes']['type'] = $mime_type . '; length=' . $file->getSize();

  // Use the description as the link text if available.
  if (empty($variables['description'])) {
    // Add new Link text here.
    $link_text = 'Download Code';
  }
  else {
    $link_text = $variables['description'];
    $options['attributes']['title'] = $file_entity->getFilename();
  }

  // Classes to add to the file field for icons.
  $classes = array(
    'file',
    // Add a specific class for each and every mime type.
    'file--mime-' . strtr($mime_type, array('/' => '-', '.' => '-')),
    // Add a more general class for groups of well known MIME types.
    'file--' . file_icon_class($mime_type),
  );

  // Set file classes to the options array.
  $variables['attributes'] = new Attribute($variables['attributes']);
  $variables['attributes']->addClass($classes);

  $variables['link'] = \Drupal::l($link_text, Url::fromUri($url, $options));
}

Or, you can create a custom field formatter which can be selected on Managed Display Page. as per example provided here, Create a custom field formatter.


How to customize the markup of radio buttons in the edit/create node view?

You can alter the output by overriding the following Drupal theme functions: theme_form_element, theme_radios, and theme_radio. (You won't need theme_radio unless you want to make changes to the <input> tag.)

Copy these functions into your theme's template.php file and replace "theme" in the function name with the name of your theme. Customize as needed. You will have to clear your cache in order for the changes to take affect.

In theme_form_element(), if you want to limit your changes to radio elements, you can add this condition:

if ($element['#type'] == 'radios' || $element['#type'] == 'radio') {
  // your stripped down mark-up here
}
else {
  // default mark-up
}

You can also check against other criteria such as #name and #id:

if (strpos($element['#id'], 'edit-group-content-access') !== FALSE) {
  // This form element has an id of 'edit-group-content-access-und-1' or 'edit-group-content-access-und-2'.
}

A real world example that only prints the wrapper for elements that ARE NOT radio elements (only alter the code that is shown and leave the rest as-is):

BEFORE

function mytheme_form_element($variables) {
  // ...
  $output = '
' . "\n";
  // ...
  $output .= "
\n";
  // ...
}

AFTER

function mytheme_form_element($variables) {
  // ...
  $output = '';
  if ($element['#type'] != 'radios' && $element['#type'] != 'radio') {
    $output = '
' . "\n";
  }
  // ...
  if ($element['#type'] != 'radios' && $element['#type'] != 'radio') {
    $output .= "
\n";
  }
  // ...
}

Bonus tip :): If you just want to alter the attributes of the wrapper, not remove it entirely, see this example.


How do I create e-products, and store order id+uid in my own tables in case of successful purchase via PayPal

OK, solved it with Conditional Actions!

I created a new product class on /admin/store/products/classes site. Let's call it "My Stuff" (class id: my_stuff).
The previous step created a new content type with the "My Stuff" name. So I went to "Create content > My Stuff" (/node/add/my-stuff).
I left "Product and its derivatives are shippable." UNCHECKED (as I didn't to be shipped). Gave it an own SKU, sell price, description, uploaded an image, etc. as usual. OK, product created.
Went to "Conditional actions" (/admin/store/ca ; don't forget to enable this module), "Add a predicate" (/admin/store/ca/add).
Gave it a title, set "Customer completes checkout" trigger, gave a description, set my own class, set status to Enabled, pushed "Save predicate" button.
Under "Conditions" tab, selected "Check an order's products", pushed "Add condition" button.
Under "Product models:", I selected the SKU given in step 3.
Clicked on "Actions" tab. Selected "Execute custom PHP code", pushed "Add action" button.
Here I could "play" with the $order and $account variables in my custom code, and this was the key. This way I could loop through $order->products array (with for or foreach), reach the customer's user id via $order->uid (or $account->uid), read quantities (in the loop, with e.g. $order->products[$product_index]->qty, where $product_index is the actual index of the loop steps) and save them in my own database tables with db_query() function. Everything needed could now be saved in my own tables where they could be handled the appropriate way, so everything works fine now. I'm happy.


Drupal Commerce - Database location of Shipping information

Drupal's entity data isn't really meant to be exported directly from the database. Is there no way for you to build a PHP script that uses the Drupal API to load and export these entities instead? Or an existing module like Patrick suggests?

Otherwise, you're going to need to pull information from a variety of tables. Shipping information is stored on an order's shipping customer profile. These are linked to the order via a customer profile reference field (whose table should be field_data_commerce_customer_shipping). From there you can find the customer profile ID you'll need to search for in the address field data, matching the profile ID against the entity_id in the field_data_commerce_customer_address table.


How do I show specific content on a separate page?

From what i understand, These tags can be taxonomy terms and you can create a view where you can use contextual filter to get the tag name from url and show the related news content.

1)Page "Property XYZ" will have a link as abc.com/news/tag1
2)You can create the view page with path /news/%
3)News content should be already having those tags,so that you can get it from that view.

If this is not what you are looking for please provide more details.

EDIT:
1)https://www.drupal.org/project/pathauto
You can use this module to create patterns according to your need for your each news node path alias.
You can use tokens of the taxonomy tag field to set those patterns.

For eg:
news/[node:title]/[node:field-news-category:1:name]
where field-news-category is the taxonomy reference field where you select tags terms

Now how to put these all these links in the menu is a different thing and that is up to you.

2)when you create a page view
set path as /news/% (% for just a tag) OR /news/%/%
(where first % can be news title and second can be tag)
% is the argument from url which is used in the contextual filter field

In right column of the view go to advanced and add a relationship field Content: Taxonomy terms on node
then add contextual filter field as Taxonomy term: Term ID

There should be a default view as Taxonomy term,which will give you some idea to go about it.
Play around a bit with contextual filters.

This might help,
Url Path Alias is not working with the "raw value from URL contextual filter"


How to specify default formatter for custom field widget?

Short answer is you can't. You can only specify a default formatter for each field type itself in hook_field_info():

  default_formatter: The machine name of the default formatter to be used by instances of this field type, when no formatter is specified in the instance definition. This formatter must be available whenever the field type is available (i.e. provided by the field type module, or by a module the field type module depends on).


I think u need to use javascript for this.
on the keypress event handler for the first textbox, u can get the text of the first textbox and update the second textbox using javascript itself


How could i configure drush to be always affirmative and verbose in a drush.ini-file?

Drush will not read options from php.ini / drush.ini by default.  Your best option would be to use a bash alias, or set $options['yes'] = TRUE; in a drushrc.php file.

If you really really have to set an option in drush.ini, you could hack this functionality by writing a policy file.  It would look something like this:

function policy_init() {
  if (ini_get('drush_yes')) {
    drush_set_option('yes', TRUE);
    // Drush does not expect a globla option to change
    // at this time, so you need to re-call _drush_preflight_global_options().
    // This is not a public API, so the name may change, etc.
    _drush_preflight_global_options();
  }
}

The only motivation I can see for doing this is if you already have some fancy mechanism for selecting your php.ini based on context.  If you wanted to do that, then put policy.drush.inc in ~/.drush, or some other location where Drush searches for commandfiles.

I have not tested this; post a follow-up comment if you really want to do this and have trouble with it.


How to move the "Main navigation" in the Bartik theme?

First the main navigation is a block. Under Structure->Blocks you'll see Navigation. Move it to where it makes sense to you. Secondly Structure->menu is where you determine what items appear in your menu.


Does a Context Condition Path need to exist?

Yes, the context module does not create pages, it allows you to position blocks on existing pages.

If you want a page that is not a node or a view you can use the empty page module or the panels module.

If you want a bunch of pages that are dynamic like FooBar/* where there are lots of sub pages, you could also create a custom module to create the pages, by using hook_menu() and returning an empty string for you page content.


Using hook_theme() when there is a preprocess

So, hook_theme is where you define your theme implementations and templates to use for them. In your case, that would look something like:

foo_alerts_theme() {
  $module_path = drupal_get_path('module', 'foo_alerts');
  return array(
    'alerts_theme_name' => array(
      'path' => $module_path . '/templates',
      'template' => 'alerts-theme-template-name',
      'variables' => array(
        'node' => NULL,
      );
    ),
  );
}

Your template file, named alerts-theme-template-name.tpl.php goes in the templates folder in your foo_alerts module folder. In your page preprocess you're going to pass in the node loaded from the alerts function to the theme function, so that would look like this:

function foo_alerts_preprocess_page(&$vars) {
  $vars['alerts'] = '';

  if ($nid = foo_alerts_check_alerts()) {
    $node = node_load($nid);

    if (isset($_COOKIE['alert'.$node->nid]) && $_COOKIE['alert'.$node->nid] == 'closed') {
      return;
    }

    $vars['alerts'] = theme('alerts_theme_name', array('node' => $node));
  }
}

That leaves all of the non-template logic still in the preprocess function, and returns the output of theme(), which will be the html from your template. Your template would then be something like this:

<div id="alert-bar" rel="<?php print $node->nid; ?>">

News Alerts:

    <?php if (isset($node->field_link['und'][0]['url'])) : ?>
      <?php print l($node->title, $node->field_link['und'][0]['url'], array(
        'attributes' => array(
          'title' -> $node->field_link['und'][0]['title'],
          'class' => array('alert-link'),
        ),
      )); ?>
    <?php else : ?>
      <?php print $node->title; ?>
    <?php endif; ?>

Does that all make sense? Do you see how the code the old dev team left you with got turned into this? If you have any questions, let me know and I'll try to explain better what I did.


This is core functionality in views and very easy to do with views relationships and entity references. Essentially, what you want to do is create a new entity reference field in your location content type to reference the workers, ex: "Related Workers". You would then add the workers to each of the locations using the normal edit form.

Now in the node output, you'll have a list of these referenced entities as a unordered list of links to the "Related Workers" node which you can customize using the display fields options.

To add these related workers (and all their fields) in a combined view (ex. the join you are referring to) you would just need to create a relationship, using this entity reference field.

This whole process is explained in this screencast from NodeOne

http://nodeone.se/sv/node/782


How to programatically create an address field

I had a similar question these days, and I tried to see if the Features module could help. Features worked to me.

You can create the field by the UI and then export a feature with the address field already created.
After that you can move the inc files for your custom module and add an include on your .module file:

include_once('[your_module].features.inc');

Then, you will need to add the some lines on your .info from the info file of the exported feature.

Your info file will need something like this:

dependencies[] = "features"
dependencies[] = "text"

features[field][] = "node-article-field_address"

This question may help you too: Develop a module that adds a new content type with custom fields.


Showing/Hiding Content-Type Fields Based On User

Yeah you could do that as well, though if you have lot of data hidding things on the server side would be better. You could just override the node template page, with something like :
node--nodeType.tpl.php, then in the variables of that page you will have your node with all its Fields available, you can then do a simple check (cookie or sessions) to render appropriate language.


Custom View : display fields linked to file upload field?

Thanks for the link, I'll read it.
I finally got an answer on drupal.org that suits perfectly.
The idea is to use the "Custom text" field :

  Add title, image, file and Custom Text field to your view.
  List item
  Edit Title, Image field and check exclude from display option and
  save.
  Edit File field and check exclude from display checkbox, In
  Formatter drop down select "URL to file" and save.
  Edit custom text field
  Click to "REPLACEMENT PATTERNS"

  Here you can find tokens for title, image and file fields. E.g. {{ title }} fir Title field and {{ field_image }} for image
  field.
  Copy {{ title }} {{ field_image }} and paste it to Text.
  Then click to "REWRITE RESULTS"
  Check "Output this field as a custom link" and enter File field token {{
  field_my_file }} to "Link Path" textfield. Save this field.
  Save the view and now its ready.


You need to create a 'Form Element' to process, validate, and render an input and corresponding 'WebformElement' to integrate the input with the Webform module.
You can use the Webform Example Element module as a starting point.


Change Pager-ItemsPerPage over URL argument

there is default option in views pager as "EXPOSED OPTIONS" while adding pager to views.

You can add range output.

So you can show per page option. set results using URL argument like http://example.com/path?limit=100


Error when viewing list of taxonomy terms

I got a similar error on my server too.
I had to change the function in TermStorage.php to get it to work.

Just a warning, this core hack and should be reverted once it is fixed in core.
Replace getTermIdsWithPendingRevisions() with the following:

  public function getTermIdsWithPendingRevisions() {
$table_mapping = $this->getTableMapping();
$id_field = $table_mapping->getColumnNames($this->entityType->getKey('id'))['value'];
$revision_field = $table_mapping->getColumnNames($this->entityType->getKey('revision'))['value'];
$rta_field = $table_mapping->getColumnNames($this->entityType->getKey('revision_translation_affected'))['value'];
$langcode_field = $table_mapping->getColumnNames($this->entityType->getKey('langcode'))['value'];
$revision_default_field = $table_mapping->getColumnNames($this->entityType->getRevisionMetadataKey('revision_default'))['value'];

$query = $this->database->select($this->getRevisionDataTable(), 'tfr');
$query->fields('tfr', [$id_field]);
$query->addExpression("MAX(tfr.$revision_field)", $revision_field);

$query->join($this->getRevisionTable(), 'tr', "tfr.$revision_field = tr.$revision_field AND tr.$revision_default_field = 0");

$inner_select = $this->database->select($this->getRevisionDataTable(), 't');
$inner_select->condition("t.$rta_field", '1');
$inner_select->fields('t', [$id_field, $langcode_field]);
$inner_select->addExpression("MAX(t.$revision_field)", $revision_field);
$inner_select
  ->groupBy("t.$id_field")
  ->groupBy("t.$langcode_field");

$query->join($inner_select, 'mr', "tfr.$revision_field = mr.$revision_field AND tfr.$langcode_field = mr.$langcode_field");

$query->groupBy("tfr.$id_field");
return 0;
//return $query->execute()->fetchAllKeyed(1, 0);

}


Load all configuration that has a particular config dependency?

Figured it out. You need to use wildcards and pass an array of potential matching values.

$form_displays = \Drupal::entityQuery('entity_form_display')
  ->condition('dependencies.config.*', ['field.field.paragraph.call_to_action.field_cta_text'])
  ->execute();


How to export content type with scheduler's settings using features

In addition to exporting "Content types", "Field bases" and "Field instances" you should also export all variables named "scheduler_*_[name of the content type]".

To be able to export variables Strongarm module should be installed.
Then on "Create Feature" page you will see section as on this screenshot.

BTW, lot of modules that extend content types save their configuration the same way, so you need include such variables in the the content type feature.


Programmatically add more than one taxonomy term in Drupal 7

You can just keep adding to the array the way you're already doing:

$newNode->field_tags[$newNode->language][]['tid'] = "a digit here";
$newNode->field_tags[$newNode->language][]['tid'] = "another digit here";

Or you could loop instead:

$tids = array(1, 2, 3);
foreach ($tids as $tid) {
  $newNode->field_tags[$newNode->language][]['tid'] = $tid;
}


Copy node.tpl.php of your theme and name it node--article.tpl.php. In this file create the html structure you like. In this file you have access to the individual fields.

<?php print render($content['field_customfieldname']); ?>

will print out content of your custom field. Wrap this filed with html id or class and style it with css.
(I am assuming you are working with a non core theme)


Url query - using a key with multiple values

How can I build a query that has parameters with multiple values separated by comma?

You already have, the commas are just encoded so they can be transported safely as part of the URL.

If you mean how can you stop the url() function from encoding special characters: you can't, without editing it. More specifically, you would need to replace its use of drupal_http_build_query with something that only selectively encodes special characters, much like drupal_http_build_query does itself for the / character.

The other options you have are

Do a string replace on the return value from url (or parse it and build it up again to your own spec)
Roll your own url function to your own spec
Contact the maintainers of the API and ask them to fix their decoding bug. Obviously YMMV on that.


You should be ok with regards to Google penalizing you because you've got a canonical link statement in each page which will tell Google that the page is really just a duplicate of the main page.

<link rel="canonical" href="/gadgets/best-racing-games-available-android">

Google canonical link info


Horizontal Tabs rendered as rendering collapsible fields

In commons_origins theme's template.php file, fieldset default functions are overridden("function commons_origins_fieldset"), pls comment or remove it to have display as tabs. Or clone this theme as custom theme in sites/all/themes folder and create as new theme by removing this function.


Error viewing articles/pages after assigning

Missing column of the contrib module indicates the corruption of the database. In your case workflow field is missing in content_moderation_state_field_data.

If this error start happening after upgrade, try running Database Update (either by going to /update.php or running drush updb command).

There is a Unofficial content_moderation 8.2.x to 8.3.0 upgrade path which can also help. It has relevant patches for content_moderation module with update hooks, which will migrate the tables accordingly.

Otherwise you'll have to reinstall the module, so its tables are re-created from scratch.