Is there an easy way to call a migration from a controller for debugging purposes

Actually, the code isn't that hard to recreate from migration_tools. Here is my controller class:

<?php

namespace Drupal\custom_migration\Controller;

use Drupal\Core\Controller\ControllerBase;
use Drupal\migrate\MigrateExecutable;
use Drupal\migrate\MigrateMessage;

class MigrateController extends ControllerBase {

  public function process() {

    $migration = \Drupal::service('plugin.manager.config_entity_migration')->createInstance('upgrade_d6_field_instance');
    $executable = new MigrateExecutable($migration, new MigrateMessage());
    $executable->import();

    return ['#markup' => 'Migrate Debugging'];
  }
}


"Enterprise" authentication, single sign-on and user provisioning for multiple sites

You would have to use a few modules working together to make this happen.

Development Seed had an interesting demo using OpenID, PubSubHub and Feeds.
They detail it at http://developmentseed.org/blog/2010/mar/02/simple-sign-openid

lordg's comment re: hubs is exactly what they did.


Unable to return session value in views Field

You need to remove session_start() from Rules. Drupal calls session_start() when firing drupal_session_start().

Check out session_start manual on php.net

  As of PHP 4.3.3, calling session_start() after the session was
  previously started will result in an error of level E_NOTICE. Also,
  the second session start will simply be ignored.

Screenshot for PHP field settings in Views:


How to apply dynamic block layout depending upon number of nodes in it (Drupal 8)?

Not everything is clear in your question, but there are some approaches for that task.
For example if you are using views module you can count number of views rows in twig template:

{% if rows|length == 2 %}
   {% for row in rows %}
//Here some staff for two rows
   {% endfor %}
{% endif %}

About twig, about views templates

Also you can use jquery $('.some-class-for-every-row').length and add some style using js.


Where are the add to cart form settings?

Turn on the Combine options in your Line Item displays and Product displays.

If you use Commerce lisense module please check this issue Commerce license does not combine line items

If not I guess this link can be helpful , you will find example of hook_commerce_cart_product_comparison_properties_alter()


EDIT: I take it back. The problem has started again in drush 8.1.8 when Drush cr is used in a script - we have it in a back up script to reduce the size of the DB before pilling a copy of it - the application of the is-Active tag is getting broken on menu elements and any styling - say turning on or off visibility to expand the menu - seems to to totally break.

Manually clearing the cache through the UI fixes the issue but is not ideal

Drush 8.1.8 seems to have fixed the problem. I have looked through the change log though and cannot see what got changed in regards to the cache-rebuild that would fix the problem but it seems to have gone away so...


Using Drupal Bootstrap, I want the 'title' of my parent menu item to be a glyphicon and to drop to the search bar!

If you're wanting to theme the menu items, you can:

Use theme_menu_link() in your theme template to alter markup / attributes before rendering
Use a contrib module https://www.drupal.org/project/menu_attributes to add a custom class name e.g. icon-left icon-myname
Select the menu item via css and manually inject it there e.g.:

.menu-class .mid-class:before {
font-family: 'glyphicon';
content: '\utf-char-code';
/* other css here */
}

Adding the search block to the dropdown depends how you want to set this up, we'd need more specifics on what behaviour you're trying to achieve. Bear in mind that you can alter individual menu items through hooks in your template (e.g. theme_menu_link() above), and you can also render blocks programatically.


External anchor link or map for attached images

You can copy the templates views uses to your theme and modify them so that a field returned in the view is used to theme another.  Views has this built in in its latest versions, but only allows divs, spans, etc, and you want an anchor.  Check out Exposing Individual Fields on Output for Styling here for an example of what I am talking about.  There they wanted to just wrap an in a div to set the color, but you could use the same concept to wrap it in an anchor.


Filling an Entity Reference programatically

You have to specify the entity id and the entity type. The example is referencing a node but you want to reference a user.

Try this:

$node->field_customer_nid[$node->language][] = array(
  'target_id' => $entity_id,
);

$entity_id should hold the referenced entity id.


Inserting a select box before the search box (Drupal 7)

If you need the form field to be placed before any other form field present in the form, you need to use, for the weight, a lower value than the one used from the present form fields. The default value is 0; use a negative value to be sure the form field is always shown first (e.g. −200).

search_box() doesn't use any value for the field's weight, which means the default value is used.

  $form[$form_id] = array(
    '#type' => 'textfield',
    '#title' => t('Search'),
    '#title_display' => 'invisible',
    '#size' => 15,
    '#default_value' => '',
    '#attributes' => array('title' => t('Enter the terms you wish to search for.')),
  );
  $form['actions'] = array('#type' => 'actions');
  $form['actions']['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Search'),
  );
  $form['#submit'][] = 'search_box_form_submit';

I have used the following code in a test module.

function code_testing_form_search_block_form_alter(&$form, &$form_state) {
  $form['my_field'] = array(
    '#type' => 'select',
    '#title' => t('whatever'),
    '#options' => array(
      0 => 'option1',
      1 => 'option2',
    ),
    '#default_value' => 255,
    '#weight' => -200,
  );
}

The search form appears as in the following screenshot.


A views field template only has these variables:

 * - $view: The view object
 * - $field: The field handler object that can process the input
 * - $row: The raw SQL result that can be used
 * - $output: The processed output that will normally be used.

This is the default views field template:

<?php

/**
 * @file
 * This template is used to print a single field in a view.
 *
 * It is not actually used in default Views, as this is registered as a theme
 * function which has better performance. For single overrides, the template is
 * perfectly okay.
 *
 * Variables available:
 * - $view: The view object
 * - $field: The field handler object that can process the input
 * - $row: The raw SQL result that can be used
 * - $output: The processed output that will normally be used.
 *
 * When fetching output from the $row, this construct should be used:
 * $data = $row->{$field->field_alias}
 *
 * The above will guarantee that you'll always get the correct data,
 * regardless of any changes in the aliasing that might happen if
 * the view is modified.
 */
?>
<?php print $output; ?>

You can see what templates you can use by going to your view, then click "advanced" and then next to "Theme", click on "information". This will show you all available templates you can use and override.

Hope this helps you out.


How to create node navigation to cycle through nodes of specific content type

Have a look at these two modules:

Flippy
Custom Pagers

Custom Pagers is more versatile, but I found it buggy.
Another solution, more custom and flexible, would be creating a custom field in the content type (via hook_field_extra_fields() or Display Suite), and creating a custom query to get the next/previous node ids. If you prefer to go with the custom way but don't want to add a custom field, you can just preprocess the node and add the variable in your .tpl file.
Previous/Next API module could be used to get the node ids without the need to create the query yourself, apparently making the solution more scalable. It's still a -dev version though.


Yes, you are correct: The quantity available for a product is not considered a product attribute. A product attribute is, for example, color, size, weight. The quantity available in store is a value associated with the store, not an intrinsic property of the product.

Using only Drupal Commerce, you cannot manage stocks. There is a Commerce Stock module, but it just has only a development snapshot, for Drupal 8, which has been updated on November, 2017.

  The stock module does two main things

  Maintain stock levels
  Implement validation of stock to prevent users from ordering out of stock items

  The module does the following stock validation checks

  Disable the add to cart button for out of stock products
  Validates the add to cart quantity widget
  Checks current Cart quantity when adding to your cart (so if stock is 10 and you got 6 in your cart you can only add 4)
  Checks that all products and quantities in the shopping cart (/cart) are in stock
  On Checkout if you attempt to enter, continue or complete with out of stock items you get redirected to the shopping cart


How to add the datepicker jQuery UI element to Highcharts in a Drupal site?

The datepicker was being displayed, it was just hidden by the Highchart. Adding z-index: 9999 !important; to the .ui-datepicker CSS solved it.


Block drush rsync command when specific alias is set as destination

In the case of rsync, $destination is equal to @staging:%files, which is different than @staging.  drush_sitealias_evaluate_path is not called until after the validate function, and calling it twice would be slow.  You could test to see if $destination is @staging OR if it begins with @staging:.  That should work well enough for your purposes.

If you wanted your policy to depend on values set in your @staging alias, then it would be best to make Drush call drush_sitealias_evaluate_path before the validate function.  That would be a feature request, and should be done by posting an issue (or better yet, a PR) on the Drush project on GitHub.


Mask User url with dynamic temprorary user

It's very unlikely; this sounds like a very specific use-case that wouldn't need a dedicated project. You're going to have to implement your own custom module to pull this off.

You could go an aliasing route in a manner similar pathauto but that is likely to leave source paths open (e.g. user/XXX) to accessibility. A better approach is to create a simple module that:

Uses a hook_cron() implementation to generate random hash to UID mappings periodically and storing them in custom table.
Implementing a hook_menu() to generate a dynamic path like user/%random_hash that maps the random hash paths in #1 to a user profile page (generated in the the same manner like user/%user)


How add custom node in a View (Nested View)?

You can use the Views Field View to show the Nested Nodes (that should be a kind of Node Reference)

  There are a lot of cases in views where you want to embed a list
  inside each row. One example could be, you have a list of groups, and
  for each groups you want to list the first and last name of all of
  their members.

For modify the content of a node you can use the template_preprocess_node() maybe you will need to Check content type of node in preprocess hook.


How to place custom module template file in theme folder

Well you can place in the theme folder or you can leave it in the module. Drupal will look in both places. So if your implementation of hook_theme is a template, Drupal will look for the following files:

themes/bluemarine/custom.tpl.php
modules/custom/custom.tpl.php

If you read the documentation for hook_theme you'll get your answer for the question when you get to the path key:

  path: [...] Ordinarily the module or theme path will be used [...]


field_collection_item not updating / old data preserved

I would love to tell you why, but I have not been able to figure it out: I just know it works.

Initially I executed the code above in hook_node_presave($node), but obviously it did not work.  So I figured I should try hook_node_update($node) - but that did not work either.

Then I discovered drupal_register_shutdown_function and now my hook_node_update looks like this:

function mymodule_node_update($node) {
  if ($node->type === 'node_type') {
    drupal_register_shutdown_function('_update_from_sync_fields', $node);
  }
}

node_type is the type of node I am checking against.  Any case, once the node is actually saved - that is all processing is done, db transactions completed, etc - drupal will call my shutdown function.  Now when I update the field values, and in specific field-collection fields - they are saved.

Of-course saving these fields and calling:

  field_attach_update('node', $node);
  field_attach_presave('node', $node);
  entity_get_controller('node')->resetCache([$node->nid]);

at the end of my shut-down function triggers hook_node_update again, but fortunately I have a token that tells me - so I do not execute the code again.

This solution works - what I am not happy about is the fact that it executes when Drupal is shutting down.

I think the problem is related to the fact that node_save starts a DB transaction, and when I update related entity (field-collection) items in hook_node_save or hook_node_presave I am starting another (nested) transaction.  Clearly my transaction updating field-collection items completes, but when the outer (first) transaction then complete, it is writing old/dirty data.

The trick is going to be to clear the dirty data from cache.  I was hoping entity_get_controller('node')->resetCache([$node->nid]); would do that - but clearly it does not?

So next I changed the hook_node_update to :

function mymodule_node_update($node) {
  if ($node->type === 'node_type') {
    _update_from_sync_fields ($node);
  }
}

in other words - from hook_node_update I simply call the 'shut-downfunction, then I rebuilt the drupal registry (drush rr`) and voila - it worked.  Now I am even more confused.  It is possible that my original code worked all along, but there was something wrong with the registry (or caches).  All things being equal, all the examples I read was right.

From hook_node_update, load the field collection entity, update and save the entity.  The clear the caches and do a field_attached_presave and field_attached_update like so:

  entity_get_controller('node')->resetCache([$node->nid]);
  field_attach_presave('node', $node);
  field_attach_update('node', $node);


How do I filter a view by the results of hook_node_access?

The problem here is that hook_node_access is a PHP function that has nodes passed through it, but Views is doing a database query for the relevant nodes. These two are incompatible, as Views would have to fetch every node in the system from the DB, then pass them all through that function, which would add major overhead.

Drupal's solution to this is the node grants system, which writes a set of grants to the {node_access} table, which can then be used in querying nodes.

To implement a grants system, you'll need to implement hook_node_access_records(), which is called when each node is saved, and sets up a number of rules by which the node being save is allowed to be accessed. Then you implement hook_node_grants(), which generates a set of potential grants for the current user, and tries to match them with the grants created in hook_node_access_records(). When there is a match, the user is granted permission to access, and this will work with DB queries.


How do I use this module which depends from a module that is not available for the core version I am using?

Welcome to Drupal Answers.

You don't need additional module for Libraries on Drupal 8, just create libraries folder in root of a Drupal project and put all libraries you need there.

In this case download juicebox library unarchive it, put the unarchived folder in libraries folder you created and rename it to juicebox, so your library should be in /libraries/juicebox.

And that's it, you can enable your module.


How to send an SMS message when a Webform is submitted?

Using the "Webform Rules" module, you should be able to have the Rules module react on an event like "Webform submitted".

So create a custom rule using this Rules Event, and then add a Rules Action to send an SMS message, similar to what is shown in the video  tutorial "How to send SMS messages" (starting from around 5:25).


Can local actions have multiple parents?

I believe it's always Many (Local Actions) to one (Parent Item) relationship as hook_menu documentation says

  MENU_LOCAL_ACTION: Local actions are menu items that describe actions
  on the parent item such as adding a new user or block, and are
  rendered in the action-links list in your theme.

If you want to change the parent of local action you can do it using tab_parent

  $items['node/%node/bar'] = array(
      'title' => 'Bar',
      'page callback' => 'bar',
      'access callback' => TRUE,
      'tab_parent' => 'node/%/foo',
      'type' => MENU_LOCAL_ACTION,
  );

Above displays action link in node/%/foo instead of node/% , tab_parent accepts single string argument... So we can rule out option of sending multiple parents using array.. For deeper analysis you can refer

function menu_local_tasks() in menu.inc which is responsible for action items and local tasks rendering..

If you would like to see it in action both places you can try below..

As @awm pointed out in comment we can add it to other pages using hook_menu_local_tasks_alter, Here is how node module does to include node/add menu item as local action to admin/content using hook_menu_local_tasks_alter

/**
 * Implements hook_menu_local_tasks_alter().
 */
function node_menu_local_tasks_alter(&$data, $router_item, $root_path) {
  // Add action link to 'node/add' on 'admin/content' page.
  if ($root_path == 'admin/content') {
    $item = menu_get_item('node/add');
    if ($item['access']) {
      $data['actions']['output'][] = array(
        '#theme' => 'menu_local_action',
        '#link' => $item,
      );
    }
  }
}

So you can do same for your own implementation using below code

/**
 * Implements hook_menu_local_tasks_alter().
 */
function YOURMODULENAME_menu_local_tasks_alter(&$data, $router_item, $root_path) {
  // Add action link to 'node/add' on 'admin/content' page.
  if ($root_path == 'node/%/foo') {
    $nid = arg(1);
    $item = menu_get_item('node/'. $nid . '/bar');
    if ($item['access']) {
      $data['actions']['output'][] = array(
          '#theme' => 'menu_local_action',
          '#link' => $item,
      );
    }
  }
}

Results in


Drupal's .htaccess does not deny access to nodes

In your settings.php file you can add the following lines and upon recognition of an HTTP_REFERER Drupal will not deliver any page data.

if ($_SERVER['HTTP_REFERER'] == 'http://spamhost1.com') {
  exit;
}

You should consider looking into existing modules that block spam though.  Trying to manage this one URL at a time seems like a lot of work.


Is hook_init() still used? If it is not anymore used, how do I convert code implementing hook_init()?

Perhaps this has changed since this question was last answered. But I think the preferred approach to replacing what is going on in hook_init is to create an event subscriber, and adding to the 'request'. Here is how you do that for those that may find it useful.

Example services.yml

services:
  init_subscriber:
    class:   Drupal\mymodule\EventSubscriber\MyModuleSubscriber
    arguments: ['@current_user'] // <- optional args
    tags:
      - {name: event_subscriber} // <- Required Tag

Then you would implement the EventSubscriberInterface (new file in the src/EventSubscriber directory) and in the implemented method getSubscribedEvents you can do something like...

/**
 * {@inheritdoc}
 */
public static function getSubscribedEvents() {
  $events[KernelEvents::REQUEST][] = array('initializeMyModule');
  return $events;
}

And add the method accordingly

/**
 * MyModule
 *
 * @param \Symfony\Component\HttpKernel\Event\GetResponseEvent $event
 *   The event to process.
 */
public function initializeMyModule(GetResponseEvent $event) {
  $request = $event->getRequest();
  ...
}


How to fix the unresolved dependency in the Flag module about Flag Friend?

According to your "unresolved dependency" error messages, you are currently using the 2.2 version of the Flag module. While the Flag Friend module requires the 2.1 version of it.

It's worth trying to replacing the entire flag folder in your modules directory as follows:

backup your flag module folder (to somewhere outside your Drupal root).
delete the flag module folder and its entire content.
download the 7.x-2.1 release of the flag module and unpack that version in the very same "flag" module folder.

Then try again and see if that helps. If not restore your backup directory (to try some other approach).


If you would like to look at an advanced application of someone doing something very similiar to you, have a look at the Recruiter installation profile for Drupal 7. Just download, install and then look at how the views, content types, taxonomy and fields are configured. Instead of musicians and skill it is configured to software developers with skills.


You would have to remove the two fields from fields.

<div class="foo">
  {{ fields.field_events_date_start.content }}
  {{ fields.field_events_date_start_1.content }}
</div>

{% for field in fields|without('field_events_date_start',  field_events_date_start_1') %}
  ...
{% endfor %}


The output of drush sql-connect is  mysql --user=root --password= --database=d8_test --host=127.0.0.1 --port=3306. Now, when I directly execute this command, it didn't work because mysql.exe was not there in the system PATH. So I added H:\xampp\mysql\bin to PATH (environment variable in Windows) and then it worked!


Is there a way to group different taxonomy/content type in a single Select List (in a View)?

You can follow this using below step:

Go to Administration -> Structure -> Views
Edit your existing view or create new new.
Add Filter for taxonomy terms you need
Click on "Rearrange" filter icon in Filter section
Click on "Create new filter group" and move filter taxonomy terms you need in new filter group.
Select Operator as "Or" in new filter group and save the form.


How can I trim a field's value for display?

Your field type needs to be Text (formatted, long).

Then on the display settings page, you can change the display format to Trimmed, and edit the settings (by clicking the gear) to change the character limit.


Profile 2 different types with single edit form

It could be accomplished using Panels:

  The Panels module allows a site administrator to create customized
  layouts for multiple uses. At its core it is a drag and drop content
  manager that lets you visually design a layout and place content
  within that layout. Integration with other systems allows you to
  create nodes that use this, landing pages that use this, and even
  override system pages such as taxonomy and the node page so that you
  can customize the layout of your site with very fine grained
  permissions.

and Profile2 Panels Module:

  Page Manager (Panels) support for Profile2.

  With this module you can take over Profile2 paths with Page Manager.
  Now it is possible to theme your Profile2 edit and view pages with
  Panels.

If you're not familiar with panels, there are numerous resources and tutorials out there


I think another angle to attack the problem would be to implement hook_schema the normal way, as if there was only one database. And then tell Drupal to use another database for some tables in settings.php. Your module will not have to be run on seperate databases and all that external database stuff is taken care of by Drupals database layer.


Optimal Settings.php for Pressflow + Varnish + memcache

Unless you are doing something quite unique, using boost & varnish is usually overkill. If you have varnish setup exactly how you want it, I would just use varnish.

Here is an example settings.php. It is a multisite safe memcache configuration thanks to the memcache_key_prefix setting.

<?php
// Skip db query that checks for blocked IP's.
$conf['blocked_ips'] = array();

// Reverse proxy settings.
$conf['reverse_proxy'] = TRUE;
$conf['reverse_proxy_addresses'] = array(
  '127.0.0.1',    // Localhost
);

// Use memcache for caches, locks, and sessions.
$conf['cache_inc'] = './sites/all/modules/memcache/memcache.inc';
$conf['lock_inc'] = './sites/all/modules/memcache/memcache-lock.inc';
$conf['session_inc'] = './sites/all/modules/memcache/memcache-session.inc';

// Memcache Settings.
// Set memcache server.
$conf['memcache_servers'] = array(
  '127.0.0.1:11211' => 'default',
);
// Set memcache bins.
$conf['memcache_bins'] = array(
  'cache' => 'default',
  'cache_form' => 'database',
);
// Set memcache prefix to be the location of the settings.php file.
$conf['memcache_key_prefix'] = basename(realpath(conf_path()));
// Try to use a persistent connection.
$conf['memcache_persistent'] = TRUE;
?>


What files are you referring to?

If there are files being generated from webform node content then the data probably has to be saved first in order to generate the files. In this case you should target to delete the nodes once the email has been sent (while allowing for them to be created at first). You can look into Rules module for that.

Webforms all have separate email settings so I'd expect the webform_clear to also offer per-form settings.


How to install a specifc commit in Composer

composer require drupal/commerce_webform_order:dev-1.x#30668342035ae3add3a2e5163e84816fc96edd92

dev-1.x points to a git branch so it accepts the commit ref
1.x-dev is dev release at drupal.org and it does not have git commits to reference like that


How to show latest and high price value first using Views?

To achieve your requirement, you have to expose the sort criteria. Select checkbox Expose this sort to visitors, to allow them to change it under sort criterion configuration.

Note: When you add any field into SORT CRITERIA, then under this field configuration you can see this option.


Export content type: 'An illegal choice has been detected. Please contact the site administrator.'

This was caused by a corrupted field. I deleted and re-added the field.


One way to remove the template from being in the list of suggestions, and ultimately not being used, would be to implement hook_theme_suggestions_alter, and unset it from the $suggestions array. This should effectively remove it, and the next specific template will be used instead.

Alternatively, you can copy the template file in from the base theme, and overwrite it to be a default rendering that is preferable to you (without removing the suggestion) and it will be used instead.


Drupal Views to Display Fields for Each Nodes of One Content Type

There are a couple of ways to this using Views. Chances are that you will have to visit the display settings of the content type to hide its content so that it does not show duplicated.

Solution 1. Create a block for each section of the page you want to relocate using Views using the argument or contextual filter so that the block use the node ID to show the right content in the right page. Then enable the blocks and make them visible by content type and you can play with the position of the block using CSS and/or the module block class.

Solution 2. Use the module EVA that it will let you create an view attachment to the node content type entity and that you can re-arrange like any other field in the content type display settings screen. The rest of the setup is similar to the way you created the blocks in solution 1.

Solution 3. You don't need to use views at all, just CSS and you are good. Reposition the fields using the content type display manager make the tags field first, then the body and last the category. Since each field will have a wrap div then use a simple "float", "with" and "margin" css to accomodate the content.

CSS Example (classes are not real)

.div-wrap-for-tags {float:left;margin-right:20px;width:200px;}
.div-wrap-for-body {float:left;width:400px;}
.div-wrap-for-category {clear:both;}


a very simple way would be to add a new alias yourself by accessing "/admin/config/search/path"

however, if you have translation set up correctly, that path should already exist.  I think maybe your translation set up is done in a non-standard way.  could you describe it in detail?


Using another html.tpl.php for specific page

Note, there's already template suggestions for html.tpl.php generated by template_preprocess_html (see last lines in the function there)

For a specific node page, you can use html--node--1715.tpl.php where 1715 is the target node id.


How to impose a global maximum limit on two webform number fields?

Install the Webform Validationmodule which allows you to easily set rules for fields. So in this case you could add a rule that the number can not go above 8.

You can also use hooks to add your own validation rules in code for more complex formulas like the child and adult combination.


In general in Drupal 8 you should leave out the template line and name the template the same as your hook, converting the underscores to dashes. This was changed because templates are the default output format for themeable output in D8. So in your case this hook_theme():

/**
 *  Implements hook_theme().
 */
function twitter_pull_theme($existing, $type, $theme, $path) {
  return [
    'twitter_pull_tweet_listing' => [
      'variables' => [
        'description' => [],
      ],
    ],
  ];
}

…would point to a template at templates/twitter-pull-tweet-listing.html.twig. (That's using short array syntax.)

Relevant change record: https://www.drupal.org/node/2231673

And also, from a block or controller, please return a render array instead of a string. That way the results can be manipulated afterwards and the raw data is still accessible down the line. In other words, avoid calling drupal_render() from your code whenever possible. This applies to Drupal 7 as well: https://www.drupal.org/node/930760#creating

So from your block:

return [
  '#theme' => 'twitter_pull_tweet_listing',
  '#description' => 'foo',
  '#attributes' => [],
];


I can think of 4 things to check in this case, in order of likelihood:

What does the preprocess function stub look like?  Are you using the variable &$vars there, too, or are you using &$variables instead (which is how it appears in the documentation)?  They, of course, have to match.
Have you cleared your cache?  D6 was bad about sometimes needing the cache to be cleared twice.
Is the function actually running?  If not, then there may be a problem with the function name that it is not being recognized, or that the cache has not been cleared (which should be taken care of by checking #2).
Is something messing with the variable afterwards that is inadvertently re-adding the core js file?


How can we display permissions to users?

To create a view of permissions you'd have to write a custom module that would allow views to do the search. I'm not aware of a module that does that now. Given how roles are defined and managed this would be a challenging module to get right.

If you just want to improve the user interface for permissions form you might look at these modules:

filter permissions
Permission Select
Fast Permissions Administration

If you want to give admins a limited number of roles they can assign the Role Assign module may provide what you need.


You might try the Lazy Image Loader.  I'm not sure if it will work for your case, but it's worth a shot.  You can also implement the lazy behavior yourself.  Use javascript to test the "complete" property of each image, and change the src attribute on any image that currently hidden from view.  When it becomes visible, swap in the original src.  I've seen good results with this script: http://www.appelsiini.net/projects/lazyload.


What is the difference between a view mode and a style plugin?

I'll give this a shot.

A view mode is a concept that exists for entities. A node has for example the view modes Full content, Teaser and RSS.
And as you say different view modes can have different settings. An image might be just an URL in the RSS view mode and a large rendered image in the Full content view mode. It is also possible to have different order and visibility settings for each field in each view mode.

A Panel region or a Panel pane has something called a Style setting, this is also a Style plugin. There are styles such as No style, Rounded corners etc. Changing style will change the markup that surrounds your region or pane. In most cases the Style setting for the pane is something you do not change.

But to answer your question, yes a region or a pane always has a set "Style" and that Style is by default set to use the style plugin "No style".

A style plugin is a concept that also exists in Views. Under the setting Format in Views you have the option to choose between Style plugins such as Grid, HTML list,
Jump menu, Table and Unformatted list. When you choose a different style plugin the markup surrounding and in between each row changes.


Can I stop D6's email sending to blocked users?

You could use hook_mail_alter() to check the mail before it's send and filter it depending on your conditions.


Template suggestions based on path alias

OK, I seem to have got it working.

function THEME_NAME_theme_suggestions_page_alter(array &$suggestions, array $variables) {
  $current_path = \Drupal::service('path.current')->getPath();
  $result = \Drupal::service('path.alias_manager')->getAliasByPath($current_path);

  $path_alias = trim($result, '/');
  $path_alias = str_replace('/', '-', $path_alias);

  $suggestions[] = 'page__path_alias__'.$path_alias;
}


Maybe you should look at the Views tree module, to see how well it would fit your needs. Here is a quote about the module (from its project page):

... provides a tree-based style plugin for Views.
It is based off of the list style. Although it generates a nested view, there is still only a single query run for the view making it quite performant.


Social Networking buttons in a list of teasers generated using views

Download the ShareThis module. This does what you need.
Here is a quote about it (from the module's project page):

Integration with the ShareThis social bookmarking utility on selected node types.
The code for this project was based on the original share project for Drupal 5.x. The code for this project has been trimmed down to only work with the ShareThis system, and not require any additional modules to work properly.


File upload with ajax and without upload button

These modules can help you

HTML5 Drag & Drop File

  HTML5 drag & drop + HTML5 file upload with XHR2. Allows the user to
  drag & drop files into a Image/File Field and uploads it immediately
  behind the scenes. In theory it should work for as many files as the
  field allows.

  Requires jQuery >= 1.5.2 (jquery_update has that)!

  It's a start...

Enable
Works for all managed_file fields
You can disable per field in the field instance config

  There's a settings form under Config > Media where you can change the
  upload method from Series to Parallel (much faster, but slightly
  riskier). If you dare, try it out. I've experienced (although not for
  a while) the full entity form being submitted by a file upload.

  If you're uploading A LOT of files, you might encounter the server's
  max file/POST size limit. I've no solution for that yet.

Drag'n'Drop Uploads(you can use dev version,I am using it and work;) )

  The Drag'n'Drop Uploads module adds the ability to drag an image from
  your local filesystem, drop it onto a node body textarea and have the
  file automatically uploaded and referenced in your node.

(maybe you just need some custom jquery coding, first hide upload button then fire upload button programmatically in your js)

Plup

  Plup module enables uploads to file fields using the popular plupload
  library. It does not require any other modules to work, but the
  plupload library must be downloaded separately (version 1.5.8 is the
  last supported version).

  Please note that you must remove the "examples" folder from the
  downloaded plupload library to avoid introducing a security
  vulnerability.

  The original developer is no longer maintaining the module, and I will
  only minimally maintain it until Media 2.x has a stable release that
  works with plupload and multiform, after which I expect to migrate to
  those modules.


How to find out which form I want to alter

The way I usually do it is just implement hook_form_alter and inside put dpm($form_id);. Reload the page and it will echo all form ID's. You should find the one you want pretty easily, you can then change the hook_form_alter into a hook_form_FORM_ID_alter.


Javascript will not load for anonymous users

The code in the question appears to be similar to what was done in Drupal 7. In Drupal 8, the dependencies for your javascript need to be explicitly defined and it is a good idea to pass them through the closure as well. You can read more about the Javascript API in Drupal 8 on the new documentation pages.

my_javascript:
  version: 1.x
  js:
    js/my_javascript.js: {}
  dependencies:
    - core/jquery
    - core/drupal

(function ($, Drupal) {
  Drupal.behaviors.myScripts = {};
)(jQuery, Drupal);


Correct way to validate config entities?

It depends on how your config-entities are created.
If the only way to create them is via a form, then you could just override the validateForm method in your form to ensure the entity is valid. In this context the entity should be available by running this code

$form_state->cleanValues();
$this->entity = $this->buildEntity($form, $form_state);

This is what content entity forms do (see \Drupal\Core\Entity\ContentEntityForm::validateForm).

However if you expect your entities to be added programatically or via REST and you need lower-level validation, then you could add a validate method to you entity and call this from the preSave method. Having it available as a public method (validate) would allow other consumers of your API to check if the entity was valid before they called save, thus avoiding the exception.

In terms of the contents of the validate method, you have lots of options. You could try and piggy-back onto core's constraint system - which uses plugins to define constraints. Or you could keep it simple and just return an array of errors. Finally you could keep use a middle-ground and just integrate with the validator component in the Symfony way, which would at least keep your validate return consistent with those for Content entities - something like so:

use Symfony\Component\Validator\Constraints as Assert;
use Symfony\Component\Validator\Context\ExecutionContextInterface;
use Symfony\Component\Validator\Mapping\ClassMetadata;
use Symfony\Component\Validator\Validation;

/**
 * Validates my config entity.
 *
 * @return \Symfony\Component\Validator\ConstraintViolationList
 *   List of violations. Empty if valid.
 */
public function validate() {
  $validator = Validation::createValidator();
    ->addMethodMapping('loadValidatorMetadata')
    ->getValidator();
  return $validator->validate($this);
}

/**
 * Defines validation rules for this config entity.
 */
public static function loadValidatorMetadata(ClassMetadata $metadata) {
  // Same validator rules.
  // Add your own as required.
  // Note this is static, so you don't have $this in scope.
  $metadata->addPropertyConstraint('someProperty', new Assert\NotBlank(['message' => 'Some property cannot be blank']));
  // But if you add a validation callback, you can operate in the context
  // of an instance.
  $metadata->addConstraint(new Assert\Callback(['methods' => ['someValidationCallback']]));
}

/**
 * Validation callback for some field.
 */
public function someValidationCallback(ExecutionContextInterface $context) {
  if ($this->something === 'something it should not be') {
      $context->buildViolation("Can't let you do that Dave.")
      ->atPath('something')
      ->addViolation();
    }
}


Here is one approach:

Start by adding a new region to the theme's .info file:

regions[navigation] = Navigation
Next, render the region. Put the code below in page.tpl.php either just before or just after the </div> in your code above. You may need to experiment a little.

<?php print render($page['navigation']); ?>
Clear your cache so your site knows that the new region exists.
Next, in Admin -> Structure -> Blocks, place the Search block in the Navigation region.
Finally, style the search form so it looks the way you want.


Problem uploading files and images containing spaces in the filename

Just I checked on different types of image files. So it could not reproduce your error. In my opinion, if your problem is in the server settings or the settings of the Drupal 8. Because viewing the forums, the Internet, communicate with colleagues at work, such a mistake, I have not met anybody.


What does the 'master' option in the attachment view settings stand for?

The master display is the default one created automatically for every view. It's not a block, so it won't show up in the list. For views, only their block displays show up in that list.

A quick trick to get access to the Master display: edit the view then without selecting any of the displays append "/default' to the URL and hit return.


May I know the difference between field_data_body and field_revision_body?

In short:

field_data_body is the current body data.

field_revision_body is a historic backup, that you can revert to if necessary.

Detailed explanation of revision:

  Drupal lets you create a new revision every time a node is updated.
  This allows you to track how the node has changed over time on your
  site.

  To enable this feature you go to the default node editing form (D6:
  administer/content management/content types/edit/workflow settings;
  D7: administer/structure/content types/edit/publishing options) and
  check the box Create a new revision in the node editing form. This
  will result in a new revision being created every time the node is
  edited. (Administrators can override this when editing an individual
  node.)

  To view and manage revisions, use the Revisions tab when viewing a
  node (you must have "view revisions" or "administer nodes" permission
  to view revisions.) From the Revisions tab, you can view the
  individual revisions, revert to an earlier revision, and delete
  revisions (you must have the "administer nodes" or "revert revisions"
  and "delete revisions" permissions).

  One interesting detail of the system is the behaviour of the reverting
  mechanism. Let's say you have revisions {1,2,3,current}. If you revert
  to revision #2, a copy of #2 is made and the copy is set as the
  current revision. Thus, after reverting you'll have {1,2,3,4,current},
  where current is a clone of #2, and #4 is the previous current
  revision.

  Another useful feature of the revision system is the Log field, which
  appears near the "Create a new revision" check box on the node editing
  form. If you add a message to the Log field when you create a
  revision, that message will appear on the Revisions tab along with the
  revision. It is a good idea to add a meaningful Log message whenever
  you create a node revision, so that others (or you, months later) can
  see why you changed the node and what your changes were, without
  having to actually view the previous revision.

  You can enhance the revisions tab by installing the contributed Diff
  module. This module allows you to see the differences between two
  revisions; without this module, you can only view the entire content
  of each revision, and it may be difficult to tell exactly what has
  changed between the revisions.

  Note that the node_revisions table in the database will always have
  one record associated with each record in the node table, which it
  keeps track of as the current revision. This will happen even if you
  do not have revisions enabled. On the other hand, if you have enabled
  revisioning, you will have multiple entries in your node_revision
  table associated with each node, corresponding, not just to the
  current revision, but all past revisions too.

Source: Node revisions

Related:

How to disable the revision feature completely?
Node Revision Cleanup


Pathauto and Token to get the first child term

You can do quite advanced things with hook_pathauto_alias_alter to replace complex aliases patterns with just PHP code.

Here's how to use it:

/**
 * Implements hook_pathauto_alias_alter().
 */
function MYMODULE_pathauto_alias_alter(&$alias, array &$context) {
  // Make sure we're dealing with nodes
  if (isset($context['module']) && $context['module'] == 'node') {
    // If this is a "my_content_type" content type
    if ($context['type'] == 'my_content_type') {
      $node = $context['data']['node'];

      // do stuff with $node, such as getting the taxonomy term
      // and loading the term.. then getting the children terms etc..

      // then assign a string value to $alias
      $alias = pathauto_cleanstring($child_term->name) . '/' . pathauto_cleanstring($node->title); // for example...

      // Clean the alias
      $function = 'pathauto_clean_alias';
      if (function_exists($function)) {
        $alias = $function($alias);
      }

      // Now just make sure the alias generated is unique to this node.
      $function = 'pathauto_alias_uniquify';
      if (function_exists($function)) {
        $source = 'node/'.$node->nid;
        $lang = $node->language;

        $function($alias, $source, $lang);
      }
    }
  }
}


Unable to use drush dl. No such file or directory filesystem.inc:267

The error:

  Failed to set default locale

sounds like tar command invoked by Drush has some problem detecting your system locale.

Try setting it to UTF-8 by the following command:

defaults write org.R-project.R force.LANG en_US.UTF-8

Source: How to fix 'tar: Failed to set default locale' error?


How to get the autocomplete feature for a taxonomy term profile field visible on the registration form?

Turns out it is a permission issue : adding the permission for anonymous users to View published content solves my problem as I do not have any reason to not let them see the website content

I guess for websites where content is for registered users only, this permission would not be granted and the widget would not be used on the taxonomy term field.. Maybe the Content Access module could help those use-cases


You need a combination of modules:

https://www.drupal.org/project/filefield_sources_plupload
https://www.drupal.org/project/filefield_sources
https://www.drupal.org/project/plupload

I have intentionally left these as URLs as these module are often confused between each other.

In the content type which you wish to use the plupload widget: manage fields > images > edit.
Scroll down until you see "File Sources", expand and select "Advanced Upload Widget (Plupload).

These basic steps should give you the option to use plupload when uploading images. You can further change the setting to allow a specific number of images etc.


Adding components to a feature via Drush

Update: there is a direct way to add components via Drush.

First, to list components drush fc (for features components) will list out all exportable components, including which, if any, feature they are currently exported to.

Next, drush fe foo_feature variable:foo_var views_view:foo_view will update, or create, a module named foo_feature. The output from drush fc can be used to populate the required component:name syntax.

Original answer

While there is no direct command, the quickest way to add components is by editing the .info file.

For example, to add a view foo_view, you would add this line:

features[views][] = "foo_view"

or, to add a variable that hadn't been added, you would add this line:

features[variable][] = "my_variable"

Once these have been added to the .info file, you can then run drush fu, and the additional components will be exported with your feature.

Update:

There is a command. See the below answer about the drush fe command.


I think you can just remove the relevant entries from the sessions table:

db_delete('sessions')->condition('uid', $your_user_id)->execute();

That should log the user out everywhere.


You should put your template in your module as well.

my_theme/templates/my-entities-property.tpl.php

Make sure to update your theme function like this :

function my_entities_theme($existing, $type, $theme, $path) {
  return array(
    'my_entities_property' => array(
      'variables' => array('element' => null),
      'template' => 'my-entities-property',
      'path' => drupal_get_path('module', 'my_entities') . '/templates'
    )
  );
}

Try to use THEME_preprocess_my_entities_property(&$variables) in template.php instead.


Interface translation conflict / same EN word, different translations

Drupal does have an answer to this problem, at least if it's your own code where you need to make that distinction. It's called context.

In the PO file, add a msgctxt line

# an explanatory comment line for your translator
msgctxt "Accomodation"
msgid "book"
msgstr "buchen"

In PHP, it works like this:

<?php
t('book', [], ['context' => 'Accomodation']);
?>

In twig, it should go like this:

{{ 'book'|t({}, {'context': 'Accomodation'}) }}

The problem with this approach is that the developer needs to be aware that a certain word might have a multiple context specific translations in another language that he most likely doesn't know. But for your specific scenario, it should work fine.


pecl uploadprogress installed, but I don't see it anywhere

Ah, I stumbled upon it right after posting. It needs to be configured on each Field in particular. I edited my Content Type and changed this setting:


Is there a generic method to retrieve entity IDs?

You're looking for the bundle key, which can be obtained from the entity type:

$entity_type = 'node';

// Load the entity type definition and get its keys.
$keys = \Drupal::entityTypeManager()
  ->getDefinition($entity_type)
  ->getKeys();

$query = \Drupal::entityQuery($entity_type);

// 'bundle' is optional, if not provided it will be the same as the entity type ID,
// but obviously you won't need to use it as a condition.
if (mb_strlen($keys['bundle'])) {
  $query->condition($keys['bundle'], $bundle);
}

$entity_ids = $query->execute();

See EntityType::getKeys() for more information.


Delaying form submission via Javascript doesn't work in IE

Try doing something like:

 $("form").submit( function () {
   //do something
   return true;
 }

Source


Basically you have to add a second parameter to your views page path so it looks somthing like this: taxonomy/term/%/%. The first % will be the category, the second will be the node type.

Now you have to add a contextual filter. Choose the filter "Content: Type". The default filter setting should work fine. You can try rewriting the title under "When value IN URL" to something like node type %2 to see if the value is correct.

You can test it in the preview at the bottom by setting the parameters to "entertainment/job" or "entertainment/job_description".


translate menu item using entity translation

With Drupal core alone, user-defined menu items are not translatable. The Menu translation module, part of the i18n package, allows users to select a translation mode for each menu.
LINK


Drupal Bootstrap THEME_menu_tree on new menu

This isn't related to Bootstrap. In your preprocessor you're using theme_links, which is unrelated to menus. Your "menu" isn't being output as a menu at all.

If page preprocessing is necessary, you can try:

function THEMENAME_preprocess_page(&$vars) {
  $menu = menu_tree_all_data('menu-banner');
  $vars['banner_nav'] = menu_tree_output($menu);
}

Or you can render the menu block (these are automatically generated if you have the Blocks module enabled):

function THEMENAME_preprocess_page(&$vars) {
  $block = block_load('menu', 'menu-banner');
  $vars['banner_nav'] = _block_get_renderable_array(_block_render_blocks(array($block)));
}

In page.tpl.php:

<?php print render($banner_nav); ?>

Either will work.

If you don't need to preprocess the menu, you can simply position it via the Blocks admin UI.

I hope that helps!


How to show a block on pages with a path like '/member/*' but not 'member/*/likes'?

Try restricting visibility to this URI:

member/*/

(trailing slash!)

Alternatively, you can download the Context module and position the block using a new context, and negate the member/*/likes path in your context configuration.


The module asks for an API key, as the description for the "Akismet API key" field on admin/config/antispam says:

  Please, enter here your Akismet API key. If you don't have one already, you can get it by simply signing up for a free account at Akismet.com. Note that this information is required in order to use the Akismet Service. Please, consult the Akismet FAQ for further information.

Drush doesn't report any error because there isn't any error to report. Only after you enable the module you can see its settings page, where you need to enter the API key. Even if you installed the module using the browser, you should not have seen any message about entering the API key.

If you cannot access the setting page to set the API key, you can:

Obtain the API key using the link I reported before
Use Drush to set the Drupal variable antispam_wpapikey

drush vset antispam_wpapikey $key

(Replace $key with the API key.)


Migration has spun ubercart into checkout redirects

I had a very similar problem with Ubercart in my site as well. The difference is that I would end up getting told that there was an infinite redirect and that seem to be quite what you're hitting. However, the root cause might be the same. I had an error in an email template that was supposed to get sent after completing checkout. I would suggest checking your server logs and possibly even setting display_errors = On in your PHP config. Also check your Watchdog logs for any errors.


Using Memcache Effectively with Drupal 7 Multisite

After much research, here is what has helped our hit ratio and memcached usage:

Upgraded memcached to 1.4.10 (the latest version with performance improvements)
Enabled binary format and compression
Use the default for bins

Our memcached conf in settings.php looks something like this now:

$conf['memcache_bins'] = array('cache' => 'default');
$conf['memcache_options'] = array(
  Memcached::OPT_COMPRESSION => TRUE,
  Memcached::OPT_BINARY_PROTOCOL => TRUE,
  );
$conf['memcache_persistent'] = TRUE;
$conf['memcache_key_prefix'] = $_SERVER['SERVER_NAME'];

Biggest Gains

The biggest gain for us was enabling compression, even though the documentations states that it increases CPU cycles. We have 4 CPUs allocated to our VM, and have not noticed a difference. Time for memcached calls went from ~1250ms to ~150ms (obtained from NewRelic) for creating a piece of content (custom Article in our case).

Hit Ratio

Our hit ratio is now ~70% -- much better than 55% earlier, but not quiet the 90%+ that some have reported ... the quest continues (-:

Hopefully this helps someone else. If you come across other improvements or have corrections/suggestions, please post comments or answers.

Update -- Version of memcahe module

We went from version 1.0-beta4 to 1.0 and our hit ratio now is 87% . I had to restart memcached as hit ratio wasn't going past 70%. We have 64MB allocated to memcached at the moment, so this was not a big deal for us.


Distance / Proximity from cck location field ? not from user or node location?

Results may vary based upon your drupal version, but basically when you create a proximity filter:

the first option is "Node location" but when you click on that:

it will allow you to use a Location CCK field as well.


Check if logo, sitename, slogan, and secondary links exist

$secondary_links = theme_get_setting('toggle_secondary_links'); is working fine.

It doesn't work if secondary menu is disabled form admin/appearance/settings

It works when secondary menu is disabled form admin/appearance/settings/theme-name

OR

It works when secondary menu is disabled form admin/structure/menu/settings source of Source for the Secondary links is set to 'No Secondary links'


Go to the Panel Configuration page into the Content section. Now choose in the dropdown field "Title type" the value "From pane".

Now select a pane with the view and click on the configuration link of this pane and choose "pane title".

Your Panel shows now the title of your selected pane.


What is best way to combine multiple fields in template preprocess?

I would do this using hook_node_view() or theme_preprocess_node(), but I'm not sure which is the best way.

function MYMODULE_node_view($node, $view_mode = 'full', $langcode = NULL) {
    if($view_mode == 'full'){
        if($node->type == 'your_content_type'){
            $field_1 = $node->content['your_field_1'];
            $field_2 = $node->content['your_field_2'];
            $field_3 = $node->content['your_field_3'];

            // remove individual fields
            unset($node->content['your_field_1']);
            unset($node->content['your_field_2']);
            unset($node->content['your_field_3']);

            // combine those fields in a tag
            $html = '
';
            $html .= ''.$field_1.'';
            $html .= ''.$field_2.'';
            $html .= ''.$field_3.'';
            $html .= '
';

            $node->content['combined_field'] array(
                '#markup' => $html,
                '#weight' => 1
            );
        }
    }
}

Another way is to alter these from THEME_preprocess_node() in the template.php.

function MYTHEME_preprocess_node(&$variables) {
  if ($variables['view_mode'] == 'full' && node_is_page($variables['node'])) {
    $field1 = strip_tags($variables['content']['field_1']['#markup']);
    $field2 = strip_tags($variables['content']['field_2']['#markup']);

    // remove individual fields
    unset($variables['content']['field_1']);
    unset($variables['content']['field_2']);

    // combine those fields in a tag
    $variables['content']['combined_fields'] = array(
        '#markup' => '
'.$field1.$field2.'
',
        '#weight' => 2
    );
  }
}


Increasing the search query limit (Apache Solr)

To do that programatically, you can implement hook_apachesolr_query_alter() to play with the rows parameter :

function yourmodule_apachesolr_query_alter($query) {
  // Increase the number of results per query
  $query->replaceParam('rows', 50);
}

Note : To disable the pager you can set a very very large number of rows, but it may impact performance. In this case you may prefer to bypass the pager at another level (for example in a preprocess function) and go with a more reasonable rows value.


hook_menu_local_tasks_alter for specific tab

You can use hook_menu_local_tasks_alter() in your template.php file for your theme or .module file in module like below:

function YOURTHEME_menu_local_tasks_alter(&$data, $router_item, $root_path) {

  foreach ($data['tabs'] as $key1 => $tabs) {
    foreach ($tabs['output'] as $key2 => $item) {

      if ($item['#link']['path'] == 'node/%/edit' || $item['#link']['path'] == 'user/%/edit') {
        $data['tabs'][$key1]['output'][$key2]['#link']['localized_options']['attributes']['class'][]  = 'CLASS_NAME_HERE';
      }
      else if ($item['#link']['path'] == 'node/%/delete') {
        $data['tabs'][$key1]['output'][$key2]['#link']['localized_options']['attributes']['class'][]  = 'CLASS_NAME_HERE';

      }
      else if ($data['tabs'][$key1]['output'][$key2]['#link']['title'] == 'View') {
        $data['tabs'][$key1]['output'][$key2]['#link']['localized_options']['attributes']['class'][]  = 'CLASS_NAME_HERE';

      }
      else if ($item['#link']['path'] == 'node/%/revisions') {
        $data['tabs'][$key1]['output'][$key2]['#link']['localized_options']['attributes']['class'][]  = 'CLASS_NAME_HERE';

      }

    }
  }
}

Hope this will help.


FormBase is abstract; it implements FormInterface, but doesn't contain methods for:

getFormId
buildForm
submitForm

You need to provide those in your class or PHP will reject it.
...
class Test extends FormBase {

  public function getFormId() {
    return 'foo';
  }

  public function buildForm(array $form, FormStateInterface $form_state) {
    // Build form then
    return $form;
  }

  public function submitForm(array $form, FormStateInterface $form_state) {
    // Perform submission tasks
  }

}


How do I check if the site is in maintenance mode?

From a procedural hook you'll probably need to use something like:

use Drupal\Core\Routing\RouteMatch;

...

$maintenance_mode = \Drupal::service('maintenance_mode');
$route_match = RouteMatch::createFromRequest(\Drupal::request());

if ($maintenance_mode->applies($route_match)) {
  // ...
}


How do I make multilangual content synchronization between two sites?

On the source site:

Make sure that your view has a column that contains an unique identifier for the item. This value must be the same for every language of the item.
Add a column to the view that contains the language code. For English this would be 'en' and for French this would be 'fr'.

On the target site:

On the feed type, map the unique identifier either to:

A non-translatable field;
Feeds item: GUID.

And mark that as unique on the feed type.

Map to all the fields that you want to map to.

Map the langcode value to the "Language" target.

Known issues
Note that there are some known issues with importing multilingual content using Feeds. I'm doing my best to resolve them.
You can currently run into the following errors:

this field cannot hold more than 1 values.
Patch available at https://www.drupal.org/project/feeds/issues/3155046

A translation already exists for the specified language
https://www.drupal.org/project/feeds/issues/3126351
No patch yet, but you could help by confirming or correcting the steps to reproduce the issue.

Column cannot be null (SQL error)
https://www.drupal.org/project/feeds/issues/3169398
You can help by describing the exact steps to reproduce this issue.


Why am i getting this Drush error after updating a site?

It looks like they just released Drupal 7.63 and in the release notes they say, "This is a hotfix release for a regression affecting some Drush installations that was introduced by the fix for SA-CORE-2019-002. No other fixes are included."


The title field will have an option on its settings to "Link this field to its content". Check off that box and save the view, and the titles should be linked to their node detail page.


How to programmatically get node ID in custom Rules Action

You can pass parameter node then you will get full node object into your action.

function MODULEname_rules_action_info() {
  return array(
    'CALLBACK_FUNCTION_NAME' => array(
      'label' => t('Send Mail to users for new content'),
      'parameter' => array(
        'node' => array('type' => 'node', 'label' => t('Current Node')),
      ),
      'group' => t('MODULE'),
    ),
  );
}


How to dynamically add options to  list in CKeditor dialog

You can pass data to ckeditor via the getConfig method in your plugin, e.g.:

public function getConfig(Editor $editor) {
  return [
    'pluginName_options' => $this->buildOptions()
  ];
}

And in the JS:

items: editor.config.pluginName_options


They are two different parameters that share the same name (and can share the same value by default). Per the docs for FloodInterface:

::register():

int $window: (optional) Number of seconds before this event expires. Defaults to 3600 (1 hour). Typically uses the same value as the isAllowed() $window parameter. Expired events are purged on cron run to prevent the flood table from growing indefinitely.

::isAllowed():

int $window: (optional) Number of seconds in the time window for this event (default is 3600 seconds, or 1 hour).

The register() parameter specifies how long that flood event will be stored (remembered) after the time of registration before ::garbageCollection() clears it out. The isAllowed() parameter specifies the max number of instances that can occur within that window before isAllowed() will return FALSE


add same class to book and it's child pages

One easy way I can think of if it's only about CSS, you can use body tag classes, it has different classes based on the nodes.


Create a module to access a 3rd party API and store the keys in the database

You can handle the storage and retrieval of the API keys in the database via the Drupal API functions:
variable_set and
variable_get.

To store the key (step 2):

variable_set('mymodule_api_key', $api_key);

To access the key (step 3):

$api_key = variable_get('mymodule_api_key', t('-key not set-'));

Where "mymodule" is the short name of your custom module.

As for a comprehensive example: There are many bridge modules in the Drupal.org repos that connects to an external service using an API and authenticates using API keys. One example of this is Mollom.


theme('table'...) function doesn't print the table header

You are using theme('table',array('headers' => $header,'rows' => $rows)), while you should be using theme('table',array('header' => $header,'rows' => $rows)). theme_table() looks for a property called header, not headers.

  Parameters

  $variables: An associative array containing:

  header: An array containing the table headers. Each element of the array can be either a localized string or an associative array with the following keys:

  "data": The localized title of the table column.
  "field": The database field represented in the table column (required if user is to be able to sort on this column).
  "sort": A default sort order for this column ("asc" or "desc").
  Any HTML attributes, such as "colspan", to apply to the column header cell.

  rows: An array of table rows. Every row is an array of cells, or an associative array with the following keys:

  "data": an array of cells
  Any HTML attributes, such as "class", to apply to the table row.
  "no_striping": a boolean indicating that the row should receive no 'even / odd' styling. Defaults to FALSE.

  Each cell can be either a string or an associative array with the following keys:

  "data": The string to display in the table cell.
  "header": Indicates this cell is a header.
  Any HTML attributes, such as "colspan", to apply to the table cell.


The better option is that you should select a formatter for the image field so that your views work properly when displaying logo images on to it.


How to 'SELECT FROM {entity_bundle} WHERE field_A + field_B <= given_number_X' with EntityFieldQuery

I dont believe you can do this with the core methods provided by the EFQ api.

But, you may always extend the default EFQ class with a version of your own. Or, you may implement a function such as hook_entity_query_alter() or the addTag() method of EFQ.

Using addTag for instance on the EFQ you could then also implement hook_query_TAG_alter() and alter the SelectQuery that is ultimately called from the original EFQ and alter the base query to include your additional (non-standard) logic.

This could look like this short example, we additionally use the SelectQuery::where() method:

// Within some function of yours, you execute your query; giving it a Tag.
$query = new EntityFieldQuery();
$query->entityCondition('entity_type', 'node')
  ->entityCondition('bundle', 'MYCONTENTTYPE')
  // Must call the method fieldCondition on field_A and field_B so
  // they get included in the SQL INNER JOIN statement.
  ->fieldCondition('field_A')
  ->fieldCondition('field_B')
  ->addTag('DoFunkyFieldLogic');
$query_result = $query->execute();

// ... elsewhere in your custom module ...

// Implements hook_query_TAG_alter
function mymodule_query_DoFunkyFieldLogic_alter(QueryAlterableInterface $query) {
  if ($query->hasTag('DoFunkyFieldLogic')) {
    // You will likely need to install Devel and call dpm($query) here.
    // Or else you wont know what the field names are in the raw SQL ...
    // you might be able to cheat and use full database table names and
    // column names, eg:
    //dpm($query);
    $query->where("field_data_field_A1.field_A_value + field_data_field_B2.field_B_value <= :my_quantity", array(':my_quantity' => variable_get('my_quantity', 5));
  }
}

There may be cleaner ways to do this -- but this approach is relatively straight forward. This code is untested; but should work.


Create a node type that acts like a PHP page?

First, you will need to enable the "PHP filter" core module in admin/modules.  I think you did.

Then, you'll need to configure the newly added text format in admin/config/content/formats and assign some role to that text format.  Note that you can also do this from admin/people/permissions.

Useless to say you'll need to be very conservative here and only allow this text format to - very - trusted users (roles).

Finally, in your node content, select the "PHP code" text format and type your code (including  tags).


How to programmatically reference entities?

As pointed out by 4k4 in the comments, the most robust way is assign an entity object to the field like so:
$new_entity = \Drupal::entityTypeManager()->getStorage('node')->create([
  'type' => 'notification',
  'title' => $entity->label(),
  'field_content' => [
    'entity' => $entity,
  ],
]);

For posterity, you can also do it by setting the field column (target_id) directly, but this is only useful if you have a saved entity. The first example will work for both new and existing entities.
$new_entity = \Drupal::entityTypeManager()->getStorage('node')->create([
  'type' => 'notification',
  'title' => $entity->label(),
  'field_content' => [
    'target_id' => $entity->id(),
  ],
]);


View add a new field it can't find the fields "All disappeared "

After spending two nights I finally manage to make it work for me by Always show the master display from /admin/structure/views/settings and enabling.

However this is a major bug in view and to be honest pain in the bottom !

Hope next release of view will consider looking into this bug.


Any way to customize default nomask used in file_scan_directory() to allow Node.js modules?

As far as Drupal/PHP are concerned, no, there's no option other than either changing the default arguments to the function, or finding all calls to that function that don't include the 2nd arg, and updating things there. Either way you're likely to have to patch a core method or two.

NPM's convention is to use a folder called node_modules. They don't want to change that (https://github.com/npm/npm/issues/2734, https://github.com/npm/npm/issues/775), but there is a prefix config option which may be suitable for your needs.


Advanced sorting question about drupal views

You will need help of views_php module. This module will help to sort views rows with a calculation. You need to go through.

But in your case, The calculation has a value from current page. So you have to get the current page value (lang, lat) in sorting field, may be you can use it as a global variable or call a function from inside the php field.

Hope this helps you. :)


How to correct my Rules Component to perform VBO operations for the Group module?

Part 1: Create a Rules Component

Have a look at this Rules Component (in Rules export format):

{ "rules_remove_selected_group_members" : {
    "LABEL" : "Remove selected group members",
    "PLUGIN" : "rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "USES VARIABLES" : { "group_mbrship" : { "label" : "Group membership", "type" : "group_membership" } },
    "DO" : [ { "entity_delete" : { "data" : [ "group-mbrship" ] } } ]
  }
}

Some more details to further explain the above Rules Component:

It uses a "Group membership" (which is an entity, remember!) as a parameter.
All it does is to perform an Action "Delete entity", for the entity specified as parameter.

By deleting such entity, you do the same as what happens when using the "Remove selected members" (for 1 specific Group membership, entered as parameter).

If you want, just copy the exported Rules Component above, and import it in your own environment. Then navigate to admin/config/workflow/rules/components in your own site and use the hyperlink "execute" to qa-test it in your own site. After you use that link, use the button that says Switch to direct input mode. Then you'll be able to enter some Group membership identifier and hit the Execute button. The Group membership for the id you specified will be deleted then.

Tip: (temporary) improve your Group Membership view to also include the field "Group Membership Id" (=mid). This makes it easy to know which ID to use when testing this Rules Component.

After you're confident this Rules Component works perfect for all variations of your nodes, it's time to move on to Part 2 below.

Part 2: Extend your VBO view

The typical next step when creating custom VBO oprations, is to edit the VBO field in your view, and enable the additional VBO operation that corresponds to the Rules Component as in Part 1.

In my case, with the VBO view I'm using, I ran into some AJAX error which I could not resolve right away. I was pretty sure it is NOT a bug, but rather something I'm doing wrong. Head over to Part 4 for more details on that.

However while further investigating this error, I realized that there is no need at all for a Rules Component to implement that VBO action "Remove selected members". Head over to Part 3 for more details on that (sometimes the solution to a problem, is to prevent the problem from happening ...).

Part 3: Enable a standard VBO action

Head back to your VBO field in your view, and enable "Delete item" (within Selected Bulk Operations). I suggest to use the "Override label"-option for it, and give that VBO action a label like "Remove selected members".

QA-test this VBO action to confirm it does exactly the same as:

what you try to achieve with the custom Rules Component in bullet 1 of your question.
what I try to achieve with my Rules Component in Part 1 of this answer.

Part 4: Heading for the golden cradle (= Solve the AJAX error)

The AJAX error as in Part 2 is resolved by using this variation of the Rules Component from Part 1:

{ "rules_remove_selected_group_members" : {
    "LABEL" : "Remove selected group members",
    "PLUGIN" : "rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "ACCESS_EXPOSED" : "1",
    "USES VARIABLES" : { "group_mbrship" : { "label" : "Group membership", "type" : "group_membership" } },
    "DO" : [
      { "entity_delete" : { "data" : [ "group-mbrship" ] } },
      { "drupal_message" : { "message" : "Membership of group [group-mbrship:group:title] removed for user [group-mbrship:user]." } }
    ]
  }
}

Note the "ACCESS_EXPOSED" : "1" added here now (apart from the extra "drupal_message" Action, which has nothing to do with the AJAX error). That turns out to be the clue to solve the AJAX error. For (way) more details on this, refer to Comment nr 13 in Support issue # 2530000. My understanding about that comment is that something in Entity API or Rules is what causes the AJAX error, and by using this access setting you prevent the issue.

With that, you now have 2 solutions/answers to solve your question ... i.e. to Remove selected members. My preference is using the Rules Component from Part 4, because:

The messages you get after executing it are more detailed as compared to Part 3.
If you want, you can add any additional Rules Action or Rules Condition in the Rules Component.

Voilà!


Drupal Commerce: Display Different Shipping Rate depening on taxonomy Term

I needed the exact thing for my webshop. Couldn't find it anywhere so a friend of mine made this module which works great!
https://drupal.org/project/commerce_taxonomy_conditions

On my site every product has either the taxonomy term 'letter' or 'package'
And then with that module you can add an extra condition to your shippingmethods to only use the products which that specific term.

If you are still in need for it then try it out :)


Since you want to do it for few fields, I would suggest to do it using custom code rather than any module.

You can implement hook_field_access($op, $field, $entity_type, $entity, $account) and check for the "field name, content type, user, operation" and then  deny or allow access.


setting default language in drupal multilingual module

Please check these steps as described on this link, How to Change the Default Language of a Drupal Site. You might come to know which step you are missing.


The form ID of the form alter function is wrong. It should have _ instead of -.

function MYMODULE_form_alter(&$form, $form_state, $form_id) {
  if ($form_id == 'project_node_form') {
     $form['actions']['submit']['#value'] = t('Publish');
  }
}


You can use the Comment limit module.

  Limits how many comments a user may post on a node.
  Adjustable on a per node type basis.

  This module can be handy for instance when comments are used as "Reviews" and "Ratings" for products and a user may only review and rate a product once.


You'll need to define an ajax callback. This callback function can then be called by the form, and can submit values to the database for you using the Drupal database layer. In this case, I imagine the ajax handler will be added to the Next or Submit button.

$form['next'] = array(
  '#type' => 'submit',
  '#value' => t('Submit'),
  '#ajax' => array(
    'callback' => 'custom_ajax_callback'
  ),
);

Your module might also want to define its own database table to store temporary values for this.


where to put addCommand when implement ajax callback commands

You put it in a controller like shown in the linked question, not the answers. Then this topic might be helpful how to trigger the ajax controller: How to Trigger Existing, Non-Form Ajax from JavaScript Event

For passing the node ID to the controller use a route parameter:

myModule.myRoute:
  path: '/myajax/node/{node_id}'
  defaults:
    _controller: '\Drupal\myModule\MyController::getNode'
    _title: 'Node'
  requirements:
    _permission: 'access content'

Now you can add the node ID to the endpoint url

var url = '/myajax/node/' + node_id;
Drupal.ajax({url: url}).execute();

and received it by the controller:

public function getNode($node_id) {


The user needs the permission "Use the administration pages and help".

Then the user can access /admin and /admin/structure.

If the user has no other admin rights, the admin menus will be rather empty. They will fill up if you assign more permissions.


How to fetch the status of profile flag?

I worked with Profile2 a while ago and it was not a joy for me. I remember having to implement a hook_user_insert and creating the profile right there and there as the profile was only created after a user saved a new profile. So if you have a flag on it and flag it without saving the profile it might just go lost as the profile does not really exist yet.


Creating default object from empty value

It sounds like your system wants to make sure $vars['rdf'] is a valid object before assigning properties to it.

Try adding:

if (empty($variables['rdf']) || !is_object($variables['rdf'])) {
  $vars['rdf'] = new stdClass();
}

Just above your line 31.

For safety's sake, add it above

if (module_exists('rdf')) {

That way the object will get initialized regardless of whether the RDF module is enabled or not.


Taxonomy Terms based on already created content

Instead of using taxonomy term use the following options:

Option 1: References module

  This project provides D7 versions of the 'node_reference' and 'user_reference' field types.

Option 2: Entity reference module

  Provides a field type that can reference arbitrary entities.


Ensure a given module (set) is enabled on a dev site

(It was me who wrote the instructions for the hook_init() hack at http://drupal.org/node/206368.)

Recent module-level ways of supporting this workflow are underway at the Environment module, and the Production check & Production monitor.

I feel they will rapidly become too bulky: Do you really need to enable a module to ensure another module is turned off?
But, at least they may be able to provide a few conventions for us, like putting the list in local.settings.php or equivalent.
I hide per-instance configs in in my site_aliases.drushrc, which is my alternative to local.settings.php

I'm not going for another script you have to call, unless it's part of a fully automated workflow.


I was recently at the NYC Drupal meetup where the maintainer mentioned this exact feature. He said that it is on the road map, but it does not exist yet. That said, he is very open to patches :)

Incidentally, please note that the YAML form module was renamed to Webform.


Umlauts grouped in summary (U and Ü, A and Ä etc)

If I had to take a guess at this it would be that your database is using utf8 and the default collation of utf8_general_ci. If I understand correctly, this collation does not handle diacritics very well, and would consider U and Ü the same. You may have better luck with utf8_unicode_ci. That said, most of my Unicode experience is with Elasticsearch, so I know less about MySQL collation (assuming that is your database). You may have more luck running this by a database-specific stackexchange.

Here is a reference on the two collation types: https://stackoverflow.com/questions/1036454/what-are-the-diffrences-between-utf8-general-ci-and-utf8-unicode-ci.


How can I create a custom calculator on a drupal site?

I see you've tagged this question with JavaScript, so it looks like you want to make a calculator using JavaScript.

To do this, you could make a custom module.

Create a module called calcform.
Create calcform.js
In your calcform.module you could create a custom block that has the calcform form.

You'll need to checkout: Creating modules | Block examples

function calcform_form(&$form, &$form_state){
  $form['number1'] = array(
    '#type'=>'textfield',
  );
  $form['number2'] = array(
    '#type'=>'textfield',
  );
  $form['calc_button'] = array(
    '#type'=>'button',
    '#value'=>'Calculate',
  );
  return $form;
}

Then in your JavaScript:

(function($){

  Drupal.calcform = {}

  Drupal.behaviors.calcform = {
    attach:function(){
      Drupal.calcform.bindEvents();
    }
  }

  Drupal.calcform.bindEvents = function(){

    $('#calc-button').click(function(e){
      // Prevent default button from submitting the form.
      e.preventDefault();
      // Do your magic here.
    });

  }

}(jQuery));

This is all very pseudo-cody, but it's the general idea.
You actually don't need to write ANY JavaScript. You could create a form submit function that does the calculations and prints out the result to the form. You can then use the $form['#ajax'] capabilities to do all the magic for you.

Drupal is amazing like that.


Under access callback you have TRUE, just change this to a function that evaluates whether the current user is the author of the current node. The function would look like this

function yourmodule_check_author() {
  global $user;
  $node = menu_get_object();
  return $node->uid == $user->uid;
}

Check this post. You will get more insight on the inner workings of the function.


Assuming you are talking about the Webform module, you can create an element with type of "markup".  There are a few options for this, including input format.  If you have everything configured properly, you can use a WYSIWYG editor on the fields, too.

If you are using the Form API, then you can use #type = "markup"; to put pretty much whatever HTML you want in your custom form.


How to make users get points when using Rate module to rate content?

You can try User Points module.

  This module provides an API for users to gain or lose points for
  performing certain actions on your site.


How to get language specific path in twig?

For a twig only solution you can define a custom twig function path_lang(), which adds the language object to options, if a language code is  provided as additional parameter:

src/TwigExtension.php:

<?php

namespace Drupal\mymodule;

use Drupal\Core\Language\LanguageManagerInterface;
use Drupal\Core\Routing\UrlGeneratorInterface;

class TwigExtension extends \Twig_Extension {

  protected $languageManager;

  protected $urlGenerator;

  public function __construct(LanguageManagerInterface $language_manager, UrlGeneratorInterface $url_generator) {
    $this->languageManager = $language_manager;
    $this->urlGenerator = $url_generator;
  }

  public function getName() {
    return 'mymodule';
  }

  public function getFunctions() {
    return [
      new \Twig_SimpleFunction('path_lang', [$this, 'getPathLang']),
    ];
  }

  public function getPathLang($name, $parameters = [], $options = [], $langcode = '') {
    if (!empty($langcode)) {
      if ($language = $this->languageManager->getLanguage($langcode)) {
        $options['language'] = $language;
      }
    }
    return $this->urlGenerator->generateFromRoute($name, $parameters, $options);
  }
}

mymodule.services.yml:

services:
  mymodule.twig.extension:
    arguments: ['@language_manager', '@url_generator']
    class: Drupal\mymodule\TwigExtension
    tags:
      - { name: twig.extension }

In twig:

{{  path_lang('entity.node.edit_form', {'node': nid }, {}, 'en') }}


Change Views Handler for entity schema field

Sure. Adding a new answer to clarify.

To my knowledge (and by that i mean my "very limited Drupal Knowledge") there are 2 ways of mapping the information between schemas and Druapl handlers: by using a custom view controller as i tried to do in the first post, and by implementing the hook_entity_property_info_(). I still don't know why the former approach didn't work but the solution for me was to go with the latter. That is, i had to write

'myfield' => array(
  'type'  => 'boolean',
  'label' => t('clever label'),
  'description' => t('clever description'),

  // Map here the field from hook_schema().
  'schema field' => 'insert_name_of_schema_field_here',
),

Mind that you will have to map EVERY AND EACH of your fields in the schema once you start with this approach.

I also noticed that sometimes doing stuff (like changing ajax config) on the view rendering my entity seems to break the mappings, and i have to clear all caches to bring back my settings.

You can find more information Here


Drupal 7.2, Views: Adding Author's Name of a node

You need to add a connection between users and content. This is done through relationships. Go to relationships and select Content: Author. Then if you add fields you will see several new fields to choose from including User: Name. When configuring User: Name there will be a drop down that lets you choose which relationship since there is only one choose that one.


Drupal custom node type add field to relate content

I found the answer, there's a module named Entity references, this allows you to add and Entity Field in your custom node type, and with this you can relate to another contents. To use it you just need to add the field, select what do you want to point to, an that's all. To render the entity field and it's fields you need to add to you tpl something this:

<?php print render($content['field_myentityfield'][0]['node'][62]['fieldof_entityfield']['#items'][0]['value']); ?>

You can check it with devel.


How to install a third party library for Printable module using composer (D8)?

This depends on how you have installed your Drupal site. There is a long description on how to use composer on Drupal.org handbook section.

The short version is this:

If you have installed Drupal 8 as you did with Drupal 7 using composer_manager module (which is depricated now)
If you have installed Drupal 8 using composer, you can require Drupal modules using composer, which automatically will download dependcies (assuming module developers has done their job by adding this information in their module's composer.json file)


How to extend the basic user object upon installation?

Fields, like most other things, are configuration (entities) now.

That means you don't have to write code to create them, you can simply create them in the UI, then export them through the Configuration management UI and put the relevant files into your config/install folder. Drupal will automatically import all your configuration from that folder.

Note that a field commonly consists of 4 parts:

The field storage, a file named field.storage.user.yourfieldname.yml (or node, comment,... for other entity types). This defines the field and storage relevant configuration.
The field, a file named field.field.user.user.yourfieldname.yml (user is special because there is only one bundle, for nodes, it would e.g. be node.article). This defines that a field is available on a specific bundle and includes configuration like the label.
One or multiple form displays, for example named core.entity_form_display.user.default.yml. User by default has two form modes, default and register. Node by default has only one. This stores the widget configuration for the field.
One or multiple view displays, for example core.entity_view_display.user.default.yml. This stores the formatter information for a specific view mode.

The first two files can just be copied to your config/install folder. The other two are bit more complicated, because they contain the widget/formatter configuration for all fields of that entity type, bundle and form/view display combination. So in the case of user for example, you do need a bit of code to add the configuration to the existing form/view display. See node_add_body_field() for example code. You can get the exact settings from the exported files.

If you own the bundle, for example, if your module defines a node type with a numer of fields, you can also just add those form/view displays to the configuration folder.


Only load Views Slideshow JavaScript when needed

If you want to only enable a Views Slideshow (or any other object) on certain pages, I recommend having Views output a block and then setting that block to display only on the necessary pages. It should only call the js (which should reside in sites/all/libraries) on pages that load the block. You can then set the block to display or hide by role, page, etc.


Parse error on JSON response containing URL value

The problem is with drupal_to_js() which is called by drupal_json() to do the job. drupal_to_js() will perform str_replace(array("\r", "\n", "<", ">", "&"), array('\r', '\n', '\x3c', '\x3e', '\x26'), addslashes($var)) to every string it receives. Converting '&' to '\x26' is making problem to me here. Anyway I cannot use json_encode() because of PHP dependency (Drupal 6).

I solved the problem by URL encoding the URL value on server side using PHP function urlencode() when preparing JSON data. And URL decoded it on browser side by JS function decodeURI().


Change height of CKEditor (per profile) without using WYSIWYG Module

UPDATE:

The patch in this thread on DO fixes this issue.

Looking at the ckeditor demo on this page it is possible to change the height of the editor with css alone.

The div .cke_contents has an element style setting the height to 300px, however a rule in the stylesheet marked as important would overrule this.

So, if you can add the roles of the user as a classes of say the body, then you could include:

.role1 .cke_contents {
    height: 400px !important;
}
.role2 .cke_contents {
    height: 100px !important;
}

Alternatively there may be a class added by the CKEditor profile type that you could use.


How to give permission for a role for editing help text for fields of custom types?

The Field help helper module seems to be a good fit for this. some more details about it (from its project page, which is also here the image originates from):

The Field help helper module adds a link to entity configurable fields so that users with the appropriate permissions may easily edit the help text and label for a field in context of where the field displays.
Once a user's role is given the Edit field help text permission any user with that permission will be able to edit the help text or label of a configurable field without having access to administer fields.

Extra bonus: comes wth an official release for both D7 and D8 ...


How can I set a node reference programmatically?

First, I"ll answer your question, then suggest another way.

Assuming that this is a monolingual site, use

$additional_node->field_created_node[LANGUAGE_NONE][0]['nid'] = $created_node->nid;

However, Rules already has actions that can change values on a node, and when you create a node using Rules, it creates a new variable containing the created node. If I were you, I'd just add actions that use that data and not write custom PHP code to do it. I just created one to assign populate a user reference field on a created node (within the same rule) the other day, and it worked fine.


change image size in media file selector of media module

The media module adds the image style 'square_crop' when it is enabled

you can alter this image style to change the display of thumbnails in the media browser (admin/config/media/image-styles/edit/square_thumbnail).

I believe the theme css also uses css to define the size, so to see the effect you will also need to make some changes in whichever theme is selected for the media browser (admin/config/media/browser):

.media-item img {
 border: 2px solid transparent;
 display: inline-block;
 margin-left: -2px;
 height: auto; /* override this in you theme */
 width: 100%; /* and this */
}


field->raw problem with date in views-view-field.tpl.php (add classes to day and year in date)

This looks like a "feature" in views, for some reason the entity_id is returned in the "raw" property, instead of anything related to the date.
So you will have to work with the "content" property and just make sure you get what you need there - in the view fields settings, set formatter to "plain" and in style settings HTML to none. This way the content will be just the date value from the database.
Check what type of a date field you are using - some of them are stored in the database as the integer timestamp, some as the textual representation of the date. If you want to work with the timestamp, you will have to either change the type of the field, or convert it in the template (probably not very good performance).
For the formatting, you can use the DateObject from the date module, it even has the handy to_array which might be of help :).


The without() filter's argument should be just the name of the key itself, which in this case is flag_class_registration without the content.. Consider - the filter only receives the expression that comes before it, so it's already inside the content array.

   {{ content|without('flag_class_registration') }}


Which is the database table in which Boost stores the cache expiry time of a node and what is the column name?

Basing on boost_schema(), the description of those fields is the following:

expire: UNIX timestamp for the expiration date of cached page
timer: Time in milliseconds that the page took to be generated

The expiration time is contained in the "expire" database column.


Ubercart Line item tax not displayed first time

I added the line items at validate. However at that moment the tax is already calculated. What needs to happen is recalc the taxes. This can be done from a ajax call when a field changes value.

function My_Module_update_line_items($form, $form_state) {
  $commands = array();
  if (isset($form['panes']['payment']['line_items'])) {
    $commands[] = ajax_command_replace('#line-items-div', drupal_render($form['panes']['payment']['line_items']));
    $commands[] = ajax_command_prepend('#line-items-div', theme('status_messages'));
  }

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


Cannot access the site after changing admin password

The problem was related to one of the two below (or both):

The error from the intel module
The session cache / cache

Currently the site is live and working great, but the Intel module is active currently  and I don't know if to disable it or not.

The second thing we did (me and the nice guy that helped me) is to clear the cache and sessions cahce  - which was problematic for me since I did not had access as admin. We used update.php after allowing every user to access it on the setting.php file (changed false to true), and clear the cache through the mysql query on the 'my php admin'.

Here are the steps:

enter my php admin
choose database
go to mysql tab
on the query:
UPDATE system SET status='0' WHERE name='intel';
then need to flash the cache - run the query:

TRUNCATE TABLE sessions;
TRUNCATE TABLE cache;
TRUNCATE TABLE cache_bootstrap;
TRUNCATE TABLE cache_block;
TRUNCATE TABLE cache_field;
TRUNCATE TABLE cache_form;
TRUNCATE TABLE cache_image;
TRUNCATE TABLE cache_menu;
TRUNCATE TABLE cache_page;
TRUNCATE TABLE cache_path;
TRUNCATE TABLE cache_update;
TRUNCATE TABLE cache_views;

I will be happy to get feedback on this solution. The site is currently working - so problem solved.
But, I don't know if I still can't disable the intel module and if I can change the admin password. I don't want to cause the problem again.


How do I set the HTML element of a text field?

Have you tried Panels Extra Styles ? As per module page :

  Panels Wrapper

  Wrap your panes and regions with unlimited possibilities.
  Go HTML5! Wrap your content in the newly defined tags. Add custom
  containers and HTM

  Wrapper: Element

  Wrap any region or pane with one of several dozen tags, including
  HTML5 elements.

  Wrapper: Raw

  Wrap any region or pane with a custom raw prefix and suffix.

  Sample output after applying the wrapper elements on 1 region and 2
  content panes: the powered by block and a main menu.


Converting the login / register / password reset tabs into three different pages?

You could create different twig templates for that three pages and remove the local tasks from the display. Depending on your theme, it may also be sufficient to just disable the "tabs" block on these three pages. Then you'd create a custom menu (and block) with these three links in it and display it where you need it.


How to get all pages of a custom content type to be displayed using a custom view?

Structure -> Views -> Add a view (`/admin/structure/views/add')
View Settings: Show Content of type MyPage.

I suggest reading the Views documentation.