Templates aren't called in custom module?

Your problem is coming from this code:

$theme_registry['page']['path'] = drupal_get_path('module', 'example_ch_hero_panel') . '/templates';

The first array key, page, means you are working the page template. You've told the system to look for page.html.twig in your module's /templates directory. It's not finding it, so you get that error.

Remove that hook altogether, it's not the right way to do what you are trying to do.


Content View to sort results to match the users Profile 2 taxonomy term

I managed to solve this:
The key is to start with an User View.
Add Relationship -> User: Profile
Pick the profile where the taxonomy was assigned.
Add Relationship -> Content: Taxonomy terms on node
Pick your vocabulary.
Add Relationship -> User: Content authored
Add Contextual filter -> Content: Has taxonomy term ID
Choose PHP as a Provide default value option:

global $user;
$profiles = profile2_load_by_user($user);
    foreach ($profiles as $profile) {
      if ($items = field_get_items('profile2', $profile, 'field_your_interests')) {
        break;
      }
    }
$tids = array();
foreach ($items as $item) {
  $tids[] = $item['tid'];
}
return implode('+', $tids);

Then add the fields and additional filters as needed.

Resources:
http://blog.ampli.fi/filtering-a-drupal-7-view-based-on-multiple-user-profile-fields/
https://www.drupal.org/node/1111722#comment-4315620
Drupal terms and arrays - thanks Aaron!


A better way to show a node-based field in a region outside of the node itself

If you aim to keep your footer region's wrappers in page.tpl.php your only option is to:

hide field in node.tpl (tpl file or field display settings)

render the field in page.tpl.php where you want it.
a) use hook_preprocess_page in tepmlate.php to set page=variable = field value (if exists); then print/render that variable in page.tpl.php
b) less elegant and more error prone: render field from page's $node variable

The above is assuming you're using standard drupal's theming system.

THE QUICKEST: Alternatively you can use something like:
https://www.drupal.org/project/fieldblock
to expose your value as a block a,d them place it in whatever region.
this one is compatible with whatever you use; panels DS; stabdrad block stystem; Context....


Enabling XML under PHP in windows - import_html module not working

The reason why drush was giving me the XSL library support error is because though I fixed the php.ini file in the drupal folder, drush uses a different php.ini file, so I had to modify that one in order to get the imports to work. Now, I get the exact same errors/warning when I import online as when I import via drush. i haven't been able to fix the warnings


Taxonomy drag and drop for only 2 levels

The theme function theme_taxonomy_overview_terms() drives the taxonomy overview table you're describing. The Drupal API function drupal_add_tabledrag() has an 8th parameter $limit that specifies the maximum depth of hierarchy. If it's set to 1, it will do what you describe.

In your theme, you can override theme_taxonomy_overview_terms() so the $limit is to 1. In order to do this.

Copy theme_taxonomy_overview_terms() to your theme's template.php.
Rename the function to MYTHEME_taxonomy_overview_terms in your template.php.
Alter the line drupal_add_tabledrag('taxonomy', 'match', 'parent', 'term-parent', 'term-parent', 'term-id', FALSE); so that the 8th parameter is 1 (i.e. change it to drupal_add_tabledrag('taxonomy', 'match', 'parent', 'term-parent', 'term-parent', 'term-id', FALSE, 1); )
Flush your theme cache to pickup the updated taxonomy overview page.


Extract PDF front page and store it as an image field in node

Oh I just realized that another module, the PDF to Image Field module does exactly what I need! Some more details about thsi module (from its project page):

The PDF To ImageField module provides automatic conversion of uploaded PDF files to images. It can be used either to create a snapshot of the front page to use as a preview thumbnail, or to generate a gallery of images from each page in the document.
The module is implemented as an additional widget for File Field where PDFs are uploaded to. It places generated images into a Image Field on the same content type.

At least, I hope this helps other people too.


Links like this are handled as attachments to the page.  They are inserted where the Drupal placeholder tags (like head-placeholder) are in the twig file.

To modify these, you need to use hook_page_attachments_alter().  Here's example code that fixes a problem with canonical URLs containing query string not getting generated properly by core (converts & to &amp;).

/**
 * Implements hook_page_attachments_alter().
 */
function mytheme_page_attachments_alter(array &$attachments) {
  if ( isset($attachments['#attached']['html_head'])) {
    foreach ($attachments['#attached']['html_head'] as $key => $item) {
      if (in_array("canonical_url", $item)) {
        $href = $item[0]['#attributes']['href'];
        $attachments['#attached']['html_head'][$key][0] = [
          '#type' => 'inline_template',
          // Formatted to include a newline in page source.
          '#template' => "{{ href|raw }}
",
          '#context' => [
            'href' => '<link rel="canonical" href="' . $href . '"/>',
          ]
        ];
      }
    }
  }
}

In the case of these entity links, these are in the 'html_head_link' area of the attachments.

FYI - This is also related to this core issue.


Why is an untranslated string not showing up?

The strings needs to be rendered a first time on a page in the not default language and your string keys will be visible in the Translate interface.

An important detail, the search is case sensitive. For example My text is different than my text.


Add image file programmatically in drupal 6

This is not good job save file in validation phase and really  where you get file from posted data ?
file exist in $form_state['value']['picture]

mybe below code help you

function yourmodule_form_submit($form, &$form_state) {

    $file = $form_state['values']['picture'];

    $validators = array();
    $file = file_save_upload('file', $validators, 'public://');
....


Updated drush, but status shows old version

In Vagrant, you need to SSH to the machine and run Drush from there.


When using page--user--login.tpl.php you have to manually fetch the user login form, as your overriding the entire page template not just the form.

You can either include this directly in the template (along with any other markup):

print drupal_render(drupal_get_form('user_login'));

Or in your mxblog_preprocess_user_login() function must return the form:

function mxblog_preprocess_user_login(&$variables){
  $variables['form'] = drupal_get_form('user_login');
}

then in the template you should be able to to do as you want:

print drupal_render($form['name']);
print drupal_render($form['pass']);
print drupal_render($form['form_build_id']);
print drupal_render($form['form_id']);
print drupal_render($form['actions']);


Druapl 7 Update displayed price of product when quantity changes

Well after some tail chasing I managed to do it. It probably is a bad solution since I had to modify uc_product_module itself. Here's what I did:

1) Created a custom module that adds two buttons in hook_form_alter- and + that will modify the quantity:

    $form['decrease'] = array(
        '#name' => 'decrease',
        '#id' => 'decrease-product-qty',
        '#type' => 'button',
        '#value' => t('-'),
        '#prefix' => '<div class="form-item form-item-qty-btn form-type-uc-quantity form-group">',
        '#ajax' => array(
            'wrapper' => 'wrapper',
            'callback' => 'decreaseProductQuantity_form_ajax_callback'
        )
    );

/**
 * AJAX callback function for addToCartFormEditQuantity_form().
 */
function decreaseProductQuantity_form_ajax_callback($form, $form_state)
{
    $nid = $form_state['values']['nid'];
    $node = node_load($nid);

//Get current quantity
$quantity = (int)$form['qty']['#value'];
// Adjust
if ($quantity > 1) {
    $quantity--;
}

$form_state['storage']['quantity'] = $quantity;

// Calculate updated price to be displayed
$displayPrice = uc_currency_format($node->price*$quantity);
// Price textfield id and class
$fieldId = "#total-price-uc-product-" . $nid;
$fieldClass = '.uc-price';

// Update field via command
$commands = array();
$commands[] = ajax_command_invoke('#edit-qty', 'val', array($quantity));
$commands[] = ajax_command_html($fieldClass, $displayPrice);

// Send the command to the page.
$page = array(
    '#type' => 'ajax',
    '#commands' => $commands,
);
return $page;
}

2) Saved quantity in $form_state['storage']['quantity'] = $quantity; as seen above. In order to keep the value form being erased add use $form['after_build']:

//Inside hook_form_alter
$form['#after_build'][] = 'addToCartFormEditQuantity_after_build';

function addToCartFormEditQuantity_after_build(&$element, &$form_state)
{
    $form_state['storage']['quantity'] = (int)$element['qty']['#value'];
    return $element;
}

3) Final step modified ubercart/uc_product/uc_product.module function uc_product_view_ajax_commands:

 * @return
 *   An array of Ajax commands.
 */
function uc_product_view_ajax_commands($form_state, $keys) {
  $commands = array();
  if (variable_get('uc_product_update_node_view', FALSE) && !empty($form_state['storage']['variant'])) {
    $node_div = '.uc-product-' . $form_state['storage']['variant']->nid;
    $build = node_view($form_state['storage']['variant']);
    foreach ($keys as $key) {
      if (isset($build[$key])) {
         //Modify display price to take qantity into consideration
        if ($key === "display_price") {
          $quantity = (int)$form_state['storage']['quantity'];
          $totalPrice = (float)$build[$key]['#value'];
          $totalPrice *= $quantity;

          $build[$key]['#value'] = $totalPrice;
        }
        $id = $node_div . '.' . str_replace('_', '-', $key);
        $commands[] = ajax_command_replace($id, drupal_render($build[$key]));
      }
    }
  }
  return $commands;
}


Drupal Core Search is designed to deal with many punctuations, but not all. Take a look at either of these modules:

Punctuation Preprocessor:

  This module implements a punctuation pre-processor that provides
  special handling for punctuation characters when they are encountered
  within word strings during searching and indexing.

Fuzzy Search:

  This module provides drupal sites with a fuzzy search engine to allow
  for broader keyword matches including partial or misspelled keywords.

or any of the other core search alternatives - they may pick up the punctuation better.


Drupal 8: How to get the ['third_party_settings'] of an image field inside hook_preprocess_image_formatter(&$variables)

Although this is pretty specific, it may help someone else with a similar problem.

The answer is in getFieldDefinition() object of $variables['item'].

In order to acquire the field name of an image object from within HOOK_preprocess_image_formatter(&$variables) which is a variation of HOOK_preprocess_HOOK(), you would use:

$field_name = $variables['item']->getFieldDefinition()->getName();

Used within the context of a module file it would look something like the following:

/**
 * Implements hook_preprocess_HOOK()
 * This allows us to pass attributes to the image_formatter template.
 */
 function MY_MODULE_preprocess_image_formatter(&$variables) {
   // Get the field name
   $field_name = $variables['item']->getFieldDefinition()->getName();
 }


How to ask for user confirmation when submitting a form using FAPI

use the confirm_form function. See Here and Here for examples

  This function returns a complete form array for confirming an action.
  The form contains a confirm button as well as a cancellation link that
  allows a user to abort the action.


Have a look on the Menu Position module. This allows you to map a specific content type to a menu item without generating "hard linked" menu entries.


The real issue is file permissions. When PHP uploads a file, it saves it in the temp directory. When that file then gets moved it retains the file permissions from the temp directory and does not inherit the destination folder permissions.

So check folder permissions of both your temp folder and the destination folder.


User profile picture - avatar uploader on all pages

Firstly,
Check avatar_uploader.js file, the default selector is '.profile .user-picture a', if you want to use this for other profile img, please change the selector
Drupal.settings.avatar_selector

Drupal.behaviors.avatar_uploader = {
    attach: function(context) {
        if (Drupal.settings.avatar_uid) {
            Drupal.settings.avatar_selector = Drupal.settings.avatar_selector || '.profile .user-picture a';
        var el = jQuery(Drupal.settings.avatar_selector);
        au.attach(el, Drupal.settings.avatar_uid, Drupal.t('Change avatar'));
         }
     }
}

Second, Check "avatar_uploader.module".

These code is to use uploader only in 'user' page in order to reduce js for browser, so you can change here

hook_init

$params = array('avatar_panel_id' => UPLOADER_PANEL_ID);
    if ($user->uid) {
        if (arg(0) == 'user' || (arg(0) == 'user' && arg(1) == $user->uid)) {
           $params['avatar_uid'] = $user->uid;
        }
    }

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


Dependency Injection in Custom Field Widget

What you are missing is to implement \Drupal\Core\Plugin\ContainerFactoryPluginInterface, which defines the create() method.

See \Drupal\file\Plugin\Field\FieldWidget\FileWidget for an example.


How do use hook_views_pre_render() to modify view fields

Found the answer:

// https://drupal.stackexchange.com/questions/272495/how-to-get-views-field-names-values-for-hook-views-pre-render
foreach ($view->result as $key => $value) {
  //- Get parent_id value
  $parent_id_value =  $value->_entity->parent_id->getValue()[0]['value'];
  //- Get parent_type value
  $parent_type_value =  $value->_entity->parent_type->getValue()[0]['value'];
  drupal_set_message($parent_id_value .' | '.$parent_type_value);
}


If you have Views enabled, this might be an issue with Media.  This has been previously reported the issue queue for the project, and there it was suggested to reinstall the latest version of the Media module, in case the files had become corrupt.


How to display page loading time in drupal 7 for each page

The Devel module will show queries and their execution time in the footer which will get you an idea of how long the page is loading.


The hook is called by the Fields Widget API in order to collect information about defined widgets. Any module can define a field widget as long as it implements the necessary hooks.

Documentation about the hook itself can be found in the docs: hook_field_widget_form().

Basically it provides widget specific Form API elements that collect the necessary data for a field. The default values are set in code (or wherever the module chose to define them) and should provide sensible defaults. In the case of the Addressfield module the default values are defined in the function addressfield_default_values in the main module file addressfield.module.


Drupal 7 + Commerce + Addressfield remove specific  from form markup

The user's answer in the comment is wrong. We never want to hack a module. But we can use hook_form_alter() to modify the #suffix and #prefix.


Trying to change the body in presave nodeapi - not working

If the body of a node differs from its teaser, it will show both when editing
(it'll append the real body to the teaser, which is why it looks like you're still seeing the old version of the body).

In other words: make sure your body and your teaser are both altered before saving.


A better approach to this would be to implement hook_node_api that checks the current $user's permissions to the loaded field then does something.

function custom_module_nodeapi(&$node, $op, $a3 = NULL, $a4 = NULL) {
  //get the current user
  global $user;

  switch ($op) {
    case 'load':
      //do some logic with $node and with the current $user's roles
    break;

    //(optional)add other cases for other operations

    default:
    break;
  }
}

alternatively you can try template_preprocess_node

function theme_name_preprocess_node(&$variables) {
  global $user;
  $node = $variables['node'];

  //do some stuff with $node and $user
}


Responsive/Fluid Views for Responsive/Fluid Website

Are you using a responsive base theme? If not, try a responsive theme like Omega. It is also possible that the order in which your CSS files being loaded, was set in a way that the base theme (assuming non responsive), overwrote what you have written. Make user that when you do drupal_add_css, you use proper weight and group value, to manage their load order.


Drupal 8: Best practice to get nid in form_submit

You're looking for $node = $form_state->getFormObject()->getEntity().

Oh, saw that you actually mentioned that. This is the correct way to do it.


add custom header in term listing tpl page

I think you're not trying to do that in the right place. The data manipulations should be made (in my opinion) in the modules part or in your template.php, not in your files.tpl.php...

If I were you, I'd proceed with Views module that allows exactly to do what you're trying to get. Answers to this question could help you to create an alphabetical pager with Views.


The answers on this question might help you.

You override maxlength in a hook_form_alter().

function hook_form_[content-type]_node_form_alter(&$form, &$form_state, $form_id) {
    $form['summary']['#maxlength'] = 40;
}

The above is not tested but should get you started. You can inspect the $form object with dpm() if you have Devel installed to check the exact name and place in the $form array of the summary field.


Is possible to redirect all 404's to the front page?

If you go to the Basic Site Settings (/admin/config/system/site-information) and enter in "/" for the default 404 (not found) page does that work for you?


Notice: Use of undefined constant FIELD_LOAD_CURRENT

Discovered that this happens when you're executing this particular function outside of drupal being bootstrapped.

Source: https://drupal.org/node/1286964


Can I write two cron( hook_cron() ) in one module

No. You can implement hooks once per module due to the namespacing of the hook (mymodule_cron). However you can put conditions within the cron hook to do different things.

You might be looking for this instead: https://api.drupal.org/api/drupal/modules!system!system.api.php/function/hook_cron_queue_info/7.x


'Failed to get available update data" behind a proxy

I solved the problem on Ubuntu 14.04.5 with Drupal 8.5.6. This should also work for Ubuntu 16.04.4. Install php7.0-curl (or php-curl or php5-curl or php7.2-curl) and write http:// before your proxy name (otherwise GuzzleHttp uses tcp://, I think).

Console/SSH

sudo apt update
# Use php --version to find out what version of PHP you're on
sudo apt install php7.0-curl
sudo service apache2 restart

Config

/var/www/html/<DRUPALFOLDER>/sites/default/settings.php

$settings['http_client_config']['proxy']['http'] = 'http://192.168.1.8:3128';
$settings['http_client_config']['proxy']['https'] = 'http://192.168.1.8:3128';
$settings['http_client_config']['proxy']['no'] = ['127.0.0.1', 'localhost'];

Optional

The old syntax is no longer necessary (but would not hurt either):

$settings['proxy_server'] = '192.168.1.8';  // HERE WITHOUT http:// !!!
$settings['proxy_port'] = 3128;
$settings['proxy_username'] = '';
$settings['proxy_password'] = '';
$settings['proxy_user_agent'] = '';
$settings['proxy_exceptions'] = array('127.0.0.1', 'localhost');

Console/SSH (again)

sudo service apache2 restart

For the Googlers: errors on my way

Show logs with

drush ws --count=100 --extended --tail
# or cd into `<DRUPALFOLDER>` and do
php drush.phar ws --count=100 --extended --tail

►►►

 *****  24/Aug **:**  update    error     GuzzleHttp\Exception\RequestException: Error creating resource: [message]
                                          fopen(http://updates.drupal.org/release-history/drupal/8.x?site_key=****************************
                                          ***************&version=8.5.6&list=**********************************************************...
                                          ...*************************************************************************): failed to open
                                          stream: Connection timed out
                                          [file] /var/www/html/******************/vendor/guzzlehttp/guzzle/src/Handler/StreamHandler.php
                                          [line] 324 in GuzzleHttp\Exception\RequestException::wrapException() (line 52 of
                                          /var/www/html/******************/vendor/guzzlehttp/guzzle/src/Exception/RequestException.php).
 *****  24/Aug **:**  update    error     GuzzleHttp\Exception\RequestException: Error creating resource: [message]
                                          fopen(http://updates.drupal.org/release-history/admin_toolbar/8.x?site_key=*********************
                                          ***************************************&list=admin_toolbar%2Cadmin_toolbar_tools): failed to
                                          open stream: Connection timed out
                                          [file] /var/www/html/******************/vendor/guzzlehttp/guzzle/src/Handler/StreamHandler.php
                                          [line] 324 in GuzzleHttp\Exception\RequestException::wrapException() (line 52 of
                                          /var/www/html/******************/vendor/guzzlehttp/guzzle/src/Exception/RequestException.php).

►►►

 *****  24/Aug **:**  notic  user  Session opened for ***.
                      e
 *****  24/Aug **:**  error  upda  GuzzleHttp\Exception\ClientException: Client error: `GET
                             te    http://updates.drupal.org/release-history/admin_toolbar/8.x?site_key=**********************************
                                   *********&version=8.x-1.24&list=admin_toolbar%2Cadmin_toolbar_tools` resulted in a `400 Bad Request`
                                   response:

 *****  24/Aug **:**  error  upda  GuzzleHttp\Exception\ClientException: Client error: `GET
                             te    http://updates.drupal.org/release-history/drupal/8.x?site_key=*****************************************
                                   **&version=8.5.6&list=******************************************************************************...
                                   ...***************************` resulted in a `400 Bad Request` response:


How to theme specific taxonomy term page?

The best way is to show it by Views module. You blocked default viewing of taxonomy and change it to Views. Video include.


You will want to duplicate one of the files with extension .tpl.php in modules/comment directory and place the dup' in your theme. Then clear cache and edit the file you dup'd and placed in your theme.

The File you want is /modules/comment/comment.tpl.php


How do I use hook_search_api_solr_search_results_alter() to alter search results?

I have installed search_api, search_api_solr and search_api_attachments.  The View that I am reading with the hook is a Solr indexed view returning solr index extracts.

I discovered this was how to read the result rows:

  $result_items = $result_set->getResultItems();
  // Iterate through doc ids
  foreach ($result_items as $docid => $value) {
    // process info from $docid and/or $value
  }

$docid will be the Solr document id, i.e.: entity:node/47:en

In my case, all the information I need, entity type and entity id, are in the document id.

If I want to remove the result row:

unset($result_items[$docid]);

And at the end of the hook:

$result_set->setResultItems($result_items);


Customize the output of the Drupal 8 Aggregator module

I believe what you are looking for is the 'Manage Display Option" viewable from

admin/config/services/aggregator/display

In other words from the aggregator admin ui.

Not sure how much control this gives you in reality. Also I am having issues with Aggregator appearing to strip out image tags from my feeds for some reason, so I am also considering using the feeds module instead that seems to have better support than the core module.

UPDATE

Ended up using the migrate module which enables custom mapping of fields from a field to a content type of your choosing with custom fields etc.


Lists the organic groups current user is not a member

You can create a view that lists all groups the current user is not a member of, but you need to develop your own custom Drupal module for it (if anybody knows of a simpler way, please share your knowledge).

The general idea is as follows: Create a view that lists all groups. In your custom module, implement the hook hook_views_query_alter. There, add a condition to the view's query that checks whether the current user is or isn't a member of a group.

You can create the view that lists all groups via the website, or implement it in your custom module as well. For the latter, you can get a rough idea from tutorials like this.

In the database, the memberships are stored in the table og_membership. The field gid refers to the group's node id in the node table. The user who is member of the group is referred as an "Entity". So for each membership, the field entity_type is "user", and etid is the user id. So, a user is a member of a group if there exists a record in og_membership with the user's id in etid, "user" as entity_type and the group's id as gid. The other way around, if a user is not member in a group, such a membership record doesn't exist. In plain SQL, you could say something like (for user id 123)

SELECT n.nid, n.title
FROM node AS n
WHERE NOT EXISTS (
  SELECT *
  FROM og_membership AS m
  WHERE n.id=m.gid AND m.entity_type = "user" AND m.etid = 123
);

In your custom module, you need to add this NOT EXISTS-Condition to the view's query. To do that, you implement the hook hook_views_query_alter. The following is a rough idea of what the implementation should look like:

// the parameters are a reference to the view and the query, respectively
function MY_CUSTOM_MODULE_views_query_alter(&$view, &$query) {

  // get the current user's info from the global scope
  global $user;

  // alter only the query for the correct view, not for every view on the site
  if($view->name == "MY_VIEWS_NAME" && $view->current_display == "MY_CURRENT_DISPLAY") {
    // the subquery to check for memberships
    $member_query = "SELECT * FROM {og_membership} AS m WHERE m.entity_type = 'user' AND m.etid = :uid AND m.gid = node.id";
    // add a new expression to the WHERE part of your view's query
    $query->add_where_expression("AND", "NOT EXISTS (" . $member_query . ")", array(":uid" => $user->uid));
  }
}


Recipes for most compatible slideshows and/or carousels?

The most common formula I implement can work for just about any JS library.

Assuming you are attaching slides to a content type, here is how I go about it.

First, you will need File Entity, for the ability to add fields to file types.

You can use the default Image type, or, create a special one like 'Slide', if you'd like to isolate field and behavior.

Add an image field to a content type. Set the widget to 'Media' embed.
Set cardinality
Hide field display from all view modes
Create a new view mode, called 'Slideshow' or 'Carousel' whatever you desire
In the new view mode, set the image reference field to render the image in a view mode from the file entity configuration.
In Image (or your new) file type, add some fields like Title, Text, and Link. Configure the chosen file display to set those fields however you like.
Create a template representing that file display with the markup you desire and placement of fields.
Create a View, add a Block display, and add a contextual filter of node nid, based on url value (when on node pages).
Set the view to only output the Rendered Entity: Slideshow mode. No fields.
Put the block in your designated slideshow region.

When adding images on the content type(s), you should have a ctools window after uploading that presents the fields you added in step 6 - that is for setting headers, text, and 'read more' link on each image.

This will output the markup you provided in those templates on nodes who have one or more files attached. From here, you would want to tweak markup to match whatever slide JS library you select and some CSS tweaking as well. Then, you can hook up an initializer in a JS file in your theme, to call as you need.

This might take 30-60 minutes to setup, but it has been the most bulletproof way for me to allow someone to add a slideshow or hero (just 1 image) to a content page while being open and flexible to whatever slide/carousel library may be required.

My favorite plugins/libraries for slide functionality are Zurb Orbit and slick.js. I don't usually need or implement any modules to do these anymore, for the smallest possible implementation without a ton of overhead.

That said, if you are perhaps using a Foundation based theme, you might find it worthwhile to leverage Field Orbit. It is built a little like the steps above, but uses a field formatter to simplify the implementation part. Disclaimer, I built that many moons ago - but I have not made any changes to it lately. I believe it works with Foundation 5.x as well.


How do I access an Entity Reference's field values?

The rules module can do this for you.  Set up a rule to fire when (new?) content is saved, set a condition that the content be of type RelatedContent and has a value in Field1.  Then set the action to be saving a value in Field2 using the available tokens of the referenced node from Field1.  It should be something like [Field1:entity:target_field]

You can do the same thing in php code with hook_node_presave.

Entity reference with a view to limit the selection options would be better used if you just wanted Field1 and wanted to pick the entity to reference based on the value that you would be storing in Field2 if you had a Field2.  This is because the view can be used to show you the label using the value of that other field, but leave the key as the entity id needed to be stored in Field1.  Since entity reference can be used for a data connection by views, rules, code, etc this is a common practice to reduce your database size and not store the same data in more than one place.  However, it is a little more complicated to configure than just using rules.


How to apply css to all pages in custom module

In module's info file, add following line:

stylesheets[all][] = folder/module.css

Substitute folder with a name of subfolder within your module you keep your CSS files in (or remove it). Repeat for all CSS files you need.

More about info files in the manual on Drupal.org.


Taxonomy terms view sorting results numerically

Try using Views Natural Sort

This allows you to emulate MYSQL's behavior of CAST() in order to treat the integers as pure values to sort by.

From the documentation:

Natural Sort also supports Numbers.

Normal Sort:

1 apple
10 apples
2 apples

Natural Sort:

1 apple
2 apples
10 apples


The HTML id has nothing to do with $form_id.

$form_id is the name of the whole form. In most cases, it is the name of the function that generates the form unless hook_forms() is used.

Instead of checking the $form_id with an if condition, it is often easier to implement the more specific hook_form_FORM_ID_alter() hook. So if the form_id is BLA, you can directly create a function yourmodule_form_BLA_alter(&$form, &$form_state)and don't need to mess with $form_id at all.

There are exception when this doesn't work or isn't practically, but it most cases, it is recommended to use that hook (It's a performance improvement too, because your function will just be called for that specific form and not every single form in Drupal).

If you are not sure what $form_id is, implement hook_form_alter() and put a drupal_set_message($form_id) in there. That should then print all form ids of the page you are on, allowing you to easily pick the one you want to change.

About the name of the form element, you can't guess that from the HTML in most cases, because unless #tree is set to TRUE, the names are flattened, so it might be $form['some_fieldset']['example'] in the $form structure and just name="example" in HTML.

So, to find the element you want to change, there are two ways.

a) Look at the source code of the function that defines the form structure.

b) Use dpm($form) (requires devel.module).

I prefer the second method, and this is usually the second step after figuring out the $form_id, if I don't know exactly what I want to do. dpm() prints complex array/object structures in a very nice and browseable way. That is actually something you should get used to all the time when you work with Drupal. Don't just guess things. You're going to be wrong pretty often. Instead, if there are any variables that you want to use but don't know the exact structure of them, add a dpm($var), load the page/trigger the action and then you can exactly see what you are working with.

Edit:

The last problem is that right now, your code does completely replace that form element. Instead, you only want to override the #size property, like this:

$form['finder_form'][2]['#size'] = 25;


How can I add special classes to only all blocks that's generated in certain region?

I am afraid this is no longer possible, according to Region-specific block templates are not available in Drupal 8.

  In Drupal 7 it was possible to specify separate block templates per
  region, such as block--header.tpl.php and block--footer.php to output
  different HTML for blocks placed in the header and footer regions. It
  was also possible to adjust variables based on region in
  hook_preprocess_block(). Both of these features have been removed.

  It is suggested you use standard CSS cascading selectors to style
  blocks differently on different parts of the page.

Therefore, you have 2 options:

1) In your page.html.twig you add a parent/wrapper class or id

{% if page.sidebar %}
    <div class="my-sidebar">
       {{ page.sidebar}}
    </div>
{% endif %}

Then in CSS use your parent/wrapper to style your blocks .my-sidebar .block { border: solid red; }

2) Individually create a block--block--[id].html.twig for each of your sidebar blocks and add my-desired-class here.


Different Terms&Conditions on multi-site

In Drupal 7 Domain Variable module will help you, in Drupal 6 this is not supported probably.
Domain Variable:

This module aims to be a replacement variable handling module for Domain Access, allowing mixed variable realms (domain x language) to be configured.
In other words, it allows setting different variable values for each domain and for each language at the same time.
This module supports almost all of the functionality provided by Domain Configuration, Domain Settings and Domain Theme. Differences are listed in the documentation.


Problem with loading translation of JS file via ajax

Answer was simple - the js translation file that drupal generates was "stuck". Seems to have been a browser caching issue.


Simplenews newsletter unsubscribe page- Access denied

The access arguments for that page are subscribe to newsletters, meaning that you need to grant that permission to anonymous users, in order to allow them to unsubscribe without logging in.

Here's how to do that:

Navigate to /admin/people/permissions.
Find "subscribe to newsletters" item.
Grant the permission to anonymous users.

Note: I just told you how to allow to do it for everyone. You need to evaluate if this fits your website and workflows.


Fatal error during add a field to a content type with a custom Field Type

This happened to me, and the solution was making sure that the file name matches the class name defined within, so in your case, the class name MUST be AnyToShowItem.

This is because the PSR-4 auto-loader would be trying to load .../sites/all/modules/something/src/Plugin/Field/FieldType/AnyToShowItem.php if the class AnyToShowItem doesn't exist. But if the class defined within doesn't match the filename, then AnyToShowItem will still be undefined but the class that IS contained in the file will be. So the next time the AnyToShowItem class is attempted to be constructed, the file is loaded again in a futile attempt to define the class, but the class within will already have been defined, and thus the redefinition error will be thrown


How to associate the current Node ID when running from Block layout?

This feature is already present in form of the contextual filters in views (not limited to D8). To do this:

Add a contextual filter in your view block of "Content: nid"
In "when filter not present" select "provide default value".
Select "Content id from the URL".

And this block will automatically take in the nid from the URL.


How to group fields and place in seperate tabs/local tasks?

You can create local tasks for this in yml. Local tasks are what appear as tabs when viewing an Entity. You can code the tabs yourself. There's not much to it: https://www.drupal.org/docs/8/api/menu-api/providing-module-defined-local-tasks

Answer from Kevin here:
How to group fields and place in seperate tabs?


How have multiple instances of a Custom Block?

Add the following function in your template.php

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

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

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

then when you want to render the block just write the following line

print render <themeName>_render_block($module_name, <id of block>, array of options like title etc)

You can find module name and block id by going to block configuration page so for the path
admin/structure/block/manage/views/locations-block_1/configure
module name is "views" and id is "location-block_1"

So the render function will be

print render <themeName>_render_block("views", "location-block_1", array("title" => t("My block title")));


Is there a way to quickly copy the same ordering and layout from manage fields to manage displays?

Since this has been posted for more than a week and nobody has responded, then I am going to assume that there is no quick and easy way.  I just ended up recreating the display by hand.  Oh well.


Why do I get pathauto errors when using node_save?

Try this:

      $path = 'your value for the path';
  $node->path = array('alias' => $path);


Administrator role can't edit html source in tinymce

I found out the issue is that the person logging in as an administrator was using Internet Explorer 11. Once they changed browsers to either Firefox or Chrome, everything worked as it should. Microsoft should really get out of the browser business.


Controlling file paths in multi domain setup

I use the sledgehammer approach and search/replace from template_process_html:

function foo_process_html (&$variables)
{
  $variables["page"] = str_replace("http://internal.example.com/", "/", $variables["page"]);
}

You can also get fancy and use preg_replace if you need better control.  I typically end up needing this when I move a site from our staging server, which is a subdomain off of ours, onto a client's own domain.

If I were in your shoes, I would think about having an internal theme and an external theme, combined with one of the choose-a-theme-based-on-domain-name solutions.  Then you can add preprocess/process as needed to just the external theme.


Set parent service when registering a service in a ServiceProvider

You can find your answer in the symfony docs, How to Manage Common Dependencies with Parent Services. In the third snippet we see:

use AppBundle\Repository\BaseDoctrineRepository;
use AppBundle\Repository\DoctrinePostRepository;
use AppBundle\Repository\DoctrineUserRepository;
use Symfony\Component\DependencyInjection\ChildDefinition;
use Symfony\Component\DependencyInjection\Reference;

$container->register(BaseDoctrineRepository::class)
    ->setAbstract(true)
    ->addArgument(new Reference('doctrine.orm.entity_manager'))
    ->addMethodCall('setLogger', [new Reference('logger')]);

// extend the AppBundle\Repository\BaseDoctrineRepository service
$definition = new ChildDefinition(BaseDoctrineRepository::class);
$definition->setClass(DoctrineUserRepository::class);
$container->setDefinition(DoctrineUserRepository::class, $definition);

Looking at the docs and your code, my understanding is you'd do something like:

use Symfony\Component\DependencyInjection\ChildDefinition;

class MyModuleServiceProvider extends ServiceProviderBase {

  /**
   * {@inheritDoc}
   */
  public function register(ContainerBuilder $container) {
    // Create services for our base normalizer classes.
    $container->register('MY_MODULE_rest.entity_normalizer_base', EntityNormalizerBase::class)
      ->addArgument(new Reference('entity_type.manager'));

    $node_definition = new ChildDefinition('MY_MODULE_rest.entity_normalizer_base');
    $node_definition->setClass(NodeNormalizer::class);
    $node_definition->addTag('normalizer', ['priority' => 1]);
    $node_definition->addArgument(new Reference('path_alias.manager'));
    $node_definition->addArgument(new Reference('language_manager'));

    // Create node normalizer service.
    $container->setDefinition('MY_MODULE_rest.node_normalizer', $node_definition)

  }
}


Best way to migrate Content from drupal 6 to 7?

Migrate might be the module you need:

  The migrate module provides a flexible framework for migrating content into Drupal from other sources (e.g., when converting a web site from another CMS to Drupal). Out-of-the-box, support for creating core Drupal objects such as nodes, users, files, terms, and comments are included - it can easily be extended for migrating other kinds of content. Content is imported and rolled back using a bundled web interface (Migrate UI module) or included Drush commands (strongly recommended).

There is specialized Drupal-to-Drupal data migration for just the task you need:

  migrate_d2d provides a framework based on the Migrate API for migrating content from Drupal 5, Drupal 6, or Drupal 7 sites into the Drupal 7 site where it is installed. As of the 2.1 release, It requires Migrate 2.6 or later. Besides addressing contemporary needs to migrate to Drupal 7, it has helped serve as a proof-of-concept for incorporating the migration approach into core as an upgrade path (https://groups.drupal.org/imp).

It's far from perfect, all right, but it's good and well tested - in my experience it is most solid way unless you want to write custom one just for your case.


Alter The User Login Form Into Multi Steps

Finally I got it to worked. here is my code, I'm pasting this here to saves someone time.

function signin_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'user_login' || $form_id == 'user_login_block') {
    unset($form['name']);
    unset($form['pass']);
    unset($form['actions']);
    if (isset($form_state['step2'])) {
      $form = signin_step2_form($form, $form_state);
      return $form;
    }
    $form['mail'] = [
      '#title'       => t('Email'),
      '#description' => t('Enter your Email'),
      '#type'        => 'textfield',
      '#required'    => 'true',
      '#maxlength'   => 40,
    ];
    $form['next'] = [
      '#name'   => 'next',
      '#value'  => t('Next'),
      '#type'   => 'submit',
      '#submit' => ['signin_form_submit'],
    ];
    $form['#validate'] = ['signin_step1_form_validate'];
    return $form;
  }
}

function signin_step1_form_validate($form, &$form_state) {
  $mail = $form_state['values']['mail'];
  if (empty(user_load_by_mail($mail))) {
    form_set_error('mail', t('The entered email is not associated with any account.'));
  }
}

function signin_step2_form($form, $form_state) {
  $form['pass'] = [
    '#title'       => t('Password'),
    '#description' => t('Enter the password'),
    '#type'        => 'password',
    #required' => 'true',
  ];
  $form['signin'] = [
    '#name'   => 'signin',
    '#value'  => t('SignIn'),
    '#type'   => 'submit',
    '#submit' => ['signin_form_submit'],
  ];
  $form['#validate'] = ['signin_step2_form_validate'];
  return $form;
}

function signin_step2_form_validate($form, &$form_state) {
  $mail = $form_state['stored_values']['mail'];
  $user_obj = user_load_by_mail($mail);
  $name = $user_obj->name;
  $pass = $form_state['values']['pass'];
  if (!user_authenticate($name, $pass)) {
    form_set_error('pass', t('The Password you entered is incorrect'));
  }
}

function signin_form_submit($form, &$form_state) {
  if ($form_state['clicked_button']['#name'] == 'next') {
    $form_state['step2'] = TRUE;
    $form_state['stored_values']['mail'] = $form_state['values']['mail'];
    $form_state["rebuild"] = TRUE;
  }
  else {
    $mail = $form_state['stored_values']['mail'];
    $user_obj = user_load_by_mail($mail);
    $form_state['uid'] = $user_obj->uid;
    user_login_submit($form, $form_state);
  }
}


Do I need a custom content type, entity, module or field?

The data would need to be shown when a node is displayed - I would like the data to be accessible from within views, but also searchable, e.g. display products where stock level < 3 for supplier xyz.

How can you say I want the data to be integrated into my website -- but not imported into Drupal. Your goal sounds like alot of work.

You could try something like Remote Entity. But honestly I would take some time to learn the Migrate module and use Rabbit Hole to insert the data as "hidden" data to drupal entities or content types in my site. Migrate is super powerful for this type of syncing of data (syncing being a topic I think you're glossing over).

EDIT

You could try to:

use hook_entity_view_alter to put content into a node view.
use hook hook_views_data and putting your DBs into settings.php to be useable by Views displays and filters.
use something like hook_search_api_query_alter to include your custom dbs in queries to search

... all of these in my opinion would be harder to maintain in the long run, rather than a recurring interval of updates or syncing of data using Feeds, Migrate, and storing a copy of the data locally in a drupal friendly format (eg a content type or entity).


This code is not to supposed to work inside panels. Regions are what you add to your themes and they are ready to use on your theme templates.Panels are used to override your theme templates, its allows to have regions as per the panel layout you choose.$page will not be available to your panels. Using new custom content you can add plain text,html,php but regions will be available here.


Long story short: It wasn't Drupal. We have the Brocade Traffic management stuff running above the site (and on local sites too so the dev environment is as close to live as possible).

The HTTP/HTTPS switching in that was causing the problem. After working with it for so long I should have checked it. Such is the life of a professional developer.


No, that was the old form of multilangual sites. This was removed in Drupal 8 in favor of entity translations.

Now every field had its own language instead of the node. This means the common properties of the node (nid, author, etc) can remain untranslated, while the values of the individual fields can be translated. (it prevents duplicate content)

So there is no way to select one node as a translation of another.


Try using the Field Collection module.

Create a collection of fields and then attach it to the content type as one field.


Javascript errors caused by  elements being wrapped inside a  tag

I found out that the checkbox 'Trim this field to a maximum number of characters' was checked in one of my views which was trimming some HTML from the field content (closing tags) and causing the issue.

checking the option 'Field can contain HTML' fixed the issue for me.


Custom PHP code to create a node with rules

In Rule:

Create a new entity
Of type Node
At the end of your action, the "Provided variables" section will give you the label of the entity created
Use that entity, already fetched, to set fields (with "Set a value") of that node.

Enjoy !


when to use include (inc) files in module development

As general rule, I would put in the module file the code that is required more often (e.g. helper functions used from more than one function), and in .inc files the code that is not used so often, or that is used for specific pages.

Since Drupal 6, the code automatically loads the files containing the page callbacks, or the form builders used for the menu items. For that reason, page callbacks for administrative pages are normally put on .admin.inc files, while page callback for normal pages are put on .pages.inc files.

Since Drupal 7, files containing classes are automatically loaded when a class is instantiated. Drupal 7 allows modules to define in which files their hooks are defined (through hook_hook_info()). For example, system_hook_info() defines the .tokens.inc files as files where hook_token_info(), hook_token_info_alter(), hook_tokens(), and hook_tokens_alter() implementations can be found; in this way, those files are automatically loaded when one of those hooks are required.
This allows to further split the code in files that are loaded when necessary, and code that is always loaded from Drupal.


D8 Programmatically change page orientation for Entity Print module

Ok so here's a solution.

As mentionned, you only need to add an event in a custom module inside

my_module/src/EventSubscriber/EntityPrintSubscriber.php

I simply use a GET parameter from url to set page orientation.

ie. yoursite.com/print/pdf/entity_type/entity_id?orientation=portrait

namespace Drupal\my_module\EventSubscriber;

use Drupal\entity_print\Event\PrintEvents;
use Drupal\entity_print\Plugin\PrintEngineBase;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\EventDispatcher\GenericEvent;

class EntityPrintSubscriber implements EventSubscriberInterface {

  public function alterConfiguration(GenericEvent $event) {
    //ie. /print/pdf/entity_type/entity_id?orientation=portrait
    $request = \Drupal::request()->query->get('orientation');
    if(!empty($request) && ($request == PrintEngineBase::PORTRAIT || $request == PrintEngineBase::LANDSCAPE)){
      $configuration = $event->getArgument('configuration');
      $configuration['orientation'] = $request;
      $event->setArgument('configuration', $configuration);
    }
  }

  public static function getSubscribedEvents() {
    return [
      PrintEvents::CONFIGURATION_ALTER => 'alterConfiguration',
    ];
  }

}

Edit:

Don't forget to add a service to your module.
So inside my_module/my_module.services.yml, add this:

my_module.entityprintconfig:
    class: Drupal\my_module\EventSubscriber\EntityPrintSubscriber
    tags:
      - { name: event_subscriber }


do i need to check expiration cache in drupal from cache_get?

It is actually pretty simple.

For your implementation of hook_flush_caches, all you need to do is return an array containing the names of your cache tables, eg

function mymodule_flush_caches ()
{
  return array("cache_mymodule");
}

drupal_flush_all_caches and cache_clear_all take care of the rest.  drupal_flush_all_caches is called anytime you manually clear the cache (the perforamnce page, admin menu, drush, etc).  system_cron does get called by cron, and also clears the cache tables, but does not do some of the other things that drupal_flush_all_caches does.

When you get something out of the cache with cache_get, expired items will have already been removed from the cache; you don't need to manually check expirations.  They will be handled automatically according to how you put them in the cache with cache_set.

That's it.


How to create a product without a variation?

It is - as You said - difference of terminology.
The easiest way for You would be trying this: https://simplytest.me/
Here You can quickly test Drupal modules and whole distributions. Please try Commerce Kickstart with this tool and during install click to install demo content.

There You'll see that Variations are more like Categories in Your meaning:
Each product display must have one or more product variations, which is why each product display type has a matching product variation type.
Different product variation types have different fields, used for storing images, attributes such as color and size, as well as any other information.

And Categories are more like taxonomy - You can list colors, sizes etc there and reuse it in multiple products.

Hope i helped You a little :)


There's a set of drush make files in the project directory. Those list the various dependencies.


I would like to be able to trap when a particular message is sent via drupal_set_message

In Drupal 6, messages are themed for display via...

function theme_status_messages($display = NULL) {
  $output = '';
  foreach (drupal_get_messages($display) as $type => $messages) {
    $output .= "
\n";
    if (count($messages) > 1) {
      $output .= "
\n";
      foreach ($messages as $message) {
        $output .= '
'. $message ."
\n";
      }
      $output .= "
\n";
    }
    else {
      $output .= $messages[0];
    }
    $output .= "
\n";
  }
  return $output;
}

In Drupal 7, they are themed similarly via...

function theme_status_messages($variables) {
  $display = $variables['display'];
  $output = '';

  $status_heading = array(
    'status' => t('Status message'),
    'error' => t('Error message'),
    'warning' => t('Warning message'),
  );
  foreach (drupal_get_messages($display) as $type => $messages) {
    $output .= "
\n";
    if (!empty($status_heading[$type])) {
      $output .= '
' . $status_heading[$type] . "
\n";
    }
    if (count($messages) > 1) {
      $output .= "
\n";
      foreach ($messages as $message) {
        $output .= '
' . $message . "
\n";
      }
      $output .= "
\n";
    }
    else {
      $output .= $messages[0];
    }
    $output .= "
\n";
  }
  return $output;
}

so I'd imagine copying the appropriate function into your theme's template.php and naming it YOURTHEME_status_messages(...) along with some suitable regexing or strposing inside would do the trick pretty directly.


How to use WYSIWYG editor with structured content in Drupal 7?

For images use Insert module. For other fields, like YouTube links and entity References, you can create your own module based on Insert's code, or expand it's capabilities and put a patch in Insert's issue queue.


Custom exposed filter to select expired nodes

What about running a cron task that sets the status of offers to  unpublished once the expiry date has passed.

Then the view can simply filter on whether or not the node is published.

If you don't want to go down that route then alternatively create a filter based on date and then with a little jQuery hide that and add some radios. Then when the radio is changed set the date filter to the appropriate value and submit the form.


How to substitute values on a page, without PHP?

This is even more new than Beta, but look at the Sandwich module that looks like most of its configuration is in 1 place (across all nodes of X type for instance).

The module sits at ~400 lines of code and has it looks like 2 small example usage modules/themes.

EDIT: to be clear this goes off custom markup I believe like, MY_CUSTOM_VALUE, in a body field of a node which would regex out to be whatever value you implement in a module. With page caching turned on shouldnt be a huge hit. You keep your "values" in code and dont depend on the Token module.


How to alter account activation mail Depending on roles

You can create a new rule like this

EVENT saying  After saving a new user account

Conditions saying  User has role(s)  check your role there.

Actions saying send mail you can send the mail what you want in that.


How to implement a text field formatter that renders a URL as the image?

You can follow the Drupal.org example on creating a custom Field Formatter. Inside the viewElements function, you can add an if statement to check if the remote file exist. If it does, assign the url to the markup. If not, assign some text:

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

    foreach ($items as $delta => $item) {
        $file = $item->value;
        $file_headers = @get_headers($file);
        if(!$file_headers || $file_headers[0] == 'HTTP/1.1 404 Not Found') {
            $url = Url::fromUserInput($file);
            $markup = "<img src={$url->toUriString()} \>";
        }
        else {
            $markup= "File Not Found";
        }
      // Render each element as markup.
      $element[$delta] = ['#markup' => $markup];
    }

    return $element;
  }

Part of this answer is from stackoverflow.
I have not tested this, but it should be close.


How to add custom field to the user profile according to its role in Drupal 7?

User role field module allows you to specify role-specific fields.
When creating a new field, you specify what roles this field is enabled for.

Fields are only visible and editable if a user has a specific role.

This role does not determine access controls for visible fields.
You could use the Field Permissions module for setting access controls.

More then 120 sites currently use this module.


How to know all the available BASE_FORM_ID?

In D8 only entity forms implement the interface BaseFormIdInterface. The code to generate the base form id is in EntityForm::getBaseFormId:

  public function getBaseFormId() {
    // Assign ENTITYTYPE_form as base form ID to invoke corresponding
    // hook_form_alter(), #validate, #submit, and #theme callbacks, but only if
    // it is different from the actual form ID, since callbacks would be invoked
    // twice otherwise.
    $base_form_id = $this->entity->getEntityTypeId() . '_form';
    if ($base_form_id == $this->getFormId()) {
      $base_form_id = NULL;
    }
    return $base_form_id;
  }

So for each config and content entity type there is a base form id available: [ENTITY_TYPE]_form

In some cases special entity forms override this method, for example the confirm form class ContentEntityConfirmFormBase defines [ENTITY_TYPE]_confirm_form.

To get all available base form ids the best approach is probably to iterate over all routes that have entity forms or build the form object with the information you find in the entity types. The most work here is to get an entity for the form object, because getBaseFormID() depends on this:

use Drupal\Core\Config\Entity\ConfigEntityType;
use Drupal\Core\Entity\ContentEntityType;

$entityTypeManager = \Drupal::EntityTypeManager();
$base_form_ids = [];
foreach ($entityTypeManager->getDefinitions() as $id => $entity_type) {
  $handler_classes = $entity_type->getHandlerClasses();
  // check if the entity type has form operations
  if (isset($handler_classes['form'])) {
    $entity = NULL;
    // for config load the first entity
    if ($entity_type instanceof ConfigEntityType) {
      $entity = reset($entityTypeManager->getStorage($id)->loadMultiple());
    }
    // for content create a new instance, because we don't know if content exists
    elseif ($entity_type instanceof ContentEntityType) {
      $values = [];
      // if the entity type has bundles we have to provide one when we create the entity
      if ($bundle_key = $entity_type->getKey('bundle')) {
        if ($bundle_entity_type_id = $entity_type->getBundleEntityType()) {
          if ($bundle = reset($entityTypeManager->getStorage($bundle_entity_type_id)->loadMultiple())) {
            $values[$bundle_key] = $bundle->id();
          }
        }
      }
      $entity = $entityTypeManager->getStorage($id)->create($values);
    }
    // if we have an entity, get the base form id for each form operation
    if ($entity) {
      foreach ($handler_classes['form'] as $operation => $form_class) {
        $form_object = $entityTypeManager->getFormObject($id, $operation);
        $form_object->setEntity($entity);
        if ($base_form_id = $form_object->getBaseFormId()) {
          $base_form_ids[$base_form_id] = $base_form_id;
        }
      }
    }
  }
}


How to limit entity reference for new nodes only?

You need to render views in the Entity Reference field.

Add a reference type display in a view.
Add a nid and title field in the view.
A list of views will be displayed in the field configuration. Select specific view in field's configuration.

Edit:

May be adding hook_form_alter to form can do the trick for you.

function hook_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'your_node_form') {
    // $form['#node'] if it is node edit form.
    // $form['reference_field']['#options'] = $altered_list
  }
}


Assuming those operations check access correctly (not doing so would be a bug), you can use hook_ENTITY_TYPE_access, e.g. in your case hook_field_config_access, there you can deny delete access for a field with a given name.


How do I assign a role to a user after the user's email is confirmed?

You'll want to take a look at Rules and LoginToboggan (as per this answer on Drupal Answers).

Rules will allow you to add a "trigger", such as adding a role to a user, and LoginToboggan will provide the "trigger" for when the account is validated.


Module compatibility between major Drupal versions

Will this work with Drupal 7 as well?

Nope. D7 and D8 are vastly different under the hood; therefore, there is no backward and no forward compatibility across Core versions. If there are none for D7 you will have to build one or upgrade your site to D8 if you see fit.


How can you remove another modules events?

Remove the event subcriber service from the container:

my_module/src/MyModuleServiceProvider.php

namespace Drupal\my_module;

use Drupal\Core\DependencyInjection\ContainerBuilder;
use Drupal\Core\DependencyInjection\ServiceProviderBase;

/**
 * Remove the foo event subscriber.
 */
class MyModuleServiceProvider extends ServiceProviderBase {

  /**
   * {@inheritdoc}
   */
  public function alter(ContainerBuilder $container) {
    $container->removeDefinition('foo_event_subscriber');
  }

}

You find the service name in the MODULE.services.yml file of the other module.

More info https://www.drupal.org/docs/8/api/services-and-dependency-injection/altering-existing-services-providing-dynamic-services


New Drupal 8 install, homepage works, all other pages throwing a 404

The problem may be that you don't have the .htaccess file on the root of your Drupal 8 website.


That usually means something in your .htaccess is causing Apache to fail. Could for example be a missing module or a configuration that denies access to something.

Try to look at the error log of the Apache server, if you have access to it. If not (even many shared hosting sites allow access to those files for your virtual host), you could ask your hosting provider support.

It is only possible to provide a more detailed solution once you post the actual error from the error log.


Catch the selection of the values in select/drop-down-box prior to the node submission

You might be looking for hook_node_presave()

  Act on a node being inserted or updated.

  This hook is invoked from node_save() before the node is saved to the
  database.

To attach a custom submit handler, create a custom module and do something like this:

function my_module_form_alter(&$form, $form_state, $form_id)
{
  if($form_id == 'form_abc')
  {
    $form['#submit'][] = "my_module_form_submit_handler";
  }
}

function my_module_form_submit_handler($form, &$form_state)
{
  drupal_set_message("The form is being submitted, do some extra stuff now...");
}


How to add a colon for Webform field labels?

With D7 webforms, you should be able to access the parts of the webform (rendered within webform-form.tpl.php) within a form alter:

function mymodule_form_alter( &$form, &$form_state, $form_id ) {}

If you have the devel module enabled, you can use it to print out the variables within the $form['submitted'] array - for example, to edit the title of a form component, you would use:

$form['submitted']['my_form_component']['#title'] = 'My new title';

To add a colon to the end of each component's attribute (i.e. to add a colon at the end of the #title attribute) you could set

$form['submitted']['my_form_component']['#title'] = $form['submitted']['my_form_component']['#title'] . ":";

If you use a variable instead of the specific 'my_form_component' name, you can set the form_alter function to loop over and add the ":" to the end of all component titles.

Small example here:
https://www.drupal.org/node/1558246


have you tried using drupal_message to make sure it's being called?

Or calling the hook_openlayers_map_alter() function and using map as an array like so:

function hook_openlayers_map_alter(&$map = array()) {
    $map['center'] => array( 'lat' => '0',
                             'lon' => '0',
                             'zoom' => '2'
                           );

}


jsonapi Cross-Origin Read Blocking (CORB) blocked cross-origin response in vue

You need to set up your Cors settings
Look at your services.yml file then read ...

How do I set up CORS?


How to make existing public files private?

Thanks a lot for the answers! FileField Paths definitely is the way to go.

Update the file field's field storage to handle private files.
Run FileField Paths' Retroactive update on your content type's file field.

Step 1. can be accomplished from within hook_update_N (if you use configuration management do that locally and then export the updated configuration and deploy the resulting *.yml):

$field_type = 'file';
$field_name = 'field_file';

if (!$field_storage_configs = \Drupal::entityManager()
  ->getStorage('field_storage_config')
  ->loadByProperties(['type' => $field_type])) {
  return;
}

foreach ($field_storage_configs as $field_storage) {
  // Note: These settings apply to the field_file field everywhere it is
  // used.
  if ($field_storage->getName() == $field_name) {
    $field_storage->setSetting('uri_scheme', 'private');
    $field_storage->enforceIsNew(FALSE);
    $field_storage->save();
  }
}

Alternatively, follow the manual config update and reimport as suggested in the question.

Step 2. is to go to your file field's edit screen and fire the Retroactive update upon saving the form:


How can I properly duplicate Fields on entities?

One way of doing this is in the theme layer. In this approach you don't need to have two fields. You could have a single Images field, and in a node template preprocess function you can break it up into two separate variables that are provided to the *.tpl.php file. So you could take the rendered output of the first image, put that in one place, and the rendered output of the rest of them could go somewhere else.


How to change fields to not be required before they are validated

I believe the form validate hook triggers after the default validation which would include checking required fields. It might be easier to not mark the fields required by default and check in your validate hook if they need to be required and then throw a form error if necessary.


Batch delete users and the content they created

As stated in the comments, Views Bulk Operations provides helpful functionality. You can use the "select all" checkbox on the /admin/people page to select all the users, then deselect the few you want to keep. From the dropdown, you can then choose "Cancel user account". After submitting, you will select the method by which to cancel the accounts in bulk (such as Delete the account and its content, or Delete the account and make its content belong to Anonymous).


Views, Display Suite - fatal error on allowed memory size - what could be happening?

The PHP memory limit is being exceeded. In your drupal site, go to /admin/reports/status/php and look for "Loaded Configuration File". It should be one of the first 5 columns in the table.  In a plain text editor, or a code editor, open the file listed there. In it, search for memory_limit and replace the value next to it with, say, `128M'. Save that file and restart your web server. You may need to increase the memory limit again, if your server still errors out.


How to create a view of counts of taxonomy reference fields by each user?

In the Advanced > Other section of the view, you should be able to enable aggregation.


From the limited details provided in your question, it could very well be that one of your enabled rules (created with the Rules module) is what is causing your issue.

To actually confirm, for sure, if it is any of the enabled rules, use these steps:

Disable of all your enabled rules. If the problem persists, you can be sure it is not because of a custom rule (don't forget to re-enabe the temporary disabled rules). If the problem is gone, continue with the next step to find which rule is causing your problem.
Re-enable your temporary disabled rules, but only 1 at a time, and check if your problem comes back (each time after you re-enabled one more rule). At some point your problem should come back. As soon as that happens, the most recent re-enabled rule is what is causing your issue. In that case, re-enabe the remaining temporary disabled rules and continue with the next step.
If you cannot find out what the actual problem might be in the re-enabled rule that causes the problem, move on to Rules debugging, as explained in my answer to "How can I display the value of a variable inside a condition?".

After you're sure it's not Rules causing the problem, I'd consider the "Workflow" module (which you also seem to be using) as the next suspect on my list. As a quick test (to see if that's the direction to go for further debugging), temporary disable the Workflow module: if the problem remains, then it is not the Workflow module either (don't forget to re-enable it afterwrds).


How to add Search form/Advanced search form view to advanced forum pages?

You need to display the exposed filters in a block, and then display that block on single forum node pages.

Here's how to do that:

Edit the Forum Search view: /admin/structure/views/view/advanced_forum_search/edit.
Under "Exposed form" -> "Exposed form in block" choose "Yes".
Save the view.
Navigate to /admin/structure/block.
Enable the "Exposed form: advanced_forum_search-page" block, and show it for example in the "Content" area and only for "Forum topic" nodes. You can change this to your liking of course.

Users now can use this form from single forum nodes, and submitting it will take them to the search page.

Update

If you want to make this available in your templates and position it within other elements, you'll have to edit the template.php of your theme add a hook_preprocess_X() implementation.

Choice depends on the template you want to add the form to. For example:

hook_preprocess_node() - to make the form available in node.tpl.php
hook_preprocess_page() - to make the form available in page.tpl.php
hook_preprocess_html() - to make the form available in html.tpl.php

Here's the code:

function YOUR_THEME_preprocess_REPLACE_THIS(&$variables) {
  // Load the view and generate the search form.
  //
  // You can have any dynamic conditions here (e.g. limit to some content types
  // and so on).
  $view = views_get_view('advanced_forum_search');
  $view->set_display('page');
  $view->init_handlers();
  $form_state = array(
    'view' => $view,
    'display' => $view->display_handler->display,
    'exposed_form_plugin' => $view->display_handler->get_plugin('exposed_form'),
    'method' => 'get',
    'rerender' => TRUE,
    'no_redirect' => TRUE,
  );
  $variables['search_form'] = drupal_build_form('views_exposed_form', $form_state);
}

Then in your .tpl.php file you would use this code to display the form:

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

Note that this way the visibility settings in admin won't be applied.


"Drupal already installed" Message on Restored site

Seeing the install page on an already installed Drupal site usually is a sign of problems with your database connection before the request has been processed by PHP.

This may have a wide range of causes, most likely related to your database server configuration.

The first thing to check is your database logs, which may give a hint on how to solve your issue.

We often experienced a similar behavior on sites that heavily use the database. E.g. sending big queries when rebuilding page caches on complex pages. The solution there was to ensure a high enough max_allowed_packet setting. See here for more details on how to do that.


Looking to make an opaque image/image caption in a teaser

I did this in CSS using the content title and the opacity feature of CSS. See below (modify for your purpose)

.view-id-programmes.view-display-id-block_1 .views-field-title {
margin-left: 10px;
position: absolute;
background-color:
white;
filter: alpha(opacity=68);
-khtml-opacity: 0.68;
-moz-opacity: 0.68;
opacity: 0.68;
-moz-border-radius: 15px;
-webkit-border-radius: 15px;
-khtml-border-radius: 15px;
border-radius: 15px;
padding: 8px;
}


Probably the sanest way to do this would be to create a new module which has little to no functionality, but includes the .inc files; then make your other modules dependent on that module. As you develop the other modules and find other functionality you want to share between them, just implement it in the "parent" module, and away you go.

If adding another module is objectionable for some reason, you could implement it as a "library" and use the Libraries API module - but that's intended for Drupal-external third-party PHP libraries like TinyMCE, not things you've built yourself.


How to apply a distinct css class to each value of a field with multiple values?

A simple approach would be to use CSS :nth-child() pseudo classes.  Assuming some HTML output like:

            [CONTENT]

            [CONTENT]

            [CONTENT]

            [CONTENT]

You can target the 2nd div with css like this:

    .entity-reference-wrapper .entity-reference:nth-child(2) {
        color: green;
    }

Odd children like this:

    .entity-reference-wrapper .entity-reference:nth-child(odd) {
        color: green;
    }

There are a lot more options over at CSS tricks here:  https://css-tricks.com/useful-nth-child-recipies/


Domain relationship module for drupal 7?

I don't think you need another module.
Just use Domain Access.

You can let users choose to which domain this node will be published.
Make sure that the user that needs to approve the node has the following permissions:

Publish content to any assigned domain
Set domain access status for all content.


You need to do the following steps in order to achieve what you need:

Download Poll aggregate patch file from here
Apply the patch file the way you want. Good Drupal reference here.
Goto Modules list page admin/modules and install/enable the following modules:

Multilingual content module
Multilingual select module
Field Translation
Synchronize translations module
Poll aggregate

Then goto Poll content type settings page admin/structure/types/manage/poll and enable Multilingual support by choosing Enabled, with translation
Create a new poll content with its options and select default language from the Language dropdown list and save the node.
Create translation Poll content for the same node by clicking on translate tab.
Replace default language content with the second language.

I hope this will solve your issue.


How to make a multi field reference multiple content types?

This is one way:

Project (Content Type)
Member (Content Type)
Position (Taxonomy - Because maybe you want to classify)

In Member you will have a field that is a Term Reference to Position.

In Project you will have a Field Collection named Project Position, which will have an Entity Reference to Member and a field that is a Term Reference to Position.


Make a gmap view embeddable on another site

You could create your own iframe: http://www.iframehtml.com/

You will most likely want to create custom page output so that you aren't including extra regions from your site. You can do so by creating a custom html.tpl.php template (might not be necessary) and page template for the map.


Setting a header for checkmark in tableselect

I ended up needing to keep the label actually in the correct column, and so went a different route.  I have jQuery available to me as well.

I added an #after_build to my form that would insert some JavaScript:

$form['#after_build'][] = 'mymodule_config_form_after_build';

Then in that function, added:

function mymodule_config_form_after_build($form, &$form_state) {
$data = <<< EOT
  jQuery(document).ready(function(){
        var liveTable = jQuery("#edit-variables table").filter(function() {return !(jQuery(this).css('visibility') == 'hidden' || jQuery(this).css('display') == 'none');}); // Get the right table
        var cb = jQuery("th.select-all input[type='checkbox']", liveTable); // get the right checkbox
        if (cb.length == 1) { // attempt at being smart
            var th = jQuery("th.select-all", liveTable); // Need the table head next
            th.css('width', '15%'); // I found the auto width logic was messing up the table, so I put in this hack to cover my label width
            cb.attr('name', 'form-select-all');
            cb.attr('id', 'form-select-all');
            var label = jQuery("<label for='form-select-all' style='padding: 0px;'>Active Replacement?</label>");
            cb.before(label).detach().prependTo(label); // put the label in and move the checkbox before it

        }
    });

EOT;
drupal_add_js($data, 'inline');
return $form;

The first jQuery filtering is needed because Drupal seems to add a hidden table to help facilitate header handling (???).  I was coming up with too many tables and check boxes.


How to add a rule condition from select-list in a webform

You can use a technique similar to what is described in my answer to "How to do a data comparison to submitted webform data when using the Rules module?". For short:

Add an extra Rules Action to Add a variable, with a value assigned to it equal to your [data:newsletter-value-raw] (assuming newsletter is the form component containing your select-option) and with a data type which equals the data type of your Webform component. In your subsequent Rules Actions you can refer to the value of this variable you just added (that's the clue!).
Use the Conditional Rules module to perform a data comparison. In this case to check the value of your select-option. If so, and only then, perform your Rules Action to add the email address as a subscriber.

PS: Instead of using the Conditional Rules module, you could also rework the Rules Action to performing Rules Components (in which you add the appropriate Rules Conditions), so that you don't need this extra module. For more details on that, refer to the answer to "What's the alternative to using the Conditional Rules module?".


It's about time this got a proper answer. Here's that explained as a step-by-step:

Creating a Search API view. None of this will work unless, when you initially create the view, you choose one of the Search API options like "Show [Search Index]" and the appropriate index instead of "Show [Content]" in the drop down at the very start of the views creation process.
Giving it a Context view display. A "Context view" is a type of View Display like a "View block" or a "View page" or an "Attachment view" etc. Create one with the "Add" button at the top of the View edit page.
Load it as a Context in Panels or Page Manager. The thing that is special about Context views, is that systems built on cTools contexts (like Panels and Page Manager) can load the view early on in the process, and also, analyse it so they know what types of data to expect. In the Contexts page for your Page Manager page or Panel, add a context, choose Views, then find the right view.
Place each part of the view as Content. Because cTools is loading the View as a context, and because cTools knows what Views are and how to make sense of them, it knows exactly what elements of the view it's going to get. If it was a views block, all it can do is just dump the whole output of the block somewhere, but since it's taking the time in the Context stage to analyse and make sense of the View, it can figure out that it's going to get seperate rows, headers, footers, exposed fitlers, etc. When you go to Content in the Panels / Page Manager interface, you'll find a 'Views Context' vertical tab with various bits of your view in it. This is the "bit more complexed" bit the guy refers to. If you want, you can go nuts and build a complex, sophisticated grid display placing the Views Row content type lots of times with different limits and offsets, with the first row highlighted, then a column showing rows 2-5, then a column showing rows 6-10... Or you can just stick the 'Views row' content in without limits or offsets (plus Views Header and Views Footer if you're using them) and it'll work as normal.
Place the Facets, Current View block, etc. This is the important bit for the question. Because the View is loaded at the start of rendering the page, the search is loaded at the start of rendering the page, so order doesn't matter. If it was a Views block, it wouldn't be done until that block was rendered. So your facets and current search blocks can go anywhere.

All of this is a bit rough around the edges and might not work first time. If you're using Search API Spellcheck, don't forget to put it in the View Header then place the View Header in Panels / Page Manager. If your view gets its search terms using Contextual Filters instead of Exposed Filters, sometimes it just works, but you might sometimes need to set the argument manually and occassionally check and patch supplementary modules like Current Search Links and Search API Spellcheck depending on how the search is set up.


How to fetch the field data in computed field

field_get_items() takes care of language negotiation for you, so the field value is one level up. e.g.

$field_items = field_get_items($entity_type, $entity, 'field_range');
if (!empty($field_items[0])) {
  $data = $field_items[0]['value']->from;
}


You can get the user entity from the proxy with AccountProxy::getAccount:

$entity = $account->getAccount();

And then the roles with User::getRoles:

$roles = $entity->getRoles;

If you don't need the entity for anything else in that method, it turns into a one-liner:

$roles = $account->getAccount()->getRoles();


How to prolong time of displaying of images in carousel slideshow

Comparing with w3schools example (specifically line <div id="myCarousel"...) - inserting data-interval="30000" there (the line then looks like
) does the trick.

In the Jethro theme (and probably in any similar case), this backbone is in the file templates/page.html.twig (in version 2.0 line 85). So that inserting data-interval="30000" there does the trick. The line then looks like
. Might be this is not the most elegant way, but it works well.


Split D7 User Account Edit Form in multiple blocks

I haven't done this in code, but I split the user profile into multiple pages on my site with the Field Group module (as the module's page says, it is only client-side).

There is a screencast about how the multipage features work.

Another option is the Profile 2 module, which will create actual separate paths for different settings.


You can add filter criteria corresponding to the field on which you want to hide the row .
Suppose you want to hide the row if content: body is empty then you can add filter criteria as Content:Body not equal to  "" (where value field should be left empty).
This will automatically hide the row if the specific field is empty
.


Access content at alias without redirecting to original content location

With the core module path you can do this:

  Tips about URL aliases

  Although it is possible to assign the same internal URL to multiple
  aliases, this is generally not a good idea for search engine rankings;
  Google, for example, penalises your site by dropping its rank if
  Google thinks that you are publishing duplicate content under multiple
  URLs (a form of web spamming).

I just tried to add 3 aliases on the same node/123 and it works without any problem. Go to Administer > Configuration > Search and metadata > URL aliases or directly to admin/config/search/path to add a new alias and see the existing ones.


The preprocess functions are about rendering the output. Removing and adding form element with FAPI must be done earlier.

You have to do this with hook_form_alter. It's also very likely that you have to add a custom submission handler to process and save the user input. You can hook in your handler in hook_form_alter as well.


Get a calculated price from Product Variation

Solved this problem, by passing the 4th argument $adjustment_types to the $commercePriceCalc->calculate method.

$adjustment_types = array("promotion" => "promotion");

So, the final version of the code

$commercePriceCalc = \Drupal::service('commerce_order.price_calculator');
$context = new Context(\Drupal::currentUser(),
                     \Drupal::entityTypeManager()->getStorage('commerce_store')->load($store_id));
$prices = $commercePriceCalc->calculate($slide->field_product->entity, 1, $context, $adjustment_types);


Internal server error when programmatically updating about 100 nodes

Give your server more memory ;)

Better to use EntityFieldQuery (but this will not speed up your script ..)
You could replace the while loop with foreach (array_keys($result['node']) as $node_id)
In the worst case you'll need to limit the $result or $nids array to 10 or something .. and run the script several times, maybe in cron ?

Or run an update query (also possible without php)

$sql = "UPDATE node node LEFT JOIN content_type_event node_data_field_event_date ON node.vid = node_data_field_event_date.vid SET node.status = 0 FROM WHERE (DATE_FORMAT(ADDTIME(STR_TO_DATE(node_data_field_event_date.field_event_date_value, '%Y-%m-%dT%T'), SEC_TO_TIME(-25200)), '%Y-%m-%d') >= '2014-09-10' AND DATE_FORMAT(ADDTIME(STR_TO_DATE(node_data_field_event_date.field_event_date_value, '%Y-%m-%dT%T'), SEC_TO_TIME(-25200)), '%Y-%m-%d') <= '2015-09-10') AND (node.type in ('event'))";

mysql_query($sql);


Turns out I just needed to take the token, [node:quiz:quiz-close] and append it with the custom date format machine name :just_the_date] to get [node:quiz:quiz-close:just_the_date]. Also, it's in the list of tokens, once you expand the date item further.


Entity Metadata Wrapper - check filtered text value is set

but there must be a better way

If you find it, do share :)

Seriously though, this is what the language gives you; exception handling is what you should use to handle exceptional circumstances, and an entity not having a field that you're expecting it to have would probably class as exceptional in most people's book. It does in mine anyway.


it's just a property of the Node itself, the nid of the node. It is the value $node->nid.

EDIT

There is also entity_extract_ids() which is 1 level up from a Node in the object hierarchy and this function interacts with Entities -- if you're trying to do something more generic than merely interact with solely Nodes ... such as a process a Queue of Entity objects all of different types but sharing a field you want set with a certain value.

  Helper function to extract id, vid, and bundle name from an entity.

  Parameters

  $entity_type: The entity type; e.g. 'node' or 'user'.

  $entity: The entity from which to extract values.

  Return value

  A numerically indexed array (not a hash table) containing these
  elements:

  0: Primary ID of the entity.

  1: Revision ID of the entity, or NULL if $entity_type is not versioned.

  2: Bundle name of the entity, or NULL if $entity_type has no bundles.


User name in view arguments and title of page

You can add on "Relationships" (right side of your view edit page, under Advanced) "Content: Author". Now the name of the author (User: Name) will be available to you in fields and/or filters. You could also follow this: http://www.drupalden.co.uk/using-views-display-nodes-author-name


Different User Points for different nodes

User points can be assigned based on default points or their particular points defined in content type form page.

If you want to override that points use hook_userpoints function. In that function points before case will execute before user points is assigned to users.

second parameter in hook_userpoints, you will get points and entity_id using that you can change points based on your condition.


You can use this template for the user page: user-profile.tpl.php

For the user edit page you can take a look at this page: Customize the User Edit page in Drupal 7 - an example.

UPDATE: To add CSS and JS to specific page you can do it like outlined below in a custom module.

/**
 * Implements hook_page_build().
 */
function MYMODULE_page_build(&$page) {

  if (request_uri() == 'path') {

    drupal_add_js( // arguments );
    drupal_add_css( // arguments );
  }
}


Do I need to delete uploaded files if I only want to parse them

According to the docs for file_save_upload() the file will be registered as a temporary file, so that it will be deleted anyway, assuming you have cron running on a regular basis.

  "The file will be added to the {file_managed} table as a temporary file. Temporary files are periodically cleaned. To make the file a permanent file, assign the status and use file_save() to save the changes."


Looks like you are creating loop redirection. But that you can test by examining logs. I believe there is an easier way: already implemented Global Redirect module:

  This module uses hook_init to interrupt the page load and action the alias lookups. If any of the above rules apply then the appropriate action is taken. If no rules apply then the page load continues uninterrupted. An example of this in use is on the site it was developed for. http://www.sportbusiness.com/node/160559 will redirect to http://www.sportbusiness.com/news/160559/lagardere-sets-up-sports-division due to the alias setup on this site.


How do I programmatically create a node with an entity reference (to an user)?

Set owner $node->setOwnerId($uid);

Set field reference $node->field_user[] = $uid;


Which Drupal core function might call SELECT * FROM on custom module table?

If grep/ack-grep can't find a SELECT * (likely) then just add an $debug_query = 'SELECT * FROM {mytable}'; if (substr($query, 0, strlen($debug_query)) == $debug_query) error_log(print_r(debug_backtrace(), TRUE), 4) or match the whole query etc and then look at the Apache error log for the pouring in backtraces. If you dont want to trash the log, log into a file in /tmp.


Deleted my secondary_links block; where to find another?

Just create a new menu and add your new links to that you can call it secondary links if you like. Then add it to a region via the blocks menu or with php through your page.tpl.php


Is there any hook_node_pre_submit() like hook?

I think hook_form_alter is also a good option to overcome this issue. You can validate by altering the webform.

for example:

function mymodule_form_alter($form, &$form_state,$form_id) {
  //dpm($form);
  if ($form_id == 'your_form_id') {

    //validate function call
  }
}


How can I show 4 latest articles in ascending order?

Just output the rows you need and reverse them with CSS.

.view-content {
  display: flex;
  flex-direction: column-reverse;
}


drupal behat test assert authenticated by role with given fields

You have a typo in your Given condition - you need to have role(s) after administrator.

Given I am logged in as a user with the 'administrator' role(s) and I have the following fields:


Which type to use for checkbox fields in hook_field_schema?

A tiny int would be most appropriate in my opinion:

$columns = array(
  'value' => array(
    'type' => 'int',
    'not null' => TRUE,
    'size' => 'tiny',
    'default' => 0,
  ),
);

A 'standard' int would be overkill for a field that will only ever hold a 0 or 1 value.

See the Data types docs for an overview of the different types available to you.


Enabling the Entity_Token sub module does help with this issue, however, you need to add a "Term Reference" type field to any of your content types in order to see your taxonomy vocabulary be listed as one of the replacement tokens.
In my case, I had enabled the entity_tokens module but I was still not able to see my vocabulary as one of the replacement tokens.  Then I added a new field to my "basic page" content type.  The field type I added was "term reference" and I selected my custom vocabulary as its default vocabulary.  This resolved my issue.


Entity References Auto create between Nodes

You can implement hook_entity_insert()

  Act on entities when inserted.

  Parameters

  $entity: The entity object.

  $type: The type of entity being inserted (i.e. node, user, comment).

and inside the hook check if you have more than one node in the reference field, in this case you will edit all the nodes and add the reference to the others.


Which modules should I use to create a community based site?

If you mostly want to configure, a distribution is probably your best bet. Looking at your requirements, I'd say take a look at Drupal Commons. It will get you most of the features you need, and you can turn on/off features as needed. The rest of your feature set can be added with specific modules.


How render first node in views result in different view mode?

You could use the Display Suite in combination with Views. This allows you for example to choose a different view mode for each row or alternating view modes or whatever you want.


How to achieve if else statement while querying with database?

I'm not sure if you can add if statement to a query but as you already have the values of $form_state['values']['fromdate'] and $form_state['values']['todate'] you can just add an if statement. If those two don't have values then execute a different query without the condition('submitted_time',  array($from_date, $to_date), 'BETWEEN') condition.


need to show user firstname and lastname in search result page

For your error replace:

<?php print drupal_render(somik_user_byline($user->uid)) &nbsp .$info_split['date']; ?>

with

<?php print somik_user_byline($user->uid) . '&nbsp;' . $info_split['date']; ?>

For preprocessing you would use:

/**
 * Process variables for the search result template.
 */
function THEMENAME_preprocess_search_result(&$variables) {
  // Change variables here.
}

There is some more info here http://drupal.org/node/223430
It also links to some other useful related pages.

You need to clear the drupal cache when you add or remove a preprocess function.

Edit:

For your "Fatal error: Can't use function return value in write context"

It is because of this part:

if (!empty(somik_user_byline($user->uid))) {
  $info['user'] = somik_user_byline($user->uid);
}

Because you can't pass a function call into the empty() function like that. You need to give it a variable.

Because your somik_user_byline() function is always returning a string you can do this:

if ($name = somik_user_byline($user->uid)) {
  $info['user'] = name;
}

You can go even further than that still.
Because your function always returns a non-empty string, you can just do this:

$info['user'] = somik_user_byline($user->uid);

Also, for it to be available in the template you have to add it to the $variables array.

For example, you are setting $info but to have it in the template you have to do

$variables['info'] = $info;

at the end and then $info will be available in your template file.

Also, in this case, $info is already full of other information to remember that this will overwrite whatever was alredy in $info from other modules.

If you want to keep the $info that is already there, but override the $info['user'] and $info['date'] parts, do this:

/**
 * Process the variables for search-result.tpl.php
 */
function somik_preprocess_search_result(&$variables) {
  $result = $variables['result'];

  // Override the user part of the info array.
  $variables['info_split']['user'] = somik_user_byline($result['node']->uid);
  // Override the date part of the info array.
  if (!empty($result['date'])) {
    $variables['info_split']['date'] = format_date($result['node']->created, 'short');
  }
  // Re-create the info string with the overridden data.
  $variables['info'] = implode(' - ', $info_split);
}


Email sent using rules chops characters off email from address

I tracked the problem down to the mimemail module.

In mimemail.inc there is a function called mimemail_headers which contains this:

  if (preg_match('/[a-z\d\-\.\+_]+@(?:[a-z\d\-]+\.)+[a-z\d]{2,4}/i', $from, $matches)) {
    $headers['Return-Path'] = "<$matches[0]>";
  }

The {2,4} at the end of the regex caused it to chop the les off of meeples. Changing it to + fixed the problem.


Print Primary and Secondary Menu Links separately

Check out the theme_menu_link and theme_menu_tree hooks.  You can add them to a custom theme, and they give you full access to the links as they are built.

Take a look at the following line in theme_menu_link:

if ($element['#below']) {
  $sub_menu = drupal_render($element['#below']);
}

If you add a test to check if the link being tested is top tier than you can change the $element['#below'] to suit your needs. checking for top tier is as simple as

$element['#original_link']['plid'] == 0

The parent link id of top tier elements is 0, so this works out.
Then, if it is top tier and has links below it, add a theme wrapper that will allow you do what you want it to.  For example:

if ($element['#below']) {
  if ($element['#original_link']['plid'] == 0){
    $element['#below']['#theme_wrappers'][] = 'my_custom_theme_wrapper';
  }
  $sub_menu = drupal_render($element['#below']);
}

I am seeing the original theme wrapper is menu_tree__main_menu.  If you want to completely replace it use you should unset that one, then set a new one as mentioned above.

If you want some pointers on theme wrappers check this post.