Need advise to link a cck field with several values to another cck field

As per your requirement I think you have need to create something like project & the task related to the project. I have done something like this.

For this you will have to create a main content type to hold the project, which will have TITLE & BODY without any other fields.

Create one another content type with reference to first content type. User can add as many task as needed below the first content if permission is given. Add a field named STATUS in 2nd content type, which will hold this COMPLETED or NOT-COMPLETED status of the task.

You can make views of it below the first content type by adding relation between first & second content type & adding the fields by help of the relation.

Let me know if it works in your scenario..


Send out mails to registered users after certain time period

you can use hook_cron() to send email using drupal_mail() and then comparing current date with the published date (timestamp of two dates) in the hook_node.
If current_date is equal to (published_date + 2 months) then send email


I think you can make this work as follows:

In the Permissions settings via admin/people/permissions, ensure ANONYMOUS USER can View comments, Post comments, and Subscribe to comment notifications
In the Comment Notify settings via admin/config/people/comment_notify, ensure comment notification is enabled for the content type(s) you care about
For each content type you care about, e.g. for Basic page via admin/structure/types/manage/page, expand the Comment settings tab in the vertical menu at the bottom of the page and ensure "Anonymous commenting" is set to Anonymous posters must leave their contact information


Module for form submitting straight to admin section

You should use the Webform module.

  Webform is the module for making surveys in Drupal. After a submission, users may be sent an e-mail "receipt" as well as sending a notification to administrators. Results can be exported into Excel or other spreadsheet applications. Webform also provides some basic statistical review and has and extensive API for expanding its features.


How programatically choose between multiple shipping methods commerce_shipping?

So, this doesn't answer the question as posted but all I had to do was set my series of conditions for the Postal Code Weight method. My scenario had to Flat Rate Shipping methods based on specific products in the cart. What I did was configure the Rule for Commerce Shipping Postal Code Weight with two conditions, 1) that it didn't contain one of the products, and  2) AN and OR condition that it didn't contain a product. I also had to specify the conditions for the two Flat Rate Methods similarly, one had to have an exclusion targeting the first product condition.


You can use:

<?php if ($is_front): ?>
 <!-- code here-->
<?php endif; ?>

In your html.tpl.php and it'll only affect the homepage.


You can specify under "Manage Display" how the content you want to feed will look in the "RSS" (or any other) viewmode. By default, you only have the body (or any additional fields) available. To have more control over what's displayed in which viewmode, you can use the Display Suite module. This module allows you (among many other features) to use another layout for this content. By enabling a layout on the viewmode you like, you also get additional fields like for example the Author and the Post date which you then can enable or disable.


Strict warning and views - site not working

There is a patch, it can be found here: https://www.drupal.org/node/893128

I used this one: https://www.drupal.org/files/issues/893128-61.views_.strict-warnings-method-declarations-php-5-4.patch but it did not fix everything. In the end I fixed some items manually similar to what is done in the patch where I replace the function arguments that are the problem from $argument to &$argument. (or sometimes the other way around).

Did you already try the latest dev version, because a patch for the issue I mentioned was committed recently, but I don't think a new version was released since then.


How to create a node based on views results

I think you need 2 relationships in Views. One that targets your field that points from user to the campaing. Second, with the author, based on the first relationship.
After, add as fields user names.
Not really sure about your structure so that was just a supposition.


Drupal 8 services are essentially helpful objects (tools), which live inside the services container (tool belt). Calling a service returns an object, essentially providing a clear path to the helper methods within that class. As previously answered, EntityDisplayRepository class contains various methods, specifically one that will return an array of entity view modes (see a list of available methods). By calling \Drupal::service('entity_display.repository') and storing it in a variable, you now have an object that you can then call EntityDisplayRepository methods from, which in your case, is to return 'node' view modes.

/**
 * Implements hook_preprocess_page().
 *
 * This function is called before the page is rendered.
 */
function modulename_preprocess_page(&$vars) {
  // call the entity service.
  $nodeEntity = \Drupal::service('entity_display.repository');

  // call the necessary method in order to return 'node' view modes.
  $nodeEntity->getViewModes('node');

  // one line: \Drupal::service('entity_display.repository')->getViewModes('node');
}


@Kevin are you sure the fix was due to CKEditor being upgraded in that Drupal version? I'm getting the same kind of issue trying to add the Link plugin, on Drupal 8.1.1, which is using CKEditor version 4.5.8.
Trying to find more insight on this issue.
edit: upon manually upgrading CKEditor to version 4.5.9 I'm getting much more illuminating error messages:

Uncaught Error: [CKEDITOR.resourceManager.add] The resource name "link" is
already registered.
Uncaught TypeError: Cannot set property 'getLinkAttributesParser' of undefined
Uncaught TypeError: Cannot read property 'icons' of null

So looks like this is colliding with the Link plugin that comes with Drupal (which is lacking some features). So I'll find a way to sidestep this name space collision and will update here.
edit: renaming the plugin proved unfruitful. Still getting:

Uncaught TypeError: Cannot read property 'icons' of null


Show/hide fields in a form based on the value of a checkbox

You can use module conditional fields if you want to do this node form


Send "Request new password" email for individual users

If you'd create an appropriate view (using Views) of your users, wit whatever filter criteria you'd want, you could use that view to combine it with the Rules Link module. And with that you have the full power of the Rules module available also to implement whatever logic you'd want.

Refer to the accepted answer to "How to show authorized users a link for relevant Views results using the Rules Link module?" for an in depth explanation about using the Rules Link module, related to a scenario which is a variation of your question here (i.e. show a link to unblock blocked users).


How to set node default language (or avoid language neutral) without Content translation module

You can enable i18n_node module that is included in i18n module. Then:

Go to edit the content type (admin/structure/types/manage/page).
Open the 'Multilingual settings' tab.
Check the 'Require language' checkbox.

Done.


#(block-id-here){
  height:200px;
  overflow-y:scroll;
}

Thanks, Smalution.

I had found out the solution for this.


Different twig template for user profiles of different role

It can done by adding a hook theme suggestion based on roles in your YOUR_THEME.theme file

/**
 * Implements hook_theme_suggestions_user_alter().
 */
function YOUR_THEME_theme_suggestions_user_alter(array &$suggestions, array $variables) {
  foreach ($variables['elements']['#user']->getRoles() as $role) {
    $suggestions[] = 'user__' . $role;
  }
}

Then you can use templates like user--administrator.html.twig, user--editor.html.twig


I don't know if this is causing the error, but you're using drupal_map_assoc() wrong...

The point of that function is to take a linear array and convert it to an associative array with the values of the given array as associated keys. e.g.

$form['distance']['search_distance']['#options'] = drupal_map_assoc(array(100, 200, 300));

I kind of suspect what you're meaning to do is this:

$form['distance']['search_distance']['#options'] = array(100 => '100 km', 200 => '200 km');

Your array is already associative, no need to try making it associative all over again :)


Commerce - how to set no payment for free orders when 100% coupon applied

Looking at your conditions, both of them match at $0.00. You'd at least need to switch Stripe to > 0 for it to work. However, simply adding a coupon on the checkout form doesn't trigger a refresh of the entire page. By that time, the form has already been built with the payment methods shown, and the only AJAX functionality on the pane is to switch out what payment details form elements may be visible.

You're either going to need review / payment on its own step (not a bad idea since you're using coupons anyways) or else write your own code to Ajax refresh the payment options as other elements on the form are updated.


Is it possible to create a list of pages in a view even if a user doesn't have access to those pages?

Have you tired disabling SQL Rewriting?

In the advanced fieldset in the right column when editing the view, click Query Settings

There is a checkbox "Disable SQL Rewriting"
which has help text "Disabling SQL rewriting will disable node_access checks as well as other modules that implement hook_query_alter()."

Try checking that checkbox and saving the View


How to add anchor link through Link field?

Drupal will automatically do that if you only enter #section1 into the Link URL.


How to wrap Drupal "$messages" in a div?

Change this:

return $output;

To this:

return '
' . $output . '
';


Ubercart attribute changes price without page reload on Drupal 7

This is planned to be included in Ubercart itself, see http://drupal.org/node/1380772 - any tests or comments are welcome in that issue.


setting comments unpublished by default for a content type?

If you don't want users to add comments without admin approval then you need to disable the below permission...

Skip comment approval

Once you disable it users would be able to post comments but they will not be visible to other users until the comment is approved by an admin.

This would set the permission for the entire contents and not for a specific content type.

If you want to set it for a particular content type then you would need to look into one of the contributed modules

commentaccess

Allow anonymous comments per node type

Comment Permissions - Stable Version only for 6 does not have a stable 7 version yet


Addressfield: format US state as two letter abbreviation?

As part of this commit, U.S. states (and other countries' administrative areas) will now use their two letter abbreviations when rendered in address formats. Additionally, we now properly provide a comma between the city and state.

Additional code to get this format will no longer be required as of Address Field 7.x-1.0-beta4.


Throw entity field value from submission to route path?

I have found the way to pass the value in edit route without using route subscriber or any pram converter. I will pass the value to Entity list builder default operations function. From there I can change the URL of edit and delete.

public function getDefaultOperations(EntityInterface $entity) {
    /* @var $entity \Drupal\my_module\Entity\entity_two */
    $operations = parent::getDefaultOperations($entity);
    $cid = $entity->cid->getString();
    $edit= \Drupal\Core\Url::fromRoute('entity.entity_two.edit_form',array('entity_one' => $cid , 'entity_two' => $entity->id()));
    $operations['edit'] = array(
        'title' => $this->t('edit'),
        'weight' => 10,
        'url' => $edit,
    );
    $delete= \Drupal\Core\Url::fromRoute('entity.entity_two.delete_form',array('entity_one' => $cid , 'entity_two' => $entity->id()));
    $operations['delete'] = array(
        'title' => $this->t('delete'),
        'weight' => 11,
        'url' => $delete,
    );

    return $operations;

}


Exception handling in drupal : How one can deal with warnings in Drupal?

The purpose of warnings are to warn you that something is wrong with the code you've executed. They are provided by PHP, not by Drupal (though Drupal can trigger them if required). Notices are similar, but considered less urgent. Warning/notices are not fatal, so don't halt the scripts' execution.

The way to "deal with" them is to simply fix the code, which might mean fixing your code, reporting a bug to a core/contrib issue queue, digging through a request to make sure that the value of variables being passed around are what they're expected/required to be, or something else.

Some people might tell you just to disable warnings/notices so that they're not bothering you visually, but as in all walks of life, hiding a problem instead of fixing it is a bad idea.

There isn't a catch-all answer to fixing every possible type of warning. You need to debug the site, find out exactly what and where the problem is, and apply your skills as a developer to fix them.

I don't know what the policy is for contributing modules that containing warnings/notices. I would hope that they are, at least in an initial review, rejected if they cause such things, but that might not be a practical expectation.

Regarding how Drupal deals with them: the answer is that it doesn't, really. You can switch on and off the display of error messages through the admin UI, but Drupal can't, and doesn't, have any interest in fixing these errors, or helping you any further to narrow down what's causing them. It's just a PHP app at the end of the day.

Incidentally, Drupal does implement its own PHP error handler (_drupal_error_handler_real()), so that it can log errors and exceptions in the watchdog, and/or to the screen.


Hide publishing options in hook_form_alter without unpublishing node?

You could just convert the element to a value type, that way it will be hidden from the form display but will be passed through to the submit handler as normal:

$form['options']['status'] = array(
  '#type' => 'value',
  '#value' => 1
);

You can do the same thing for the rest of the elements in that fieldset, then set the fieldset itself to a container type and remove the title:

$form['options']['#type'] = 'container';
$form['options']['#title'] = '';


After disabling and uninstalling memcached module, I get this PDOException and WSOD?

Each time I saw the "Mysql server has gone away" error, it was caused by the max_allowed_packet setting (in the my.ini setting file) that was too small.


Displaying the data export/feed icon only when there are search results

You can override the template for the views.

There is a variable called $empty this field contains the text to be displayed if the node is empty. You can use this to check if view is empty or not.

If you have placed the attachment before the node then you would edit the below section.

<?php if ($attachment_before): ?>

      <?php print $attachment_before; ?>

  <?php endif; ?>

You can change this to

<?php if ($attachment_before && !$empty): ?>

      <?php print $attachment_before; ?>

  <?php endif; ?>

This would make sure that the attachment is printed only if the view has a result.


How do I edit individual meta tags on a panelized page?

Apparently it has nothing to do with the panels; the Metatag plugin just doesn't support landing pages. Converting the needed landing pages to customized content pages solved my problem.


How to modify the existing field in a form?

You'll usually find the elements for fields buried in the form and you'd alter them like so:

$form['field_my_field']['und'][0]['value']['#ajax'] = array(
  // ajax settings
);

I strongly recommend installing the Devel module and using the dpm() function to perform debugging. You can use it to print any variable to the standard message area, and it allows you to inspect arrays and objects.

You could easily find out where abouts in the $form array the fields you're looking for are by including a line like this in your form alter function:

dpm($form);


Without knowing how your view looks like (or what slideshow module you use, if any) it is hard to give a definite answer - but check the image field in your view. If you edit the field there should be an dropdown titled 'link this image with' and right now it is probably set to 'content'. Set it to 'nothing' to remove the link.

Note: I am not sure about the exact labels as I work with a german drupal instance right now, but they should come close. The dropdown is right above the Design Settings fieldset.


If you want to set a specific canonical URL for a given node, just edit your node and uncheck "Generate automatic URL alias" in the URL alias section and you'll be able to write your own URL.
You might need Path module to be enabled to do that.
If you want to have specific automatic patterns for your URL alias depending on the type of node, then you will need the module Pathauto (https://www.drupal.org/project/pathauto) ; just enable it and configure your patterns for each type of node


How do I get the highest `field_id` value that exists in content of a specific type?

The easiest sulotion I can think about is to use Computed field module and the id field will be computed field.
Then,  in the field read the last value using variable_get() and then update that value using variable_set().


The url function returns a render array, so you can't concatenate it with a string.  You must first convert it to a string.

try render_var():

{% set support_url = render_var(url('<front>')) ~ 'support' %}

<h1>{{ support_url }}</h1>

This will convert the render array created by the url function to a string.


How to include jquery.js before other javascript includes?

Use hook_js_alter to change the order of js presentation.

For example, edit your theme's template.php:

function youtheme_js_alter(&$javascript) {

  $javascript['misc/jquery.js']['group'] = -500;

  $javascript['misc/jquery.js']['weight'] = -500;

}


Is there any alternative to the Quiz module?

Webform is an option. You can show different questions in different page (something that quiz doesnot do). You will require little bit of programming to show the answers for the questions and their scores once the webform is being submitted. This is if you want to capture the score.


It worked (in views plugin).

// create subquery using database api
$sub_query = \Drupal::database()->select('node__field_event_date', 'n');
    $sub_query->addField('n', 'entity_id');
    $sub_query->addExpression("MIN(n.field_event_date_value)", 'EarliestEventDate');
    $sub_query->groupBy("n.entity_id");

// create join
$join_definition = [
      'table formula' => $sub_query,
      'field' => 'entity_id',
      'left_table' => 'node_field_data',
      'left_field' => 'nid',
      'adjust' => TRUE,
    ];
$join = $this->joinManager->createInstance('standard', $join_definition);
$this->query->addRelationship('event_date', $join, 'node_field_data');

Edit:
If you do the same thing in hook_query_alter, change the last two lines like this.

$join = Drupal::service('plugin.manager.views.join')->createInstance('standard', $join_definition);
$query->addRelationship('event_date', $join, 'node_field_data');


Navigation links in a region rendering vertically

You can copy the responsible template file from bootstrap theme and put it in sub theme. I think you will find your template under Menu folder in tempaltes of bootstrap theme (parent theme)
You will find these files and you have to modify one of these in order to achieve what you said.

menu-link.func.php
menu-local-action.func.php
menu-local-task.func.php
menu-local-tasks.func.php
menu-tree.func.php

Thanks


how do I add extra classes to a date field at views?

You can do this without any additional modules.

Add the date field. Exclude this from the display.  Choose custom, and write d in the box (as in php date for the day).  Change the 'Style Settings' - Customize field HMTL (set to none) and  Customize field and label wrapper HTML (set to none).
Add the date field again.  Exclude this also from the display. Choose custom, and write M in the box (as in php date for the month).  Change the 'Style Settings' - Customize field HMTL (set to none) and  Customize field and label wrapper HTML (set to none).
Add the date field again. Exclude this also from the display.  Choose custom, and write Y in the box (as in php date for the year). Change the 'Style Settings' - Customize field HMTL (set to none) and  Customize field and label wrapper HTML (set to none).
Add the date field again (LAST TIME!).  DO NOT EXCLUDE THIS FROM THE DISPLAY. Choose custom, and write G:i (as in php date for the hours and minutes). Change the 'Style Settings' - Customize field HMTL (set to none) and  Customize field and label wrapper HTML (set to none).
Rewrite the results of this final date field.  Using the replacement patterns, you can then write something like this:

    [created]

    [created_1]

    [created_2]


How do I limit the number of Views results on specific pages?

This works for me:

function MYMODULE_views_pre_build(&$view) {
  if ($view->name == 'view_name') {
    $view->items_per_page = 5;
  }
}


Should I use securepages?

No. The best practice these days is to just go with https for the whole site.

How do I go about caching my https content?

On a normal site, the https wouldn't matter, you can cache static content regardless of how encrypted it travels. BUT. The caching questions are legitimate because it is an eCommerce site and with that (by default), even anonymous users will have a session. Most default caching systems do not work with per-user sessions, unless you use something like authcache.


How to display one image in multiple sizes across the site?

Imagecache module has been moved into core for Drupal 7

It's called Image Styles

I haven't used the module, but Image Formatter Link To Image Styles module exposes the Image Style presets in in the imagefield


Zen theme - recommended way to display 2 blocks next to each other in a region

Plain old CSS

Plain old css will work. Set your widths with those two blocks and float them.

Zen Grids

If you create custom classes the zen grid sass extension can be used as well to set up layouts using sass

More on zen grids:

http://zengrids.com/help/
http://thinkshout.com/blog/2013/10/candice/getting-started-sass-drupal-and-zen

Block class

Block Class is a good way of setting blocks up to line up accordingly next to each other:

  Block Class allows users to add classes to any block through the block's configuration interface. By adding a very short snippet of PHP to a theme's block.tpl.php file, classes can be added to the parent  element of a block. Hooray for more powerful block theming!


Unfortunately—and this is not an ideal solution, but seems to be what everyone is using successfully—I have had to use the following brute-force SQL statement in the past.

First, backup your entire Drupal database!

Then, execute this in your favorite SQL manager:

DELETE FROM menu_links WHERE module = 'system';

Then visit /admin/config/development/performance and clear the cache.

taken from https://drupal.org/node/865702#comment-4015758


How to put 2 'views' side by side in 1 region using the bootstrap theme?

You need to use CSS. Inspect element with your browser, find the div class of the 1st view and use

.view-myviewname { float: left; }

JS Fiddle Example


The only way I found for now was to, inside views_pre_view, deep clone the $view object using $view = unserialize(serialize($_view)), so when Drupal passes again on form_alter the form would be untouched and I can just recreate some selects.


MedialEment.js module not seeing the installed library

The easiest way to debug something like this is to look at the MediaElement module itself.

Its implement of hook_library() contains the following:

$libraries['mediaelement'] = array(
    'title' => 'Media Element',
    'website' => 'http://mediaelementjs.com/',
    'version' => '2.1.6',
    'js' => array(
      // The mediaelement script detects the path to itself to call other files
      // in the same location. With preprocessing this is problematic as the
      // script is no longer in the same directory as its other assets. There
      // is an option that can be passed into the script with its location.
      // @todo Update all calls to mediaelement to pass in the assets location.
      $path . '/build/mediaelement-and-player.min.js' => array('group' => JS_LIBRARY, 'preprocess' => FALSE),
    ),
    'css' => array(
      $path . '/build/mediaelementplayer.min.css' => array('group' => CSS_SYSTEM),
    ),
  );

So it would appear the module is looking for

sites/all/libraries/mediaelement/build/mediaelement-and-player.js
sites/all/libraries/mediaelement/build/mediaelementplayer.min.css

If you make sure those files are in the right place, you should have no more issues.


Does hook_node_info() have to be in .module or can it be in .install?

hook_node_info should be in the .module file. However, you could implement the hook in the module file and then just call module_load_install from there to include another function in the .install file, if that helps. Another option is to export the content type using a module such as Features instead.


No chance for working: https://www.drupal.org/node/2043177

!@#!@#!


Clearing cache via the UI and via drush both end up calling drupal_flush_all_caches(), but there is a subtle difference.

When you run from the UI, the PHP executes as Apache (or however you have your webserver configured).  When you run from drush, it runs as the user who executed the command.

The problem in your case is that the LESS module will run its cron functions, which clears out the less directories in sites/default/files and makes a new one.  When this happens, there is often a permission problem:  your drush user owns the less directory and Apache can't write to it.  Therefore, your CSS files don't get regenerated and your site end up unstyled.

My solution is to make sure my drush user is also in the Apache group on my server, and that my sites/default/files directory has 2775 permission on it and with ownership by apache:apache.  I also make sure that the umask of httpd makes things group writable.

This makes sure that any files and directories that get created always have group ownership by apache, and that Apache can write to any directories that get made, regardless of whether it was done by httpd or from the command line.

EDIT:

There is one more difference that is worth noting.  When you clear with drush, you just clear the caches.  When you clear from the UI, you clear the caches and then the page reloads.  When the page reloads from a cold cache, the parts used to rebuild that page get cached again.  This includes making CSS files from the LESS sources.


that's a hard point that i'm also dealing with.

Actually i imagine 2 differents ways to solve this :

i install the module paragraph
It is pretty anwsome by changing the way a user contribute. But it doesn't allow to add a slideshow in a Body field.
Creating a plugins for CKEditor that create (a new button) that will add the slideshow HTML in the Body Field.
This button will be like "Create a table" button, you will decide how many images is needed and you will just add the  to it.
The HTML is quite simple, for bxSlider (http://bxslider.com/) for Exemple you will need to add this :

And for SlidesJS it's :

I didn't start this plugins yet because i finally decide to use Paragraph but i think this plugins for CKEditor can be a good tool in the futur.


How do I reference a file field and node title from another content type & node?

Ok - I got it figured out.

All I needed was the entity reference field.

I then followed the steps in the article posted below which allowed me to then be able to attach my document entities to my plan info nodes.

https://www.ostraining.com/blog/drupal/entity-reference-view/

Then i was able to create a view of the plan info nodes by creating a relationship in views to the referenced entity on the nodes, then I had the necessary fields available to me as fields for my view, and that solved everything.


Views: Multiple Contextual Filters (Taxonomy)

I spent lot of time to figure this out, but finally found a solution:

Instead of Content: The name of Taxonomy (taxonomy_vocabulary_#) you need to select Content: Has taxonomy term ID Contextual filter and enable Allow multiple values to able to use multiple values in the form of 1+2+3 (for OR) or 1,2,3 (for AND).


Solve "Cron run failed" without Watchdog

To enable the recording of the watchdog() messages, you just need to enable the Database logging module (short name: dblog). Once you enable it, on admin/reports/dblog you will start reading the recent log entries.

As for the possible error that could return cron, they are the following ones:

Cron has been running for more than an hour and is most likely stuck
Cron is already running and you try to re-run it

This is evident from Drupal code. The function that is executed when you go to admin/reports/status/run-cron is system_cron_run(), which returns the error you are seeing when drupal_cron_run() doesn't return TRUE. This is that function code.

  // Try to allocate enough time to run all the hook_cron implementations.
  if (function_exists('set_time_limit')) {
    @set_time_limit(240);
  }

  // Fetch the cron semaphore
  $semaphore = variable_get('cron_semaphore', FALSE);

  if ($semaphore) {
    if (time() - $semaphore > 3600) {
      // Either cron has been running for more than an hour or the semaphore
      // was not reset due to a database error.
      watchdog('cron', 'Cron has been running for more than an hour and is most likely stuck.', array(), WATCHDOG_ERROR);

      // Release cron semaphore
      variable_del('cron_semaphore');
    }
    else {
      // Cron is still running normally.
      watchdog('cron', 'Attempting to re-run cron while it is already running.', array(), WATCHDOG_WARNING);
    }
  }
  else {
    // Register shutdown callback
    register_shutdown_function('drupal_cron_cleanup');

    // Lock cron semaphore
    variable_set('cron_semaphore', time());

    // Iterate through the modules calling their cron handlers (if any):
    module_invoke_all('cron');

    // Record cron time
    variable_set('cron_last', time());
    watchdog('cron', 'Cron run completed.', array(), WATCHDOG_NOTICE);

    // Release cron semaphore
    variable_del('cron_semaphore');

    // Return TRUE so other functions can check if it did run successfully
    return TRUE;
  }

As for why Drupal thinks cron is still running, that happens when an error in the code (generally one of the hook_cron() implementations) doesn't permit drupal_cron_run() to execute the following line:

    // Release cron semaphore
    variable_del('cron_semaphore');

This means that to debug why cron doesn't work properly, you need to check any hook_cron() implementation, and see what is wrong with them. The problem could also be an implementation of hook_node_view() which is wrongly calling drupal_goto().


Drupal 7: hierarchy disabled setting on taxonomy vocabulary

I found how to do it. I ended up using hook_form_FORM_ID_alter on the taxonomy form in the admin area, like so:

function hook_form_taxonomy_overview_terms_alter(&$form, &$form_state) {
        $form['#parent_fields'] = FALSE;
}


Is there a way i can import users having profile2 with feeds

There's a module called Feeds Profile2 which extends the built-in User processor so that Profile2 profiles can be created and updated as part of a user importer.


Getting the node id from the node containing an entityform in submit handler

I've solved it like this:

I've added a hidden field to the EntityForm called parentid and set that value with the id of the ShowForm-node when the node is created. This way I can use this parentid to redirect to the correct ShowForm-node when submitting a form.


Highlight View parent menu item on node page and rebuild breadcrumb

To display the "Ressources" menu in a testimonial node page, Drupal should believe that we are actually on the "Témoignages" Views page. Plus, it will highlight automatically the good menu item.

But, we also need a correct breadcrumb. That's why we have to save in a variable the "true nature of the page" (a node) before letting know to Drupal that we are on a view.

That's that we do here:

function pwe_testimonial_node_view($node, $view_mode, $langcode) {
  // When we are on a Testimonial node page
  if($node->type == "testimonial" && $view_mode == "full") {
    // We save the true nature of the page
    $_SESSION['pwe_testimonial_active_trail'] = serialize(menu_get_active_trail());
    $_GET['pwe_node_id'] = $node->nid;
    // And set the active menu item as "Témoignages"
    menu_set_active_item("testimonial");
  } else {
    // If we are not on a Testimonial node page,
    // we unset the custom variable.
    if(isset($_SESSION['pwe_testimonial_active_trail'])) {
      unset($_SESSION['pwe_testimonial_active_trail']);
    }
  }
}

To rebuild the true breadcrumb, we use the variable saved in previous function.

function pwe_testimonial_menu_breadcrumb_alter(&$active_trail, $item) {
  if($item && $item['path'] == "testimonial") {
    if($_GET['pwe_node_id']) {
      if(isset($_SESSION['pwe_testimonial_active_trail'])) {
        unset($_SESSION['pwe_testimonial_active_trail']);
      }
    }
    if(isset($_SESSION['pwe_testimonial_active_trail'])) {
      $original_active_trail = unserialize($_SESSION['pwe_testimonial_active_trail']);
      if(is_array($original_active_trail)) {
        $total = count($active_trail);
        $active_trail[$total] = $item;
      }
    }
  }
}

That's all. I hope this little Q&A sharing knowledge will help someone in the future.


How to Use Ajax in form alter in Drupal 7?

I would be able to give you some detailed information about what you are doing wrong with hook_form_alter if you included some actual code from your custom module. However, since you are not giving any specifics, you can watch the video: How to build beautiful forms in Drupal 7 (note that I entered the URL so that it starts at the moment where the ajax is described). About 5 minutes of watching this will probably give you the answer to your question (since it describes exactly how to use ajax with hook_form_alter), but if you are really impatient, the actual code is shown somewhere around here.

If you want to see a live, well-tested and documented example of a form being altered using ajax, there is one in the Examples module. You can find the actual hook here and the callback function here.

I hope this helps. If it doesn't, give us some more background about your code and we will be able to tell you exactly what you are doing wrong.


I can not change the author of the material, an error occurs. error code inside, along with a screenshot

The AJAX path used for autocompleting usernames (user/autocomplete) requires a user to have the access user profiles permission:

  $items['user/autocomplete'] = array(
    'title' => 'User autocomplete',
    'page callback' => 'user_autocomplete',
    'access callback' => 'user_access',
    'access arguments' => array('access user profiles'),
    'type' => MENU_CALLBACK,
    'file' => 'user.pages.inc',
  );

Make sure that is true for the user account that's entering the data into the autocomplete field.

If the account does have the permission then the problem is specific to your environment (e.g. a module that alters access callback / access arguments of router item) and requires further debugging that falls out of the scope here.


Metatag: How to programmaticaly set a node's canonical URL

look into the hook: metatag_metatags_view_alter().

/**
 * Implements metatag_metatags_view_alter()
 */
function mymodule_metatag_metatags_view_alter(&$output, $instance) {
  // Add Custom logic to overwrite the canonical tag here.
  $canonical = 'http://www.mysourceurl.com';

  // Alter canonical tag.
  $output['canonical']['#attached']['drupal_add_html_head'][0][0]['#value'] = $canonical;
}


You can use the url():

$imgurl = drupal_get_path('theme', 'YOURTHEME') . '/images/image.png';
$final_url = url($imgurl, array('absolute' => TRUE));

This will provide a url like http://example.com/sites/all/themes/YOURTHEME/images/image.png


How can I have the JS/CSS cache refresh on every page load?

As long as you don't have JS or CSS aggregation turned on, you shouldn't have to clear cache to see your changes to existing files. You can see this settings by going to;

Admin->Config->Development->Performance(admin/config/development/performance).

If you are adding new CSS or JS files, you'll probably have to clear cache to register them with the theme system.

If you really want to clear cache on every page load, you should create a custom module that implements hook_init() and runs drupal_clear_css_cache() and drupal_clear_js_cache() (or any other cache clearing functions you may want), but this should be unnecessary.


Adding an information icon to a form element

You can use '#prefix' => 'Some title ' instead of '#title' => t('Name')

$component[$this->componentName] =  array(
                  '#prefix' => t('Some title*') .' ',
                  '#type' => 'textfield',
                  '#size' => 30,
                  '#maxlength' => 45,
                  '#default_value' => $item->Name,
                  '#attributes' => array(

                  );

You can add any markup to '#prefix' element of this array.

Or you can add markup even directly to title '#title' => t('Some title*') .'', but i think there can be some issues with asterisk when a field is required.


You have to iterate your field's delta ; here, you only affect $form['field_company']['und']__[0]__, not  $form['field_company']['und']__[n]__

Stay in your hook_form_alter but iterate it each time your $form is rebuild :

    foreach($form['field_company']['und'] as $delta => $field) {
        if(is_array($field) && is_numeric($delta)) {
            $form['field_company']['und'][$delta]['value']['#autocomplete_path'] = 'autocomplete/company';
        }
    }


If you just want to show the logo or the screenshot of the theme in your drupal site, just replace your own images with the logo.png or screenshot.png in yoursite/themes/bartik/, remember you have to name them 'logo.png' or 'screenshot.png' exactly.

Not sure if this is what you want. Good luck.


You need to grant permission to search content. Peoples > permission > Use search checkbox


JOINs are a query-level concept and don't really make a lot sense in the context of a schema definition.

I suspect what you're asking is how to add a foreign key from your location table to the users table. If so I'm afraid you're out of luck; Drupal does not enforce foreign key relationships, so you'll need to define and maintain your relationships at a code level.

There is a foreign keys property that can be applied to tables defined by the schema API, but it is for documentation purposes only, no foreign keys are ever added at the database level.

Just in case you are asking how to join a table in a query:

$query = db_select('location', 'l')
  ->fields('l');

$query->join('users', 'u', 'u.uid = l.uid_column_name');

$results = $query->execute();


Drupal does not know "dependencies" on it's own, so I assume it's something provided by the module you named. Yes, it is possible. After all that module is doing exactly this. Just read it's code and see, PHP is an interpreted language after all. It seems there is no module with that exact name on Drupal.org, so I can't provide more detailed instruction now. To find it yourself, you need:

Find implementation of hook_menu() in this module
Locate entry for GUI page that shows what you want
Find implementation of a function that obtains data for that GUI page


"messages status" div not showing up when submitting page comment

I would look at the following permissions:

to see what is going on.  On first blush, I'm going to assume post comments without approval is checked for more roles than you want or expect.

You can also surf over to admin/content/node-type/CONTENT-TYPE and click on "Comment settings" to see if anything is set for that specific type of node.

If these don't give you any "AHA!" moments, look around to see if any other comment approval modules are in place on the system.

Also, a lot of page.tpl's in D6 wrap their various content areas with something like this:

<?php if ($messages): ?>
  <div id="messages">
    <?php print $messages; ?>
  </div>
<?php endif; ?>

which basically means if you don't have any content for that area, there is no need to print an empty <div> which probably explains why you aren't seeing anything (eg, there was no message in the first place).


I had a similar issue. But I had Bean and Bean-all module installed, so only in the blocks ticked in admin/config/system/bean-all the move/edit actions were "real" or commited, although success message was showed in the non-ticked ones.


How to modify contents of drupal select form element based on what was selected in a preceeding select element

You can create it with built-in Ajax Framework (you don't need to use javascript). Here is a nice example (and I'll include the code here):

function sandbox_ajax_dropdown($form, &$form_state) {
  $form['sandbox_ajax_dropdown']['province'] = array(
    '#title' => t('Province'),
    '#type' => 'select',
    '#options' => _load_province(),
    '#ajax' => array(
      'event'=>'change',
      'callback' =>'sandbox_ajax_dropdown_city',
      'wrapper' => 'city-wrapper',
    ),
  );

 $form['sandbox_ajax_dropdown']['wrapper'] = array(
    '#prefix' => '
',
    '#suffix' => '
',
  );

  $options = array('- Select city -');
  if (isset($form_state['values']['province'])) {
    $options = _load_city($form_state['values']['province']);
  }

  $form['sandbox_ajax_dropdown']['wrapper']['city'] = array(
    '#title' => t('City'),
    '#type' => 'select',
    '#options' => $options,
  );

  $form["sandbox_ajax_dropdown"]["submit"] = array(
    "#value"  => t("Submit"),
    "#type"   => "submit",
    "#submit" => array("sandbox_ajax_dropdown_submit"),
  );

  return $form;
}

function sandbox_ajax_dropdown_city($form, $form_state) {
  return $form['sandbox_ajax_dropdown']['wrapper'];
}

function sandbox_ajax_dropdown_city($form, $form_state) {
  return $form['sandbox_ajax_dropdown']['wrapper'];
}

function _load_province() {
  $province = array('- Select province -');
  $query = db_select("sandbox_province", "a");
  $query->fields("a", array('id', 'name'));
  $query->condition("a.status", 1);
  $query->orderBy("a.name");
  $result = $query->execute();

  while($row = $result->fetchObject()){
    $province[$row->id] = $row->name;
  }

  return $province;
}

function _load_city($province_id) {
  $city = array('- Select city -');
  $query = db_select("sandbox_city", "a");
  $query->fields("a", array('id', 'name'));
  $query->condition("a.status", 1);
  $query->condition("a.province_id", $province_id);
  $query->orderBy("a.name");
  $result = $query->execute();

  while($row = $result->fetchObject()){
    $city[$row->id] = $row->name;
  }

  return $city;
}

And also take a look at Examples module.


How can I know which button was clicked?

You must use $form_state->getTriggeringElement().

Best practice is to define a #name attribute for your button, so you can have this value in the triggering_element.

For example:

$form['delete'] = array(
  '#type' => 'submit',
  '#value' => t('Delete'),
  '#name' => 'delete',
);

In this example:
$form_state->getTriggeringElement()['#name'] will return "delete" when called within public function submitForm(&$form, $form_state)

If you don't define this attribute triggering_element will hold the button's #value (the text that user can read), but this is discouraged as other modules may change this value or be changed by the localization).

You may use $form_state['clicked_button'] too, but this is deprecated.

You can read more info at the drupal_build_form function documentation page.


Notify a user if a node has a comment or status updated

I recently did something similar, for reacting when the node is updated i used hook_node_presave(). Here's an example on how to send an email when the node is updated and the status is changed from "open" to "pending".

function my_module_node_presave(NodeInterface $node){
  if($node->getType() == 'your_content_type_name' AND $node->isNew() == FALSE) {
   $status_original = $node->original->get('status_field')->value;
   $status_updated = $node->get('status_field')->value;

 if ($status_original !== $status_updated AND $status_original == 'open' AND $status_updated == 'pending') {
   send_mail();
  }
 }
}

For creating the send_mail function or whatever you'd like to call it i used the following resource and modified the code where necessary: How to send a mail programmatically in Drupal 8. Also, i used the SMTP Authentication Support module to send the emails using a gmail account: SMTP Authentication Support. The configuration page of the module is on admin/config/system/smtp.

For checking if a comment has been posted you can use hook_ENTITY_TYPE_insert() and replace "ENTITY_TYPE" with "comment" and inside the hook you can call again the send_mail function.

I did not quite understood how you are storing "all the users on the ticket", but it would be the case of getting the users email address with getEmail();


Execute custom JavaScript code after Webform has been submited with Webform Ajax Module

Okay, try this. After the ajax request is completed on "#myform", it runs the function.

$("#myform").bind('ajax:complete', function() {

     // tasks to do

});

Source | API Documentation


Export the default system email text to code?

Settings in files for version control was one of the biggest changes in the 7 -> 8 jump. Drupal 7 has no built-in way to do it. You may wish to see How to version control data stored in mysql.

If you want Drupal-specific tool, investigate Configuration Management module:

  The configuration management module enables the ability to keep track of specific configurations on a Drupal site, provides the ability to move these configurations between different environments (local, dev, qa, prod), and also move configurations between completely different sites (migrate configurations) without the use of modules with all configuration being owned by the site.


Block not showing up in Custom Blocks for Panel

I made a custom block from code and it is listed in "miscellaneous" section insted of "custom blocks". Maybe your modules are there.


Custom layouts with the Display Suite module

In your theme folder, create a THEMENAME.layouts.yml file:

clean_empty:
  label: Clean empty page layout
  category: Display Suite
  class: '\Drupal\ds\Plugin\DsLayout'
  type: partial
  template: templates/nodes/clean-empty
  regions:
    title:
          label: Title
    ds_content:
      label: Content

Then just create your twig file. In this example, create a clean-empty.html.twig file inside THEME/templates/nodes:

{#
/**
 * @file
 * Custom display suite layout
 *
 * Available variables:
 * - title
 * - ds_content: content region
 */
#}
{{ title_suffix.contextual_links }}
<h1>{{ title }}</h1>
{{ ds_content }}


Custom target URL for Views content pane exposed filter (block)

Use form redirection in hook_form_alter.


How to get the operation Links in my own EntityListBuilder

Ok, after I found the documentation at drupal documentation I get it! The naming of the link list must be:

* @ContentEntityType(
*   id = "mytest",
*   links = {
*     "canonical" = "/tested/{mytest}",
*     "delete-form" = "/tested/{mytest}/delete", // EDIT!
*     "collection" = "/tested"
*   },
* )

That's all!


You can also use hook_views_query_alter() to alter the query before it's run. I think this is similar to hook_views_pre_execute, but makes it easier to modify the query. You basically get access to each part of the query through a keyed array. I haven't found much official documentation, but there's a pretty good example of it at https://www.appnovation.com/blog/using-hook-views-query-alter. This is also the approach I had to use to fix a date bug in the Calendar module.


Attach shipping courier selection at drupal cart commerce line item

I think Commerce Delivery module solved your problem.

Or you need to add Shipping plugin.

Please check this two links. I think this may help you.

Link 1

Link 2


How to password protect terms in Taxonomy

These modules may help, for D7 & D8 on DEV version is Taxonomy Access Control Lite, on approved versions (recommended): D7 is Taxonomy Access Control and for D8 is Permissions by Term, review wich one fit best your needs.


Current answer is not 100% correct for Drupal 7. In Drupal 7 there is a hook called hook_hook_info. In core this is implemented with the token module via system_hook_info. That means that for tokens the hook can be located inside of module_name.tokens.inc. So yes you can put hooks in related files by groups. Just remember that hook_hook_info must be inside of your .module file.

An example using blocks

<?php
/**
 * Implements hook_hook_info().
 */
function mymodule_hook_info() {
  $hooks['block_configure'] = array(
    'group' => 'blocks',
  );
  $hooks['block_info'] = array(
    'group' => 'blocks',
  );
  $hooks['block_info_alter'] = array(
    'group' => 'blocks',
  );
  $hooks['block_list_alter'] = array(
    'group' => 'blocks',
  );
  $hooks['block_save'] = array(
    'group' => 'blocks',
  );
  $hooks['block_view'] = array(
    'group' => 'blocks',
  );
  $hooks['block_view_alter'] = array(
    'group' => 'blocks',
  );

  return $hooks;
}
?>

You should be able to then use a mymodule.blocks.inc file to hold all your blocks information as long at the above code/hook is inside of your .module file.


Display a block on some pages according to the fields content of that page

Simplest way is to conditionally output region in node.tpl.php
But there is no $page in node.tpl.php. So you need to make it happen. In your template.php add function

mytheme_preprocess_node(&$variables) {
  // List of all regions for the current theme
  foreach (system_region_list($GLOBALS['theme']) as $region_key => $region_name) {
    // Add content to $region variable
    if ($blocks = block_get_blocks_by_region($region_key)) {
      $variables['region'][$region_key] = $blocks;
    }
    else {
      $variables['region'][$region_key] = array();
    }
  }
}

Then in node.tpl.php use:

print render($region['region_name']);

to output your region. Of course wrap it in if, case or any other logic you fancy.


Node form redirect based on submit button value

The answer was to attach my submit handler to the submit button rather than the form, and then the $form_state['redirect'] would work as needed.


How to redirect a page to the custom location after form validation?

You shouldn't really do it in validator. Redirect in submit handler, with code like:

$form_state['redirect'] = 'comment/reply';

For more details of form redirecting consult official documentation.


Annnnd after asking I read my question and realized my answer. The key base_theme is not one word, it's two.


Drupal 7, form api - file field default_value

No, there's no way to do this. The restriction is with HTML, not Drupal. A file input simply doesn't have the capacity for a default value to be set; allowing such behaviour would introduce a security hole (imagine you pre-filled it with /~/.ssh/id_rsa, auto-submitted the form, and the user didn't have permissions set up correctly). See this post.

If you check the FAPI guide you'll see there's no #default_value available for a file field type.

You'll need to switch to a managed_file element if you need a default value for the field.


How to wrap node output with a link using Display Suite?

A good option for this is Field Group Link.

For your case, basically you need to create a field group wrapping the whole node, and set the group type to 'Link'.


In submit of form store your data in session variable $sid with _drupal_session_write('mysession', $value); and in every where you want read it with _drupal_session_read('mysession');

you shold start session before you write or read session variable like php.

drupal_session_start();
_drupal_session_write($sid, $value);
_drupal_session_read($sid);


Why is search disabled by default for anonymous users?

In Drupal almost all permissions other than access comments, view published content and exceptionally use text format filtered_html are disabled by default for anonymous users. There is no specific reason for search other than the rest.

It is up to you and the purpose of the site you want to build, which permissions you want to give the users.


How to change a term URI based on content type

My answer is going to use two modules, that are tools, not solutions. You will get the flexibility to do most anything you want with the paths, at the cost of needing to understand how the modules work. I will provide an outline of the required configuration below, there are useful videos here, and I will try to update the answer if you get stuck anywhere specific.

Install and enable the Page Manager, as well as Panels
Go to admin/structure/pages/add, and add a Page, with the path video/%video_term
On the next page, click "Change", and pick "Taxonomy term: ID", then pick ID, or Name, as it suites you.
Pick any layout, and just move on until you can click "Finish" to end the wizard. Now fill your layout with whatever content you wish.
Repeat steps 1-4 for your "photo" page.

Since Drupal doesn't allow you to use a variable at the first level, you can't do /%content_type/%term, so instead we create two pages. Personally, I would opt to do something like /products/%content_type/%term, as a single page will lower your maintenance burden down the road. That however, will require understand "Variants", to accommodate two pages in one. The videos will explain that.


Yes - you can do it hardcoded in twig, this can be translated via the user interface translation: /admin/config/regional/translate. The locale module needs to be enabled.

  BUT, i would only recommend this method for static content (and maybe random)!

For dynamic content i suggest to use the drupal multilingual feature(s). Start by enabling the module content_translation.
Then you can edit a node, and add a translation for it in the backend (node/x/edit). See the docs on d.o. for further information.


tabledrag submit - $form_state missing values

The answer is quite simple - markup doesn't make it into $form_state. Place the item id ($entity->ref in the below code) in a textfield or number field instead and use the following to hide and disable it (not sure if disabling is necessary):

    $form['mytable'][$id]['label'] = array(
    //'#plain_text' => $entity->ref,
    '#type' => 'number',
    '#title' => "",
    '#default_value' => $entity->ref,
    '#disabled' => TRUE,
    '#access' => FALSE,


How do I avoid duplication in a view result?

If Views' distinct parameter doesn't work for your case, you can always use a views_pre_render() hook to do anything with the result before it is rendered.  Something along the lines of...

YOURMODULE_views_pre_render(&$view) {

  if ($view->name=='NAMEOFVIEW') {

    // drupal_set_message('<pre>' . print_r($view->result, TRUE) . '</pre>');

    $states_found=array();

    foreach($view->result as $delta => $row) {

      if (in_array($row->LOCATION_FIELD_NAME_VALUE, $states_found)) {
        unset($view->result[$delta]);
      } else {
        $states_found[]=$row->LOCATION_FIELD_NAME_VALUE;
      }

    }

  }

  // any other pre_render()ing here...

}

What this does is loop through the rows of your view result keeping track of what states have been found and unsetting any duplicates.  The commented out dsm at the beginning will help you figure out what LOCATION_FIELD_NAME_VALUE you need to use in your specific case.


How to stop same-state state changes in Workflow state change block?

Implement hook_form_workflow_transition_form_alter().

/**
 * Implements hook_form_form_id_alter().
 * Alter transition form to remove current state button.
 */
function MYMODULE_form_workflow_transition_form_alter(&$form, &$form_state, $form_id) {

  // Get current state to remove current state button.
  $current_sid = $form['workflow']['workflow_sid']['#default_value'];
  unset($form['workflow']['workflow_sid']['#options'][$current_sid]);

  // By default workflow button label became (Update workflow) if the options
  // count equal one. So, We will use the state label name instead of
  // (Update workflow).
  // Check if option count equal one.
  if (is_array($form['workflow']['workflow_sid']['#options']) && (count($form['workflow']['workflow_sid']['#options']) == 1)) {
    $submit_label = current($form['workflow']['workflow_sid']['#options']);
    $form['workflow']['actions']['submit']['#value'] = $submit_label;
  }
}


views aggregation - number of results per group

If what you're trying to show is the number of nodes tagged with a certain term (I'm assuming that color field is a term, not a select text field), then the following Drupalwoo tutorial has detailed step-by-step instructions on creating a view that shows the number of nodes per term.

Here are the basics - just without the screenshots.

Your view should be setup to display taxonomy terms, not nodes.
Add a relationship that is 'Taxonomy term: Content using <term name>', in your case the term name will be something like 'Color'
Configure the relationship to be required or not: depending on whether you want to show colors even if there are no nodes tagged with that color
Select to use aggregation in the view's advanced settings
Add a node field to this view that is excluded from the display, but is used to count the number of node instances under each term.  I would select the 'Node: nid' field for this purpose.  Make sure to use the relationship setup above
Finally - select 'Count DISTINCT' as the type of aggregation for this field
You'll probably want to style the output a little: in your example you want to use a colon between the term and the count, while in the blog's example above there are parentheses!  Feel free to style however!


Forms alter submit button callback not working

Expanding on my comment, be sure you have the correct form ID in the hook_form_FORM_ID_alter. This is an example of how I made this work. You'll need to modify the name of the hook and the FORM_ID

function tempo_form_profile2_edit_pet_ownder_form_alter(&$form, &$form_state){

    $form['actions']['new_button'] =  array(
            '#type' => 'submit',
            '#name' => 'personal_info_alt',
            '#value' => t('Info Save'),
            '#attributes' => array('alt' => t('get data')),
            '#submit' => array('testing_to_see'),
        );
}

function testing_to_see(&$form, &$form_state) {
  drupal_set_message('I am in call back');
}


Ditch user points and download and install Rules instead.

Make sure you enable Rules UI.

Go to user fields and add a field of type Integer. Example: Lets name it Term A Points.

React on: (under node) After saving new content

Restrict by type: None

Add condition >> (under node) Content is of type >> select your content type (If you want multiple, hold the Ctrl button on your keyboard to highlight the content types you want)

Lets assume your term reference field is called hello world

Add Condition >> Data Comparison >> node:field-hello-world >> (type the term name here)

Add Action >> Set a Data Value >> node:author:field-term-a-points >> (click on switch to data selection) >> Data Selector: node:author:field-term-a-points >> Click on OFFSET and put the points you want to award, ex: 5

You can then use the Field Permissions module if you want to hide the Term A Points field from users so they cant see it and/or edit it.

Then you can create another rule when Content is deleted, do the same except OFFSET -5

If you want to diplay a message:

Add Action >> (under system) Display a message on the site >> Type your message here. Ex: [user:name] you have been awarded 5 points.


Read data using countries module in view

While adding relationship with countries, the most important, Check the checkbox Require this relationship and then add Countries: Name as fields you want.

It works for me (see) and hope for you too


How can I support product prices which have a precision greater than the currency's minor unit in Drupal Commerce?

Commerce allows to define the amount of decimals per currency in hook_commerce_currency_info, defaulting to 2. So you could implement hook_commerce_currency_info_alter and change that for USD.

However, due to the way prices are stored (with decimals set to 2, $5.00 is stored as 500), this will affect all existing prices, so when you change it e.g to 4 decimals, then $5.00 will now just be $0.05.

So, maybe you could instead set up a virtual currency with the same name and as many decimals as you want and then let Commerce automatically handle the conversion to USD during payment.


Views page list of all content grouped by taxonomy term

Here's how you would go about doing this:

Include the tag you want to group by in your fields (see map)
Click on your format settings. (see map)
Set grouping field to the tag.
Set exclude from display to true in your tag field.

That should get you to where you want to be.

Here's a map of where 1 and 2 would be located.


Here you have the framework for Form-handling:

function customregister_custom_form($form, &$form_state){
  $form['first_name'] = array(
    '#title' => t('Vorname'),
    '#type' => 'textfield',
    '#default_value' => '0',
    '#required' => TRUE
  );
  $form['last_name'] = array(
    '#title' => t('Name'),
    '#type' => 'textfield',
    '#default_value' => '',
    '#required' => TRUE
  );
  $form ['submit'] = array (
    '#type' => 'submit',
    '#ajax' => array (
    'callback' => 'customregister_custom_form_callback',
      'wrapper' => 'customregister-custom-form'
    ),
    '#value' => t ( 'Lancer la simulation' ),
    '#weight' => 10000
  );
  return $form;
}

function customregister_custom_form_validate($form, &$form_state) {

  if (! is_numeric ( $form_state['values']['first_name'] )) {
    form_set_error ( 'first_name', 'ERROR !' );
  }
  if (! is_numeric ( $form_state['values']['last_name'] )) {
    form_set_error ( 'last_name', 'ERROR !' );
  }
}

function customregister_custom_form_callback($form, &$form_state) {
  drupal_set_message('custom_form_callback');
  //customregister_custom_form_submit($form, $form_state);
  $formular = drupal_get_form('customregister_custom_form');
  $formular = render($formular);
  return $formular;
}

function customregister_custom_form_submit($form, &$form_state) {
  drupal_set_message('custom_form_submit');
}


in hook_preprocess_views_view you need to suggest theme hook for every page, because you want to have one view, so define one views template file. visit this question for more information.


Cannot Find property after adding it with hook_entity_property_info_alter (callback not firing)

I think this is what's going on...

With your current code you've described the property to the entity API module; if you want to access it via that you already can:

$node = node_load($nid);
$wrapper = entity_metadata_wrapper('node', $node);
print $wrapper->test_property->value(); // Prints '10'

But the core entity system has no knowledge of test_property, so it doesn't show up on a node object from node_load(). To get it there, you'll need to implement hook_node_load():

function mymodule_node_load($nodes, $types) {
  foreach ($nodes as $node) {
    if ($type == 'mynode') {
      $node->test_property = mymodule_test_property_getter_callback($node);
    }
  }
}

There's also the outside chance that your getter callback will rely on something having been added to the node object already, by another module's implementation of hook_node_load(). You can get past that by moving your implementation to last in the queue, with hook_module_implements_alter().

If you want Views support, I think you'll also need to implement hook_views_data_alter() to add the property to the node table. But maybe the entity module will magic that up for you, it's a good'un.


Drupal views table with multiple agregation

Yes you can do by using Views Merge Rows module.

  Sometimes when you use relationships in views you get a number of rows
  with the same content in some of the fields. This results in a huge
  table (grid, list, etc.) that affects the usability of your view. The
  Views Merge Rows module provides a way to combine rows with the same
  content in the specified fields.


Create a view from one result of another view and link to it

With much help from an answer in this post I was able to solve my issue.
Here are the steps in case it is helpful to anyone else:

create a view (in my case, to show information from the quiz_node_results table, using quiz result ID or result_id)
create a PDF view containing the same fields as in the first view; use the views PDF module
in the first view, add a Global PHP field (use the Views PHP module) and add some PHP to print a link to the data in the row of the table from the PDF view if the score is at least the score threshold (pass_rate) for getting a certificate:

<?php
if ($row->score>=$row->pass_rate) {
print l('Print','/data/'.$row->result_id);
}
?>

in the PDF view, make sure the URL to the view is /data/% and add a contextual link; in my case, for the quiz result ID, set to show all if validation is provided and to show basic validation to show all if not provided


Can Panels provide a panels context based on the URL string or URL query?

Page Manager can take arguments from the URL and provide them as context.

For instance if you create a path in Page Manager lik foo/%bar/%baz both 'bar' and 'baz' will be automatically available as Arguments.  You just need to tell Page Manager what it is looking for (i.e. should it be a taxonomy term id? a node number? maybe just a plain string...)


How to replace login in "to" mail field?

I just had to fill 'to' field in a format 'custom name ', instead 'address@mail.com'.


Views 3.8: Show taxonomy hierarchy in three columns (grandparent, parent, child)

If you've only 3 level of hierarchy then you can create a view as below:

Above view should give the output as below:

Hope this helps.


How to render field of one type of node to another type node

After you made reference between prices and metals implement hook_preprocess_node like the following:

use Drupal\node\Entity\Node;
/**
 * Implements hook_preprocess_node().
 */
function MyTemplate_preprocess_node(&$variables) {
  if ($variables['node']->bundle() == 'prices') {
    $price_node = $variables['node'];
    //- Get reference target id
    /**
     * @TODO: change field_reference_metals by the referenced field.
     */
    $metals_node_target_id = $price_node->field_reference_metals->getValue()[0]['target_id'];

    //- Load metals referred node
    $metals_node = Node::load($metals_node_target_id);

    //- Set field_gold from metals node
    $variables['field_gold'] = $metals_node->field_gold->value;
    //- Set field_silver from metals node
    $variables['field_silver'] = $metals_node->field_silver->value;
  }
}

In node--prices.html.twig template add:

   {{ field_gold }}
   {{ field_silver }}

Change MyTemplate by your custom theme/module name.
Change field_reference_metals by the field from your prices content type referred to metals.
clear cache.


Should I choose MyISAM for notification tables?

DISCLAIMER : Pure MySQL Perspective
IMHO, you should leave it as InnoDB. MyISAM is not good in high-write situations. Why ?
LOCKING GRANULARITY
Each time you issue an INSERT, UPDATE, or DELETE query on a MyISAM table

The query performs a full table lock
All other queries needing to do the INSERT, UPDATE, or DELETE queries are handled on a first-come first-serve basis

InnoDB has row-level locking. In order to accommodate this, InnoDB caches INSERTs, UPDATEs, and DELETEs in the Buffer Pool, Log buffer, and Undo Logs.
DATA CACHING
MyISAM caches index pages from each MyISAM table's .MYI file in the key buffer.
MyISAM does not cache data. It has to piggyback from the OS for that. You can change the row format of the MyISAM to increase read speed from disk at the expense of double the table's disk usage. Write speed may be adjusted with concurrent INSERTs.
InnoDB caches data and indexes pages in the InnoDB Buffer Pool. You may need a decent size to accommodate data and indexes.
EPILOGUE
You just have to tune some vital settings. Here are some of my past suggestions from the DBA StackExchange.
In favor of InnoDB

Jan 11, 2013 : Very poor insert performance MySQL / Percona Server
Dec 06, 2012 : InnoDB insertion faster
Aug 03, 2012 : Slow insert performance in mysql innodb table for solr indexing
Jul 04, 2012 : Capabilities of InnoDB INSERT Performance

In favor of MyISAM

May 03, 2012 : Which is faster, InnoDB or MyISAM?
Jan 03, 2012 : Optimized my.cnf for high-end and busy server
Sep 20, 2011 : Best of MyISAM and InnoDB
Aug 12, 2011 : Which DBMS is good for super-fast reads and a simple data structure?

Although I lean towards InnoDB, I will leave it to you to decide which storage engine you want to use and tune for.


Why does file_create_url() not work for theme images?

You don't need file_create_url() to turn those URIs into a URL to use in theme_image().

For theming images in Drupal 6, just supply a path string relative to base_path() (the base of the Drupal install directory). For module/themes this can path can be retrieved with drupal_get_path().

For example:

//Render an image under the admin_menu project
print theme('image', drupal_get_path('module','admin_menu').'images/bkg_tab.png'))


How to use loadByProperties when one of the properties is an array?

Configuration entities are not queried via SQL, you search within a multilevel array.
See the code docs:
core/lib/Drupal/Core/Config/Entity/Query/Query.php
  /**
   * Overrides \Drupal\Core\Entity\Query\QueryBase::condition().
   *
   * Additional to the syntax defined in the QueryInterface you can use
   * placeholders (*) to match all keys of an subarray. Let's take the follow
   * yaml file as example:
   * @code
   *  level1:
   *    level2a:
   *      level3: 1
   *    level2b:
   *      level3: 2
   * @endcode
   * Then you can filter out via $query->condition('level1.*.level3', 1).
   */
  public function condition($property, $value = NULL, $operator = NULL, $langcode = NULL) {
    return parent::condition($property, $value, $operator, $langcode);
  }

In your case the second level keys are the same as the values. So you have to ignore the second level with an * to query these values.


How to create statistical reports about data contained in various content types?

You may want to look at Computed field. You can use PHP to do calculations from information from other fields and show display the result. If you want, you can also save it to databse for use elsewhere. You can also try to do it in Views with Views calc. I think Views would be your better bet.


How to provide a specific node template in a custom module

/**
 * Implements hook_theme().
 */
function custom_theme() {
  return [
    'node__custom_content_type' => [
      'base hook' => 'node',
    ],
  ];
}

Then make sure that you have the content type template under custom/templates/node--custom-content-type.html.twig


How to can create a user profile with approve changes by admin

A custom way can be(will need custom coding) do not expose profile fields directly to users to edit, instead each user will have a node(one to one strict mapping) node will have fields that will be mapping to user profile fields. Once a user edits a node you can set a workflow to mark it as unpublished and once admin reviews and publish fields user profile fields will be updated with node fields.

So a possible workflow can go something like

User can edit node(name it user_node) belongs to user only, you can keep user reference field on node to check the edit permissions.
When a node(user_node) is edited check the current user if user is not admin set $node->status = 0, you can use hook_node_presave() for this.
If a node(user_node) is edited by admin keep a checkbox as approve(field visible to admin only, you can use field permissions module to allow admin to see this field).If admin approves the node again in hook_node_presave() change $node->status = 1 and take the uid from the user reference field on the node, update the user profile fields with the current node field values, you can use user_save() function for this.

This is just a rough idea which require coding, I have not checked if there is a module which can set workflow for user profile if there is any it can provide you want you want out of the box.


How can I filter a view by Content Type -or- Taxonomy Term and have both sets of items show?

For others Solution is adding a views relationship
see Documentation: https://www.drupal.org/docs/8/core/modules/views/add-a-relationship-to-a-view


Best way to update/upgrade things in the drupal database

Features seems to be what the community is clustering around, and is well worth a look. You can use update hooks, but it can be complicated for large updates, as you fear. It also dosn't make it easy to reset values to a default.

Features seems to be much simpler to use. It can't do everything but most core content can be exposed and managed via features.

Features also has drush hooks.

drush features-revert myfeature

Will set the system to reflect the content of myfeature. The down side of features is that it is still fairly immature, or more to the point many of the add on modules are immature, so sometimes code is a little buggy.


How to prevent SubFormState storage leaking into parent?

So far, I have solved it by using #array_parents for getting/setting values into form state storage in plugin forms since there cannot be a key collision in parent form this way.

Small issue with this is that I have to provide the whole parents in there. So if the plugin form is not flat, I have to add all those additional parents in there since they will appear in the ...

... additionally to this in ajax plugin form submit handlers and ajax callbacks I have to get the the "root" element(ie. the form element for the plugin) by detecting #array_parents on the trigger and extracting the proper form element by #array_parents and extracting the #array_parents from it to get to the data in the storage.

Overall it is a massiv DX fail. I have a ***load of plugins and to bulletproof them this way will take a lot of unnecessary time now.

I was thinking about extending the SubformState as KeyedSubformState where the state would "hide" the plugin's storage under provided key so the parent form would control this and be responsible for avoiding key collision and the plugin form doesn't have to be altered in any way(since values are already taken care of) but I have decided not to do it this way since it feels like adding additional layer is not a good idea in the long run...also it won' work for ajax submit handlers since they receive the full form and state and not the subform element and state.

If anyone has a better solution, I'm all ears. But for now it seems plugins are treated like homeles people :D

Also, for the love of god, do not use #parents in plugin form. Or you'll be leaking values into the parent form. Overall, just make the plugin form as dumb as possible. Flat and no ajax, just to be safe.

This is, currently working, plugin with ajax.

/**
   * {@inheritdoc}
   */
  public function buildConfigurationForm(array $form, FormStateInterface $form_state) {
    $ajax = [
      'wrapper' => Html::getId($this->getPluginId() . '-countries-ajax-wrapper'),
      'callback' => [get_called_class(), 'ajaxRebuildCountries'],
      'progress' => [
        'type' => 'throbber'
      ]
    ];

    $form['allowed_countries'] = [
      '#type' => 'fieldset',
      '#title' => $this->t('Allowed countries'),
      '#prefix' => '
',
      '#suffix' => '
'
    ];

    $country_list = $this->countryManager->getList();

    // @see https://drupal.stackexchange.com/questions/243812
    // @see https://www.drupal.org/node/2902121
    $state = $form['#array_parents'];
    $state[] = 'allowed_countries';
    $state[] = 'countries';

    if ($form_state->has($state) === FALSE) {
      $form_state->set($state, $this->getSetting('countries'));
    }
    $countries = $form_state->get($state);

    $form['allowed_countries']['countries'] = [
      '#type' => 'table',
      '#default_value' => [],
      '#empty' => $this->t('No countries have been added yet.')
    ];

    foreach ($countries AS $iso => $level_1) {
      $row = [];

      $row['iso'] = [
        '#markup' => $iso
      ];

      $row['label'] = [
        '#markup' => $country_list[$iso]
      ];

      $row['level_1'] = [
        '#type' => 'value',
        '#value' => []
      ];

      if ($level_1_list = Address::hasLevel1($iso)) {
        $row['level_1'] = [
          '#type' => 'select',
          '#title' => Address::getLevel1Label($iso),
          '#options' => $level_1_list,
          '#default_value' => $level_1,
          '#multiple' => TRUE
        ];
      }

      $row['delete'] = [
        '#type' => 'submit',
        '#value' => $this->t('Delete'),
        '#submit' => [[get_called_class(), 'deleteCountrySubmit']],
        '#name' => 'delete_country_' . $iso,
        '#ajax' => $ajax
      ];

      $form['allowed_countries']['countries'][$iso] = $row;
    }

    $form['allowed_countries']['add_country'] = [
      'country' => [
        '#type' => 'select',
        '#title' => $this->t('Add country'),
        '#options' => array_diff_key($country_list, $countries),
        '#ajax' => $ajax + ['trigger_as' => ['name' => 'add_country_submit']],
        '#empty_value' => '',
        '#empty_option' => t('- Select -')
      ],
      'submit' => [
        '#type' => 'submit',
        '#value' => $this->t('Add country'),
        '#submit' => [[get_called_class(), 'addCountrySubmit']],
        '#name' => 'add_country_submit',
        '#ajax' => $ajax,
        '#attributes' => [
          'class' => ['js-hide']
        ]
      ]
    ];

    return $form;
  }

  /**
   * Form submit handler for attaching a new allowed country.
   *
   * @param array $form
   * @param \Drupal\Core\Form\FormStateInterface $form_state
   */
  public static function addCountrySubmit(array $form, FormStateInterface $form_state) {
    $element = static::getFormElement($form, $form_state);

    // @see https://drupal.stackexchange.com/questions/243812
    // @see https://www.drupal.org/node/2902121
    $get_country = array_merge($element['#parents'], ['add_country', 'country']);
    $get_countries = array_merge($element['#parents'], ['countries']);
    $set_state = array_merge($element['#array_parents'], ['countries']);

    $country = $form_state->getValue($get_country);
    $countries = $form_state->getValue($get_countries);
    $countries[$country] = [];

    ksort($countries);

    $form_state->set($set_state, $countries);

    $form_state->setRebuild();
  }

  /**
   * Form submit handler for removing allowed country.
   *
   * @param array $form
   * @param \Drupal\Core\Form\FormStateInterface $form_state
   */
  public static function deleteCountrySubmit(array $form, FormStateInterface $form_state) {
    $element = static::getFormElement($form, $form_state);

    $country = substr($form_state->getTriggeringElement()['#name'], strlen('delete_country_'));

    // @see https://drupal.stackexchange.com/questions/243812
    // @see https://www.drupal.org/node/2902121
    $get_countries = array_merge($element['#parents'], ['countries']);
    $set_state = array_merge($element['#array_parents'], ['countries']);

    $countries = $form_state->getValue($get_countries);
    unset($countries[$country]);

    ksort($countries);

    $form_state->set($set_state, $countries);

    $form_state->setRebuild();
  }

  /**
   * Ajax callback for rebuilding the allowed countries form elements.
   *
   * @param array $form
   * @param \Drupal\Core\Form\FormStateInterface $form_state
   *
   * @return mixed
   */
  public static function ajaxRebuildCountries(array $form, FormStateInterface $form_state) {
    return static::getFormElement($form, $form_state);
  }

  /**
   * Helper method to retrieve the form element containing the plugin
   * configuration "form" from the parent form for ajax calls since
   * there is no SubformState involved and we are getting the whole
   * parent form.
   *
   * @param array $form
   * @param \Drupal\Core\Form\FormStateInterface $form_state
   *
   * @return mixed
   */
  public static function getFormElement(array $form, FormStateInterface $form_state) {
    $trigger_parents = $form_state->getTriggeringElement()['#array_parents'];
    $key = array_search('allowed_countries', $trigger_parents);
    return NestedArray::getValue($form, array_slice($trigger_parents, 0, $key + 1));
  }

  /**
   * {@inheritdoc}
   */
  public function submitConfigurationForm(array &$form, FormStateInterface $form_state) {
    $values = $form_state->getValue(['allowed_countries', 'countries']);

    // Fix Level 1 administrative area.
    $values = array_map(function($value) {
      if (is_array($value) && isset($value['level_1'])) {
        return $value['level_1'];
      }
      return $value;
    }, $values);

    $form_state->setValues(['countries' => $values]);
    parent::submitConfigurationForm($form, $form_state);
  }


How do I add JS files inside libraries conditionally based on versions of IE7 and IE8?

You have the right idea. You can do what you've done for IE7 with IE8 as well.

js:
  js/script7.js: { browsers: { IE: 'IE 7', '!IE': false } }
  js/script8.js: { browsers: { IE: 'IE 8', '!IE': false } }


Views Exposed Filters AND result for multi select field

Views' filters default to an OR between all the options selected. If you pick the "Is all of" option, it will change to an AND operator.


The exception can be fixed by visiting the following page: 'admin/config/regional/entity_translation'.

Then make sure that under the vertical tab 'taxonomy term' and the fieldset of your vocabulary the following is unchecked: 'Hide language selector'.

You may need to check 'Exclude Language neutral from the available languages' if that doesn't work.


Look up nodes that reference a given node

Well, you know, this is one of the problems that gave birth to relation. Nonetheless, an EntityFieldQuery with a fieldCondition('name_of_the_reference_field', 'nid', $nid) is what you want.


How to use url alias in views for taxonomy terms?

This is a kind of workaround but
I thinks the simplest solution for you would be to use the module:
TVI: Taxonomy View Integrator

Then when when you modify the terms vocabulary you can use a view to replace the default page default view:  the url alias of the term alias would call your view.


If you mean the email message for a password reset. You can use hook_mail_alter to change the email contents before it's sent out to the user.

If you mean the form the user sees on the webpage, then you can use hook_form_alter to change the verbiage shown on the screen.

Edit

override the displayed form with the reset button to goto your own form_submit action. In your custom module action, simply copy and paste user_pass_reset function body into your own function and tweak it as needed to change the messages (careful).


How to prevent closing ctools modal window with ESC?

I had similar kind of a problem. I had to disable closing modal popup by pressing ESC.
In my case solution was adding unbind for modalEventEscapeCloseHandler for page where I was going to get modal popup:

<?php
      drupal_add_js('
      jQuery(document).ready(function(){
        jQuery(document).unbind("keydown", modalEventEscapeCloseHandler);
      });
      ', 'inline');
?>


You can use a view to show the nodes that can be referenced, have a look at the settings of the widget, it's been a while since I used D6, but if you select title and code inside your view it should be visible when you edit a Material node.


Where to write hook_commerce_payment_method_info() in drupal8?

Payment methods are now called Payment gateways and they are plugins, like anything else.

So, look for the @CommercePaymentGateway annotation, like in this example: https://github.com/drupalcommerce/commerce/blob/8.x-2.x/modules/payment_example/src/Plugin/Commerce/PaymentGateway/Onsite.php and the others in that folder.


How to create a view block only visible to the Referenced Content Type's Author?

Easiest way to do this:

Add a content relationship for the node reference field (i.e. Content: field_item_for_sale_ref)
Add another relationship for the Content Author and select the node reference field relationship from the dropdown list at the top of the window.
Filter the view for the current logged in user by selecting the author relationship that was just created in step 2.

OR

Add a content relationship for the node reference field (i.e. Content: field_item_for_sale_ref)
Add a contextual filter for the Content: Author uid, select the node reference field relationship from the dropdown list (top of window), select: provide default argument of type: user id from logged in user

Either way the result is the same and it's what you need.


This is the default behavior of Garland. Have a look in the themes/garland/template.php file:

function garland_preprocess_comment_wrapper(&$vars) {
  if ($vars['content'] && $vars['node']->type != 'forum') {
    $vars['content'] = '
'. t('Comments') .'
'.  $vars['content'];
  }
}

Where did you put your code? Depending on your theme, you most probably want to theme comment-wrapper.tpl.php, which only gets output when there are comments to be displayed. Which what you want. :-)


Reset/Delete the value of a field with node_save()

If you want to do by changing the database entry then you need to check key constraints for the field table and also you need to remove its dependency from the parent table.


How to only access a page through drupal_goto() function?

Below is a solution that should work for users who are logged in (using Drupal 7, I assume).

Use the Content Access module to limit access to your download page to only those users who have a role like (say) "DownloadAllowed". Since you want to protect that download page, you'll need "some" access module.

And use the Rules module to implement a rule like so:

Step 1: Store your serial number (entered when your form is submitted) in a field which will be used in the next step. Even though you can use any "machine name" for that field, let's assume you call it "field_serialnr"

Step 2: Use a variation of the Rule included in my answer to "How to specify a Rules condition related to select list values?". Here is what you should tune in that rule:

Replace the Rules Event to something like "After saving new content (of some type that matches your form)".
Replace the "Value C" in the Rules Condition to the value of your serial nr.
For debugging reasons, start with a Drupal message to be shown (to ensure your rule works correct if the serial nr is ok, and to also verify it works as you want if the serial nr is wrong or missing). After the message shows up as you want it to show, replace the Rules Action with something like "Assign role to user". The role to assign is ... you probably guessed it ... "DownloadAllowed".

With that, those users who entered your serial nr correctly, will just-in-time get permission to access the download page. Those who didn't will be stopped by the Content Access module ... Which is exactly what you want.

PS: for anonymous users trying to access your download page, you could create another Rule to set a Drupal message indicating that they must be logged in before they can access that download page. For that, just use Rules Event "Drupal is initializing" and a Rules Condition to check if the URL they entered matches the one from your download page.


How do I add image captions using a custom style?

One way would be to create your own theme_image() in your theme's template.php file.  It would be pretty straightforward, just grab drupal's default theme_image() from theme.inc and add a span to it:

If Drupal 6:

function YOURTHEMENAME_image($path, $alt = '', $title = '', $attributes = NULL, $getsize = TRUE) {
  if (!$getsize || (is_file($path) && (list($width, $height, $type, $image_attributes) = @getimagesize($path)))) {
    $attributes = drupal_attributes($attributes);
    $url = (url($path) == $path) ? $path : (base_path() . $path);
    return '' . check_plain($title) . '';
  }
}

If Drupal 7:

function YOURTHEMENAME_image($variables) {
  $attributes = $variables['attributes'];
  $attributes['src'] = file_create_url($variables['path']);

  foreach (array('width', 'height', 'alt', 'title') as $key) {

    if (isset($variables[$key])) {
      $attributes[$key] = $variables[$key];
    }
  }

  return '' . (isset($variables['title']) ? $variables['title'] : '') . '';
}

Clear caches/theme registry and now every image will have a span with class caption after it with the image's title in it (or blank if none obviously).  If you want to get fancier with wrappers and so forth, just put whatever html you want/need in the return's above.

Then CSS this however you want.


Yes but it's not pretty. Drupal really doesn't want you to change field definitions after they've been created.

The correct way would be to create a new field definition and migrate values from the old field into the new one.

The quick and dirty way would be to manually change the field definition in the database directly.

The quick and dirty way that is deployable via code is to do a two-step process:

Export the field (such as with Features) and alter the #maxlength setting in the code.
TEMPORARILY hack core by commenting out the code in hook_field_update_forbid() in field.api.php.
Deploy a tag containing 1 and 2. Run updates.
UNCOMMENT hook_field_update_forbid and deploy that tag so further changes are not allowed and core is put back in its natural state.

This is terrible but I have done it and it works.


Import your own interface translations automatically during profile or module installation

To import your own translations you should use the interface translation properties on your module.

I'm using a folder translations in my modules where my language files like de.po or fr.po can be found. To load the translations you have to insert the following lines into your example_module.info.yml:

'interface translation project': example_module
'interface translation server pattern': modules/custom/example_module/translations/%language.po

And to update your translations use this:

drush locale-check && drush locale-update && drush cr

EDIT:
To update existent translations you should take a look at the settings page (/admin/config/regional/translate/settings):

You can try to use local translation files only or to overwrite any existing translation.


Apply a ranged contextual filter to a date in Views

Views Contextual Range Filter might do the trick for you. Install the latest beta and then see if you need to apply this patch. It's got just the functionality you're looking for.


Drupal 8 uses the annotation reader from Doctrine Common but it does not use the ORM. The handbook page for the Drupal entity field API is being written at https://drupal.org/node/2078191


How to print the drupal username -without a link to it- inside the node profile?

I do not have the exact answer you are looking for.
However I'd use get_defined_vars() in all template files to list the defined variables.

In case you are not a programmer, here's the code.

<pre>
<?php
  print_r(get_defined_vars());
?>
</pre>

http://php.net/manual/en/function.get-defined-vars.php


First off, the implementation of a hook never has a name starting with hook_; you always replace hook_ with the machine name of the module, followed from an underscore. Similarly, the name of the file containing an implementation of hook_uninstall() must be the machine name of the module followed by .install.
So, if you are literally calling the function hook_uninstall(), and mymodule is not the machine name of your module, Drupal will never consider that function a hook implementation.

Second, if you are using echo to check if the hook is being invoked, you will not get any output. Use watchdog() (Drupal 7) or \Drupal::logger($module)->error($message) (Drupal 8) inside a hook, if you want to verify a hook is invoked.

Third, hook_uninstall() is invoked from Drupal only when a module is uninstalled. There is no other way to be sure Drupal is invoking that hook, if not installing and uninstalling the module implementing it. In Drupal 7, don't get confused from disabling a module, and uninstalling it: Disabling a module doesn't cause Drupal to invoke hook_uninstall().


How to remove the separator between values of a multi value field in a Views result?

Finally, I found the solution. I'm not sure if is the best, but it works.

function MY_THEME_preprocess_views_view_field(&$variables){
  $view = $variables['view'];

  if ($view->id() == 'VIEW_ID'){
    $output = str_replace(',', '', $variables['output']);
    $variables['output'] = \Drupal\views\Render\ViewsRenderPipelineMarkup::create($output);
  }
}


How do I set the options for a programatically created content type?

You can set a node_options_[type] variable,

e.g:

node_options_article: Array
(
    [0] => status
    [1] => promote
)

which can be set with:

// Make my_type nodes published and not promoted to front page by default
variable_set('node_options_my_type', array('status'));


How to use Views 3 API to display custom tables?

After lots of research and work, this answer is for people who faced the same problem. The Data module does this for you. This module allows you to adopt a table (created in your Drupal Database and is not a part of any content type, basically a standalone table) and creates a view for that table. The view can be customized. The requirement here is that the table must have a primary key. You can also index this view by creating a content type and using the Views References Module. This will facilitate the indexing of the content in the table and make it show up in search results. Hope this helps.


Update query with a dynamic expression in Drupal 7?

You want to use an expression: http://api.drupal.org/api/drupal/includes--database--query.inc/function/UpdateQuery%3A%3Aexpression/7

Example:

db_update('warrior_members')
  ->expression('points', 'points + 1')
  ->condition('uid', $liv_user)
  ->execute();

Or to make the 1 dynamic:

db_update('warrior_members')
  ->expression('points', 'points + :amount', array(':amount' => 1))
  ->condition('uid', $liv_user)
  ->execute();


Redirect unauthorized user to login page

In the permissions, make sure anonymous users don't have access. Then go to Configuration -> System -> Site information (admin/config/system/site-information). At the bottom, put your home page in 'Default 403 (access denied) page'.

All traffic going to an unaccessible page, will be redirected here.


Insert multiple checkbox value from webform into table

It works if I replace these codes:

$selectedData=db_query("SELECT data FROM {webform_submitted_data} WHERE nid = :nid AND cid =:cid AND sid= :sid",array(':nid'=>$accessnode, ':cid' => 1, 'sid'=>$lastestSub))->fetchAll();

by this:

$selectedData=db_query("SELECT data FROM {webform_submitted_data} WHERE nid = :nid AND cid =:cid AND sid= :sid",array(':nid'=>$accessnode, ':cid' => 1, 'sid'=>$lastestSub))->fetchCol();


In theory, it's no problem to add tables to the database. It won't hurt Drupal. That said, I wouldn't recommend it. If things already are separated and there is no important reason to use a single db, just keep them separated for flexibility and performance in the future.


Technically putting things straight into a template may have better performance.

However if you create a static block and make sure it is cachable on the whole site the difference will be negligible. There are many other ways to improve performance and this is right a the bottom of the pile.

There are many other things that you can do to improve performance. Taking the view of the site as a whole. The flexibility that a block gives you may give you may outweigh the performance gains you achieve.


Simple views handler to compute math expression.

Instead of creating own handler you should use already existent Global: math expression that allows you using of tokens to calculate everything you want.


It sounds like the only requirement here is a per-node, role-based, permission setting on content. If that's the case, I'd drop your role reference field in lieu of Content Access. The module enables such a requirement and it hooks deeper into the Drupal permission system so you don't have to build a bespoke permission checking for every situation (e.g. views access, node page access, etc.).


Configure page title block for contact form pages only

You only need to select the Contact form bundles you want to display the page title on. Leave anything else untouched.


The function is theme_field() which could be customized by having the right override of the field.tpl.php template in your theme (through template suggestion, see the theme_field() function documentation.

Inside this function/template, the image is rendered by a field formatter. The print render($item) statement print that rendering. The exact used function/template depends on the configured formatter. If your are usign the default formatter, that would be theme_image_formatter().

Note: See the theme() function's documentation for how to override the theme_* functions in your theme or module.


in php you can do something like :

  shell_exec("drush status");

if this is temporary, you can execute it from devel/php, but if it's a production site solution that you need, you can per example add a custom form that does this in its submit method


Make a block display in one page and not in other

In the block's Region settings you can specify the block to be displayed in which region of respective themes(Admin and site theme) as below: