Create custom meta tag with the metatag module

You can either use Custom Meta module or roll your own module:

From Custom Meta project page:

  The module allows you to define and manage custom meta tags. Simply
  select the Meta attribute (property, name, http-equiv) and set the
  value and content value in the format and the module will add your
  meta tags to all non-admin content for your site.

An example of writing your own module:

my_metatag.info

name = My Metatags
description = Provides my custom Metatags.
core = 7.x
version = 7.x-1.x
dependencies[] = metatag
files[] = my_metatags.metatag.inc

my_metatag.module

<?php

/**
 * Implements hook_ctools_plugin_api().
 */
function my_metatags_ctools_plugin_api($owner, $api) {
  if ($owner == 'metatag' && $api == 'metatag') {
    return array('version' => 1);
  }
}

my_metatag.metatag.inc

<?php
//
// Implements hook_metatag_info().
//
function my_metatags_metatag_info() {
  $info['groups']['my_metatags'] = array(
    'label' => t('My Custom Metatags'),
  );

  $info['tags']['my_custom_metatag'] = array(
    'label' => t('My Custom Meta Tag'),
    'description' => t('This is a custom meta tag'),
    'class' => 'DrupalTextMetaTag',
    'group' => 'my_metatags',
  );

  return $info;
}

//
// Implements hook_metatag_config_default_alter().
//
function my_metatags_metatag_config_default_alter(array &$configs) {
  foreach ($configs as &$config) {
    switch ($config->instance) {
      case 'global':
        $config->config += array();
        break;

      case 'global:frontpage':
        $config->config += array();
        break;

      case 'node':
        $config->config += array(
          'my_custom_metatag' => array('value' => 'This is a default value.'),
        );
        break;

      case 'taxonomy_term':
        $config->config += array();
        break;

      case 'user':
        $config->config += array( );
        break;
    }
  }
}

Hope that helps.


PHP Fatal error: Call to a member function get_option() views/includes/view.inc on line 2493

Enable the Devel module and insert a ddebug_backtrace() statement before the line containing the get_option() method call. It should print out a stack trace that you can follow to some view id.


I'm not sure I understand your question. If it helps: this is a view. You can access views list from /admin/structure/views  and  that specific view from /admin/structure/views/view/blog/edit/page

There you'll be able to change the output of page display.


Getting all revisions of an entity with EntityFieldQuery

In this case, use db_select instead EntityFieldQuery to get all revisions from the revision table:

$result = db_select('your_entity_revision_table', 'yert')
    ->fields('yert')
    ->condition('entity_id', {your Entity ID})
    ->execute()
    ->fetchAllAssoc('revision_id');

kpr($result);


Add conditional javascript from CDN (external library)

The Boilerplate theme does it for CSS by adding to template.php in the theme:

function boilerplate_preprocess_html(&$vars) {
  if (!module_exists('conditional_styles')) {
    boilerplate_add_conditional_styles();
  }
}

function boilerplate_add_conditional_styles() {
  // Make a list of base themes and the current theme.
  $themes = $GLOBALS['base_theme_info'];
  $themes[] = $GLOBALS['theme_info'];
  foreach (array_keys($themes) as $key) {
    $theme_path = dirname($themes[$key]->filename) . '/';
    if (isset($themes[$key]->info['stylesheets-conditional'])) {
      foreach (array_keys($themes[$key]->info['stylesheets-conditional']) as $condition) {
        foreach (array_keys($themes[$key]->info['stylesheets-conditional'][$condition]) as $media) {
          foreach ($themes[$key]->info['stylesheets-conditional'][$condition][$media] as $stylesheet) {
            // Add each conditional stylesheet.
            drupal_add_css(
              $theme_path . $stylesheet,
              array(
                'group' => CSS_THEME,
                'browsers' => array(
                  'IE' => $condition,
                  '!IE' => FALSE,
                ),
                'every_page' => TRUE,
              )
            );
          }
        }
      }
    }
  }
}

Then added to the .info file:

stylesheets-conditional[lte IE 8][all][]  = css/compiled/ie8.css
stylesheets-conditional[lte IE 7][all][]  = css/compiled/ie7.css
stylesheets-conditional[lte IE 6][all][]  = css/compiled/ie6.css

I'm sure this could be easily adjusted for JavaScript instead


Pathauto URL alias Node taxonomy term translation

That is a bit complicated and is not possible with the normal translation methods.

You will need to use Entity Translation Module and Title module

Once you have the above modules configured you should have an option to include translated token for all the entities.


The newsletter module already has this built in by default.

Go into permissions and enable "Subscribe newsletters" to all roles.

Then, go to the Blocks UI and enable the "Newsletter: Subscribe" into the region of your choosing.


Views uses a lot of JavaScript, also AJAX to get latest info from the server. I had a similar problem a long time ago but that was because my Drupal instance was on my localhost and that gave errors with AJAX requests.


How to Skip the Workflow Launch by admin/user in Drupal-Commons using Maestro Module?

A solution we have used where we needed to have a menu item launch a workflow for expense approval using an entityform. The menu URL just needed to pass in the maestro workflow template_id

The callback function for the menu hook launches the workflow and then executes past the START task in the maestro template, to the first interactive task for the user (fill out form). It redirects the user to the task console and automatically opens the expense form to be filled in. The following code can be added to a custom module and re-purposed for your use.

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

  $items['pi_workflow/launch_eform'] = array(
    'title' => 'Launch Entityform Workflow',
    'page callback' => 'nextide_launch_eform_workflow',
    'page arguments' => array(2) ,      // Passing in wildcard which should be the maestro workflow template_id
    'type' => MENU_CALLBACK,
    'access arguments' => array('maestro taskconsole')
  );

  return $items;
}

/* Launch an entityform workflow where the first task
 * after the start task is the entityform task.
 * User will be redirected to the taskconsole and launch the first task (open form for editing)
 */
function nextide_launch_eform_workflow($template) {
  if (intval($template) > 0) {
    $sec_token = drupal_get_token('maestro_user');
    $new_process_id = maestro_launch_workflow($template, $sec_token);

    // Run the orchestrator to execute the first task after the start task which is the interactive entityform task
    maestro_orchestrator();
    $maestro = Maestro::createMaestroObject(1);
    $process_data = $maestro->engine()->getQueueHistory($new_process_id);

    $task = MaestroTask::createTaskObject($process_data[1]->id);
    $data = $task->prepareTask();
    $task_data = unserialize($data['serialized_data']);

    // Default will be to redirect user to the task console unless overlay module is available
    $link = 'maestro/taskconsole';
    $options = array();
    // Test that we have valid process data and then test for the task we are looking for to get the task id
    if (is_array($process_data) AND isset($process_data[1])) {
      // If overlay module is enabled and user has overlay permission, open entityform up in overlay
      if (module_exists('overlay') && overlay_get_mode() ) {
        $options = array('fragment' => "overlay=eform/submit/{$task_data['entityform_id']}/maestro/" . $process_data[1]->id);
      }
    }
    drupal_goto($link, $options);
  } else {
    drupal_set_message(t("New Process Code FAIL! - No Template ID Given"));
  }

}


"Add an item to a list" using rule just works for plain text

You have saved your textarea field as Plain text, change it to Filtered Text (in Text formats admin settings you should check allowed tags):


Is there any way to hide author information from custom article rather than content type?

No, but it would be easy to implement:

Add a Boolean field called show_author_info or something
Create a node template for that content type in your theme (or for nodes in general if you don't need to specify a type)
Add a conditional to the template to only output the author information if the node has a positive value for that field


You don't need to pull the string, you can use the markup object in a string comparision directly:

$markup = \Drupal\Core\Render\Markup::create('Test');

if ($markup == 'Test') {
  // the markup string is "Test"
}

When you want to use triple equals then you have to type cast the object to a string first:

if ((string) $markup === 'Test') {
  // the markup string is "Test"
}


500 internal server error while installing

As Clive says above, it's nearly impossible to help without knowing more about your particular setup and debug info.

Common pitfalls are :

Various php.ini settings : max_execution_time as mentioned by monymirza above, but also memory_limit. This last can be raised during install and dev, then lowered for production.
Lacking .htaccess at Drupal's root. Standard unix commands often don't copy hidden files, and .htaccess is more or less mandatory for D7 to work.
Lousy DB connection, particularly on shared hosting.
Misconfigured vhost : perhaps a particular setting messes up things between domains, or subdomains. Also, you have to check the AllowOverride All directive on Drupal directory for it to function properly.

There are others, but these should get you started.


Is there a way to convince drupal to take in into $form_state['values']

Yes...use the Form API :)

To expand; Drupal builds and caches the fields for a form on the server side, and uses that cache upon submission to make sure the form hasn't been altered. Drupal, rightly, sees the injection of arbitrary HTML into the structured form as an attack vector, a security hole which must be plugged up.

Consider what would happen if this weren't the case - a client using your form could inject some HTML form values, overriding your particular intentions for the form submission. As Drupal cannot possibly reconcile the context in which that HTML string was added, it has no way to know if it's come from a trustworthy source.

Bottom line - if you want to add a field to a form that's managed by the form API, your code absolutely needs to conform to the same API - the alternative is to fight against it, which is never fun.

It's physically possible to get around the validation, but the amount of time it would take to convince Drupal to accept your injected form values, and at the same time keep it secure, would far outweigh how long it would take to use the form API as it was intended.


Couldn't avoid duplicates and merge rows on my views

Consider using the Views Distinct module. From its project page:

  Relationships or other joins in Views often create "duplicate" results. For example, a node with a field that has multiple values may show up in the View once per value in the multi-value field. It's frustrating, and the "DISTINCT" SQL query option in the Views UI does not actually solve the problem because the result row is technically distinct. This module aims to give a simple GUI method to remove or aggregate these "duplicate" rows.


In your sites/default/settings.php file, comment the $base_url line, you don't need to specify one, Drupal can do it for you.
In your .htaccess, uncomment RewriteEngine on
In the same file, RewriteBase / must be  also uncommented, and if your website is hosted under a subfolder of your root web folder, you must specify your folder  here. Eg: RewriteBase /subfolder/
Activate clean URL's in admin/config/search/clean-urls
In apache httpd.conf file, check if mod_rewrite is enabled


Print out a Drupal Commerce field only if it has a value

Content for the referenced product fields is incorporated into the product display(node) using field_extra_fields and normally contents go into the #markup key.

You can use template_preprocess_node and use something like this:

if (!isset($variables['content']['product:field_NAME']['#markup'])) {
  unset($variables['content']['product:field_NAME']);
}

You could also try Field formatter conditions module.


You can use hook_js_alter() in a module. For example, this code replaces the jQuery library used by Drupal with the file present in the jquery_update directory.

function jquery_update_js_alter(&$javascript) {
  // Swap out jQuery to use an updated version of the library.
  $javascript['misc/jquery.js']['data'] = drupal_get_path('module', 'jquery_update') . '/jquery.js';
}

The same can be done for inline JavaScript code. The differences are:

Instead of 'misc/jquery.js', the first index is a number
$javascript[$index]['data'] will contain the JavaScript code

This means that first you have to find the entry for the JavaScript code to replace, and then alter it. The following code should work in this case.

function mymodule_js_alter(&$javascript) {
  $old_code = 'The code to alter';
  $new_code = 'The new code';

  foreach ($javascript as $index => $info) {
    if (is_numeric($index) && $info['data'] == $old_code) {
      $javascript[$index]['data'] = $new_code;
      break;
    }
  }
}

As alternative, if you need to alter the library implemented by a module, you can implement hook_library_alter(). For example, this is the code implemented by the latest version of the jQuery Update module.

function jquery_update_library_alter(&$javascript, $module) {

  // We are updating just the system module. For all other cases we return.
  if ($module != 'system') {
    return;
  }

  $path = drupal_get_path('module', 'jquery_update');

  // Make sure we inject either the minified or uncompressed version as desired.
  $min = variable_get('jquery_update_compression_type', 'min') == 'none' ? '' : '.min';
  $cdn = variable_get('jquery_update_jquery_cdn', 'none');

  // Replace jQuery with the latest version.
  $version = variable_get('jquery_update_jquery_version', '1.5');
  jquery_update_jquery_replace($javascript, $cdn, $path, $min, $version);

  // Replace jQuery UI with CDN or local files. If from a CDN include all of jQuery UI.
  jquery_update_jqueryui_replace($javascript, $cdn, $path, $min);

  // Replace the jQuery Cookie plugin.
  $javascript['cookie']['js']['misc/jquery.cookie.js']['data'] = $path . '/replace/ui/external/jquery.cookie.js';
  // Noting the version based on git commit as no version number is available.
  $javascript['cookie']['version'] = '67fb34f6a866c40d0570';

  // Replace jQuery Form plugin.
  $javascript['jquery.form']['js']['misc/jquery.form.js']['data'] = $path . '/replace/misc/jquery.form' . $min . '.js';
  $javascript['jquery.form']['version'] = '2.69';

  // Replace files for jQuery 1.7 and up
  if (version_compare($version, '1.7', '>=')) {
    $javascript['drupal.states']['js']['misc/states.js']['data'] = $path . '/replace/misc/1.7/states.js';
  }
}

This is valid also for JavaScript code used by Drupal core, since for those JavaScript files, the System module implements hook_library(). (See system_library().)

hook_js_alter() can be used for any JavaScript file/code, even for files used by Drupal core. Between hook_js_alter() and hook_library_alter(), it is preferable to implement the latter, when the JavaScript files are exposed as library.


Using PHP in your body field is considered bad practice. Read: What are the downsides of using PHP Filter code in blocks, nodes, views-args, etc?

Even in the module page it clearly says:

  Warning

  Enabling this module can cause security and performance issues as it
  allows users to execute PHP code on your site. There are better
  alternatives out there that do not expose such vulnerabilities on your
  site.

The proper way to add your PHP:

Use a preprocess function in theme_name.theme located in your theme's folder.
Create a custom module that uses hooks or preprocess functions.

Furthermore, Twig has several filters and functions that you can make use of. Which in some cases, you don't even need to use PHP at all.


How can i modify the height of input textfield in login form in drupal 7?

The easiest way to do this, is with CSS

An example could be:

.form-submit {
  height: 30px;
 }

You can't set height on textfields and submit buttons AFAIK, only text areas.


how to display labels of empty profile fields

Use the Empty Fields module. With this you can place custom text as filler until content has been entered. This will have the labels show up.


You need to implement hook_views_data() just like in Drupal 7. See comment.views.inc.


Adding a CSS class to every form in Drupal 6 in a theme

Override the theme function theme_form(). See About overriding themable output for an explanation of how to override theme functions.


Remove "required" status from the Date field

This is most probably because you don't just use a simple datefield, but one provided by e.g. the Date Module.

You should make sure that the module implementing your custom hook_form_alter runs last. That way, no other module can change it back to "required" again.

Furthermore, some modules implement a different "required" allthogether. E.g. the business-logic "if start-date is set then end-date is required too" cannot be implemented with simple "required" flags but will fire on the hook_validations for that form.

To override that, you will need to either exclude certain validations from running, by removing them from the element_validate or from the entire forms #validate.

You might want to replace these original validations with your own copies, to be sure you don't change ugly behaviour.


I assume that you have your entity reference field (pointing to speaker) on the content type "Presentation" below and that it is called "field_speaker".

In Views add a new View. Choose Show:Content (nodes), of type: Presentation.

Now you have all your presentations listed, with their titles. Let's leave it at that for now.

Open up Advanced to the right and open up Relationships, choose "Entity Reference: Referenced Entity - A bridge to the Content entity that is referenced via field_speaker".

Now we have the same result as before but we will be able to fetch data for the speaker through the relationship in the content type Presentation.

Under fields, click add and add the field called "Content: Title", now you have a dropdown that says "Relationship". Choose the only on available (field_speaker). Click apply.

You now have each presentation listed with it's title and the title of the presentations speaker.

Now you can go ahead and add the fields you wanted, sort the list etc.


template_preprocess_HOOK: what do I put for HOOK?

The HOOK corresponds to the theme function or template you are preprocessing.

If you wanted to alter page.tpl.php, you would use function MYTHEME_preprocess_page(&$variables).

If you wanted to alter theme_item_list(), you would use function MYTHEME_preprocess_item_list(&$variables).

A note, any dashes should be converted to underscores.

So views-view.tpl.php would be altered by function MYTHEME_preprocess_views_view(&$variables).


How can I set default value (prepopulate) for field in views exposed filter?

Dimetry. Since it is a drupal view you can add the default value in views itself. Please open your view and in the Filter Criteria section select the field you want to add the default value. It opens up a popup in that you can able to see "Value" field. Please give your default value there.

Please see the below picture for your reference.


You can do the access check from hook_mail_alter instead of hook_mail (let it prepare the default message based on parameters, and alter it later) by something like:

function HOOK_mail_alter(&$message) {
  // can add additional check for particular mails here,
  // by checking the value in $message['id']
  if (TRUE) {
    $message['send'] = FALSE;
  }
}

Note: You should clear the cache in order to make the changes effective.


You can use hook_permission() in your module. This allows you to add a custom permission. For example:

return array(
  'your permission name' => array(
    'title' => t('your permission title'),
    'description' => t('Description.'),
  ),
);

Afterwards, go to the permission page and set the ticks where you need them.


Composer is git cloning modules instead of download them?

Yes, that's what it does when you specify a dev version.

The recommended way to handle a composer project is to not commit composer managed code. all you commit is the composer.lock file and it is guaranteed that a composer install with install the exacty same versions, every time.

See https://getcomposer.org/doc/faqs/should-i-commit-the-dependencies-in-my-vendor-directory.md for more information on that and ways to work around it if you really want to.

Have a look at https://github.com/drupal-composer/drupal-project, it gives you a project environment that is preconfigured using the recommended git ignore settings and follows modern standard by keeping the vendor folder and other non-publich files out of the public web folder.

Update: One of the reasons why git does it, is that drupal.org AFAIK does not give you the possibly to download a specific dev snapshot, only the latest. And one of the main features of composer is to build the lock file and get the very same commit every time you run composer install, until you run composer update again.


Why do I get a backup file that has three different sizes?

456kb does sound very small, maybe you don't have much content/field data? Backup and migrate will exclude data from core cache tables, and the sessions and watchdog tables (though not cache tables installed by contrib modules) by default; so that might account for it. It's also probably gzipped.
An export through phpmyadmin will include all those tables (and perhaps isn't gzipped), so it should be larger than the backup and migrate version
The size of the database on disk, on the server, isn't and can't be proportional to the size of an SQL dump file. There are indexes and other meta data which take up space, so it will almost always have a larger footprint.

You don't need the cache table data, so as soon as you've confirmed that the dump from backup and migrate has the content you need in it (always a good idea to check), you should use that one going forward.


Any risks associated with habitually updating/reverting ALL features in drush?

In my opinion, first and foremost thing which should be taken into consideration is that your feature should not have any changes different from your development environment.

secondly, make sure that all of the fields of a content type have same type and widget as that are in your production environment.

You can also take backup of the db before reverting the features in case you are making any major changes.


Move file to specific folder after upload in forum

Here is how I implemented it using hook_node_insert() function.

function modulealter_node_insert($node) {
    // See if a file has been added
    if ($file_items = field_get_items('node', $node, 'field_file_attachment')) {
        // Get the first file item
        $file_item = array_shift($file_items);

        // Load the file object from the cache/database
        $file = file_load($file_item['fid']);

        // The path to the file is in $file->uri
        //var_dump($node->group_audience['und']['0']['gid']);

        //Set the destination folder where do you want to move it
        $destination = "private://filedepot/filedepot/test/".$file->filename;
        $file = file_copy($file, $destination, FILE_EXISTS_REPLACE);
    }
}


If a user does not have a role, keep redirecting them to the same form until they complete it?

You can use hook_entity_view, this is called when a user views any entity type, also hook_ENTITY_TYPE_view can be used if you want to redirect on specific entity type view like node.


Custom user profile titles interfering with user views block

You could check the url using the arg function and only set the title if the current page is a user/* page. You could try something like the following.

function MYMODULE_user_view($account, $view_mode, $langcode) {
  if (arg(0) == 'user') {
    $wrapper = entity_metadata_wrapper('user', $account);
    $auth_name = $wrapper->field_account_auth_name->value();
    if ($auth_name) {
      drupal_set_title('Profile overview for ' . $auth_name;
    } else {
      drupal_set_title('Profile overview for ' . $account->name);
    }
  }
}


Howto drag & drop field images in editor

Insert is a utility that makes inserting images and links to
  files into text areas or WYSIWYGs much easier. It adds a simple
  JavaScript-based button to FileField and ImageField widgets. When used
  with ImageField and ImageCache, images may be inserted into text areas
  with a specific ImageCache preset.

2) Vimeo Screencast Colorbox for Drupal 7, part 2: Inline images with the Insert module


Best module where you create a block and select a node from drop-down to render?

The Nodes In Block module seems to give you the desired outcome - albeit a different workflow to what you described. Here is an excerpt about it from the module's project page:

  ... makes it possible to add nodes into a block. A number of configurable blocks are generated which you can assign to a region. Visibility settings of this block are automatically set to 'Show on only the listed pages'. On the node content form, you define the weight and visibility per node thus making it easier for content administration as all your content is now in the same place. With this module, you don't have to explain your customers how blocks work but is still able to decide on which pages content must be rendered.


Limit Teaser to display only the first value of a Field

Create a custom module, replace MODULENAME with the name of the module and field_image with the name of your field:

/**
 * Implements hook_entity_view().
 */
function MODULENAME_entity_view($entity, $type, $view_mode, $langcode) {
  if ($view_mode == 'teaser') {
    $entity->content['field_image']['#items'] = array_slice($entity->content['field_image']['#items'], 0, 1);
  }
}

See the hook_entity_view() documentation for more details.


How to find the cause of 'The following module has moved within the system'?

It might be tough to find the module that causes your error message.

However, you may want to have a look at 'How to fix "The following module is missing from the file system..." warning messages' which describes a few possible causes and corresponding solutions, such as:

You removed a module from the file system without disabling and uninstalling it.
You moved the module inside your Drupal installation.
Leftover fields or other configuration entries.
Obsolete modules existed from a previous Drupal version.
There is a bug in a module installed on your site.

The one I ever used in the past (to get rid of that message) is to use the module 'Module Missing Message Fixer' (also mentioned on that same page).


Changing '#view_mode' in content type's render array

function team_bio_node_view(array &$build, \Drupal\Core\Entity\EntityInterface $entity, \Drupal\Core\Entity\Display\EntityViewDisplayInterface $display, $view_mode) {
  if($entity->bundle() == 'about_us'){
    if($view_mode == 'full'){
     if($display->getComponent('field_team_bio')){

       $team_bios_full = [
        '#theme' => ['team_bio_full_wrapper'],
        '#weight' => $build['field_team_bio']['#weight'] + 1,
       ];

    foreach(Element::children($build['field_team_bio']) as $delta){
      $team_bio_full = $build['field_team_bio'][$delta];
      $team_bio_full['#view_mode'] = 'default';

      $team_bios_full['#team_bios'][] = $team_bio_full;
    }

    $build['team_bios_full'] = $team_bios_full;
  }
 }
}
}

Then I passed team-bios-full-wrapper into class and render it.Like this:

{%
  set classes = [
  'team-bios-full-wrapper',
  ]
%}
<div{{ attributes.addClass(classes) }}>{{ team_bios }}</div>

Sorry i have different variables, i just rethought and rewrote the code. Hope this helps out someone.


In Drupal 7, the template file that sets the title shown in the browser page is html.tpl.php, while the template that sets the page title is page.tpl.php.

Both the templates don't receive a variable containing the user object to which the page is referring, as those templates are used for every page. If you want to change the titles only for user pages, then you need to get the user object using menu_get_object('user'). The function returns FALSE if the currently shown page is not a user profile page; that is what happens when the viewed page is, e.g., example.com/node/1.


How do I declare my custom entities as non-multilingual?

Translatability for config and content entities is different. Translation handler is a content entity thing. Storage for translations needs to be explicitly enabled by adding a data table.

For config entities, it's different. Translatability works automatically there through config overrides. There's nothing that you need to do to opt-in to being translatable, but you also can't prevent it. What you can is control which properties are translatable through the config schema. Like the label,which is, technically, a translatable, user-provided string.

If you don't need it translated, just don't create any translations for it  or if you don't need any configuration translations, don't enable the config translation module.


How to prevent pager_default_initialize from getting initialized?

The easiest way would be to override theme_pager():

function MYTHEME_pager($variables) {
  if (!pager_is_disabled()) {
    return theme_pager($variables);
  }
  return '';
}

Where pager_is_disabled() is a function you write that determines the current status. You could store that info in static vars, a Drupal variable, database, cache, whatever makes most sense for your use case.


Programmatically set active facets on non search page

So, despite the overwhelming response ;) after about 20 hours of banging my head against the desk I have this figured. I'm not sure if it is the most efficient way to do this, but I don't think the overheads are massive.

I did end up hooking into the adapter class but I couldn't find a facetapi hook that was called at the right time. In the end, I used hook_init.

You will need to get your parameters ($SOME_ID_VARIABLE) into the code. I used the current URL via request_path() and got node IDs from this.

The important bits of the code looks something like:

function MY_MODULE_init(){
  $searcher = 'search_api@MY_INDEX';
  $adapter = facetapi_adapter_load($searcher);
  $param_arr = array();

  $param_arr['f'][] = 'field_WHATEVER_FIELD:'.$SOME_ID_VARIABLE;
  $param_arr['q'] = 'VIEWS_SEARCH_PAGE/search';
  $adapter->setParams($param_arr);
}

Oh, and you still need to use a views facet block to get the facets to show up on the non-search page. I have used some caching on this block and everything still seems to work as expected.

The info on this page got me going in the right direction.


How close the admin overlay on submit for a drupal form shown within the admin overlay

I don't have experience with the admin overlay, but from what you are writing, I understand that you want to add the class "overlay-close" to an element (admin overlay?) when submit button is pressed. You can adapt the following code for that:

$('#form_id').submit(function(){
  // Add "overlay-close" class to the proper element
  $('#element').addClass('overlay-close');
});


Disable Commerce Card on File for Donation Product Type

If you go to the Payment method configuration screen (admin/commerce/config/payment-methods), you'll see that each payment method is a rule. If you click on 'edit' you'll get a rules configuration screen.

Next, click on "Add condition" under the conditions section. Here you can choose the various conditions that allow (or disallow) a payment method to be selected.

You've got the order object here so you can choose 'Order contains a particular product'.

Then enter the SKU of your donation product in the field provided:

Finally, make sure 'Negate' at the bottom of the rule configuration page is checked.

Now that payment option will only show up if the order does not contain that product.


is it possible to edit default output of services module?

Using the Services API this is possible: http://cgit.drupalcode.org/services/tree/docs/services.alter.api.php?h=7.x-3.x

/**
 * Implements hook_services_request_postprocess_alter().
 */
function example_services_request_postprocess_alter($controller, $args, &$result) {
  switch ($controller['callback']) {
    case '_node_resource_retrieve':
      $result->foo = 'bar';
      break;
    case '_user_resource_retrieve':
      $result->bar = 'chew';
      break;
  }
}

You could use the Views JSON module (a sub module of the Views datasource module) to build a View with a User ID contextual filter, and then return the field(s) you want for that particular user.


Make block visible to specific IP (in D6)

The commentators questions and remarks pointed me in the right direction, so here's the solution to my own question:

With page caching enabled, the above PHP condition is evaluated only occasionally on cache rebuild. If someone with the correct IP visits the site at the right moment the block can get visible and cached. Visitors with the wrong IP may then also see it (from the cache). Therefore the above approach is wrong.

Correct solution: Use IP login to authenticate some real or special user, then make the block visible to this user with the PHP condition:

<?php
  global $user;
  if($user->uid==123) {
    return true;
  } else {
    return false;
  }
?>

Of course, one could also define a new group and use the group-based visibility settings.


Per language menu item settings in node forms

Okay the problem was that I used the Node view permissions module. Which works perfect but not for multilingual websites. That's why they also made Now view language permissions. By installing this and uninstalling the Node view permissions module the problem was solved.

Now it is possible to create a node and its translation and add them to the menu. By unpublishing the translation you see the default one in the menu and hide the translation from the menu in the other language.


Products do not show under category in Commerce Kickstart

Here's the proper steps for creating a new product type with matching product display (so you always have a 1:1 relationship of content type to product variation type.)

When making a variant it will ask to create a matching content type for the product display - which it sounds like you've opted for this.

On your created Product Display content type, make sure you add the existing Product Category term reference field. The Commerce Kickstart 2 catalog is very specific to its initial setup (demo or no demo, regardless.) It does some work to hijack the callback path for the provided taxonomy vocabulary.

In fact, for best results you should make sure the new content type mimics the default product display until you're familiar with how it all works.

Lastly, Commerce Kickstart 2 comes with the Inline Entity Form module. It is opinionated that products will always be created from the node form, not individually. So make sure you're creating nodes and populating the products through there.


Autocomplete field where title is replaced with NID

You need the array keys to be nids, so change it to
$returnArray[$result->nid] = check_plain($result->title);


I fixed it using this solution
https://www.drupal.org/node/1578484

function mytheme_file_formatter_table($variables) {
  $header = array(t('Attachment'), t('Size'), t('Date'));
  $rows = array();
  foreach ($variables['items'] as $delta => $item) {
    $rows[] = array(
      theme('file_link', array('file' => (object) $item)),
      format_size($item['filesize']),
      format_date($item['timestamp'], $type = 'short'),
      );
  }
  return empty($rows) ? '' : theme('table', array('header' => $header, 'rows' => $rows));
}


Set #tree => TRUE on the parent elements, then the values will be nested accordingly


Display fields from a paragraph as a single field

If you wish to have absolute control on the display of your date range, I'd recommend you to create a module with a new FieldFormatter to expand one of the DateRange fieldformatters (the original files are in code/modules/datetime_range/src/Plugin/Field/FieldFormatter).

By overriding the viewElements() function, you'll be able to set the desired display(s) for your date range from one place and independent from the site theme files.

Once your new fieldformatter file is created, go to your paragraph "manage display" page and modify the display of your date range field to your new fieldformatter.

Hope this helps.


How can I disable "Delete the account and its content"?

You can implement hook_form_alter() in a custom module or theme to either remove the radio button entirely, or disable it which grays it out. You'd need to add additional logic to check the role of the user and disable it appropriately. I've shown both examples in the code example below, just uncomment the one you want to use.

function mymodule_form_alter(&$form, &$form_state, $form_id) {
  if ($form['#id'] == 'user-multiple-cancel-confirm') {
    // Set '#access' to FALSE to remove the radio button.
    // $form['user_cancel_method']['user_cancel_delete']['#access'] = FALSE;

    // Set '#disabled' to TRUE to disable the radio button.
    // $form['user_cancel_method']['user_cancel_delete']['#disabled'] = TRUE;
  }
}


Where should one add the js file (D7) to be attached to the custom theme's template.php file

Quick example of use in your theme's template.php

function MYTHEME_preprocess_page(&$variables) {
    drupal_add_js(drupal_get_path('theme', 'MYTHEME') .'/mytheme.js', 'file');
}

Reference : https://api.drupal.org/comment/14344#comment-14344


There are a couple of things you can try out:

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

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

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

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

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


I was able to solve for my use case by dropping the secondary function, and just using the following code:

function cs_menu_alter(&$items) {
  $items['user/%user/edit']['access arguments'] = array('administer users');
  $items['user/%user/edit']['access callback'] = 'user_access';
}


When you change the order, the changes are saved as the delta in the database. For example if your field was called file you would access $node->field_file[$node->language][delta]. In your example above, the second file would be $node->field_file[$node->language][1] as the first file would be 0


How to use Migrate module to import Videos?

I had to migrate a few thousand flv and mp4 videos. I ended up just migrating the file name into a field, uploading the videos files to s3 and then using a custom node.tpl.php to render the player:

<?php
  //display legacy videos
  $mediaid = $content['field_mediaid']['#items'][0]['value'];
  if ($mediaid != '') {
      $video2 = '';
              flowplayer_add('#player', array(
                'clip' => array(
                  'autoPlay' => TRUE
                ),
              ));
        print $video2;
 }
 //hide the mediaid field from display
 hide($content['field_mediaid']);
?>

Not very elegant but it got the job done. I used migrate 7.x-2.2 back then, maybe 2.5 has better video and/or file import features.


Instead of altering the menu link per role (which is tricky considering the process with which menus are built and cached), I would suggest you go for adding redirects per role.

The Url Redirect module should be able to help you achieve it.

  Url Redirect is a simple, flexible module for allowing user(s) / role(s) to redirect from one
  path to other.
  Url Redirect is also handy to add / edit / delete url(s) , specify role(s) / user(s) for url
  redirect, set a message for url redirect, enable / disable.


You shouldn't really try. If form is served via HTTP, attacker already stolen your user's data using MiM attack to inject his own JS code into your site, so sending it via HTTPS is pointless at this moment.

If you need reliable security, always serve form using encryption. If you don't, don't waste resources on unneeded SSL processing.

See Transport Layer Protection Cheat Sheet for more details, as Clive suggested.


The fastest possible way is to create a Views page and a Views block.
Then change the front page path with the one you used for the View (Configuration > Basic site settings > FRONT PAGE)
Then create the block instance in the Content region (Structure > Block layout)

Also, make sure you are using 2 different Pager ids in your view (in your view, under Pager > Settings > Pager ID) You may just use 1 for one of the views and 2 for the other one.


DrupalVM ubuntu 14.04 vagrant provision error 'packages cannot be authenticated'

I ended up reinstalling the host machine, Virtual Box and Vagrant. It seems like I broke something by manually deleting the Virtual Machine via the Virtual Box Admin Interface.

With the new installation and the same configuration it worked perfectly.

I suggest using vagrant destroy to delete your virtual machine files.


Changing the number of search results per page with the core search module

Overriding the hook implemented from the Node module is not possible because hook_search_execute() is invoked by search_data() using the following code.

  if (module_hook($module, 'search_execute')) {
    $results = module_invoke($module, 'search_execute', $keys, $conditions);
    if (module_hook($module, 'search_page')) {
      return module_invoke($module, 'search_page', $results);
    }
    else {
      return array(
        '#theme' => 'search_results',
        '#results' => $results,
        '#module' => $module,
      );
    }
  }

$module is the parameter passed to search_data(). hook_search_execute() is similarly to hook_form() which is invoked for the module implementing the content type, not for every module.

I was looking for a way to alter the query executed to search nodes, and the only way I found is to alter the page callback for search/node. That is the way that requires less code.  Otherwise, the only alternative I can think of is implementing a search module to replace the search tab implemented for the Node module.

Since Drupal uses hook_search_info(), but doesn't uses hook_search_info_alter(), and hook_search_info() doesn't return much useful data (at least to help overriding the search query), I think there aren't other alternatives.


Is there any way to take a preexisting field with content, and generate taxonomy from it?

It sounds like a job for an entity reference field

For example, add a "field_classes" entityreference field to "Instructor profile" referencing the class nodes that instructor teaches.

Alternatively, add a "field_instructor" entityreference field to the "Classes" content type, referencing the instructor profile(s) for that class.

Using Entity Reference, each content type can easily list the related instructors and classes.


Adding fields to content type edit form (not to the node itself)

It sounds like you need to create custom entities.
Try reading Creating a content entity type in Drupal 8 and maybe this module can help: Entity API


How to get my custom module to recognized a exported view?

The first part of a config item filename is the module responsible for the config type, not the module installing it.

In your case that's "views", so the file should be named views.view.user_assigned.yml.


How to delete a managed folder and its contents programmatically via hook_uninstall?

Drupal doesn't consider a folder to be a group of files, and doesn't have a method for bulk deleting managed files (like it does for unmanaged files: file_unmanaged_delete_recursive). So you'll need to identify which files you want to delete manually. A query with WHERE uri LIKE 'public://folder_name/%' might be sufficient in this case, for example, but you'll know you're own setup better than I can guess.

Once you have a list of file IDs, load up the objects, loop through them, and call file_delete on each. If you have the File Entity module installed, you can shorten this by using file_delete_multiple(), and just pass the IDs.

Once you're happy all the files have been deleted (you could stat the folder after running the loop), then remove the folder with drupal_rmdir().

Bear in mind that file_delete() is not guaranteed to remove the file; other parts of the system can declare their interest in a managed file by way of the file_usage table. If you want to unconditionally remove files regardless of any other entity in the system that they're attached to, you can use the file_usage_* methods in file.inc.


Is it possible to show only node contents in shadowbox pages?

For Drupal7:

Add to your theme template.php (or add inner of function code to existing function prepropress_page closer to the end) next function:

/**
 * Override or insert variables into the page templates.
 */
function YOURTHEME_preprocess_page(&$vars, $hook) {
  if (isset($_GET['shadow']) && $_GET['shadow']) {
    $vars['theme_hook_suggestions'][] = 'page__empty';
  }
}

Add page--empty.tpl.php to your theme folder - take original copy from page.tpl.php, but remove printing all header, sidebars, footer regions. E.g.:

<?php
/**
 * @file
 * Returns the HTML for Drupal page only with content region = empty page.
 */
?>
<?php if ($title): ?>

<?php print $title; ?>

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

Make shadowbox scripts added to any page (shadowbox ui settings), and you can do next anywhere:

About

So, any link with url?shadow=1 and rel="shadowbox" will shown on shadowbox popup window only content without sidebars. Control size of window on rel="shadowbox" as documented.

For shadowbox links that generated automatically (views, fields) you should override it via settings or template.


/admin path display login box along with access denied message (drupal 7)

You need to give anonymous users "View the administration theme" permission. Then to provide a login box along with the access denied message, use the Login Toboggan module.


How to solve limitations of 32-bit PHP in drupal 8

There is a "continue anyway" link at the bottom. I've had the same problem, but for the install process this is only a warning, and will not prevent you from using Drupal 8.

Also, credit to Clive for mentioning this first.


INPUT query for cache_menu returns mysql #2006 error in MAMP

Backup and migrate exports the database automatically without (large) values in the cache_menu table. Thus, re-exporting the database using the backup and migrate module solved the issue.


Custom Top Admin Menu: Intergrating Permissions

First of all I assume that the Admin Menu module isn't suffient for your needs? If not then I think you're approaching the custom module in the incorrect way.

Basically all menu routes in Drupal (node/add for example) use access arguments to determine who can access the route in question. So if you're looking to build a custom admin bar, I would rather create a new custom Drupal menu, and then add all my links in there. Then if a user does not have sufficient access rights to a menu route, Drupal will not display that specific link within the menu to the user.

If your menu links are coming from a custom module that you've written, you could apply the following example to include your module's menu items into your custom menu. You would use this within your hook_menu declarations:

$items['my/custom/route'] = array(
  'title' => 'Custom module section',
  'page callback' => 'mymodule_custom_page',
  'access callback' => 'mymodule_custom_access',
  'weight' => 0,
  'type' => MENU_NORMAL_ITEM,
  'menu_name' => 'my-custom-menu-id'
);

Using a custom menu instead of using your $my_links[] array you included above, will allow greater control over each menu item within the Drupal UI too.

*EDIT: provided further explanation based on comments*

Regarding your comments I still think your approach of implementing access controls within hook_preprocess_html is not the best way. We should always be looking to separate our application logic from our frontend logic, and using that hook to apply access control goes against that best practise.

I still recommend that you create a custom menu and then add your admin links and restructure as you want it to be. Then set which roles can create each content type within your system from here /admin/people/permissions, and Drupal will automatically exclude the link for content types the logged in user doesn't have access to.

With regards to displaying the menu, you can just assign the menu's block to a region within your theme, and use CSS to apply styling and positioning within the browser. You can also adjust the access permissions for the block, so only certain roles will ever see your custom menu. You can do this by editing the Visibility settings for menu's block.

Wow I didn't expect this to be such a long winded answer haha! :)


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

Create term ref field in User account
And under article cck, add term ref under "add existing field", only then this works!!

Documentation for this module has to be updated, wasted so much of time without proper documentation. Otherwise, great module.


How to limit Node refernce field selection to user own nodes?

You can create a View of type References, and then configure the Node Reference field to use that View.

So you configure the View to only list nodes that the current user is the author of, and any additional filters you want.  That should give you what you want.

Look for this area when you edit the Node Reference field:


Hide view when node's taxonomy value is empty

With the help of my co-worker, we were able to make it work by adding two contextual filters: one for category and one for department taxonomy:

All other check boxes unchecked.


Go to /admin/structure/block
Go to your theme (top tabs)
Move your login Block
WIN!


How to render a multiple value field of type generic file

That module provides formatters for the following field types:

entityreference
node_reference
user_reference
link
field_collection

(gathered from here).

There's no support for file fields so you'll need to either implement the functionality yourself, or file a feature request to the Textformatter issue queue.


How do i show/hide page content depending on the users role?

There are two good ways you could go about this.

Install Panels and
enable Page manager. Panels has a huge collection of what are called
'visibility rules' for individual panes. These allow you extremely
fine grained control over who sees what portion of the page. Panels
offers a lot of power, but brings a lot of complexity along with it.
Put your messages each in their own block. Blocks come with the ability to show and hide for certain roles.
This method is much simpler, but if you have a lot more content than just
the welcome message you want to show and hide panels
will end up being a more customizable solution.


How do I make the output of a View a particular Field?

Turns out my Field was there in that list, but its name was different. It had adopted that name of a Paragraph it was used on. Apparently, if the Field is used in a Paragraph, the name you give it in that instance will be trump any other names you give it.

I don't know why this is or why this feature is useful.


How can I allow front end users to add their own custom fields?

Use Field Collection module.

Install Field Collection module

Create a field collection field to a content type and set to unlimited.

Then create a fields with two text fields - "label" (for 'colour' and 'year') and "value" for that field collection

So when the node add form loads user will have two fields, Label and value with add more button there user can click and add another set of "label" and "value" pair.


The config system has switched already to events and the documentation for events describes in "My First Drupal 8 Event Subscriber" how to subscribe to a config event:

https://www.drupal.org/docs/8/creating-custom-modules/subscribe-to-and-dispatch-events

See also this example from the Color module:

/core/modules/color/src/EventSubscriber/ColorConfigCacheInvalidator.php

<?php

namespace Drupal\color\EventSubscriber;

use Drupal\Core\Cache\CacheTagsInvalidatorInterface;
use Drupal\Core\Config\ConfigCrudEvent;
use Drupal\Core\Config\ConfigEvents;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;

/**
 * A subscriber invalidating cache tags when color config objects are saved.
 */
class ColorConfigCacheInvalidator implements EventSubscriberInterface {

  /**
   * The cache tags invalidator.
   *
   * @var \Drupal\Core\Cache\CacheTagsInvalidatorInterface
   */
  protected $cacheTagsInvalidator;

  /**
   * Constructs a ColorConfigCacheInvalidator object.
   *
   * @param \Drupal\Core\Cache\CacheTagsInvalidatorInterface $cache_tags_invalidator
   *   The cache tags invalidator.
   */
  public function __construct(CacheTagsInvalidatorInterface $cache_tags_invalidator) {
    $this->cacheTagsInvalidator = $cache_tags_invalidator;
  }

  /**
   * Invalidate cache tags when a color theme config object changes.
   *
   * @param \Drupal\Core\Config\ConfigCrudEvent $event
   *   The Event to process.
   */
  public function onChange(ConfigCrudEvent $event) {
    // Changing a theme's color settings causes the theme's asset library
    // containing the color CSS file to be altered to use a different file.
    if (strpos($event->getConfig()->getName(), 'color.theme.') === 0) {
      $this->cacheTagsInvalidator->invalidateTags(['library_info']);
    }
  }

  /**
   * {@inheritdoc}
   */
  public static function getSubscribedEvents() {
    $events[ConfigEvents::SAVE][] = ['onChange'];
    $events[ConfigEvents::DELETE][] = ['onChange'];

    return $events;
  }

}


Elasticsearch-Connector: can't index with Search-API

Elasticsearch has deprecated the string type in 5.x versions, and is now using text or keyword. (see https://www.elastic.co/guide/en/elasticsearch/reference/5.5/string.html)

In /admin/config/search/search-api/<CLUSTER>/<INDEX>/fields, you may change string by text in ID field. Considering this is an integer -id-, you may choose the type integer.


I had the same situation: ajax login/register form until the fields are correctly filled, and then redirect the user to the logged in section.
This is what I used, and it works fine for me, in the ajax callback function:

ctools_include('ajax');
ctools_add_js('ajax-responder');

$commands[] = ctools_ajax_command_redirect('<front>');

return array('#type' => 'ajax', '#commands' => $commands);

the full function looks like this:

function ajax_signup_detailed_submit_callback($form, &$form_state)
{
  $commands = array();
  $messages = drupal_get_messages(NULL, FALSE);

  if (count($messages))
  {
    $commands[] = ajax_command_replace("#better-messages-wrapper", theme('status_messages'));
  }
  else
  {
    ctools_include('ajax');
    ctools_add_js('ajax-responder');
    $commands[] = ctools_ajax_command_redirect('<front>');
  }

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

Hope this helps,
Istvan


how to implement jquery image gallery in drupal theme tpl.php files?

If you want the bluemasters rotator exactly, you need to copy their javascript and css that apply to the rotator element (image_reel) and install it in your theme. The following instructions would also be relevant for other slideshow scripts with obvious substituions.

First, you need to add the rotator script from bluemasters to your theme. The name of the file is bluemasters.js and is in bluemasters/js/ in the theme folder.

To install it in your theme, you could just add it as a script tag in your page.tpl.php file in your template, ex:

There are much better ways of adding this, using drupal_add_js and page_preprocess functions but this is the easiest way to make sure it is loaded on every page.

Next, you're going to need to isolate the css bluemasters is using to create their slider. From their css file, it looks like all of the css for the front page slider is in one block in the file, starting with the comment 'Front-page slider'

/*
 * Front-page Slider
 */
.main_view { float: left; position: relative; }

...etc.

Grab that and add it to your theme's css file.

If you've got these two files added to your theme correctly, then anywhere the image_reel class exists (with the following structure) on your pages, their code will convert it into a slideshow. The exact structure (from their demo file) is just a list of links like this:

You can add this code in as a block or on a page or in your template directly and it will create the same slider effect.


How do I display tokens in a block using PHP code?

I dont recommend using PHP in a block for  many reasons.

I would recommend you to use proper implementation of hook_block_view and hook_block_info to do you custom PHP codes in there.


The Auto Assign Role module will allow this.

It allows you to:

Provide an automatic assignment of roles when a new account is created.
Allow the end user to choose their own role or roles when they create their account.
Provide paths that will trigger a specific role when an account is created.


In order to do this, I will create a custom module, an event, dispatch it in a  hook_ENTITY_TYPE_insert implementation and subscribe to it so that we can insert the data into different custom table.

https://x-team.com/blog/creating-and-subscribing-to-events/


Image title in Views replacement patterns?

The replacement pattern is:

{{ field_image__title }}

See this screenshot from Views:


I think from what I understand; you are trying to add each file(s) to its node folder public://results/[nid]/filename.ext

As solution to your issue, first you need to save the node before you attach the file(s) to it. Then move/save file(s) to its desired location. Then attach the moved file(s) to the selected node again.

Change your code to look like the following:

$result = new stdClass;
$result->type = "results";
node_object_prepare($result);

//add values to text fields here

// save node
node_save($result);

//open the source directory

$d = dir($seasonDir);

while(false !== ($entry = $d->read())) {
  if($entry != "." && $entry != "..") {

    $dir = 'public://results/' . $result->nid;
    // create folder str
    if(file_prepare_directory($dir, FILE_CREATE_DIRECTORY)) {

      //set the file location
      $fileLocation = $seasonDir . "/" . $entry;

      //get the file contents
      $fileContents = file_get_contents($fileLocation);

      //save the file - added nid as sub folder
      $file = file_save_data($fileContents, $dir . '/' . $entry, FILE_EXISTS_RENAME);

      // important if you are importing none image files
      $file->display = 1;

      // you don't need to copy files to an array anymore

      // create entity object to store file(s) to the node

      $entity = new stdClass();
      $entity->nid = $result->nid;
      $entity->vid = $result->vid;
      $entity->type  = $result->type;

      //create an array to assign to the various file fields
      $file_details = array(LANGUAGE_NONE => array('0' => (array)$file));

      switch($entry) {
        case "results.inc.html":
          $entity->field_results_html = $file_details;
          break;
        case"clubs.inc.html":
          $entity->field_clubs_html = $file_details;
          break;
        case "events.inc.html":
          $entity->field_events_html = $file_details;
          break;
        case "index.xml":
          $entity->field_results_index = $file_details;
          break;
        case "events.xml":
          $entity->field_results_events = $file_details;
          break;
        case "clubs.xml":
          $entity->field_results_clubs = $file_details;
          break;
        case "results.xml":
          $entity->field_results = $file_details;
          break;
        default:
          //because the resuls_files field allows multiple files, this
          //field has to use a different method of assigning the file
          $entity->results_files[LANGUAGE_NONE][] = (array)$file;
          break;
      }

      // save entity
      field_attach_presave('node', $entity);
      field_attach_update('node', $entity);
    }
  }
}
$d->close();


What's the best way to delete all content without a content type?

Due to an error during migration, some of the content has been left
  hanging without a content type and did not port over correctly

If you're comfortable writing code you could write an SQL query to look for nodes or entities without a type set -- and output or save their IDs to a list. You may be able to use EntityFieldQuery for this but it may blow up, I'm not sure.

Once you have the IDs of content missing it's type you could try to use Drush Entity on your site to delete the entities. It supports deleting a list of entities by their ID (I assume in the Node table). Below is an excerpt from entity.drush.inc

  $items['entity-delete'] = array(
    'description' => 'Delete entities.',
    'arguments' => array(
      'type' => $type,
      'nids' => $nids,
    ),
    'options' => array(
      'json' => $output_json,
      'bundles' => $bundles,
    ),
    'examples' => array(
      'entity-delete' => '.',
      'entity-delete node 64' => '.',
      'entity-delete node --type=story' => '.',
    ),
    'aliases' => array('ed'),
  );

So you could try to take your IDs and issue the command:

drush entity-delete node -v --nids=<list-of-nids-seperated-with-commas>

If this fails try:

drush entity-delete node --debug --nids=<list-of-nids>

Obviously you could try to do this all by hand with a query, and using node_delete() for instance, but I'm trying to find  you a slightly less programming intensive solution.

EDIT

1) ALWAYS BACKUP YOUR WEBSITE FILES + DB FIRST BEFORE ATTEMPTING DISASTER RECOVERY.

2) If the data is somehow improperly save and fragmented across disjointed tables good luck -- I've fixed mess-ups like this but end up scanning tables visually by hand and dropping obsolete fields or field_instances for example.


Drupal doesn't output list of children on custom module page

Another Solution here would be to do what the admin pages do for those pages

$items['admin/somemodule'] = array(
 'title' => 'My Module Section',
 'description' => 'Manage My Module',
 'page callback' => 'system_admin_menu_block_page',
 'access arguments' => array('access administration pages'),
 'file path' => drupal_get_path('module', 'system'),
 'file' => 'system.admin.inc',
);


Making columns into sort asc/desc in search api-based view

I figured this one out. I have to set the field to 'string' in Search API configuration > index > edit. The default is 'fulltext', which sounds right, but isn't for this usage.

Then you have to change the settings for the format: table to make the field sortable.


Under /admin/config/content/webform you can enable your event content type for webforms, and the form will be created as part of the node creation process.

Edit: Misunderstood!

Webforms are one-off forms. If I now understand correctly, you want to re-use a standard form on each event page (only one form created).

To do this, create a webform with the required fields, and while editing the form, go to the webform tab > Form Settings. Under Advanced Settings at the bottom select 'Available as Block'.

You can then use the Block settings to display the form on every Event page as required.


Clear your cache completely. Disable your current them and enable a core theme like Garland. If the error goes away, you'll know it's with your theme.

If not:

Was the database fully migrated?
Were your files (and theme!) fully
migrated?
When you say "standard" block.tpl.php file, where did it
come from? It should have come from /modules/block/block.tpl.php.


Clive's comment is right.  You should understand the reasons why, however,  I will give you the short answer ;)

Use db_select()

$query = db_select('challenges', 'c');
$query->fields('c');
$query->condition('c.cid', $id, '=');
$result = $query->execute();


Inject a theme setting form into a block

You can create a custom block: https://www.drupal.org/docs/8/creating-custom-modules/creating-custom-blocks/create-a-custom-block

In the build() method, you can return the form:

public function build() {
  return \Drupal::formBuilder()->getForm('Drupal\system\Form\ThemeSettingsForm');
}


Override templates for one view page or block

Yes.

The pattern will be something like views-view-promotions--display_name.html.twig

See https://api.drupal.org/api/drupal/core%21modules%21views%21views.theme.inc/group/views_templates/8.2.x

Also, I recommend you activate Twig debugging (https://www.drupal.org/docs/8/theming/twig/debugging-twig-templates) to see actual suggestions.


Ok, alright. I'm not going to kill anyone.

Turns out there was a line in my settings.php file:

  $GLOBALS['conf']['clean_url'] = 0;

Commented it and everything worked just fine.

That was 2 hours of my life wasted...


How can I theme the Views Exposed Filter?

Exposed filters use the form API, so you can implement a hook_form_FORM_ID_alter():

function MYMODULE_form_views_exposed_form_alter(&$form, &$form_state) {
  $view = $form_state['view'];

  if ($view->name == 'my_view' && $view->display == 'my_display') {
    // do something awesome
  }
}

Normal Form API procedures then apply.


Change shown fields in a grouped view depending on group

These types of problems are often solved by creating another Views display.

Add a Filter to your original Views to only show the results with the terms where you want to show the additional fields.
Then Duplicate this display as Attachment, attach it to the original views display.
Override the Attachment Filters and change the one for the terms - reverse the choices to filter out only the terms where you don't want additional fields
Override the Attachment Fields, remove the ones you don't want.

The Attachment results will display below or above the original results, depending on whether you choose to attach it After or Before.


Conflict with db_set_active and variable_get

I've been reading around, and on db_set_active  API page on d.o the 2 comments on that page mention the problem with caches and multi dbs.

So I went on to look at variable_get API page and it uses global $conf variable. I did a quick search on google on how to "refresh global variables conf" and got this page on d.o DrupalWebTestCase::refreshVariables(). Basically this function refreshes the global variables like so:

protected function refreshVariables() {
  global $conf;
  cache_clear_all('variables', 'cache_bootstrap');
  $conf = variable_initialize();
}

So I'm guessing (I haven't tried it and I don't have a multisite installation at hand to test it) you just need to utilise the code from the above function and clear the variables cache and re-initialize the variables in your foreach loop. I'm not sure how efficient it is so that's another issue if it's not efficient and slows down your page.

global $conf;
foreach ($multisites as $multisite) {
  // Not sure if cache_clear_all should be called before or after switching the database. You should test and figure out what's best.
  cache_clear_all('variables', 'cache_bootstrap');
  db_set_active($multisite['db']); //switch context
  // Re-set $conf global variable so when variable_get gets called it uses the updated $conf.
  $conf = variable_initialize();
  $links = language_negotiation_get_switch_links(...,...) // run core-function
  db_set_active(); //switch to default
}

Hope this helps steer you in the right direction. Good luck


The easiest way is just to add it on your theme's .info file:

scripts[] = js/my_jquery_plugin.js

The only exception is if you are adding an external resource (CDN/hosted script), in which case you should use drupal_add_js(), as explained by Jamie Hollern


If you use Display Suite, you can create a custom field with the Display Suite Format and use the following (with your own date field name). You could also use a custom PHP field or some kind of hook, but the following logic still applies.

<?php
if (!empty($entity->field_event_start)) {

    // Get the starting time value and the timezone.
    $start_value = $entity->field_event_start['und'][0]['value'];
    $timezone = $entity->field_event_start['und'][0]['timezone'];

    // Create the date objects for now and the day of the event.
    $start_date = new DateObject($start_value, $timezone);
    $now = new DateObject(time(), $timezone);

    // Take the difference between now and the beginning date, in days format.
    $duration = $now->difference($start_date, 'days');
    print $duration . ' Days';
}
?>

You should end of with something like the following, and then jazz it up with your own styling.

Edit

I just realized you wanted "since" as in after, so just switch it up a bit and use the end date instead of the start date, if one exists. I also made a quick video on how to add in the custom code field, so hopefully this helps!

Custom Date Since field in Display Suite


How i can popuplate user's facebook data into my built-in drupal register form?

The Dupal for Facebook module kind of does the trick.

The problem is that it uses soon to be deprecated FB APIs, and it isn't exactly Drupal 7 ready yet (though it's very well maintained and I am sure it'll catch up soon), so you might as well want to write your own module from scratch. These are the basic info you should check if you want to get into this

Get user Authentication and Permissions. (You will
probably need to also look into offline_access permissions.)
Access to the FB user object using the PHP SDK for Basic profile informations. It is session based, so you can access it from anywhere in your site, for instance to pre-populate you registration form. (Don't forget to include the PHP SDK to your script.)
Access or write other user data (e.g., activities, picture, wall feed) via the Graph API.


Contextual filters not allowing multiple values

I don't know if this would answer your questions, but I just noticed that, not only you need to check "Allow multiple values", you also need to specify "Term IDs separated by , or +" in the "Filter value type" select list.

(using Views 7.x-3.14 at the moment)


How do I get a block to use a URL to configure a contextual filter?

A views page can read the url and use a path for the page to read a taxonomy term input for a contextual filter.  A URL such as example.com/a/term/b would be read by the view page with a path of a/%/b.  The value for the % in the URL is passed in to the contextual filter to determine what content to include in the view.

Since a block doesn’t possess a path it is necessary to do a bit more configuration to achieve the result. To do so:

Click on the contextual filter on the block view form in views.
Under When the filter value is NOT available select Provide default value.

If the page in the path is a taxonomy term try this step 3 and 4:

Choose Taxonomy term ID from URL from the Type drop-down box.
Check Load default filter from term page.

Or otherwise try this:

Choose Raw value from URL
Identify which part of the URL is the term. eg. for A/term/B the term is in the second position.

Then:

Under When the filter value IS in the URL or a default is provided check "Specify Validation criteria"
Select Taxonomy term and the specific vocabulary being used.
Under Filter Value type pick term name converted to term ID"
Checking Transform dashes in URL to spaces in term name filter values will ensure that any auto generated path alias' that have converted spaces to dashes are properly handled. Try your view with this checked and unchecked.

If your view is not appearing on the page troubleshooting steps should include verifying that the view works by testing input in the view preview. Make certain that any spaces are handled to match up with the setting in step 8. Also make certain that your view block is exposed in admin/structure/block.


open a modal just before submit to get an answer yes or no and then submit

Create a file named as 'search_result.js' and include it into the particular module using drupal_add_js(path/filename.js); and the copy and phaste the following code into search_result.js

 (function($, Drupal, window, document, undefined) {

Drupal.behaviors.searchResults = {
  attach: function(context, settings) {

       $("#elementID").click(function(){
        if(confirm("Are you sure that you want to proceed?")){
            return true;
            }
        else {
            return false;
            }
        });
  }

}
})(jQuery, Drupal, this, this.document);

Note: "#elementID" is the id of the element on which when you click the confirm window is shown


Well, here is the code that I've put in place. So far it's respecting the CSS selector patterns that the WordPress theme rendered.

       <?php
       print theme('links__system_main_menu', array(
         'links' => $main_menu,
         'attributes' => array(
           'id' => 'nav',
           'class' => array('menu')),
         'heading' => t(''))
       );
       ?>


content is just the render array composed of renderable elements.

If you want to break up the fields, then you need to not use {{ content }} and instead call each field where you want them:

{{ content.field_MYFIELD }}

Those fields are controlled by their field templates.

An improvement on your code would be to not check for view modes in one template, but just make each view mode a template like node--article--teaser.html.twig, node--article--full.html.twig, node--article--some-other-mode.html.twig. It will make your code cleaner.

So you'll need to debug and find what the content variable has, and just start outputting it where you want them to render in the template.


You can use any sms integration api. I personally like Twilio.

There is a module for twilio integration as well: link

You will need to find a place from where the email has been sent, it would be in the code or possibly through Rule module, in either case you need to add a line of code which should utilize twilio api and send sms to the destined users.


Printing out translated Views' variables

$title = $view->get_title();

Views' human-readable name is just for developers and is not translated by i18nviews. You might want to get title.


How to send email when customer cancel payment?

I think you can implement it via the module Rules

Just add the action "Send email" for a custom rule that has the "order state changes" event conditionally on order state "cancelled."


How to check a boolean value in twig templates?

Time for another promotion of my blogpost from a while ago :)

https://www.md-systems.ch/en/blog/techblog/2017/02/20/twig-and-entity-field-api-or-how-to-take-control-of-nodehtmltwig

The relevant part:

Only display a field if a checkbox is checked, optionally with custom wrapping HTML.

{% if node.field_checkbox.value %}
   <div class="only added when there are values">
  {{ content.field_name }}
  </div>
{% endif %}

You don't need == '1' or same as or anything like that, because it directly evaluates as to a boolean value. I also wouldn't recommend to use type safe checks with content entities because they are not type safe. Values are stored in the database and anything coming out from there is a string but sometimes values might not be. The boolean field is actually the perfect example for that, it is a string one, aka a nice mix of 3 different data types.


How to use URL as a filter in view module?

You need to add a Contextual filter under the Advanced pane in your view's edit page.

Look for your field, it would probably be Content: News type then add the field
Under WHEN THE FILTER VALUE IS NOT IN THE URL select Provide default value
Choose Raw value from URL for Type
Choose 2 for Path component
Check Use path alias


Since I answered this in IRC, I'll rewrite the answer.

block--user--login.tpl.php

The easiest way to find all of the possibilities for naming template files is to put print_r($variables['theme_hook_suggestions']); at the end of your theme's template_preprocess_HOOK(). Doing so works great for block, node, page...


You are not doing the query quite right.  There are a few things you are missing.

You need to remember that fields can be on multiple entity types, and that entity IDs are not unique globally.  This needs to be part of the JOIN clause.

The other is that there is a deleted column, that represents whether the data item has been deleted or not.  This also needs to be part of the JOIN clause.

You also need to ensure node access rights are maintained for any query against the {node} table.

EntityFieldQuery will take care of all of this for you.  Otherwise, you should use db_select() to build the query, as you can ->addTag('node_access') the query.

Something like this would be a start for node entities:

$query = db_select('node', 'n')
  ->addTag('node_access');

$query->join('field_data_field_products f', 'f.entity_id = n.nid AND f.entity_type = :entity_type AND f.deleted = :deleted', array(
  ':entity_type' => 'node',
  ':deleted', 0,
));

$query->fields('n', array(...))
  ->fields('f', array(...))

You would modify this to use different tables and types for different entities.  If you aren't querying against the {node} table, then you can skip the ->addtag();

If you end up using EFQ, remember that it only returns the entity_ids, so you have to entity_load() the results (or use the entity specific version like node_load()).

Regarding the query, it is a good habit to put your base table first and then join the secondary tables.  This helps with readability.  You should also try to explicitly pick the fields you need and avoid * results.  There is no rule against this, it is just considered best practice by some.


Is it possible for 3rd Party Script to Create Users

And also it's very simple to create users in D8 by program:

$newuser = \Drupal\user\Entity\User::create([
          'name' => $name,
          'pass' => $pass,
          'mail' => $mail,
          'status' => 1,  // or 0 if inactive
          'init' => $initmail,
          'created' => time(),
          'login' => 0,
          'access' => 0,
        ]);
      $newuser->addRole("myrole");
      $rc = $newuser->save();
      if ($rc == SAVED_NEW) {
    ...whatever...
    }

For bootstrapping external scripts, you can look i.e. here: Bootstrap from external script


Yes, it is possible. Firstly you need to read and understand the Drupal 7 Template (Theme Hook) Suggestions documentation to render and rearranging field items.To alter Title , Body, Save etc you will need to understand hook_form_alter, it is used for altering a form and hook_form_FORM_ID_alter is a smarter way to do the same as hook_form_alter.There is a cool hook_form_alter tutorial hope will help you.


Why is ddebug_backtrace coming up blank?

For me the command had to be called without the extra d

dpm(debug_backtrace());


Rule condition to check which language is used by the visitor?

Seemed like a useful thing to have.

I created a patch for Rules, adding this functionality. I posted it in the Rules issue queue. That seemed better than providing the code directly here, as this way you can still use it anyway that suits you, yet it may actually get into core Rules.

Also see this question, "How do I add a new condition in Rules 2?".


Comment Forms - place label inside the inputs

Right, answered my own question with a bit of help from the Form API Docs!! https://api.drupal.org/api/drupal/developer!topics!forms_api_reference.html/7

'#title_display' => 'invisible'

was what I needed!


How to backtrace a variable in php template

You can do it using devel module and ddebug_backtrace() api function exposed by devel..

Below is the function call stack for page.tpl.php executed using below command..

<?php dpm(ddebug_backtrace());?>

I believe above tpl is related to views module... $rows are generated dynamically by views module based on your views settings...


Content type structure (nested content: Gallery / Photo)

I think I found a solution for this using the Node Gallery module. Here is a quote about it (from the module's project page):

  ... allows you to create multimedia galleries where both the galleries and the gallery items are nodes (as opposed to gallery items being file fields, like Media Gallery).


How to translate admin interface in Drupal Commerce Kickstart?

I did a search on my computer, I found product.html which contains the text you were looking for:

Help on products

Each product has both a display and can have many variations (size, color, etc). This page lists all of the products grouped by display.

To see the variations of a product, click on â€œQuick Edit.â€ Using bulk updates (located at the bottom of the page) more than one product can have various actions applied.

More Information

Product Management Overview

Choosing between Products and Product Variations

Adding a New Product

What are Product attributes and variations?

What are Product Node Displays?


You can style it by writing css that target the elements of the navigation menu. If you use the inspector in your browser you should be able to figure out what classes the menu is wrapped in so you can properly style it.

If you are using a custom theme you can start by adding a css file to a css folder. In this case I named mine style.css.

/path/to/custom/theme/css/style.css

.menu li{
    background: blue;
}

Then I came up with a name for my css library in mytheme.info.yml

name: MyTheme
description: My custom Theme
type: theme
core: 8.x
libraries:
  - mytheme/global-css

regions:
  header: 'Header'
  content: 'Main Content'
  footer: 'Footer'

Then I made sure that the library included our style.css file.
In mytheme.libraries.yml I had

global-css:
  css:
      css/style.css: {}


You can use a combination of the modules Rules Bonus Pack, Conditional Rules, and Commerce Rules Extra to create condition loops to compare a data value and set the shipping type in the actions.

Ex:
Event = When calculating shipping

Condition = If cart contains item of type X

Action = add IF > Order total is greater than $50 > Add line-item: Free shipping

     add ELSE > Add line-item: Standard shipping


How do I display social media buttons on new content pages on my Drupal Commerce site?

Kickstart 2.0 Distro uses the service links function.  That's what you're seeing below the "add to cart" button.  Pretty easy fix.  Make sure the service links module is enabled and hit configure, or visit: .../admin/config/services/service-links.

At the top, you can just check the boxes on whichever content type you want these links displayed, as well as a bunch of other fun features below.

Enjoy!


table content_type_answer show to merge it with node table

$q = db_query("
SELECT node.title, node.nid
FROM content_type_answers cta, node
WHERE cta.nid = node.nid");
    while ($r = db_fetch_array($q)) {
      $rows[] = $r;
    }
    print theme('table', $header, $rows);


How do I throw values calculated back to buildForm()?

You can add the following code:

/**
 * {@inheritdoc}
 */
  public function buildForm(array $form, FormStateInterface $form_state) {
     ...
     if (!empty($form_state->get('total')) {
       $form['total'] = array(
         '#type' => 'markup',
         '#markup' => '
 Total is: ' . $form_state->get('total') . '
',
       );
     }
    //$header = array(
    //  'total',
    //);
    //$output = array();
    //foreach ($form_state->getValues() as $key => $value) {
    //   $output['total'] = $total;
    //}
    //$form['mytable'] = array(
    //  '#type' => 'table',
    //  '#header' => $header,
    //  '#rows' => $output,
    //  '#empty' => t('No Data'),
    //);
    return $form;
   }

Add the following code to your submit handler:

/**
 * {@inheritdoc}
 */
 public function submitForm(array &$form, FormStateInterface $form_state) {
   ...
    $total = $form_state->getValue('number1') * $form_state->getValue('number2');
    $form_state->set('total', $total);
    $form_state->setRebuild(TRUE);
    return $form
 }


View to display content type and media type

If there are no relationships among the three entity types, as you have indicated in comments, you could use attachments or blocks. (I'm assuming you want a page that displays all the information.)
Attachment Solution:

Create your View with a page display of one of the entity types.
In the same View create two attachment displays, and use overrides to base them off the other entity types. Attach them to the page display.

Block Solution:

Create your View with a page display of one of the entity types.
Create additional, separate, Views of each of the other entity types, with block displays
Use the block configuration system to place those blocks on the page display


Hide admin email address in user's from field (Webform)

After saving the new component, visit the emails tab. Select the newly created component from the "Component value" select list and select add. The final results will look similar to this.


Permissions by taxonomy for taxonomy and nodes

I Think You need to take a look at Permissions By Term and you may need to get an extra step to implement some code to provide the required term and assign it for the required permission according to your required hierarchy.


Due to Clean Url issue, the site is not working

I was having the same problem, I opened the /etc/apache2/apache2.conf file and located this portion of the file

<Directory /var/www/>
        Options Indexes FollowSymLinks
        AllowOverride All
        Require all granted
</Directory>

And found that AllowOverride is set to None. Go ahead and replace it with All.

Restart your apache service when done. Similar question is asked here


Drupal URL encoding breaks redirects/links

This is drupal core functionality that converts special correctors to string when using in toolbar shortcut menu.


I think the problem is how your views are cached - if you say it is sometimes slow, it is most probably because those times the cache is beeing saved.
If the content doesnt change often, you might just prolongue the interval. Another option is to use Views content cache.
But basically if you have enough visitors (and enough people hovering the images :), they will only wait from time to time ...


Source entity type and id in webform node

a naive solution:

function THEME_preprocess_node(&$variables){
  //adding query source entity and type to a webform node
 if($variables['node']->getType()=='webform'){
   if (\Drupal::request()->get('source_entity_type') && \Drupal::request()->get('source_entity_id')){
     $variables['content']['webform'][0]['#entity_type'] = \Drupal::request()->get('source_entity_type');
     $variables['content']['webform'][0]['#entity_id'] = \Drupal::request()->get('source_entity_id');
  }
 }
}


Error in drupal_form_submit when taxonomy reference (tid) is set

It is possible that 24 is not a valid taxonomy term ID in the system, but I'm not sure if that's it. So I would check that using taxonomy_get_term_by_name or something. Also, and perhaps first, make sure to verify the field_gender field exists, as it might not always be there in the system and you don't want nasty bugs down the road.

// Check if field_gender field exists for node type yvb_ct1
$field_instances = field_info_instance('node', 'field_gender', 'yvb_ct1');
if (isset($field_instances['field_gender'])) :

  // Now check if the taxonomy ID is correct
  // I assume you are looking for a term name of 'female'
  if (!empty(taxonomy_get_term_by_name('female', 'gender')))
    // now try setting term reference field value

endif;

This is untested but I hope it might help get you closer.


How do you normally structure your Menus?

One option you have is to leave your menus as they are and use CSS to style the page so it appears nicer.

You can do things like reduce the amount of space between menus.

Another way (this depends on your sites menu requirements - it may not fit with what you need), is to have primary links be your sitemap.
Add everything you want in your site map to the primary links, going in as many levels deep as you need.
Then don't actually display all the levels in your menu (unless you want to and have deep drop down menus).
Then have the site map just display the primary links menu.

This will give you a nicer looking site map.

In my opinion, site maps are something drupal does not do well (short of doing something more custom). I have never seen a satisfactory result (to my standards) from using the site_map module.

Another option would be to use the menu_block module, which would allow you to create a bunch of menu blocks for specific menus (and levels of those menus), which you could then position on your site map page in a grid (or whatever layout you prefer).
This allows you to be very specific with what is displayed on the sitemap and how it is displayed.
Menu blocks also means you can customise the heading specifically for that block, without changing the name of the menu.
You could assign the blocks to a node page that has some introduction text for the body, of you could use something like the empty_page module to add a non-node sitemap page to assign your blocks to.

You can call your menus whatever you prefer, but I would not rename them to primary and secondary links. It is better to use more semantic names.
This is important in cases where you want the menu title displayed with the menu, and also when the menu title is there but hidden, to give screen readers better context, for accessibility.

Whether or not to display the manu titles in the site map also depends on your site setup and what you want to achieve.
If your menus are for distinct sections of the site it might be useful to have those sections stated in the sitemap, however if the title is not really relevant, for example "Main manu", "Navigation", "Footer links" etc., then it would likely be best to not show them.


How to force users to re-authenticate on specific pages?

I think this module suits to my requirement: Protected Pages. Some details about it (from its project page):

  ... allows the administrator to secure any page in your website by password. You just need to go to configuration page of this module and add path, password. After that the added path will be password protected. This module also allows you to send the details of this protected page to multiple users by email.


Theme CSS libraries always loaded after module libraries

The proper way to modify the loading order is weight property as described here.  The lower the weight the further up your library should go.

Try something like the following in your trent/trent.libraries.yml

bootstrap:
  css:
    base:
      libraries/bootstrap/bootstrap.min.css: {weight: -50}

You might have to adjust the number to get it to desired position.

NOTE: weight is in the process of being replaced by dependencies. Work done can be seen in this issue and when ready this sort of problem will be easier to tackle.


How can I set a variable in the body of a node?

take a look at What is best method for token replacement within node content?

If you are feeling lack of available tokens, you can extend it with tokens hooks.


How to Create twig template files in drupal 8 for customizing user login,profile edit and forget password forms?

Using hook_theme_suggestions_alter, you can create whatever template suggestions you like.  For example, based on the form id.  Just remember, the suggestion has underscores ("_"), but the template file has hyphens ("-").

function Yourtheme_theme_suggestions_alter(array &$suggestions, array $variables, $hook) {

  if ($hook == 'form' & !empty($variables['element']['#id'])) {
    $suggestions[] = 'form__' . str_replace('-', '_', $variables['element']['#id']);
  }
}

then you would create templates in your theme, such as

form--user-register-form.html.twig

and

form--user-login-form.html.twig

You are doing some non-standard and unnecessary things by rendering the form in a preprocess hook and registering custom theme hooks for your forms.  You don't need to create new hooks in hook_theme, you can just use the suggestions, and it will do the rest, after you clear cache.

You can render your elements within the template.

For example, for form--user-login.html.twig:

    <form{{ attributes }}>

hello world

            {{ element.messages }}
            {{ element.name }} {# username element #}
            {{ element.pass }} {# password element #}

                <input id="show_password" class="show_password" type="checkbox" />
                Show password
                Forgot Password?

            {{ element.form_build_id }} {# required #}
            {{ element.form_id }} {# required #}

                {{ element.actions.submit }}

    </form>


D8 Migration: Can 'Default Bundle in Destination Plugin be dynamic?

In your config, use a row instead of the default value plugin.

Instead of this:

process:
  type:
    plugin: default_value
    default_value: course
  title: title
  etc.

use this:

process:
  type: target_bundle
  title: title
  etc.

Then you can set the target_bundle dynamically in your source class's prepareRow function.

$row->setSourceProperty('target_bundle', $target_bundle);


How do you programatically render a views exposed filter form block in a tpl in Drupal 6?

views_embed_view displays the whole views block. Therefore in your template you put:

print views_embed_view('most_read_today', 'block_1');

If you are needing to pass arguments to your 'exposed filter', add a 3rd argument.


Replace field label in content type template

OK it's a bit round the houses, but you should be able to do:

$content['group_details']['field_city']['#label_display'] = 'hidden';
print '
Title
'; // change to any HTML
print render($content['group_details']['field_city']);


How to download Database results as PDF or in EXCEL

By Views PDF module you can output a View as a PDF.

  With this module you can output a view as a PDF document. Each field of the view can be placed on the PDF page directly in the administration interface. Therefore a new display called "PDF" is added.

Since you have your custom query, by Custom query in Views you can alter the results of the View. The print the output of view is PDF using the above module.

UPDATE

Since you created a node and fetch database result via that node you must use Printer, email and PDF versions module

  This module allows you to generate the following printer-friendly versions of any node:

  Printer-friendly version (webpage format) (at www.example.com/print/nid)
  PDF version (at www.example.com/printpdf/nid)
  EPUB version (at www.example.com/printepub/nid)
  Send by email (at www.example.com/printmail/nid)

where nid is the node id of content to render.

so by www.example.com/printpdf/nid you can create a  PDF output of the node.


Drupal custom coding checkout redirect not working

Your fault is want using drupal_goto in form builder!!!

Change your code to this

 $items['buynow/%'] = array(
    'title' => t('buynow'),
    'page callback' => 'custom_module_my_form3',
    'page arguments' => array(1),
    'access arguments' => array('access content'),
    'type' => MENU_CALLBACK,
  );

function custom_module_my_form3() {
   global $user;
   $id=arg(1);
   $product_id=$id;
   $product = commerce_product_load($product_id);
   $quantity=1;
   $line_item = commerce_product_line_item_new($product, $quantity);
   $line_item_added = commerce_cart_product_add($user->uid, $line_item);
   $order_id=$line_item_added->order_id;
   drupal_goto('checkout/'.$order_id);
}


How to use [submission:values] in Email template in Webforms

I haven't such problem, but I know, how to get special values from webform.

  Webform tokens from submitted data. Includes the value and field label. Replace the "?" with the "Field Key". Append ":nolabel" for just the value.

So, you can use [submission:values:?:nolabel], where ? is field key of your component.

 Name: [submission:values:name:nolabel]
 Address: [submission:values:address:nolabel]

For me result is the same as for [submission:values]:

  Name: Kate
  Address: Moscow, Russia :)

Webform version: 7.x-4.0-alpha6 (7404).

Webform Tokens module is not needed.

Update

If you are using HTML mail, labels are outputted via theme_form_element_label and look like <label>Title</label>\n.

You can override webform-submission.tpl.php. Copy this file to the theme for rendering the emails from admin/config/system/mailsystem.
To add : I suggest just to modify render array:

if ($format == 'html') {
  foreach ($renderable as $i => $item) {
    if (is_array($item) && !empty($item['#title'])) {
      $renderable[$i]['#title'] .= ':';
    }
  }
}

print drupal_render_children($renderable);

But you can output substitutions fully yourself.