Is Drupal forum module suitable for a massive forum

It depends on how 'massive' is your forum, what level of control you expect to have on the forum and how powerful and well configured is your server. There are Drupal forums with couple of hundred thousand users that work kind of fine, but if your main goal is to have a large and capable forum, you get much better performance and features out of specialized forum software like VB.

While Drupal forum provides rudimentary functionality, you will have hard times attaining many common specialized forum features like assigning different moderators to each forum, post thanks (which exists in D6 but not in D7), merging threads, banning users for certain amount of time, limiting posts/threads per day, and the list goes on and on.

The only pros that I can think of is integration to Drupal core, which makes sense only if you already have a Drupal site.


Need to identify higher value and lower value stored in the multivalue field

Never put code in the database. It is impossible to maintain and debug, and you spend hours wasting your time.

The computed field gives you the option to add the code to a custom module.

My answer used these three fields added to the content type:

Temp (machine name field_temp, integer, multi-value)
Highest (machine name field_highest, computed, int)
Lowest (machine name field_lowest, computed, int)

Method:
Create a custom module (just module and info files), then add this to the module file:

function computed_field_field_highest_compute(&$entity_field, $entity_type, $entity, $field, $instance, $langcode, $items) {
  $temps = field_get_items($entity_type, $entity, 'field_temp');
  if (count($temps)) {
    $max = $temps[0]['value'];
    foreach($temps as $temp) {
      $max = $temp['value'] > $max ? $temp['value'] : $max;
    }
    $entity_field[0]['value'] = $max;
  }
}

function computed_field_field_lowest_compute(&$entity_field, $entity_type, $entity, $field, $instance, $langcode, $items) {
  $temps = field_get_items($entity_type, $entity, 'field_temp');
  if (count($temps)) {
    $min = $temps[0]['value'];
    foreach($temps as $temp) {
      $min = $temp['value'] < $min ? $temp['value'] : $min;
    }
    $entity_field[0]['value'] = $min;
  }
}

Read the documentation page for the computed field module to see the naming convention for adding a custom function. The function name is also visible in the field settings.

In the two functions I refer to 'field_temp'. It is the machine name of the multi-value field holding the temperature values.


Change line 4 in your .module file

foreach($form['strings'] as $name => $field){

with this

foreach($form['strings']['all'] as $name => $field){

It should do the job


Colorbox not working for anonymous users, but works fine for logged in

I had a javascript conflict in my theme. Works great now that that has been cleared up. Thanks!


To render the existing image, please use the below code

$form['project']['image'] = array(
  '#type' => 'managed_file',
  '#title' => t('Image'),
  '#default_value' => array(10),
);

You need to give the fid in array format. Please try it and let me know whether you got the result


Hide user fields on profile2 registration form

to hide and show fields on user registration form while using Profile2 path - try the following in hook_form_alter in template.php.

if ($form_id == 'user_register_form') {

// get current path
$request_path = request_path();

// check if current path corresponds to your registration form for a particular role
if (strpos($request_path,'buyer') !== false) {

// removes the field that should be hidden
$form['field_1']['und'][0]['value']['#access'] = FALSE;

// or
unset($form['field_1']['und'][0]['value']);

// set the state of the field to required
 $form['field_2']['und'][0]['value']['#required'] = TRUE;

}
}

simple warning - you may find that Location  module fields that utilize ajax (same goes for Address Field module) have a bug that breaks the user reg. form produced by Profile2 Path if it is submitted with errors and exposes fields hidden with method described above. Look for insight in this issue (https://www.drupal.org/node/2558335).


How to add Retargeting tag into each page?

drupal_add_js() doesn't support the async property (there is a patch however) but the simplest solution would be to just just add that line to your html.tpl.php as Geoff suggested.


Tokens in the "Help text" field work, at least for the taxonomy term reference field.

I tried adding "[current-date:long] [current-user:ip-address]" to the help text of a taxonomy reference field, and I obtained the following.

Tokens didn't work for the image field, though.

I have also tried with [current-date:custom:e], and it worked.

What confused me is that I didn't notice the summary of available tokens I normally expect from the Token module. It doesn't appear for the taxonomy reference field, but it appears for the image field, for which the tokens are not replaced.


How to sort null field values in Drupal?

You can achieve it by installing Views Sort Null Field module.

  This module provides an additional sort for FieldAPI fields, which
  sorts by whether the field is empty or not. This allows empty (i.e.
  NULL) values in fields to be sorted last.


Then you can do it like this:

Use view-field--field-average-score.tpl.php which will affect all views that have this field, but we can add an if statement to target the views you only want the special markup.

Ex: In here we check if it has view_name with block_1 OR view_name_2 with block_1

<?php if (($view->name == 'view_name' && $view->current_display == 'block_1') || ($view->name == 'view_name_2' && $view->current_display == 'block_1'): ?>
<?php $rating = round(($output/100) * 5, 1); ?>

  <?php print $rating . '/5'; ?>

<?php else: ?>
<?php print $output; ?>
<?php endif; ?>

In case you are wondering, current_display is the machine name

The $view->current_display check is optional. This is so it only affects a certain Display of block/page that is inside your view.

So for line 1, you could use this instead:

<?php if ($view->name == 'view_name' || $view->name == 'view_name_2'): ?>

If you want to affect all blocks/pages that are inside these 2 views.


Remove the '#' from the form field key and clear cache. $forms['theme'] instead of $forms['#theme'].

$forms['theme'] = [
    '#theme' => 'moduletheme',
    '#test_var' => $this->t('Test Value'),
];


node:menu tokens not working in Pathauto

Just encountered that, after a full debug, it seems that menu_tokens() is not called at all.

  // There is a huge bug with menu tokens not being detected, to fix that, load
  // token include file and force repicking the menu_tokens() function as
  // implementation of hook_tokens()
  module_load_include('inc', 'token', 'token.tokens');
  module_implements('tokens', FALSE, TRUE);

That crappy hack fixed my problem but Why... just WHY ?

So yeah, after a deeper investigation, in module_implements():

  $include_file = isset($hook_info[$hook]['group']) && module_load_include('inc', $module, $module . '.' . $hook_info[$hook]['group']);
  // Since module_hook() may needlessly try to load the include file again,
  // function_exists() is used directly here.
  if (function_exists($module . '_' . $hook)) {
    $implementations[$hook][$module] = $include_file ? $hook_info[$hook]['group'] : FALSE;
  }

Okay, so the only thing that is preventing menu from being picked is the sorting:

if menu is processed before token in this module_implements(), the menu.tokens.inc include file will not be picked as it doesn't exist
if token is before menu, the token.tokens.inc thus menu_tokens() function will be discovered and picked up after

So if you don't want any code, just alter the weight of token and menu so that menu's is higher than token's.

But NO, there is a token_module_implements_alter() that just does that, but it is not called, and that is the thing I couldn't figure out. So the final hack was:

  // Rebuild implementation cache
  cache_set('module_implements', array(), 'cache_bootstrap');
  cache_clear_all('hook_info', 'cache_bootstrap');


entity_metadata_wrapper Changes not being saved to user Profile2 profile

I believe entity_metadata_wrapper expects the second parameter to be an object. As in:

$profile_wrapper = entity_metadata_wrapper('profile2', $profile_profile);


How to approach scheduled rules to real deathline?

Rule scheduler works with CRON only so you have to run CRON frequently, but you can use Elysia Cron module, where you can specify different schedule for different hook_cron(), so if you want your rules scheduler to run frequently then configure rules_scheduler_cron() to run say every five minutes and  configure other hook_cron() to run every two hours.

In that way you run reduce the load.


It looks like the issue is that the permissions are created before there are defined (since you need to have the content types created before the permissions are created).

This could be fixed with proper dependencies (since the feature with the permissions depends on the feature(s) with the content types.


A strategy question regarding content types vs. basic pages plus taxonomy/tags

You could use radio buttons for your 'content type' taxonomy terms and make it required.  That way your user sees all the content types available and has to pick one.  For your free tagging, you might be able to use a module like Active Tags to make it a bit more accurate as well.


How to hide empty blocks supplied by the User Relationship module?

Rules block visibility

Have a look at the Rules block visibility module. Here is a quote from its project page:

  The Rules block visibility module allows Rules components to be used to control block visibility. This provides Drupal administrators and developers extreme flexibility in controlling when blocks should be displayed on their websites, in addition to the default visibility options provided by Drupal.

  The general idea is that if you can do it with Rules, you can use it to control block visibility, so the possibilities are limitless:

  Need to show a block only for users registered more than a month ago?
  Perhaps you have a block that must be shown only between 8am-5pm on weekdays?
  What about displaying or hiding a block based on current weather conditions?

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

With that, and as per the "if you can do it with Rules, you can use it to control block visibility" above, you've reduced your question to making Rules check situations such as "is this a node posted by the logged in user" (so that the block is not to be shown).

For an illustration of how to use this module, refer to my answer to "How to stop a Views block from displaying to admins, such as user/1?".

Advanced debugging options

To futher investigate the "The website encountered an unexpected error, please try again later" (as in your comment to this answer), keep in mind that such errors originate from some PHP exception that occured somewhere. To get more details about such error, check your 'Recent log messages' (within "Reports", located at /admin/reports/dblog), which is available if the Database logging module is enabled.


How to keep Display Suite CSS classes in code?

Seeing that you use Drupal 7, have you checked out the Features and Strongarm modules? Both modules allow you to export most configs as code.


Mysterious "Page not found" on every page load for authenticated users

After further investigation, this appears to be an issue with CloudFlare. Disabled it, and the problem went away... re-enabled it, and the problem returned, but with a different image url!

Yet further investigation shows Cloudflare's Website preloader to be the culprit. So nothing to do with Drupal.


I have a field which looks corrupted. How should I remove all traces of it?

This is totally off the top of my head so use with much caution, and after taking lots of backups!

// Remove taxonomy index records. Do this BEFORE removing field data tables.
$indexed_tids = db_query("SELECT field_foo_tid FROM field_data_field_foo WHERE entity_type = 'node' AND bundle = 'bundle_field_is_attached_to'")->fetchCol();
db_delete('taxonomy_index')->condition('tid', $indexed_tids)->execute();

// Remove the field data tables completely
db_drop_table('field_data_field_foo');
db_drop_table('field_revision_field_foo');

// Remove the field config
db_delete('field_config')->condition('field_name', 'field_foo')->execute();
db_delete('field_config_instance')->condition('field_name', 'field_foo')->execute();

// Clear up
drupal_flush_all_caches();

That should get tid of a taxonomy field called field_foo, and all associated index data.

Note this is for a core install - if you have other modules installed that rely on that field or taxonomy data in some way, things might not be so easy.


External login should set custom properties in user object

I've done the same thing in D7. I see you're using the user-login-form directly and skipping over UID = 1 .... thats ok.

What you want todo is essentially copy the PHP logic of user_external_login_register into your own function, you're already calling your own *_authenticate() function to process the login page.

So you would change your:

// This sets up the external user with Drupal by creating a local entry.
// If they don't exist they are added.
user_external_login_register($name, "myy");

To like:

// This sets up the external user with Drupal by creating a local entry.
// If they don't exist they are added.
MYMODULE_user_external_login_register($name, "myy", $external_data);

and define the necessary function that mimics the D7 login logic AND adds you're own fields for the user upon creation (I mean literally copy the D7 function body into your function body and tweak as needed)  -- I've added additional fields using the Field UI found at /admin/people to my User accounts as seen below.

So I have this function to do that:

function MYMODULE_auth_idstaff_user_external_login_register($name, $module, $external_ldap_details) {
  $account = user_external_load($name);
  if (!$account) {
    // Register this new user.
    $roles = user_roles();
    $userinfo = array(
      'name' => $name,
      'pass' => user_password(),
      'init' => $name,
      'status' => 1,
      'access' => REQUEST_TIME,
      // This is where we are different from the default function and add our fields.
      'roles'        => array(array_search('staff', $roles) => 1),
      'mail' => $external_ldap_details['mail'],
      'field_first_name'   => array(LANGUAGE_NONE => array( 0 => array('value' => $external_ldap_details['first_name']))),
      'field_last_name'    => array(LANGUAGE_NONE => array( 0 => array('value' => $external_ldap_details['last_name']))),
    );
    $account = user_save(drupal_anonymous_user(), $userinfo);
    // Terminate if an error occurred during user_save().
    if (!$account) {
      drupal_set_message(t("Error saving user account."), 'error');
      return;
    }
    user_set_authmaps($account, array("authname_$module" => $name));
  }

  // Log user in.
  $form_state['uid'] = $account->uid;
  user_login_submit(array(), $form_state);
}

I've actually done the same exact thing in Symfony 1.4.x a few years ago ... except it was all object oriented lol (because Symfony's forms are Objects).


Alternative link to download modules from drupal.org

Click on the version control tab on the module page and it will give you instructions to download it via Git.

To get up and running with Git look at Installing Git.


How to integrate the link embedded in custome HTML(using ) to breadcrums?

you can either extend the breadcrumb array with your link in your theme with theme_breadcrumb  (further information here) or drupal_set_breadcrumb in your module, or use one of the many modules around breadcrumb. maybe custom breadcrumbs fits your needs.

you can extend the breadcrumb array with html, like:

$breadcrumb[] = l(t('My first page'), 'node/x');

or push it to the second postion with array_splice, like:

array_splice($breadcrumb, 2, 0, l(t('My first page'), 'node/x'));


save cart for anonymous user after registration

There is a module called Commerce Checkout Redirect, which redirects an anonymous user to Register or Login page and redirects to checkout on filling of either form, that would come handy for you.


How do I remove js from a specified page?

You can use hook_js_alter()

function MYTHEME_js_alter(&$javascript) {
  if ($some_condition) {
    unset($javascript['path/to/script.js']);
  }
}


Trying to print translated field label/values to twig

First the {{ trans }} and {{ var|t }} methods only do substitutions from the UI language strings (e.g. specific strings (e.g. "More") that have translations defined (in the UI or code). So, this will not work for 'random' text entered into a field.

That said, it looks like tab_label is an entity reference field.  So, tab_label.entity will always get the default language entity.

I would say do the theme_preprocess_xxx to add the current language to what you are rendering (e.g. if it's a block or a node use those, not just page.  Preprocess variables may or may not trickle down.  I'd only pass on the langcode just to save a bit of memory.  So the preprocess function would look like:

function theme_preprocess_XXX(&$variables) {
    $language = \Drupal::languageManager()->getCurrentLanguage();
    $variables['lang_code'] = $language->getId();
}

Next in the twig file, you can use this code to get the translations:

{% if tab_label.entity.hastranslation(lang_code) %}
  {% set tabLabel = tab_label.entity.translation(lang_code).field_tab_title.entity.label %}
{% else %}
  {% set tabLabel =tab_label.entity.field_tab_title.entity.label %}
{% endif %}

{{ tabLabel }}

Using the set will help keep your HTML easy to validate in the template.


You’re calling a library with dashes but it was defined with underscores. Update it to match the name.

You should be calling it via 'mytheme/library-name', so:

library: mytheme/ds_2col_stacked_custom


Choose Checkbox Insted of radio as a widget in drupal custom content type

You need to edit in Field Settings to set Number of Values to Unlimited or more than 1. Then Checkboxes will be used.

Radio buttons are used when user can only select one value.


Cleaning a Drupal database from anything which is not nodes, taxonomy and other regularities?

I don't think that this is possible because the core can not know what you need before you have it configured (fields, nodetypes etc).

You would need kind of a transaction checkpoint at the DB structure, and the possibility to rollback every structure manipulation and data therein that has happened after that point.

I usually have a system besides of my content staging system to test contributed modules. Copy content stage to dev, apply module on dev, test, rollback or move the module to content stage.

If you are the module dev yourself - make up your correct uninstalls :-)


How to display a custom block in a view?

If you want to add it to the header or the footer, edit your view, and in the middle column next to header or footer click add and then select Rendered entity - Custom block

When adding the block, just use the block ID (that can be found in the block's URL - in the image you uploaded your block ID would be 103)

Make sure these options are checked / filled in.


select list in webform containing the list of node titles

Check out https://groups.drupal.org/node/71588 for providing dynamic select options to the webform module. You'll have to specify the content type, but here's a query that can be used to populate it (replace product with the machine name of the content type):

SELECT nid, title FROM {node} WHERE type = 'product' AND status = 1 ORDER BY title ASC


How to make sure you're not on the production website in Drupal 7?

Environment Indicator is designed to do that:

  This module will help you to keep sane while working on your different environments by adding a configurable color bar to each one of your environments. The Environment Indicator adds a coloured bar on the site informing you which environment you're currently in (Development, Staging, Production, etc.). This is incredibly useful if you have multiple environments for each of your sites, and like me, are prone to forgetting which version of the site you are currently looking at.


create relation between two nodes using the relation module

I have a module that uses Hierarchical Select to give users a nice looking UI to create relations from.

Below is an excerpt of how I create the relation.

  $tid = 1; // A term id.
  $node = node_load(1);
  $relation_bundle = 'a_type_of_relation';

  $endpoints = array();
  $endpoints[] = array('entity_type' => 'taxonomy_term', 'entity_id' => $tid);
  $endpoints[] = array('entity_type' => 'node', 'entity_id' => $node->nid);

  $new_relation = relation_create($relation_bundle, $endpoints);

  if ($rid = relation_save($new_relation)) {
    drupal_set_message(t('Relation created'), 'status', FALSE);
  }
  else {
    drupal_set_message(t('Creating relation failed'), 'warning', FALSE);
  }

Adding more useful validation and messages is left as an exercise to reader, as that will be very context sensitive.


You could add a simple checkbox to your content type and call it "sticky" or somewhat. Then you add an attachment to your view, choose position before your default view and let this attachment display only the nodes with "sticky" checked, while you exclude the sticky ones from your default view.

In the second step you can add more logic to the sorting of your sticky nodes inside your view attachment. I really like DraggableViews for such tasks. But maybe that's already too much, then you might simply add another integer field to your content type and let the sticky nodes sort by that.


How do I programmatically close webform by node date field?

I haven't tried this module, but you might look at "Scheduled Updates"

Here's a walk through:
https://www.mediacurrent.com/blog/scheduling-content-changes-drupal-8/


Headless Drupal for managing multilanguage resources for Web/Android/IOS apps?

Use .po files that drupal uses for translations and sets it under sites/default/files/translations.

Build a custom module that manage the .po files status as yo need above and move it to sites/default/files/translations folder if approved, assume you have created another folders to hold not approved files.

Fetching any content from drupal will be automatically translated to the language you set by changing the path prefix for example (/en, /fr, /de if you used that method for detection).

Editing the translation strings in single click yo have to read the file and display it in a form for each record as a text field and rewrite the file after submit.

Hope that helps


The general rule of thumb was to use InnoDB to write intensive tables (due to its row locking nature) and MyISAM for the read-heavy loads. I have seen a few very busy sites fully on InnoDB running without any hiccups or drop in performance too.

Drupal 7 defaults to InnoDB as the database abstraction layer has been rewritten and immensely improved.

You could look into MariaDB which is a drop-in replacement for MySQL, faster and has extra engines. There is also Percona, another high performance replacement. They both address some of the downsides of InnoDB.

The reason I am listing the alternatives is that Oracle made a few very suspicious moves and it may be that pretty soon we won't be able to use MySQL for free. (see http://arstechnica.com/business/news/2011/09/oracle-may-fork-itself-with-recent-mysql-moves.ars)

If bigger changes are not viable/possible, I'd recommend making a clone of the site using InnoDB and load test it using tools like Apache Benchmark, siege, New Relic


I thought it easier if I just mark up the code a bit, I've tried to notate where I made changes.  Can you run this and tell us what it does, if it doesn't solve your problem?

<?php

  /**
   * @file
   * definition of uc-bitcoin-account-outgoing-escrows.tpl.php.
   */

  /** clr use $account instead of $user in case global $user is already in scope **/
  $account = user_load($variables['uid']);
  /* also, loading the user seems extraneous if you're not checking
   * anything else (is user valid, is user in a certain role, etc.)
   * if so, you should include an additional check.  If not, just
   *  do your query using $variables['uid']
   */
  global $base_url;

  /** clr drupalized the query **/
  $transactions = db_query("SELECT * FROM {uc_btc_escrow_payment} WHERE from_account=:user_id", array(':user_id' => $account->uid));

  $header = array(t('Escrow ID'), t('Amount'), t('Payment'), t('Allocated to'), t('Release'), t('Dispiute'), t('Date'));

  $rows = array();

  /** clr adding a check here **/
  if (!$transactions) {
    die('No Transactions were found');
  }
  /** clr clean up the anchor tags **/
  foreach ($transactions as $transaction) {
    $release_href = $base_url . '/user/orders/release-escrow/' . $transaction->escrow_id;
    $dispute_href = $base_url . '/user/funds/dispute-escrow/' . $transaction->escrow_id;
  $rows[] = array(
    $transaction->escrow_id,
    $transaction->amount, $transaction->status , $transaction->to_user,
    l('Release Payment', $release_href),
    l('Dispute Payment', $dispute_href),
    date('d/m/Y   g:i:s A', $transaction->created)
  );
}

print t('
Outgoing Escrows
');

print theme('table', array('header' => $header, 'rows' => $rows));
?>

And then your function:

function uc_escrow_release_payment($form, &$form_state, $escrow_id) {

/** check $escrow_id **/
if (!$escrow_id || $escrow_id == '') {
  die('Do something here, because you don\'t have everything you need');
}

/** clr not sure why '$' is used in $form key? */
$form['#$escrow_id'] = $escrow_id;

/** clr changed to fetch object **/
$transaction = db_query("SELECT * FROM {uc_btc_escrow_payment} WHERE escrow_id=:escrow_id", array(':escrow_id' => $escrow_id))->fetchObject();
/** check transaction **/
if (!$transaction) {
  die('No transaction was found; In ' . __FUNCTION__);
}
/** clr don't use $user for same reason above **/
$account = user_load($transaction->reference);
$to_user = $transaction->to_user;
/** check_plain() is only necessary when you're dealing with user supplied text.
 *  that being said, I guess it never hurt to be over cautios */
return confirm_form($form, check_plain('Release Escrow Payment?'), 'user/orders', check_plain('Are you sure you want to release this payment and send the funds to ' . $to_user . '?'), check_plain('Yes'));
}


How to redirect a user to the current page?

Like this you get the actual path:

\Drupal::service('path.current')->getPath()

and then you just use it as:

$current_page_link = new Drupal\Core\Link('So here you are', Drupal\Core\Url::fromUri('base:' . Drupal::service('path.current')->getPath()));


Subtheme: How to use the template function of a parent theme (from inside the parent theme)

The problem

Pay attention to your first sentence:

  I have created a theme that contains several functions.

The link that you have provided warns about what type of functions hold a template.php in a theme.

  There are two main types of functions in template.php: theme function
  overrides and preprocess functions. The template system handles these
  two types in very different ways.

Is legendary_views_field_compare_value() any of these cases? OK, we agree that the anwers is No. It's a custom function that you have written.

Why should not you put your custom functions in template.php?

Because Drupal has a registry of implemented hooks and templates that have been overriden. The system only load the template.php when match the hook in the registry. So, the template.php is not always load.

The solution

First of all, you should keep separate the custom functions from the theme functions. You need to create a file called for example my_custom_functions.inc , and insert all your custom functions in that file.

How do i load a file with custom functions that i need to call in my templates?

To keep separate the logic from the theme functions, i would stored the custom functions in a module. But, it is also possible store the functions in your theme. In both cases, you have to follow the next strategy.

It's really easy. Every time that a template is rendered, a preprocess function is fired by default to let other modules to act. So, it is always fired a preprocess (and process) function before the slideshow.tpl,php. In this moment, we will load the file with our custom functions.

Here an example:

/*
 *  Implements hook_preprocess_slideshow()
 *
 *  The file will load  before rendering slideshow.tpl.php
 */
 function NAME_OF_YOUR_THEME_preprocess_slideshow(&$variables){

     include_once 'my_custom_functions.inc';
 }

Please, pay attention to the name of the template. In my simulation, i have changed the template called views-slideshow.tpl.php . So, when you implements in hook_preprocess_HOOK(&$vars) , you need to change the hyphens. The result would be NAME_OF_YOUR_THEME_preprocess_views_slideshow(&$vars)

If you have to load the same file with custom functions in lots of templates, you could implement the general hook_preprocess($vars), that it is always fired. Here an example:

 /*
 *  Implements hook_preprocess()
 *
 *  The system always load the file
 */
 function NAME_OF_YOUR_THEME_preprocess(&$variables){

     include_once 'my_function.inc';
 }


Creating a registry of all form IDs on a site is, in general, impossible because you can create dynamic form IDs by using hook_forms. If you want to add an identical button to, say, every image in a gallery you might actually want to do that.

function example_forms($form_id, $args) {
  $forms = array();
  if (!empty($args) && is_object($args[0]) && isset($args[0]->nid) && $form_id == 'example_myform_' . $args[0]->nid) {
    $forms[$form_id]['callback'] = 'example_myform';
  }
  return $forms;
}

now you can call drupal_get_form('example_myform_' . $node->nid, $node) without a problem for any node and have as many form IDs as nodes. I find this easier than putting the gallery inside a form (say, it's generated by Views...) and generating a different-named button with a button-level #submit handler.

Anyways, I am sure there are other problems making it necessary to have an arbitrary number of form IDs.


Is there a way to get the controller class from a Request object or any other service class?

You find the controller class in a request attribute:
$controller = \Drupal::request()->attributes->get('_controller');

You need to instantiate the controller and run the code a second time. For not-so-easy logic it might be a better idea to refactor the code to a service which then caches the result for the second run, as @Hudri commented.
Or take a different approach. Place a custom block with a static placeholder on the page and replace it by attaching bubbleable metadata to the controller output. See Add an attribute to $variables from a Controller
Instead of a render array you can also replace the placeholder in a lazy-builder callback.  This depends on the structure of the data in controller and block and how dynamic this is. At the end this is all about caching performance.


Both Solr modules provide APIs:

Apache Solr Search
Search API Solr

But neither provide an after-node-update hook. If I had to guess I'd say it's both modules send data to Solr in batches, not one node at a time.

You might get some joy with the core hook_node_update_index():

  Act on a node being indexed for searching.

  This hook is invoked during search indexing, after node_load(), and after the result of node_view() is added as $node->rendered to the node object.


Convert links in content to internal form?

In terms of non-technical (which I read as custom development) solutions, what you're describing is one of the features of LinkIt.

  Linkit provides an easy interface for internal and external linking
  with editors and fields by using an autocomplete field. Linkit links
  to nodes, users, managed files, terms and have basic support for all
  entities by default. Linkit has three major advantages over
  traditional linking

It provides a WYSIWYG toolbar button from which a user can paste a URL for embedding a link. Upon setting up a LinkIt profile for you input type, there's a Insert paths as setting with a Raw paths option that defaults the inserted link as Drupal's internal path.


Get locations search: Show all markers by default

Try using Open layers Module which has an option for adding multiple locations n single map...

OpenLayers:

  The OpenLayers core code stores map's object configurations: maps, layers, styles, sources, controls, interactions and components. It combines them to create maps using the OpenLayers JavaScript library on any Drupal site.


Cannot edit my views.. I get a JSON string?

Based on @Clive's suggestion in the comments, I found this issue:
JQuery Update breaks Views UI

So Views UI is not compatible with jQuery 1.8, and the OP has already confirmed that this was the problem.

This problem isn't limited to Views though. Other contrib modules depend on the default core version of jQuery (including Rules). An issue exists in the jQuery Update queue to Allow different version for administrative pages. And a patch was applied to dev on 20 MAR 2013.

The dev version of jQuery Update provides a update to the Configuration Form that allows you to select a different version of jQuery on administrative pages.

Before

After

I can confirm that setting the "Alternate jQuery version for administrative pages" select list to "1.5" after upgrading to the dev version of jQuery Update fixes the issue with Views.


you can implement hook_node_view and make alterations in the breadcrump
eg:

/*
 * Implements hook_node_view().
 */
function my_custom_module_node_view($node, $view_mode) {
  if ($node->type == 'my-node-type') {
    $type == $node->field_test_field['und'][0]['value'];
    if ($type == 0) {
      $breadcrumb = drupal_get_breadcrumb();
      $breadcrumb[1] = 'new breadcrumb';
      drupal_set_breadcrumb($breadcrumb);
    }
  }
}


How to display content type field values in tab panel format?

im using the Quick Tabs module for creating tabs. Here is a quote about it (from the module's project page):

... allows you to create blocks of tabbed content, specifically views, blocks, nodes* and other quicktabs*. You can create a block on your site containing multiple tabs with corresponding content. Clicking on the tabs makes the corresponding content display instantly, using jQuery. With the 6.x-2.x branch, this can be done in either ajax or non-ajax mode:

if you choose ajax mode for your Quick Tabs block (and this is chosen on an individual QT basis), only the content of the active tab will be loaded on page load and the content of the other tabs will be loaded via ajax on tab click (this is good for performance if you are loading, for example, several large views)
in non-ajax mode the tab content is just hidden / shown on tab-click. This latter method is an ideal way to do something like the Most Popular / Most Emailed stories tabs you see on many news websites, where it is used more as a space-saving device in your sidebar. If however, you want a QT block as the main content of your entire page, then the chances are that ajax mode will be more appropriate.

Once created, the Quick Tabs blocks show up in your block listing, ready to be configured and enabled like other blocks. Multiple Quick Tabs blocks can be placed on a single page.
For theming of the tabs, several styles have been provided for you to choose from (in the 7.x-3.x branch this functionality comes in a separate submodule, Quicktabs Tabstyles), along with the default option of no style, if you prefer to add your own theming instead.


Menu block doesn't appears where I expect it

Solved that! Inspecting the code of Menu Block cleared it out for me that this module doesn't work with URLs. What a pity!

But:

There is a completely awesome bunch of modules: Context withContext:Menu Block which make it possible.
Context menu block modules make Menu Block module being aware of context. Also this page may be useful.

But still, if you have better solutions, please write it here.


views - get teasers of "related nodes" referenced in entity fields on current node

Don't use an Entity Reference relationship for this, but rather, change your Show: to "Fields" and add the referenced entity field. Then you will be able to set the "Formatter" to "Rendered entity", and the "View mode" to "Teaser".

You may need to add a contextual filter or set this up as an attachment display rather than a block.

I can post a few screen shots if my answer isn't clear.


Creating an alternative login page other than /user/login

Yes, your code is complete, and is as safe as the default login form.

However, do bear in mind that if you want to replace the /user/login form, you will need to think about all scenarios in which users might end up there (e.g. [site:login-url] token, other modules, etc.) and handle them appropriately via redirects or access denied response (e.g. if you will be the only registered user on the site).

Here are the basics:

Redirecting

If you want to redirect users from /user/login to /authenticate for whatever reason, you will either need to use the Redirect module, or implement hook_menu_alter() in your custom module:

function YOUR_MODULE_menu_alter(&$items) {
  $items['user/login']['page callback'] = 'drupal_goto';
  $items['user/login']['page arguments'] = 'authenticate';
}

Replacing

If you want to make /user/login inaccessible to all other users, you can simply disable that path by again implementing the hook_menu_alter() in your custom module:

function YOUR_MODULE_menu_alter(&$items) {
  $items['user/login']['access callback'] = FALSE;
}

However, do bear in mind that you will have to test everything thoroughly and make sure that you have no modules that depend on the system /user/login, as well as that there are no workflows that will be affected (e.g. [site:login-url] tokens).

Hope this helps.


AFAIK, VBO should be able to do the job, but I haven't tried it myself to delete comments.

Another way is to run some code (in a module or in Devel module's 'execute php' block) that gets a list of all queries from the db, builds an array of the comment IDs and passes that array to the comment_delete_multiple function. Note that this can take a while to complete (depending on server performance and the number of comments), so you may have work your way around that, for instance by using set_time_limit (http://php.net/manual/en/function.set-time-limit.php) or Drupal's batch API.

[update: see Chris Cohen's answer for example code based on this approach.]


Webform Fields not hidden anymore after update to 8.x-5.0-rc19

Please see #states breaks when OR is used


How to make menu badges count disappear after the page is viewed?

To make the Menu Badges counter disappear when visiting the page at notifications/new (as in your question), is something you can do by using a special feature of the Rules module, i.e. a technique that is similar to what is described in the answer to "How to execute VBO list of nodes in Rules on After updating an existing user account event?". Read on for more details about the steps to be completed, specific to your question here.

Step 1:

Create a VBO view of your unread messages, similar to what is described in my answer to "How to allow users to manage their own Message Stack messages?".

Step 2:

Create a custom Rules Component that will execute the VBO list of unread Messages, and which looks like so:

{ "rules_mark_all_unread_messages_read" : {
    "LABEL" : "Mark all unread messages read",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules", "views_bulk_operations" ],
    "ON" : { "init" : [] },
    "IF" : [
      { "user_has_role" : {
          "account" : [ "site:current-user" ],
          "roles" : { "value" : { "2" : "2" } }
        }
      },
      { "text_matches" : {
          "text" : [ "site:current-page:url" ],
          "match" : "user\/\\d+\/messages\/unread",
          "operation" : "regex"
        }
      }
    ],
    "DO" : [
      { "views_bulk_operations_action_load_list" : {
          "USING" : { "view" : "messages_by_user|page_3" },
          "PROVIDE" : { "entity_list" : { "unread_msgs_list" : "A list of unread messages" } }
        }
      },
      { "LOOP" : {
          "USING" : { "list" : [ "unread-msgs-list" ] },
          "ITEM" : { "current_msg" : "Current message" },
          "DO" : [
            { "component_rules_flag_a_message" : { "message_to_flag" : [ "current-msg" ] } },
            { "drupal_message" : { "message" : "The message with ID [current-msg:mid] (created [current-msg:timestamp]) was marked as read." } }
          ]
        }
      }
    ]
  }
}

Some more details about the rule above:

Rules Event: Drupal is initializing
Rules Conditions:

only for authenticated users.
check if the path being visited is user/%/messages/unread (adapt this path if you use another path).

Rules Actions:

Create a list of unflagged messages.
Loop over each of the unflagged messages found, and flag those messages.

This rule also performs an extra "set message" action, so that you can see what it does if you want to try it in your own site (it shows a message (oeps!) for each message being flagged). Remove that message after QA-testing if you want.

That's it, works like a charm!

Note: this solution can also be used in combination with the solution detailed in the related answer. So maybe you want to set a special permission if you want to combine both solutions, so that admins only can mark selected messages as read or unread, if needed.


Bypass comment validation for SOME anonymous users, based on the provided email address?

Make a rule with event after saving a new comment. Then make a view with the list of emails which should be bypassed. Compare this with the current email of the user, if there is a match publish the comment on the node.
The comparing can be done with views + vbo and the rules action: Load a list of entity objects from a VBO View.combined with a loop statement.


You should alter the register form and set new redirect value.

function MYMODULE_user_register_form($form, &$form_state) {
  $form_state['redirect'] = 'path/to/somewhere';
}


How to place blocks in code with zen theme?

Add the following function in your template.php

function THEMENAME_render_block($module, $delta, array $options = array()){
  $default_options = array(
    'title' => '<none>',
    'region' => -1,
  );

  $options = array_merge($default_options, $options);

  $block = db_query('SELECT * FROM {block} WHERE module = :module AND delta = :delta', array(':module' => $module, ':delta' => $delta))->fetchObject();
  if($block) {
    $block = block_load($module, $delta);
    $block->title = $options['title'];
    $block->region = $options['region'];
    $blocks = array($block);
    $rblocks = _block_render_blocks($blocks);
    $render_array = _block_get_renderable_array($rblocks);
    return drupal_render($render_array);
  }
  return "";
}

then in your tpl file of your specific page/node

<?php print THEMENAME_render_block('<moduleName>', 'delta', array('title' => t('Block Title'))); ?>


View does not display attached file without Display field checked

Under advanced > query settings > check "Disable SQL rewriting" - it should prevent any access or visibility checks for nodes and fields. Don't forget to add the ones you need directly to a view if you do this.


Permission error while downloading file through IE8

Updated download_file module header.

 $headers = array(
   'Content-Type'              => 'force-download',
   'Content-Disposition'       => 'attachment; filename="' . $file->filename . '"',
   'Content-Length'            => $file->filesize,
   'Content-Transfer-Encoding' => 'binary',
   'Pragma'                    => 'private, no-cache',
   'Cache-Control'             => 'private, no-store, no-cache, max-age=0, must-revalidate',
   'Expires'                   => '0',
   'Accept-Ranges'             => 'bytes'
 );


array value within Rule's PHP action always gives 0 instead of related uid

I think the problem is with your $account variable. I don't see where it's instanciated in your code. It's probably related to the current logged in user, so you've to find a way to access this information from Rules. Try to use dsm($account); if you're using the devel module and check if the variable is empty.


Why is $node->taxonomy not populated when implementing a custom hook_nodeapi?

I think I am explaining this right, but the issue here is that hook_nodeapi() called with op = load returns a keyed array that is later on merged into the node object.  It doesn't do this in sequence and progressively build up as each module's hook is executed, eg, it doesn't modify the node object itself. Thus it does not allow other modules to look at any other extra load information from other modules until later on.

For example, taxonomy_nodeapi() called with op = load loads up the taxonomy term info and returns it as $output['taxonomy'].  So, it is never available to any other modules until the node_load() where it is then turned into $node->taxonomy based upon that key.  Here, all other modules that add to $node in the same way also add in their extra stuff.

So yes, this is probably best described as default behavior.


How to check if an article is referenced from a collection?

To load all collection id's, which have a reference to $article_id:

$collection_ids = \Drupal::entityQuery('node')
  ->condition('type', 'collection')
  ->condition('field_article_ref', $article_id)
  ->execute();
if ( count($collection_ids) > 0 ) {
  echo "the article $article_id is referenced in one or more collections";
}


$form_id: What is the difference between #id and #value?

$form_id always has _ in it. Because in hook_form_FORM_ID_alter() you always have to put replace FORM_ID with $form_id so you can't put - in function name.

$form_id: String representing the name of the form itself. Typically this is the name of the function that generated the form.

And #id is html safe id. id attribute for form tag.


Sage, edit the content type, go on the COMMENTS FIELDS tab, then click on edit on comment_body.
Make sure you set 'Text processing'  to PLAIN TEXT


Setup different pager settings for same view

I dont think its possible, you can achieve this by adding another page/block display to an existing view and specify the pager values accordingly.

As Ursula said, When you change your pager on the second display, do not forget to change the 'for' pulldown menu on the modal window from 'all displays' to 'this page (overwrite)'. Otherwise, you changed the pager for all displays.


How to delete paragraph when uninstalling the module?

Add this to the relevant config file(s) in config/install:

dependencies:
  enforced:
    module:
      - custom_module

That will force the config item(s) to be removed when the module is uninstalled.


How do you expose/display a product type's custom field in a product display?

I have been through my settings for my product & it's display to check my settings. I have several fields added to my product which I display on product display. I have Display Suite module enabled at my instance.

So what I have done is - I have checked Full content in my custom display setting tab at my product as well as product display in manage display. You can also do Product -> Manage display -> custom display setting -> full content(check) & save.

I have enabled all fields in my product in full content tab, which looks like --

After that when I visit my product display -> manage display -> full page, I find those field, which I have enabled to be visible. It looks like --


InvalidArgumentException: Cannot redirect to an empty URL. in Symfony

This solution is working  when

Successfully Logout with empty blank page website encounter error.

You need to override the core logout function available in user module
by creating your custom module

that is UserController::logout function

Create a Route subscriber

/module/src/Route/RouteSubcriber.php

<?php

namespace Drupal\modulename\Routing;
use Drupal\Core\Routing\RouteSubscriberBase;
use Symfony\Component\Routing\RouteCollection;
/**
* Listens to the dynamic route events.
*/
 class RouteSubscriber extends RouteSubscriberBase {
 /**
  * {@inheritdoc}
  */
  public function alterRoutes(RouteCollection $collection) {

    if ($route = $collection->get('user.logout')) {
      $route->setDefaults(array(
       '_controller' =>
       '\Drupal\modulename\Controller\RouteController::logout',
      ));
    }
  }
 }

Create Services file

module/modulename.services.yml

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

Create Controller File
module/src/Controller/RouteController.php

<?php
/**
 * @file
 * Contains \Drupal\modulename\Controller\RouteController.
 */
namespace Drupal\modulename\Controller;

use Drupal\Core\Controller\ControllerBase;
use Drupal\Core\Url;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Request;

class RouteController extends ControllerBase
{

  public function logout() {
    //redirecting to home page if you want you can
    // redirect to some other page. by concating path with it.
    $value = \Drupal::request();
    user_logout();
    return new RedirectResponse($value->getBaseUrl());
    //return new RedirectResponse($value->getBaseUrl().'/somepath');
  }

}

that is it.enable the module and try logout will work with out blank page error


get menu link Page Settings from View configuration

The menu tree is built from two sources, menu link content and menu config. For views you find the menu configuration in each view. There are several ways to access this information. You can use the config api to read the values in php, export the view to a yml file and inspect it or use drush.

For example to show the view for block content with drush:

drush cedit views.view.block_content

This contains this configuration for the page:

 page_1:
    display_plugin: page
    id: page_1
    display_title: Page
    position: 1
    display_options:
      display_extenders: {  }
      path: admin/structure/block/block-content
      menu:
        type: tab
        title: 'Custom block library'
        description: ''
        parent: block.admin_display
        weight: 0
        context: '0'
        menu_name: admin
    cache_metadata:
      max-age: 0
      contexts:
        - 'languages:language_content'
        - 'languages:language_interface'
        - url
        - url.query_args
        - user.permissions
      tags: {  }

After inspection the structure of this array you can use the configuration api to access it in php:

Simple Configuration API


How to add a css class to sidebar first render

Create a template file with name region--sidebar-first.tpl.php in side the your theme template folder. Copy below code to inside the newly created template file

<?php if ($content): ?>
     <div class="my_class <?php print $classes; ?>">
       <?php print $content; ?>
     </div>
  <?php endif; ?>

replace my_class with you desire class name, clear the drupal cache. It will wrap a new class on the sidebar first region. Good luck


Use page.html.twig template variable in another twig template

The book-tree.twig is rendered in its own scope.  It does not "know" any of the context it is being rendered in, so it can't tap into the variables from the page twig per se.  It only gets the variables you give it.  So you could implement a THEME_preprocess_book_tree(&$variables) hook to add it in.  $variables['page_nid'] = // your code here will make it available in twig as {{ page_nid }}.

However at the risk of being "that annoying guy" who tells you not to do things instead of just answering your question

  This variable will be used in a set statement, comparing it to the item.original_link.nid to set an active class.

Personally I would eschew this approach as it ends up placing logic inside the presentation layer.  I would rather use the hook to compare item nids to page nid, and add the active class to that item's attributes as appropriate.  That way the twig can be kept extremely "stupid", and simply dump out whatever attributes for all items, and those attributes will magically contain (or not contain) the appropriate classes.


"drush up" fails with "pm-updatestatus failed."

I was able to fix the problem by editing the file /path/to/drush/includes/exec.inc and changing line 331 from

return _drush_escapeshellarg_windows($arg, $raw);

to

return _drush_escapeshellarg_windows($arg, TRUE);

as described by peterromero here https://github.com/drush-ops/drush/issues/2152


Swiftmailer currently expects a plain \stdClass object in files as this part hasn't been fully ported from D7. See https://www.drupal.org/node/2713651.

So you need to do something like

$file = (object) [
'filename' => $file->getFilename(),
'uri' => $file->getFileUri(),
'filemime' => $file->getMimeType(),
];
$message['params']['files'][] = $file;


Why can I only view content published to current domain?

After researching the api and reading up on how the permissions work (here) it looks as if the Node Access module limits a user (who is not user 1) to only be able to see content of the domain of which they belong, regardless of their editing permissions. You could, however, play around with grants (specifically grant_edit) to try and override the active domain. I would suggest some custom script to allow Role X grant_edit, or bite the bullet and use the "Bypass content access control" permission.

I understand this probably isn't the answer you wanted, however hopefully it helps in some way!


How to scan a directory to list all sub folders not files

If file_scan_directory usually returns directories then perhaps you can use the regex mask to search for names that don't have a dot (.) in them.

There are very few files in a Drupal installation that don't have an extension, and I imagine there will be none in your folder structure if all it contains is .json files...

file_scan_directory($your_root_folder, '/^[^\.]+$/');

The above should match all items in the directory structure that don't contain a dot, thanks to this answer.


Load more content with ajax when clicking more link in a view

So this is one of those problems that multiple people in the drupal world have tried to solve.

I recently gave a presentation on this exact same issue and how to accomplish it with drupal. Sadly I never posted any of my slides up anywhere where the rest of the world can see.

Here's the Break down of modules:

Views Infinite Scroll

Does Not work with Views Ajax support -- It hacks around it to make is own ajax request
Makes a full page request -- This is because it doesn't use the Views Ajax request
Requires Views 3.x -- This is a plus, because the pager is plug-able in 3.x

Views Infinite Pager

Support Views 2.x -- This is really not a good thing, because the pager isn't plug-able
Because it works with 2.x it really hacks around the pager theme, the regular views ajax, and preprocessing behavior. So it breaks some functionality.

And last but not least is a new project in which I just added in light of this question.  The reason for the project is my need for also needing views that support load more except the issues mention above we're not acceptable for my project.

Views load More

Requires Views 3.x - This is on purpose.
Support views regular pager options, such as offsets, page count
Fully supports views ajax feature

If Ajax is enabled on the view, the load more will add content to the bottom of the list
If ajax is disable the page will refresh and replace the old content with the new content
It does not do a full page request when doing the ajax callback, it lets views do is natural callback and instead of replacing the content it appends to it.

If you're using the waypoint module the view can be configured to automatically get new content when the user scrolls to the bottom of the page.
Supports JQuery effects (right now only the fade effect is supported, more soon to come).

Hope this answers your question. This is my "unbiased" ;-) opinion on all the views load more module.


In Views 3, under "advanced settings", there is a setting for enabling aggregation, which will give you group by options.

Most likely they are hidden by default as the UI is complicated enough as is.

You can also check out chapters 28-30 in the NodeOne Taming the beast learn views with nodeone which are all about aggregation.


Normally, you would execute these commands on particular sites with Drush and site aliases (drush sa lists the aliases). I do it all the time.


Is it safe to clone a EntityMetadataWrapper Object?

Well, It's not safe/ I don't know why yet, But, Sometimes it result in saving only last cloned entity.

It's not a good answer till it says why!


As far as I know, the menu itself is exportable by the built-in config management but the links are not (because the menu is config, the links are content). So when you export the configs and import it on the target environment, you get an empty menu.

What you could do is manually create the menu links programmatically during deployment. One technique is to use a "deployment module", where you use a dummy module and take advantage of hook_update_N. As for creating the menu items in Drupal 8, this answer can probably help you.


How to (double) opt-in the user registration process before admins are notified for approval?

If I understand you correctly, this is default Drupal functionality.

Go to the Account settings (admin/config/people/accounts).
Under Who can register accounts?, Select the option Visitors, but administrator approval is required.
Directly below this option, select the checkbox Require e-mail verification when a visitor creates an account.

That's all.


How to create a custom content type with a quiz field?

You can use the Field Quiz module. It already has an alpha version for Drupal 8.

According to the module description,

  This module provides a simple field that can be used as a simple quiz
  or multiple choice questions. It provides a field with a textfield and
  a checkbox / radio selection combined. If added to any entity
  (node/content type, user, taxonomy term, ...) the editor of the entity
  can enter multiple answers in the textfields and determine which
  answers are correct.

  This module is for everybody who does not want to use the whole
  complex system of the quiz module, but just a simple field for
  multiple choice questions.


getting 404 error while developing an example module

The indentation of your hello.routing.yml file is wrong. It should be as the following one. (See user.routing.yml.)

user.pass:
  path: '/user/password'
  defaults:
    _form: '\Drupal\user\Form\UserPasswordForm'
    _title: 'Reset your password'
  requirements:
    _access: 'TRUE'
  options:
    _maintenance_access: TRUE

Indentation in YAML files is very important, since it changes the file content.

Notice that you can use _access: 'TRUE', when the page doesn't require a specific permission. The _maintenance_access: TRUE line is not necessary. If you use it, users have access to your route even when the site is in maintenance mode; other requirements are still respected, so you could have something similar to the following.

user.login:
  path: '/user/login'
  defaults:
    _form: '\Drupal\user\Form\UserLoginForm'
    _title: 'Log in'
  requirements:
    _user_is_logged_in: 'FALSE'
  options:
    _maintenance_access: TRUE

Before making any changes, uninstall the module, fix the file, and re-install the module.

As side note, you don't need the use Drupal\Core\Routing\RouteMatchInterface; line in your hello.module file, since you aren't using that PHP interface.


User's to edit roles and permissions for any user less privileged

Drupal core doesn't have any out of the box functionality to manage roles and permissions in a hierarchical manner.

However, there are a couple modules that provide extra permissions which might be helpful in what your trying to achieve.

Role Delegation gives you a new set of permissions which are very fine-grained. From the module page-

  For each role, Role Delegation provides a new assign ROLE role permission to allow the assignment of that role.

Administer Users by Role. From the module page-

  This module allows site builders to set up fine-grained permissions for allowing "sub-admin" users to edit and delete other users — more specific than Drupal Core's all-or-nothing 'administer users' permission. It also provides and enforces a 'create users' permission.

From the readme of the module-

  NEW PERMISSIONS

  Access the users overview page
  See the list of users at admin/people.  Only users that can be edited are shown.

  Create new users
  Create users, at admin/people/create.

  Edit users with no custom roles
  Allows editing of any authenticated user that has no custom roles set.

  Edit users with role XXX
  Allows editing of any authenticated user with the specified role.
  To edit a user with multiple roles, the sub-admin must have permission to
  edit ALL of those roles.  ("Edit users with no custom roles" is NOT needed.)

  The permission for cancel work exactly the same as those for edit.

(1) should give what you need but still including (2) which might have a new permission that you wouldn't want to miss out on.


Importing Content Without Including `nid`

I think you should use Features and Universally Unique IDentifier.

When you update an existing node, thanks to UUID, it will be updated in production site because they should have the same UUID (but can have different IDs). If the UUID doesn't exist, then it will create a new node.


No - at this point it is not possible to export tokens using the custom tokens module. There is an open issue here on Drupal.org referring to this that has been waiting for a while without response and its unlikely the module maintainers will add this functionality as this is meant as a simple solution for developers who don't want to create their own tokens in PHP.

Depending on the complexity of your token operation, the best option might be to either manually sync up the two environments or to create your own custom token function following the instructions here (or other guides on the web). I would encourage you to try writing your own export functionality, its easier than it would seem and will open up more possibilities for you on future projects.


How can I get the taxonomy term name from a term ID?

Or you can simply use The entity Term class:

use Drupal\taxonomy\Entity\Term;

and in your code:

$term = Term::load($tid);
$name = $term->getName();


Can 1 FullCalendar show dates from more than one content type?

Well I found the answer before I even finished posting this.  Thanks to those "Similar Questions" over there on the right...

I got my answer from How to use multiple content types in a "Calendar" View sorting by the field type of "Date"?


What format should date (ISO date) be when using Migrate Module?

For date migration, you should use Migrate Extras module. Then you will be able to remove your code from prepareRow(), and just map the date field.

Migrate Extras will take care of reading you date and parse it.

In my migration I just had to set the timezone when I was importing birth dates.

Here's my mapping, as an example:

$this->addFieldMapping('field_birth_date', 'birthdate')->arguments(MigrateDateFieldHandler::arguments('Europe/Rome', 'Europe/Rome'));


How to let public access to the sitemap page?

As far as I can tell, this is permission based, so you need to give anonymous users the access site map permission.

From the module:

/**
 * Implements hook_permission().
 */
function site_map_permission() {
  return array(
    'access site map' => array(
      'title' => t('View published site map'),
    ),
  );
}

/**
 * Implements hook_menu().
 */
function site_map_menu() {
  $items['admin/config/search/sitemap'] = array(
    'title' => 'Site map',
    'description' => 'Control what should be displayed on the site map.',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('site_map_admin_settings_form'),
    'access arguments' => array('administer site configuration'),
    'file' => 'site_map.admin.inc',
    'type' => MENU_NORMAL_ITEM,
  );
  $items['sitemap'] = array(
    'title' => 'Site map',
    'description' => 'Display a site map with RSS feeds.',
    'page callback' => 'site_map_page',
    'access arguments' => array('access site map'),
    'type' => MENU_SUGGESTED_ITEM,
  );

  return $items;
}


What is the correct way to send a node list to the REST API?

Solution 1: Custom Endpoint

Unfortunately, entities are expected to be created one by one when using RESTful web services. You can create your own web service endpoint by writing a custom module and there, you can create support for creating multiple nodes with a single request. However, you'll still have to use batches of say, 50 nodes per request for things to work smoothly. This is more of a push import.

You might also want to try the jsonapi module to see if supports importing multiple operations in a single request.

Solution 2: Migrate API

Have you considered Drupal's migrate API instead? With migrate, you can import nodes from a remote XML / JSON document with a simple drush command which you can setup as a part of cron on your server. You can update existing items and create non-existing items. Migrate will also create nodes one by one, but it will be much faster than REST requests because it will not involve 1 HTTP request per node. This is more of a pull import.


Is there a module or technique to display blocks or panels based on device width?

How about using the Themekey and/or Mobile Detect for switching mobile and desktop version of themes? Here is a quote about these modules (from their project pages):

Themekey:

ThemeKey allows you to define simple or sophisticated theme-switching rules which allow automatic selection of a theme depending on current path, taxonomy terms, language, node-type, and many, many other properties. It can also be easily extended to support additional properties exposed by other modules.
... in combination with Drupal's theme inheritance you can easily achieve features like ... "mobile themes for different auto-detected mobile devices".

Mobile Detect:

... intended to aid developers utilizing mobile-first and responsive design techniques who also have a need for slight changes for mobile and tablet users. An example would be showing (or hiding) a block or content pane to a particular device.


Wow that was much harder to do than I really thought it would be, for anyone interested in how to do this, you can use the information below, in case anyone is interested I've taken most of the information from this site about how to remove the drag handles, but the principle is the same, added to which, I wanted to remove the drag handles anyway

First you have to create your own module, and use hook_theme_registry_alter to change where the default theming is defined for multiple value fields

/**
 * Implements hook_theme_registry_alter().
 */
function mymodule_theme_registry_alter(&$theme_registry) {
  if (isset($theme_registry['field_multiple_value_form'])) {
    $theme_registry['field_multiple_value_form']['type'] = 'module';
    $theme_registry['field_multiple_value_form']['theme path'] = drupal_get_path('module', 'mymodule');
    $theme_registry['field_multiple_value_form']['function'] = 'mymodule_theme_field_multiple_value_form';
  }
}

Then you can re-define how it's themed by copying the existing theme_field_multiple_value_form code and writing it into your new function. BUT, be aware that this is going to redefine how ALL unlimited field values work, so really you just want to add in an 'if' clause somewhere, I just put mine at the start

function mymodule_theme_field_multiple_value_form($variables) {
  $element = $variables['element'];
  $output = '';

  if (($element['#cardinality'] > 1 || $element['#cardinality'] == FIELD_CARDINALITY_UNLIMITED) && $element['#field_name'] != 'field_myfield') {

  // Input normal code, this is for any unlimited input field you DON'T want altering

  } else if (($element['#cardinality'] > 1 || $element['#cardinality'] == FIELD_CARDINALITY_UNLIMITED) && $element['#field_name'] == 'field_myfield') {

$table_id = drupal_html_id($element['#field_name'] . '_values');
$required = !empty($element['#required']) ? theme('form_required_marker', $variables) : '';

$header = array(
  array(
    'data' => '' . t('!title !required', array('!title' => $element['#title'], '!required' => $required)) . "",
    'colspan' => 2,
    'class' => array('field-label'),
  ),
);
$rows = array();

// Sort items according to '_weight' (needed when the form comes back after
// preview or failed validation)
$items = array();
foreach (element_children($element) as $key) {
  if ($key === 'add_more') {
    $add_more_button = &$element[$key];
  }
  else {
    $items[] = &$element[$key];
  }
}
usort($items, '_field_sort_items_value_helper');

$count = 1;
// Add the items as table rows.
foreach ($items as $key => $item) {
  unset($item['_weight']);
  $cells = array(
    array(
      'data' => $count,
      'class' => array('count'),
    ),
    drupal_render($item),
  );
  $rows[] = array(
    'data' => $cells,
  );

  $count++;
}

$output = '
';
$output .= theme('table', array('header' => $header, 'rows' => $rows, 'attributes' => array('id' => $table_id, 'class' => array('field-multiple-table'))));
$output .= $element['#description'] ? '
' . $element['#description'] . '
' : '';
$output .= '
' . drupal_render($add_more_button) . '
';
$output .= '
';

  } else {
      foreach (element_children($element) as $key) {
        $output .= drupal_render($element[$key]);
      }
    }

    return $output;
  }

Hope this helps someone in the future


how to inject dependencies into an access controller?

This can be done using services. Here's an example which injects the entity type manager interface.

eclone_extras.services.yml:

services:
  eclone_extras.access:
    class: Drupal\eclone_extras\Access\EcloneExtrasAccess
    arguments: ['@entity_type.manager']

Route subscriber:

 /**
   * Alters existing routes.
   */
  public function alterRoutes(RouteBuildEvent $event) {
    $collection = $event->getRouteCollection();

    if ($route = $collection->get('entity.node.clone_form')) {
      // Add custom access
      $route->setRequirement('_custom_access', 'eclone_extras.access::access');
    }
  }

Access class:

namespace Drupal\eclone_extras\Access;

use Drupal\Core\Session\AccountInterface;
use Drupal\Core\Access\AccessResult;
use Drupal\Core\Entity\EntityTypeInterface;
use Drupal\Core\Entity\EntityTypeManagerInterface;

class EcloneExtrasAccess {

  /**
   * The entity type manager.
   *
   * @var \Drupal\Core\Entity\EntityTypeManagerInterface
   */
  protected $entityTypeManager;

  /**
   * Constructs a new ContentEntityCloneBase.
   *
   * @param \Drupal\Core\Entity\EntityTypeManagerInterface $entity_type_manager
   *   The entity type manager.
   * @param string $entity_type_id
   *   The entity type ID.
   */
  public function __construct(EntityTypeManagerInterface $entity_type_manager) {
    $this->entityTypeManager = $entity_type_manager;
  }

  /**
   * Custom access checker for the create lock requirements route.
   *
   * @see \Drupal\content_lock\Routing\ContentLockRoutes::routes()
   */
  public function access() {
    // do access stuff
    return AccessResult::allowed();
  }

}

The access callback gets some parameters as well, such as Account and possibly request.

Refs:

https://www.drupal.org/docs/8/api/routing-system/access-checking-on-routes


Complicated 'double' contextual and relationships view

I would create a View of the Content Type Location (these are the nodes created by your users, right?).

Create a Relationship to Author.
Create a Filter to user: current and select Yes in Is the logged in user (NB: this a a regular filter, not a Contextual Filter)
Create a Relationship to the Event type through its reference field to Location (NB: select Entity Reference: Referencing Entity . If you select "Require this relationship" the View will limit the Location types to only those referenced in an Event node
Add any field to the View, but be sure to select the relationship you created in 3 above to show field from the Event type

That's it! Nice question!


Error adding one content type. Bundle missing in term references

Your issue is most likely related to the Media module, and specifically this issue: 'Missing bundle property on entity of type file error'. In your troubleshooting efforts, did you run across this info? A quick check to confirm if this is the culprit is to follow the step(s) outlined in comment #5.


Thanks to the comment above I was able to find a solution. This function allows to access three fields within a paragraph (term reference field, text field, boolean field).

public function viewElements(FieldItemListInterface $items, $langcode) {
$element = [];

  // Render each element as markup in case of multi-values.
  foreach ($items as $delta => $item) {

    // Desired fields: field_network_name (term reference), field_network_specific_site_code (text), field_network_verified (boolean);
    // this return the termID
    $network_name_tid = render($item->entity->field_network_name->target_id);
    // this termID is used to load the term object
    $full_taxonomy_term_object = taxonomy_term_load($network_name_tid);
    // then you can get the name of the term, or any other information about the term
    $network_label = $full_taxonomy_term_object->getName();

    // getting the values for the text and boolean fields is more straightforward
    $network_site_code = render($item->entity >field_network_specific_site_code->value);
    $network_site_verified = render($item->entity->field_network_verified->value);

    // in the end you put them together, have conditions and format them as you need
    $element[$delta] = [
      '#markup' => $network_label . $network_site_verified . $network_site_code
    ];
  }

  return $element;
}

However, the problems of hard-coding something like this persist. Even though this can be tackled by having the right failsaves in place.

Edit: You don't need the "render" either. Addtionally, the "render" causes a notice in the system logs. I also stumbled upon this useful cheat sheet: https://www.metaltoad.com/blog/drupal-8-entity-api-cheat-sheet


Is it safe to connect to another server to send form data?

If you clear your required flow then a better solution can be suggested.

It is not a good practice to perform at page--path.tpl.php

Use hook_init in your custom module and check arg(1) to confirm your path.

Data can also be posted using drupal_http_request($server_url, $headers, 'POST', $data);


How can I render or change programmatically the responsive image style for an image field for a paragraph?

You don't need to swap the image, only the information how to render the image. And you can't do this in a field template. This is only possible in the paragraph template, where both fields are available:

function mytheme_preprocess_paragraph(&$variables) {
  if ($variables['paragraph']->hasField('field_image_style')) && isset($variables['content']['field_image']['0']) {
    $image_style = $variables['paragraph']->field_image_style->value;
    $variables['content']['field_image']['0']['#responsive_image_style_id'] = $image_style;
  }
}


How can get five star rating data in drupal 6 services views?

You can use Services views module to achieve this,

Procedure :

Using services views you will need to add all your required fields on your views.

Step 1: For adding new view navigate to

[your-site]/admin/structure/views/add

Step 2: Adding your fields

You will fetch the resource as below,

http://example.com/<endpoint path>/views/<view name>


Unfortunately, I don't believe you can.

Many core hooks, such as hook_menu, let's you define a file and a file path which Drupal can use to find the actual callbacks for the menu.

However, I don't believe this functionality is supported by hook_xmlrpc.

Considering also that the module is likely to leave core soon, it's unlikely that there will be any large improvements to it.


Is there any way to add comments to pages which are NOT nodes

API the module that handle the pages you see at api.drupal.org, has the same problem; the documentation pages you see are not nodes, but the module allows to add comments to them.

The page callback invoked for the documentation pages is api_page_function(), which is associated to the path api/%/%/function/%api_item in its implementation of hook_menu() (see api_menu(), starting at line 125 of the linked file). The page callback uses _api_add_comments(), which contains the following code:

if (module_exists('comment') && user_access('access comments') && variable_get('comment_api', COMMENT_NODE_READ_WRITE) != COMMENT_NODE_DISABLED) {
  $output .= comment_render(node_load($documentation_object->did));
  if (user_access('post comments')) {
    $output .= comment_form_box(array('nid' => $documentation_object->did), t('Post new comment'));
  }
  // ...
}

API creates empty nodes that associate to the documentation pages; the reason of this is that the Comment module still need a node object to return any comment that is associated with that node.


Will URLs with spaces in the path work on all major browsers?

Spaces should be at least encoded as %20 .

It's not a good practice, not a standard, to use spaces in URLs at all. In my opinion it is better to replace all spaces with dashes or to concatenate them.

Spaces will cause problems with links, for example you might get:

www.example.com/problem with link

instead of:

www.example.com/problem with link


Create new content of a different type within the article edit screen?

The Inline Entity Form should help assuming the content types need to reference each other as well!

  Provides a widget for inline management (creation, modification,
  removal) of referenced entities. The primary use case is the parent ->
  children one (product display -> products, order -> line items, etc.),
  where the child entities are never managed outside the parent form.

It was created primarily for Drupal Commerce (Product display -> Product references on one page), but the functionality is there for other entities (out of the box it supports nodes, so it should be fine for your needs).

(Assumed) use case:

Add an entity reference for Songs onto an Album content type
Configure the entity reference to use the inline entity form (IEF) as its widget
Add an album - from here you can add songs to the album using the IEF
When you save the Album, it'll create the Album node plus all of the Song nodes and keep an Album->Song reference


The BookTree module does the job. Some details from its project page:

A simple tree presentation of one book.
What it does is to take as input a series of Book nodes and create a tree-like structure using Book node relationships.
Usage of the module is quite simple and flexible, and options exist to set the root node, the tree depth and to shorten long titles.

The BookTree Example contains a demo of it.


How to allow the setting of the Views Exposed Filters one at a time, instead of showing all available exposed filters at once

I believe the views dependent filters module will do it for you.

I haven't used it but from what I can see it works just like dependent fields.


Get the value from:

$_temp_var_ = $form_state->getUserInput('_field_name_');

Use getUserInput() instead of getValue().

And then set the value to:

$form['_field_name_'] = $_temp_var_;


I already know how to resolve this issue.

In the .install file instead of trying to create a View in the hook_schema in hook_install you can just use de db_query and create the view. Don't forget in the hook_uninstall to drop the created View.

With my researches i found that is impossible to create a view directly in hook_schema like you do in a table, but if someone knows how to that please share.

Hope this help someone out there.

EDIT: Thanks for the correction kiamlaluno


I don't have a D5 system handy, but this would do it in D6:

$count=0;
foreach ($node->taxonomy as $t) {
  if ($t->vid==VID_IN_QUESTION) {
    $count++;
  }
}

and it "should" be the same in D5, but I've said that a lot about D7 and D6 :)  If not,

drupal_set_message('<pre>' . print_r($node->taxonomy,true) . '</pre>');

should give you the object information you need to modify above to count.  If that doesn't work,

$foo=taxonomy_node_get_terms_by_vocabulary($nid, $vid);
$count=count($foo);

certainly is a roundabout way of getting them if you already have the node loaded.


Here is the documentation on joins which should put you on the right path to answering the question.
Untested, but something like this should work:
$query = db_select('node', 'n');
$query->join('comment', 'c', 'n.nid = c.nid');
$query
  ->fields('n', array('nid', 'title'))
  ->condition('n.type', 'page')
  ->condition('n.status', '1')
  ->orderBy('n.created', 'DESC')
  ->addTag('node_access');


Filtering Taxonomy term descriptions in Views

Create a block view of Taxonomy terms from your desired vocabulary.
Add a Contextual Filter (Taxonomy term: Term ID)
Check "Provide Default Value"
Select "Taxonomy term ID from URL" from the dropdown.
Check "Load default filter from node page, that's good for related taxonomy blocks"
Check "Limit terms by vocabulary"
Select your vocabulary ("Remarque prix" if I understood your question properly).
Add the Taxonomy Term name and description fields.

Now you simply add the block to your product pages (easiest is just using Drupal's blocks, but you may have a different way you want to handle this.

Appendix

It doesn't matter if your taxonomy term ID is visible in the URL or not, Drupal understands and will acquire it.

Note: If I understand you context accurately, it seems as if your content type for Product has a 1:1 ratio with your SKU vocabulary. At this point, I would consider whether it's actually necessary to have that vocabulary. Generally vocabularies are best used to group content similar in some ways (i.e. the same taxonomy term is used in multiple places). It might be better to make this a text field on the content type rather than a separate vocabulary. But I also don't know your exact situation, you may have good reason for doing it that way. Just some food for though.


Drupal commerce based recommendations engine

I would not use comments to be recommendations but I would use nodes. This will give more flexibillity.

Here is a possible architecture:

I would use the flag module to let user flag (recommend) a product.
On flagging, I would use hook_flag to create a new node (content type: recommendation). This node would reference to the product. The new node would contain a body field that will contain the actual recommendation. Finally, I would attach the rate module to this node so that users will be able to vote on it.

As far as I know the flag 3.x module is now an entity, which means that you can attach fields to the flag. So, another possible architecture would be to use the flag itself for storing the recommendation. Have not tried this though but seems interesting.


How do I get a view to display as themed within a simplenews html email?

This sounds very similar to what I did a while ago. I documented my setup on drupal.org. This seems to work for your already. I think your MailSystem is the source of error here. Make sure the MailSystem that is used by Simplenews is using the required style sheets and of course the custom templates from your web theme. Also note, that not all styles that are possible on a website an be used in an email, in fact, only a pretty small subset of styles will work at all.

Take a look at the Emogrifier module, it converts your stylesheets to inline styles for emails. Also, for images and other URLs, the Pathologic module may be of help as it converts relative URLs to absolute ones.


Thanks to Geoff. As my long-text never was bigger than the textfield size (255) I could use this solution with ease. I did it the following:
Created a new field "textfield"
Did a database action:

INSERT INTO newtable (newfields)
SELECT oldfields FROM oldtable

and then deleted the old field.


Anonymous users cannot see listed Commerce products in a View with a relationship to product

By default commerce products do not give anonymous permissions to be viewable. This is the reason when a View contains Commerce product relationships it will show nothing when your logged out. You will have to give users the permission setting:

--- View any product of any type ---


Allow users to publish content to their profiles

You can create a block view (Optional  with a filter to show the type of content you want to show) Add the Content title fields and any other field you want to add.

Then You have to set a Contextual Filter of the type Content Author.
Select the "provide default" option and from the type dropdown select user id from url.

Place this block in the user profile page.


How to create template suggestion for image like IMAGE--BLOCK-TYPE or IMAGE--FIELD-TYPE

Solution is here
https://www.drupal.org/forum/support/theme-development/2021-02-23/how-to-create-template-suggestion-for-image-like-image#comment-14017195
It is alternative solution but it works with this module
https://www.drupal.org/project/image_class


How to trigger the click on the field collection button "add another item" using jQuery

jQuery('.field-add-more-submit').mousedown();

works in Inspector.

$('.field-add-more-submit').mousedown();

probably works from a module.

.click() doesn't work for some reason. More info here.


Multiple Node Variants with Different Paths

Try creating aliases that point to the same path (your page manager page). To create aliases go to Configuration > Search and metadata > URL aliases


It's important to understand that taxonomy is not a menu system, the menu system is.  There are ways to make the menu system mirror taxonomy, but they are separate systems.  Taxonomy_menu might be able to help.


Devel kpr, dpr, dpm, etc. only print after cache flush

hook_field_widget_info_alter() is cached.  Follow these steps to Suppress caching (for development) or to use an external page cache

  when developing for Drupal you might want to suppress all caching of
  data to make sure new hooks, theme functions, etc are recognized
  immediately.

  This will have performance detriments, of course, so must not be used
  in production. To turn on this development mode, add the following to
  your Drupal 7 settings.php file:


How do I use the Hierarchical Select module?

Solution

It seems that the read me file for Drupal 7 needs updating. Things have changed from Drupal 6 to Drupal 7. You will find Hierarchical Select available as a widget for the term reference field. To use it, select it at for the field you want to use it for. Also you should use alpha releases at your own risk. They are expected to have bugs.

README

You should read the README file!

From the Drupal 7 version:

  Installation

  1) Place this module directory in your "modules" folder (this will usually be
   "sites/all/modules/"). Don't install your module in Drupal core's "modules"
  folder, since that will cause problems and is bad practice in general. If
  "sites/all/modules" doesn't exist yet, just create it.

  2) Enable the module.

  3) If you want to use it for one or more of your vocabularies, go to
  admin/content/taxonomy and click the "edit" link for a vocabulary. Now scroll
  down and you'll find a whole range of Hierarchical Select settings. All
  settings are explained there as well.


Calling a field in views-view-fields--view-name.tpl.php ---- Error

From the commentary, some points are being missed, but this template is used to create the "row" of fields from a View.

Let's create a simple one:

which has three fields, a title, a new field and a custom field, which when run looks likes this:

Now, let's create a views-view-fields--for-da.tpl.php, rescan for templates, and add some debugging information to the top of it:

drupal_set_message('
' . print_r(array_keys($fields), TRUE) . '
');

and running it again, this will give us:

So, now, anyplace we want inside this template, we have access to the individual field's content as:

$fields['title']->content
$fields['field_new_field']->content
$fields['field_my_custom_field']->content

so throwing them in similar drupal_set_message()s produces:

But now, let's say you are exluding one of these fields from display, eg:

then you will get this:

but some more digging into $row via:

drupal_set_message('
' . print_r($row->field_field_my_custom_field, TRUE) . '
');

will give you this:

or access to the content of the excluded field via:

$row->field_field_my_custom_field[0]['rendered']['#markup']

Obviously, the field names are different here than in your specific example, but I hope you can follow the logic.

Also, if you don't want to dig into $row you could always include the field in the display via the Views UI and then exclude it in this template, eg, something like this:

<?php foreach ($fields as $id => $field): ?>
  <?php if ($id != 'field_my_custom_field'): ?>
    <?php if (!empty($field->separator)): ?>
      <?php print $field->separator; ?>
    <?php endif; ?>

    <?php print $field->wrapper_prefix; ?>
      <?php print $field->label_html; ?>
      <?php print $field->content; ?>

        <?php print $fields['field_my_custom_field']->content; ?>

    <?php print $field->wrapper_suffix; ?>
  <?php endif; ?>
<?php endforeach; ?>

which would print all the fields with the exception of the custom one, but would then include its content after the content of each of the other fields.


Oops, looks like this request tried to create an infinite loop. We do not allow such things here. We are a professional website!

This is because you're using the Redirect mudule, this issue has been posted here already.. Installing the latest dev version, and applying this patch should fix it..


FieldConfigBase has a method named getName(). That will retrieve the field name:

public function getName() {
  return $this->field_name;
}


Wrong order of entities, how to change that?

Take a look at the Drupal API taxonomy_select_nodes(). You are missing the $order argument.

taxonomy_select_nodes($tid, $pager = TRUE, $limit = FALSE, $order = array('t.sticky' => 'DESC', 't.created' => 'DESC'));


Drupal 8 Development - How to Loop Through Field Formatter Elements

You define N #theme render arrays, if you want to be able to control the output in a single template, you need to define only one #theme element and pass it either two array of values or an array of arrays with a uri and filename key each.

$element[0] = array(
  '#theme' => 'video_file_display',
);
foreach ($items as $delta => $item) {
  $element[0]['#items'][] = array(
    'uri' => file_create_url($item->entity->get('uri')->value),
    'filename' => $item->entity->get('filename')->value,
  );
}


The differences are laid out in text.module.

text fields are stored as varchar with a maxlength of 255 characters, and their default widget is a simple text input.
long text fields are stored as longtext, with a maximum length of 4 GiB (maximum characters depending on the encoding), and their default widget is a textarea
text with summary fields are like long text fields, except that text processing is enabled by default. That is, summary text can be included along with the main text, and the content will be processed through input filters. The default widget is a "textarea with summary"

Generally, long text and text with summary fields are used for, well, long text— anything longer than a few words or a few dozen characters: body text, lengthy embedding code, data tables, and so on. Ordinary text is better suited to short snippets of text: a personal name, a company tagline, a favorite color.

I think it would be rare that your data would be suitable to either type. If you're storing a biography for a user profile, for example, you would have a clear idea as to whether it is expected to be a narrative of several paragraphs or simply a short personal motto.


Running Drupal code inspections via PHP Storm returns incorrect results

OK - Embarrassingly enough, this was indeed "user error". The path to the coding standard that PHP Storm was using was indeed slightly different than the path I thought it was using. The paths were quite similar so I didn't catch it during my own reviews.

What helped is that you can configure PHP Storm to output the exact command it runs in the debug log by doing the following: Open Help > Debug Log Settings and add there com.jetbrains.php. Then run the inspection and look at the debug log.


Drupal 7 Views Table Blocks Common Fields Sorting not working in single page

You need to change the Filter identifier under the More fieldset at the bottom of the exposed filters in the View


Select form, write selected item to database

First of all, there is a small error in your code, $options should be an array. Moreover, if you add a key=>value pair for each option, you can get the key of the selected option in the form_submit function. Here is what your foreach could look like:

foreach($result as $row) {
  $options[$row->ID] = $row->color . ' ' .$row->name;
}

and in your submit function you can grab the ID of the selected option like this:

$color_id = $form_state['values']['color'];

Good luck!


Weirdness in views when grouping by a field, and a user has more than one entry in that field

In your hidden entity reference field's setting in Views, scroll down to Multiple field settings and uncheck Display all values in the same row.

When grouping, the content / user will get shown twice instead of what your screenshot shows.


Install Flippy module.

 1. Go to desired content type -> admin/structure/types/manage/<content_type>
 2. Click on Flippy Settings tab
 3. Select "Build a pager for this content type"
 4. Customize the module or template, theme as you want.


Drupal 7: "Maintenance mode" message when the site is NOT in maintenance (Yes, I´ve cleared cache, 4 times now)

Search variable table in database. Variable named maintenance_mode should be there, and should be a serialized representation of false (or numerical 0). If it's not, your site will have a problem.
If this appeared after upgrade, re-running update.php might help


Thans for your reply. We've already solved the problem. It was bug in sql in file_managed. The total truncate of the table helped.


How to force absolute links on a menu tree in Drupal 7

What you probably want to do is theme the menu links differently for this menu.  In D7, you would  be overriding this function:

/**
 * Returns HTML for a menu link and submenu.
 *
 * @param $variables
 *   An associative array containing:
 *   - element: Structured array data for a menu link.
 *
 * @ingroup themeable
 */
function theme_menu_link(array $variables) {
  $element = $variables['element'];
  $sub_menu = '';

  if ($element['#below']) {
    $sub_menu = drupal_render($element['#below']);
  }
  $output = l($element['#title'], $element['#href'], $element['#localized_options']);
  return '
' . $output . $sub_menu . "
\n";
}

In menu_tree_output(), it also sets up per menu theme overrides, so, in your template.php file, you could create your own YOURTHEME_menu_link__MENU_NAME() function.  On first flush, it could look something like this:

function YOURTHEME_menu_link__menu_sitemap(array $variables) {
  $element = $variables['element'];
  $sub_menu = '';

  if ($element['#below']) {
    $sub_menu = drupal_render($element['#below']);
  }
  $output = l($element['#title'], $element['#href'], array_merge($element['#localized_options'], array('absolute' => TRUE)));
  return '
' . $output . $sub_menu . "
\n";
}

but this is an intellectual exercise for me, not a real world one, since I don't have a D7 sandbox to test it out in but it looks pretty accurate, or at least a starting point.


Form input returns "1" instead of real value

I already got it.

I added this:

foreach ($files as $record){
    $options1[$record] = $record;
 }

And then use $options1 as '#options'


How to change the HTML Output of a view?

Drupal likes to put  and
 around every item. When you don't like that, you can override the PHP file that's causing this.

Look in the sites/all/modules/views/theme folder at the views-view-list.tpl.php, views-view-field.tpl.php and views-view-fields.tpl.php files.

Save a copy of these files in your own theme's 'templates' folder. Then you can edit the copies to strip code that makes   and
 etc. You should also rename your version of these files according to the view's template suggestions so the changes only affect your view.

I used this for a view where I wanted to make 3 columns, so I wanted the classes li_1, li_2 and li_3 (in file views-view-list.tpl.php)

<?php
// $Id: views-view-list.tpl.php,v 1.3 2008/09/30 19:47:11 merlinofchaos Exp $
/**
 * @file views-view-list.tpl.php
 * Default simple view template to display a list of rows.
 *
 * - $title : The title of this group of rows.  May be empty.
 * - $options['type'] will either be ul or ol.
 * @ingroup views_templates
 */

global $cnt_ul;
global $cnt_li;
$cnt_ul++;

$classNameUl = (($cnt_ul % 3) == 0)? "ul_". $cnt_ul ." last" : "ul_". $cnt_ul;
?>
<ul class="<?php print $classNameUl ?>">
<?php
foreach ($rows as $id => $row): $cnt_li++;
$className = (($cnt_li % 3) == 0)? "li_". $cnt_li ." last" : "li_". $cnt_li;
?>
<li class="<?php print $className ?>"><?php print $row; ?>

<?php endforeach; ?>


Why am I getting the error "Unknown data property" when the field exists?

If it is a custom field that you have defined in your module (using hook_field_info()) then you need to add a property_type to your field info.  See https://www.drupal.org/docs/7/api/entity-api/property-info-for-fields for an example and https://www.drupal.org/node/905580 for a full list of possible types.

If your field is a complex (multiple value) data structure you may also additionally need to include property_callbacks as well.  See http://d7.thecarneyeffect.co.uk/describe-field-properties-make-custom-fields-work-entity-metadata-wrappers for a good example of this.