How to prevent caching of field element data in custom field formatter?

For anonymous traffic in general there are probably better solutions client-side. If you want to build this server-side in Drupal then better use a session, this will pass the built in page cache for anonymous traffic.

If you want to handle your own cookies you have to uninstall the Internal Page Cache and cache the pages only in the Internal Dynamic Page Cache. Then for better caching performance set a cache context for the cookie instead of max-age:

  $elements['#cache']['contexts'][] = 'cookies:Drupal_visitor_resource_gate';


It is no problem to put form elements in a table. See the example in core/lib/Drupal/Core/Render/Element/Table.php:

$form['contacts'] = array(
    '#type' => 'table',
    '#title' => 'Sample Table',
    '#header' => array('Name', 'Phone'),
  );

  for ($i=1; $i<=4; $i++) {
    $form['contacts'][$i]['name'] = array(
      '#type' => 'textfield',
      '#title' => t('Name'),
      '#title_display' => 'invisible',
    );

    $form['contacts'][$i]['phone'] = array(
      '#type' => 'tel',
      '#title' => t('Phone'),
      '#title_display' => 'invisible',
    );
  }

Maybe you should start from here and then put step by step your code in this example and see when it breaks.


Why some twig templates have no file name suggestions

You can use the theme hook given to create your own theme hook / template suggestions or see additional suggestions that are not showing up in Twig debug, this happens occasionally. (I wonder if this is a bug?)

For example, the theme hook here you are targeting is views_view.

If I do:

function MYTHEME_theme_suggestions_views_view_alter(&$suggestions, $vars, $hook) {
  kint($vars);
}

... If the name of my view is "News" and it's a page display, I see in the theme area printed out in kint:

views_view__news__page_1
views_view__page_1
views_view__news__page
views_view__page
views_view__news

You can take any of these and replace the udnerscores with dashes and then add .html.twig and you should be good to go.

e.g. views-view--news--page-1.html.twig

Resources:

function hook_theme_suggestions_HOOK_alter
Drupal 8 Theming Tutorial: How to Craft Custom Theme Hook Suggestions and Templates


Drupal CKeditor image-upload plugins don't delete unused files

Try to check out the Fancy File Delete module. One of the things it can do based on the module page is

  Deleting unused files from the whole install that are no longer attached to nodes & the file usage table. AKA deleting all the orphaned files.

I think this would require a manual process of deletion but this may solve the issue of deleting orphaned or unused duplicate images in your site.


How do you perform a Guzzle POST request with "Basic Auth" for the current user?

You were so close  main thing here is the "Authorization" Header ...

 $current_user = \Drupal::currentUser();
 $account = $current_user->getAccount();

 $username = $account->name;
 // pass would be hard to get as stored hashed
 //... so you would need to get a bit tricky to "catch" the users password when they log in...
 $pass = 'admin';
 $auth = 'Basic '. base64_encode ($username . ':' . $pass);
 $rest_response = $client->post($endpoint, [
   'body' => $serialized_entity,
   'headers' => [
     'Authorization' => $auth,
     'Content-Type' => 'application/hal+json',
     'X-CSRF-Token' => $token,
  ],
]);

And just for fun:

  var basicAuthCredential = username + ":" + password;
  var bace64 =  btoa(basicAuthCredential);
  var Auth =  'Basic ' + bace64;
  fetch(url,{
    method: 'POST',
    headers: {
      'Accept': 'application/json',
      'Content-Type': 'application/json',
      'Authorization': Auth,
      'X-CSRF-Token': token
    },
    body: JSON.stringify(data)
}).then(response => response.json())...


Cascading taxonomy term selection widget

You can use the Hierarchical Select module:

  This module defines the "hierarchical_select" form element, which is a
  greatly enhanced way for letting the user select items in a hierarchy.


Contextual filter with Node Reference and Pathauto

I'd try this with a contextual filter for the research brief content:nid and then use the default value: node id from the url. This works regardless of pathauto and always provides the correct node is for the research brief.

Then add a Views relationship (join) from the Research brief to the Grant. Select the node reference field for this relationship.

Finally select the fields you want to display, using the Grant relationship.


Get value for a field from url while saving a new node

With the comments so far , I could understand that you have a content type with 10 fields, so the time so create a node you will be putting 9 fields on the node form and the 10th field has to be filled with some value from url parameter,so lets assume your site url while adding the node looks like www.sitename.com/node/add/your_content_type?field_value=xyz.

One of the possible way can be to pick the value from url and make it as 10th field default value, an example code can go something like below.

 // Assuming 10th field as textfield.
 function mymodulename_hook_form_alter(&$form, $form_state, $form_id) {
   if($form_id == "your_node_add_form_id") {
     if (is_null($form['nid']['#value'])) {
         $form['your_10th_field_machine_name'][LANGUAGE_NONE][0]['vaue'][#default_value] = $_GET['field_value'];
     }
   }
 }

Rest saving of fields will be handled by drupal itself.


How can i give link in block for only listed paths based on user id?

Try "extended_block_visibility" module, install it and then on block setting page select last option "pages on which this php code will return true" and then you can write php code inside php tag like :

<?php
if(arg(0) == 'user' && is_numeric(arg(1))){
return TRUE;
}
return FALSE;
?>

But remember this code will save inside the DB and will break site if write wrong code. Alternatively you can define theme specific visibility using this module.


Steps required for transforming some table into a Pie Chart & Bar Chart and by only using core modules?

If you wanna build your own custom module you can grab code from any one of the following modules and use them in your custom module.
Charts

Transform Data into Information. Charts are a very good way to visualize a lot of data in a way that can be quickly digested.

Other modules
Views Charts

Provides a "charts" style output for Views module so you can render result-set not just as text (list, tabular) but as pie-chart, bar-chart, scatter-plot etc.

Charts and Graphs

Charts and Graphs is an API for developers. It can easily be extended by third-party modules that want to add their own charting implementations. It does nothing by itself. It should only be installed if some other module requires it.


have you considered adding a standard HTML block at

Admin > Structure > Blocks > Add Block ?

/admin/structure/block/add

Drupal provides a standard interface for editing the HTML block content.

Alternatively, if you have PHP code, combined with alot of static text in the block, you could load a node into it instead, and use regular node editing for maintaining that text content.

e.g, in hook_block_view

$node = node_load($nid); // Load the text content from node
// PHP logic to build some content...
// ...
$block['content'] = $data; // php content
$block['content'] .= render(node_view($node)); // node content


You can send custom emails to addresses submitted in the form. When creating the form, you have to select 'email' for the field type. Once you've done that, go to the 'Emails' tab in the webform, and add a new email using the 'Component value' menu; you should see your Email field in there (you can add as many of these as you want). This sets it up to send an email to the email address entered in the form, in your case the friends' email addresses.

From there you can customise the email options.

Edit: Whoops, this answer is for Drupal 7 specifically, but (if I remember correctly) the option exists in Drupal 6 as well.


Changes made in hook_node_view() are not applied?

Hi you have added extra fields in the content variable so you have to override the old title


You could use:

// replace this with the url from the node object
$imgURL = 'https://foo.com/fooimage.jpg';
$style  = 'article {';
$style .= 'background: url(' . $img_url . ') no-repeat center;';
$style .= '}';
drupal_add_css($style, array('type' => 'inline'));

For the $img_url though you need to fond out how to get the image url. You would need to load the node using node_load() then use dsm() from the Devel module or just use print_r() to display the field array.


Where can I find in database that page (panel) is disabled?

Panel pages requires Page Manager module which comes with Ctools Module.... Below function in page_manager/page_manager.admin.inc is responsible for enable / disable action...

function page_manager_enable_page($disable, $js, $page) {
  if (!isset($_GET['token']) || !drupal_valid_token($_GET['token'], $page->task_name)) {
    return MENU_ACCESS_DENIED;
  }
  if ($page->locked) {
    if ($disable) {
      drupal_set_message(t('Unable to disable due to lock.'));
    }
    else {
      drupal_set_message(t('Unable to enable due to lock.'));
    }
  }
  else {
    if ($function = ctools_plugin_get_function($page->subtask, 'enable callback')) {
      dpm($function);
      $result = $function($page, $disable);
      menu_rebuild();

      // We want to re-cache this if it's changed so that status is properly
      // updated on the changed form.
      if (!empty($page->changed)) {
        page_manager_set_page_cache($page);
      }
    }
  }

  // For now $js is not actually in use on this.
  drupal_goto('admin/structure/pages');
}

When a panel page (Custom Created , Not default pages that comes with module) is enabled or disabled below function is called in ctools/page_manager/plugins/tasks/page.inc...

/**
 * Callback to enable/disable the page from the UI.
 */
function page_manager_page_enable(&$cache, $status) {
  $page = &$cache->subtask['subtask'];
  ctools_include('export');
  ctools_export_set_object_status($page, $status);

  $page->disabled = FALSE;
}

You can find panel pages details inside variable table under the variable

  default_page_manager_pages

When Disabled

a:1:{s:15:"test_panel_page";b:1;}

When Enabled

a:0:{}

Default pages that comes with module enable / disable status also stored in variables table...


Since everything looked just fine in your code, I tried the following in a custom module:

#test.links.task.yml
test.node_test:
   title: 'Wooorking'
   route_name: entity.node.canonical
   base_route: entity.node.canonical

And this is working like a charm. Also when I added a custom routing, which was pointing to a form controller, it showed up! (although not worked, because I didn't handled the node parameter in the routing configuration)

So the problem lies another where.

So I suggest you to do it step by step way (building your routing and task yml) to understand your problem. Clearing the cache each time when you change something in your YML files. If you found the problem, please post the solution, so also we can learn from this.


When looking at the code from the claimItem method it only returns FALSE if no items are available to claim.

So if $queue->claimItem() returns FALSE you can be sure that all available items are claimed (or failed to be claimed).

public function claimItem($lease_time = 30) {
  // Claim an item by updating its expire fields. If claim is not successful
  // another thread may have claimed the item in the meantime. Therefore loop
  // until an item is successfully claimed or we are reasonably sure there
  // are no unclaimed items left.
  while (TRUE) {
    try {
      $item = $this->connection->queryRange('SELECT data, created, item_id FROM {' . static::TABLE_NAME . '} q WHERE expire = 0 AND name = :name ORDER BY created, item_id ASC', 0, 1, [':name' => $this->name])->fetchObject();
    }
    catch (\Exception $e) {
      $this->catchException($e);
      // If the table does not exist there are no items currently available to
      // claim.
      return FALSE;
    }
    if ($item) {
      // Try to update the item. Only one thread can succeed in UPDATEing the
      // same row. We cannot rely on REQUEST_TIME because items might be
      // claimed by a single consumer which runs longer than 1 second. If we
      // continue to use REQUEST_TIME instead of the current time(), we steal
      // time from the lease, and will tend to reset items before the lease
      // should really expire.
      $update = $this->connection->update(static::TABLE_NAME)
        ->fields([
          'expire' => time() + $lease_time,
        ])
        ->condition('item_id', $item->item_id)
        ->condition('expire', 0);
      // If there are affected rows, this update succeeded.
      if ($update->execute()) {
        $item->data = unserialize($item->data);
        return $item;
      }
    }
    else {
      // No items currently available to claim.
      return FALSE;
    }
  }
}


I made a mistake in the letter case in the class file (emtFilter.php -> emtfilter.php)


drush archive-dump and archive-restore remotely

After multiple tests using the command drush archive-dump and archive-restore, I came to the conclusion that it is necessary to install drush in the final servers.
I wasn't able to run the command archive-dump from a server which has drush installed to make a backup of the other server which doesn't have drush installed  because using the aliases file the drush cmd in the source server raises the following error:

bash: drush: command not found

That means that drush is needed in the destiny server. The way I concluded this was making a debug from the source server using the option --verbose and I realized that when you use the aliases file in drush command at the end this command makes a call with ssh like this:
executing

ssh -o PasswordAuthentication=no user@server 'drush --verbose --uri=urlserver.com --root=/var/www/html archive-dump --destination=/home/user/backup/example.com.tar.gz --overwrite 2>&1'

If you notice the drush command is simply being passed to the destination server.


You can't load protected values. So kint is not much help here.

But you can try this, load directly the uri value:

{{ file_url(data.picture['#value']['#file'].uri.value) }}


The only way to avoid a query is if the alias is already in the cache. Rather than worry about that yourself, it's best to use the API (even more so in Drupal 8 as path alias storage is pluggable and may not be in the database):

Drupal 7, using drupal_get_normal_path() :

$system_path = drupal_get_normal_path($path_alias, $langcode);

Drupal 8, using the path alias manager service:

$system_path = \Drupal::service('path.alias_manager')->getPathByAlias($path_alias, $langcode);

As always it's preferable to inject the service into the consuming class if context allows.

Both methods will get you the system path, e.g. taxonomy/term/1, from which you can extract the term ID.


How do I group by and display only first row of each group?

If you are using D7 - View Merge Rows module can provide the functionality that you need.

In your scenario, select field subject as Grouping field Nr.1.

Access Merge setting in Advanced section of your View.

For the Subject field - select the setting "Use values of this field as a filter".

For the Due_Date field - select the setting "Use the first value of this field".

If your View contains more than two fields, you will need to select the settings for Merge rows to accommodate processing of added fields.


Remove search form from search result page in Drupal 8

There is not much you can customize in core search. So you probably need to override Drupal\search\Controller\SearchController::view and remove this line:

  $build['search_form'] = $this->formBuilder()->getForm(SearchPageForm::class, $entity);

Put your extended class into the route search.view_node_search in a RouteSubscriber.

But I don't think it's worth the effort. You can either simply hide the form in CSS or if you want a fully customizable search solution use Search API.


How to use predefined drupal elements in a custom block/module?

When building your own form in your module, you can simply read your defaults from $user variable. Then, in your submit function, use user_save() function to update your user.


How to check if filefield has a value or not by Rules

I believe that "has value" needs to return TRUE or FALSE. You need to do the assessment yourself, because the value that it should have might not necessarily be a one or a zero (I would use this rule if I wanted to evaluate if a field has the value of 5, say: If yes, return true.)

You can either put in a value in the text input (5) which it will match for you and return true/false, or you can use PHP to evaluate it and return true or false yourself.


drush cim creates and immediately deletes field

Okay, there was a second field.field.node.forum.comment_forum.yml in the code of a custom module. It was just a simple setting which sould rewrite the code above but lead into a conflicting import. It looks like the second yml file gets imported first.
So far deleting the second yml file fixed the problem.

P.S. We will now try to find out why the rewrite doesn't work in the correct order.


How To Upload Image From Media Library Programmatically?

Not sure what you are trying to achieve here, but files uploaded via media are already permanent managed files once you get to the submit stage, I believe.

The value in the form_state array you need is $fid = $form_state['values']['apply_now_image']['fid']);

You can then use that in a file_load: $file = file_load($fid);

So your code becomes

$file = file_load($form_state['values']['apply_now_image']['fid']);
file_usage_add($file, 'user', 'user', $user->uid);
$apply_now_image_path = file_create_url($file->uri);
variable_set('rgit_apply_now_image', $apply_now_image_path);
variable_set('rgit_apply_now_image1', $file->fid);


How to get the children terms of a taxonomy in views?

Depending on how many levels of the tree you want to show. If entire, complex vocabulary, then Views Tree module would be an answer.

  This module provides a tree-based style plugin for Views.

However if this is just a 2-level tree, you might want to set up a view that displays terms and groups them by their parent. For that you'd need to select also Term: Parent, exclude it from display and group the view by Parent.


Vote up/down module undefined constant errors

The module page for Vote Up/Down says (emphasis mine):

  7.x (unstable, on development, do not use this version for production)

NODE_BUILD_PREVIEW was a constant in Drupal 6. I imagine that the maintainers of Vote Up/Down have branched off of the old D6 version to create the D7 version...and haven't completed the changes yet.

There's not even a dev/unstable release available for download on the module page so you definitely shouldn't be using this module for the time being.


Drupal 7 - View listing Organic Groups AND content within that group

You can create a view that listas all content (filter by your choice), make sure you include the field Content: Audience group (og_group_ref).

Then you can go to Format > Format > Settings (style_options) and group by that field.


Allowing a user to control and/or view their own revisions

The revisioning module gives you this ability:

  Revisioning is a module for the configuration of workflows to create,
  moderate and publish content revisions.


How to update multiple fields using ajax?

You can use ajax_command_replace() when replacing more than one element/field. Check this ans. The answer says as:

  Instead of returning the HTML of the single element to update, your
  ajax callback can return an array of ajax commands. So it can return
  two ajax_command_replace to replace each element.


Is it possible to apply FAPI #states to profile2 fields on the user registration form?

If you want to alter a form, you need to create a custom module and implement hook_form_alter (or hook_form_FORM_ID_alter) in it. In your hook_form_alter implementation you will have the $form array available. Look up the element you're interested in and add a #states property to it.

The above is just theory; I have not tried it specifically with the profile2 form and a #states property, but I assume that it would work.


Interval module may help you. It provides an interval field type and also a rules action: "Apply an interval to a date".


Assuming you are trying to implement a *_form_alter() function in a module (which is what I got out of your post), you can implement hook_form_BASE_FORM_ID_alter(), which in this case would be hook_form_node_form_alter(). If you implement this, it will only be executed if/when you are on a node form, and therefore you will know you are in a node form.


This is not possible in a Views template. Form elements rendered here can't be submitted because they are not in a html form (between <form>/</form>).

You need a custom form template so that you are inside of the form. For the Views exposed form there is already a customizable form template in core:

/core/themes/stable/templates/views/views-exposed-form.html.twig

{#
/**
 * @file
 * Theme override of a views exposed form.
 *
 * Available variables:
 * - form: A render element representing the form.
 *
 * @see template_preprocess_views_exposed_form()
 */
#}
{% if q is not empty %}
  {#
    This ensures that, if clean URLs are off, the 'q' is added first,
    as a hidden form element, so that it shows up first in the POST URL.
  #}
{{ q }}
{% endif %}
{{ form }}

You can copy this twig to the /template folder of your theme and start theming the form elements:

  {{ form.field_category_target_id }}
  {{ form.field_address_locality }}
  {{ form|without('field_category_target_id', 'field_address_locality') }}

See How do I assign a template to the user edit form? for more info how to add and use these form templates in other forms.


Form has a div within it. How can I add classes to this div?

That's not what you want. What you want to do is add it to the form structure like this:

$form['#attributes']['class'][] = 'my-class';

Since you didn't list an element on the form, I can only assume you want the class on the form itself. If you want to wrap an element with a div with a class on it, you can do:

$form['element']['#prefix'] = '
';
$form['element']['#suffix'] = '
';

That will wrap the entire element.


How to check if a user is logged in inside a view

I managed to accomplish this task by creating my own custom view field plugin

in mymodule.views.inc I used

function mymodule_views_data() {

  $data['views']['table']['group'] = t('Current User');
  $data['views']['table']['join'] = [
    // #global is a special flag which allows a table to appear all the time.
    '#global' => [],
  ];

  $data['views']['logged_in'] = [
    'title' => t('Logged In'),
    'help' => t('Check if user is logged in'),
    'field' => [
      'id' => 'logged_in',
    ],
  ];

  return $data;
}

and then in /mymodule/src/Plugins/views/field/LoggedIn.php I had

<?php

namespace Drupal\mymodule\Plugin\views\field;

use Drupal\views\Plugin\views\display\DisplayPluginBase;
use Drupal\views\Plugin\views\field\FieldPluginBase;
use Drupal\views\ResultRow;
use Drupal\views\ViewExecutable;

/**
 * A handler to provide a field that is completely custom by the administrator.
 *
 * @ingroup views_field_handlers
 *
 * @ViewsField("logged_in")
 */
class LoggedIn extends FieldPluginBase {

    /**
     * {@inheritdoc}
     */
    public function init(ViewExecutable $view, DisplayPluginBase $display, array &$options = NULL) {
        parent::init($view, $display, $options);
        $this->field_alias = 'logged_in';
    }

    /**
     * {@inheritdoc}
     */
    public function usesGroupBy() {
        return FALSE;
    }

    /**
     * {@inheritdoc}
     */
    public function query() {
        // Do nothing -- to override the parent query.
    }

    /**
     * {@inheritdoc}
     */
    protected function defineOptions() {
        $options = parent::defineOptions();

        return $options;
    }

    /**
     * {@inheritdoc}
     */
    public function render(ResultRow $values) {

        $logged_in = \Drupal\mymodule\Modules\CurrentUser::isLoggedIn();
        return $logged_in;
    }

}

Some of the contents of LoggedIn.php might not be necessary (not 100% sure) I was using another module as an example.


Creating 2 forms to work together on the same page for the same query

From your question... you are saying you have 3 forms...

The first form (on its own page) leads to the other 2 forms (which are on a different page, but both forms are on that single page)... it's not completely clear what the problem is - only that both forms are supposed to alter a query, but this is not happening?

Perhaps you could place the fields for both forms in a single form and assign different actions to each of the submit buttons... technically there will only be one form, but visually through styling you can make it appear as two separate forms through CSS - for example using tabs where the fields for the first form is on the first tab... and the fields for the second form is on the second tab... the first tab would have a submit button defined like this:

        $form['submit1']=array(
        '#type' => 'submit',
        '#value' => t('Submit form 1'),
        '#submit' => array('::processForm1'),
        );

and on the second tab you can define another submit button:

        $form['submit2']=array(
        '#type' => 'submit',
        '#value' => t('Submit form 2'),
        '#submit' => array('::processForm2'),
        );

Enough to say in the form object, you will need to define both the processForm1 function and the processForm2 function... in order to decipher which button triggered the submit in the formValidation and formSubmit functions you will use a line such as:

      $trigger=$form_state->getValue('op');

where $trigger will hold the label of the triggering button.

Hope that helps and makes sense.


Drush is always scanning the whole drupal directory?

There might be something wrong with your module... You say there are more than a thousand files scanned but are they placed in your module's directory ?

Drush is not supposed to scan your sites/default/files folder for instance or any other data folder you might have set. As a  best practice you should not place data in your module's path (obvious... isn't it ?). If you have done so, you should think about moving them somewhere else.

When executed, Drush scans all activated modules path (along with a few others such as sites/all/drush) for .drush.inc files. This is the expected behavior and that might cause your slow script execution.


How to set Drupal Commerce shipping rules by the longest of the shortest dimensions of a product?

The best way to do this will be to create a custom rules action that sets this the way you want it. Writing rules actions isn't very scary. It's mostly a wrapper around a PHP function. Then you can get the logic just right. You could:

Write an action that takes the order as a parameter, returns the dimension you want, and then calculate the shipping in Rules, or
write a function that applies a shipping line item directly to the order.

Option 1 is easier to write and would be my initial tack on the problem. Option 2 is a bit more holistic but requires that you look at the shipping modules to see how they properly add a shipping line item to the order.


How to parse out links and img src references from body copy?

It's never easy to do something like this because parsing HTML is a bit hit-and-miss, depending on how well formatted the input is.

I've always found the best way to do it is to load the HTML into a DOMDocument object, loop through and change whatever element attributes/values I need to, then use the DOMDocument to give me the new output.

This is a very rough example but hopefully it'll give you the idea:

$html = '

Blah blah blah

Link Text

';

$doc = new DOMDocument;

// This is a reasonable use of the @ operator as malformed HTML will produce
// a lot of warnings. Please don't shoot me ;)
@$doc->loadHTML($html);

// Get the links.
$links = $doc->getElementsByTagName('a');
foreach ($links as $link) {
  // Change the value of an attribute based on the current value.
  if ($link->getAttribute('href') == '/some-path') {
    $link->setAttribute('href', '/some-other-path');
  }
}

// Get the images.
$images = $doc->getElementsByTagName('img');
foreach ($images as $image) {
  // Change the value of an attribute based on the current value.
  if ($image->getAttribute('src') == '/some-path.jpg') {
    $image->setAttribute('src', '/some-other-path.jpg');
  }
}

// Get the new HTML
$new_html = $doc->saveHTML();

// Strip out the tags that loadHTML() introduces to get the clean HTML.
$patterns = array("/^\<\!DOCTYPE.*?/si", "!$!si");
$body_text = preg_replace($patterns, '', $new_html);

// Update the node body.
$node->body[$node->language][0]['value'] = $body_text;

EDIT

I knew I'd seen a good question about this on SO; have a look at How to parse and process HTML with PHP? for a good discussion on the subject in general.


Plugin ID doesn't equal Block ID, example.

isForbidden is not a static function, need to use forbidden.

if ($block->id() == 'downloadourapp') {

    // If the user's phone is Android.
    if(preg_match("/(android)/i", $_SERVER["HTTP_USER_AGENT"])) {

    return AccessResult::forbidden()->addCacheableDependency($block);

    }
}


Yes hook_file_download() is the one you want to implement, assuming you're using the private file system. The docs have examples of how to use that hook.

There's no built-in way to do this (at least no way that involves Drupal) for public files, as those are served directly at the web server level without the application ever getting involved.

You'll be able to implement a solution for public files based on modifying the .htaccess file to not pass those files straight through, and implement your own path system similar to the core private files one; the particular functionality will obviously depend on your exact requirements, if you decide to go this route I'd recommend spending some time looking at the core system and file modules to see how the mechanism is implemented.

Unfortunately it's not a few-lines-of-code job so I can't provide an example, it's something you'll have to put together yourself.


How to fix sorting by node title in glossary View when viewing page in non default language?

Now you get view rows for the original language and sort them still untranslated, because you translate them later when rendering.

You need to filter the rows for the current language to be able to sort the translated titles:


How to set custom block to not in any region, therefore user can selete region by ownself?

Simply remove 'region' => 'none' from hook_block_info().

region: (optional) Initial value for theme region within which this block is set. Most modules do not provide an initial value, and any value provided can be modified by a user on the block configuration screen.

  Note: If you set a region that isn't available in the currently
  enabled theme, the block will be disabled.


How do I remove the underscore a view adds to a rewritten link?

This issue happens when the field value is rendered with HTML (which is appended by Drupal date formats).
In your View, edit your time field and make sure to use Custom formatter rather than any of the predefined ones, and provide the custom pattern in 'Date/time format' field. And then underscore should go. Check this useful answer.
In my case I was struggling with underscore appended after Year value (mysirte.com/tag/1994_), and when I created custom format and used 'Y' the underscore disappeared, see picture:


How can i override all node book/book_alias usng alias

Quick and fast method for D7 by using Pathauto 7.x-1.2, VBO 7.x-3.0 and Admin Views 7.x-1.0:

drush dl views_bulk_operations
drush en views_bulk_operations
drush dl admin_views
drush en admin_views

Go to /admin/content, edit the view with contextual menu on top right of view.

Then Click the "Bulk operations: Content" field. Then click the "Update node alias" checkbox and save.

Go back to /admin/content and select all nodes

Choose an operation, then select "Update node alias", then execute!

===================

Although pathauto in 6.x-1.x provides a utility to "bulk generate paths", this one-off action fails on thousands of nodes, and does no "batch" processing.
This results in timeouts, memory overruns, and failure. (Pathauto token generation can be expensive, and becomes painful over thousands of nodes)

This "batch" issue is being addressed in 6.x-2.x & 7.x

Until then, you still have an alternative, and it's better!
The pathauto 6.x-1.x module already exposes the pathauto path-rebuilding function as a node operation that can be applied through the content management screen, or if using "Views Bulk Operations" - as a bulk operation there.

This means you will be able to select only and all nodes of a desired content type, and do them all in a "batch" mode without processing overruns.
Get Views Bulk Operations

See the project itself for install and configuration options.

Once enabled, a new action "Update URL alias" becomes available as an available action within VBO. (when editing the view, and the Style: Bulk Operations settings)
You will want to turn that on.

At the same time, ensure that VBO will use "batch mode" ( To execute operations: "Use Batch API" )

Once that is on, the update task will show up on the VBO screen, and you can, for example, choose to regenerate updated alias paths for 3000 'Article' type nodes without doing the same for 15000 'Image' type nodes.
Advanced usage

The global pathauto settings do not allow for any extra logic, though sometimes you want to to different things to different content (especially if working with bulk imported content, or re-architecting)

You can set the pathauto settings to agressively discard or overwrite any existing paths, then trigger the bulk update over a selection of pages you have defined through VBO. (ones you really need to rewrite)
After that you can change the global pathauto settings to just 'update' or 'leave existing aliases' for other content from then on. Or vice versa or something else.
Without VBO, you could do one or the other of these updates, but not both.
It takes a few more steps, but it's possible.


Get the value from $node inside two objects

The correct way would be

print $node->field_episode_tags['und']['0']['taxonomy_term']->name

without the square brackets and quotes. Elements with in objects are accessed with

->objectname

and elements with in arrays are accessed by ['object']


You should use Drupal 8 classes to generate the link. If you get the nid from an existing node object you can do the following in the .theme-file of your theme:

function yourtheme_preprocess_block(&$vars) {
  $node = Drupal::request()->attributes->get('node');
  $vars['link'] = $node->toUrl()->setAbsolute();
}

In twig you can output:

    {% for key, image in imageurl %}

            {{ block_title[key] }}

    {% endfor %}

To generate the URL of your node just knowing the nid (here in variable $nid) you can use the following in your .theme-file:

function yourtheme_preprocess_block(&$vars) {
  $options = array('absolute' => TRUE);
  $url = \Drupal\Core\Url::fromRoute('entity.node.canonical', ['node' => $nid], $options);
  $vars['link'] = $url->toString();
}

Again you can use {{ link }} to output the URL where ever you need in yout twig template.


How to add auto taxonomy to node fields?

If I understand you, there is a few modules which can handle it:

Word Link (I recommend it)

  The Word Link module allows you to automatically convert specific
  words into links. It works as text filter. This can be useful for
  crossposting your site's pages, or for the contextual advertising of
  your partners (SEO).

Active Taxonomy Links

  Active Taxonomy Links module processes nodes of selected content types
  replacing words in the nodes with links to taxonomy terms.

Glossify (this one supports Drupal 6 also)

  The Glossify module provides filters that scan and parse content and
  replace terms in the text with links to their pages. The d7 version is
  a complete rewrite of the module to be as simple and performant as
  possible.


You have to add a custom submit handler to handle these fields. The form fields you add are custom, so they won't be attached to the node.

$form['user_registration']['#submit'] = 'custom_user_registration_handler';

In the submit handler you'll be able create the user like you're doing no in your presave function. The presave function should load the user and attach it to the node.

Edit \

Problem: The node_presave hook does not contain the email adres so it's not able to lookup the right user.

Solution: The default node form has an author form field. You probably hid that field but I think your still able to fill the value. What if you fill the 'author' field with the email value, this will be the user name.

So in your custom submit handler:

Create the user;
Fill the (hidden) author form field with the right value (fill the right value in the form_state object/array?).

The the default form submit handler will do all the hard work for you.


Quick and dirty way: make a view that displays just one row, take the source html, edit relevant part of it so that it looks the way you would like to printed when there are no results, ie remove field contents and leave only field titles. Copy and paste that html to No results behaviour -> Global text area.

The view title should always be displayed, right?


How to convert an existing field from Text to Link in Drupal 7

Install the Link module in order to allow link fields.
In your database, run:

UPDATE field_config set type='link_field', module='link' WHERE field_name='YOUR_FIELD_ID'
Then run the following query:

UPDATE field_config_instance SET data='a:7:{s:5:"label";s:LENGTH_OF_YOUR_FIELD_NAME:"YOUR_FIELD_NAME";s:6:"widget";a:5:{s:6:"weight";s:1:"9";s:4:"type";s:10:"link_field";s:6:"module";s:4:"link";s:6:"active";i:0;s:8:"settings";a:0:{}}s:8:"settings";a:10:{s:12:"validate_url";i:1;s:3:"url";i:0;s:5:"title";s:8:"optional";s:11:"title_value";s:0:"";s:15:"title_maxlength";s:3:"128";s:13:"enable_tokens";i:1;s:7:"display";a:1:{s:10:"url_cutoff";s:2:"80";}s:10:"attributes";a:5:{s:6:"target";s:6:"_blank";s:3:"rel";s:0:"";s:5:"class";s:0:"";s:18:"configurable_title";i:0;s:5:"title";s:0:"";}s:10:"rel_remove";s:7:"default";s:18:"user_register_form";b:0;}s:7:"display";a:1:{s:7:"default";a:5:{s:5:"label";s:5:"above";s:4:"type";s:12:"link_default";s:8:"settings";a:0:{}s:6:"module";s:4:"link";s:6:"weight";i:16;}}s:8:"required";i:0;s:11:"description";s:0:"";s:13:"default_value";N;}' WHERE field_name='YOUR_FIELD_ID'
(optional) Go into the table for your field name (field_data_field_YOUR_FIELD_NAME) and remove the column field_YOUR_FIELD_NAME_format
In the same table as #4 above, change the column field_YOUR_FIELD_NAME_value to field_YOUR_FIELD_NAME_title. This will make the previous values for these text fields now become the title of any links placed in the new Link field.
In the same table as #4 above, add the columns field_YOUR_FIELD_NAME_url VARCHAR(2048) ALLOW NULL, and field_YOUR_FIELD_NAME_attributes MEDIUMTEXT ALLOW NULL

This solution worked well for me.


override theme function in facetapi module

You're nearly there, but a preprocess function doesn't look applicable to what you're trying to do. A preprocess function is used to set up variables for a theme function, not to actually produce the markup.

What it looks like you're trying to do is to override theme_facetapi_link_inactive() completely, in which case you don't use a preprocess function, but instead you call the function MYTHEME_theme_function_name() and the theme engine will use that instead of the original function.

So all you need to is change the name of your function like so:

function MYTHEME_facetapi_link_inactive($variables) {
  // Same code as in your example
}

After you clear the caches Drupal will start using that function in place of theme_facetapi_link_inactive() whenever it's called.


Got it after a number of days searching:

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

            $(document).bind('drupalOverlayBeforeLoad', function(event) {
                $('#simple-dialog-container', context).dialog('close');
            });
        },
        weight: 11
    }

})(jQuery);

The other events seem to have the wrong order. 'drupalOverlayOpen' almost works except that the editing overlay never 'becomes active'. This is why I was trying to work on the target editing screen events rather than the open dialog.

overlay_paths without there being'use case documentation' it looks like it only applies to menu items. How to manually use Drupal 7's admin Overlay? shows you how to add content nodes to the admin paths. This displayed my node in the admin overlay, but without the background context being visible - defeating the point - and with some further quirks.


Different Theme for Current URL - Using Javascript?

You couldn't select a Drupal theme through JS, unless you reloaded the entire page using JS after the initial load.

The better way to do this would be to use hook_custom_theme() to set the theme. Since you need to track the theme with Optimizely, you can send a JS variable from PHP and then pass that to Optimizely in order to track which theme is being viewed.

You could do this in hook_custom_theme() to have 50% of the users use one theme, 50% use the other:

function hook_custom_theme()
{
  $theme = variable_get('switch_custom_theme', 'theme_1');
  $new_theme = $theme == 'theme_1' ? 'theme_2' : 'theme_1';
  variable_set('switch_custom_theme', $new_theme);
  return $new_theme;
}

Then you can get the theme in JS at Drupal.settings.ajaxPageState.theme (Drupal 7). I can't help you with the Optimizely side of things as I don't use it, you'd have to look at their documentation.


How to selectively disable CKEditor on specific pages?

AFAIK, you can only control access to the wysywyg editor on a per-user basis, not on a per-node basis.  If the user shall be allowed to use the wysywyg editor in general (but be banned from doing it only on specific pages, you need to create write PHP-code that prevents the user selecting the wysywyg text format on the pages were this shall not be allowed).

What you can control on a per page/node basis is the default editor.

To not make the wysywyg default for an existing page, open up the page as Admin, locate the box labeled "Text format" below the main edit area, and select a format (e.g. "Plain text" *) that has not been set up to use wysywyg.

Save the node.  Wysywyg will no longer be default when it is reopend for editing (but it can be selected).

However: If that user has global access to at least one text format tied to wysywyg, he or she can restore the wysywyg for that page at will.

To stop the user from doing this, you must prevent the user from changing the text format.  You can do this by using hook_form_alter() to remove the pull-down menu that changes the text format for the node edit form.

*) If you want something more advanced than "Plain text", and the "Filtered HTML" (for instance) format has been assigned to wysywyg, just clone the text format you want to use, but do not set it up to use wysywyg.


I haven't time to actually investigate the details of this right now, but if you enable the devel module, put

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

somewhere in your template file somewhere, and then refresh the page twice you will get a list of available variables which you can then click on to expand and drill down into the arrays and objects.

If you still cannot find the tid anywhere to use, try adding the tid as a hidden field to your view, then it will definitely be in there somewhere for you to use.


The answer to your question very much depends on your how your theme is built and what you want to accomplish. If you want just to link the site logo to another location, I would suggest you to find a corresponding piece of code in page.tpl.php of your theme and replace it with correct link.

If you want to give your site administrators  ability to change that link to whatever they want, then I would do this this way:

Create a module that adds a page to admin menu of drupal (using hook_menu).
On that page render a form with one input field. When the form is loaded extract previously saved value using variable_get function.
On form submit save the form value using variable_set function
In your hook_preprocess_page extract value using variable_get, compose correct link and pass it to the template
In your page.tpl.php just render it in the proper place


db_query() PDOException (no parameters were bound)

Don't need execute()，

db_query('
    INSERT INTO {account_floodprotect} (ipaddress, soapcount, mailcount)
    VALUES (:ipaddress, :soapcount, :mailcount)
    ON DUPLICATE KEY UPDATE
    soapcount = soapcount + :soapcount,
    mailcount = mailcount + :mailcount',
  array(
    ':ipaddress' => $ip,
    ':soapcount' => $soapcount,
    ':mailcount' => $mailcount,
  ));


The entire node object is available as $node so you should be able to do something like:

$author=user_load($node->uid);
print check_plain($author->name); // reasonably safe given the 'Spaces are allowed; punctuation is not allowed except for periods, hyphens, apostrophes, and underscores.' validation upon registration but let's check_plain() it anyway

or

$author=user_load($node->uid);
print check_plain(format_username($author));

if you have modules installed that modify the display of the user name.


How to create landing pages and Main Menu based on taxonomy

This seems like the perfect use case for Organic Groups

  Enable users to create and manage their own 'groups'. Each group can
  have subscribers, and maintains a group home page where subscribers
  communicate amongst themselves.

  They do so by posting the usual node types: blog, story, page, etc. A
  block is shown on the group home page which facilitates these posts.
  The block also provides summary information about the group.

There is also a kick-ass set of tutorial videos from BuildAModule here that should help you set it up.


Check if it's the front page in the template

The variable you're looking for is called is_front:

{% if is_front %}

The available variables for a template are documented at the top of the .html.twig file, however there is also a set of default variables available to all templates (which are not documented in every single template). You can find them in _template_preprocess_default_variables().


This issue is already fixed by Drupal community. Please check this imagecache_actions.

Its a typo issue and it exists in:

.../imagecache_actions/canvasactions/imagecache_canvasactions.module


How to generate a stack trace upon errors

You can use the Devel module, and select one of the "Krumo Backtrace" options it provides in its configuration page at admin/config/development/devel.

Make sure to visit admin/config/development/logging and select "Errors and Warnings" or "All Messages". If you have the Syslog module, or any other logging module enabled, you may need to disable it and enable the Dblog module.


Drupal core issue regarding this problem:  https://www.drupal.org/project/drupal/issues/3042423

After patching, I would implement the new hook_oembed_resource_data_alter:

function MY_MODULE_oembed_resource_data_alter(array &$data, $url) {
  if (strpos($url, 'youtube.com/oembed') !== FALSE) {
    $thumbnailUrl = str_replace('hqdefault', 'maxresdefault', $data['thumbnail_url']);
    $data['thumbnail_url'] = $thumbnailUrl;
  }
}

Then I would also run an update hook to update the existing thumbnails:

function MY_MODULE_update_N(&$sandbox) {
  /** @var \Drupal\media\MediaStorage $mediaStorage */
  $mediaStorage = \Drupal::entityTypeManager()->getStorage('media');
  if (!isset($sandbox['progress'])) {
    $result = $mediaStorage->getQuery()->condition('bundle', 'video');
    $mediaItems = $result->execute();
    $max = count($mediaItems) - 1;
    $sandbox['progress'] = 0;
    $sandbox['mediaItems'] = array_values($mediaItems);
    $sandbox['max'] = $max;
  }
  $progress = $sandbox['progress'];
  /** @var \Drupal\media\MediaInterface $media */
  $media = $mediaStorage->load($sandbox['mediaItems'][$progress]);
  if (!$media->get('thumbnail')->isEmpty()) {
    $media->get('thumbnail')->delete();
  }
  $media->updateQueuedThumbnail();
  $media->save();
  $sandbox['progress']++;
  $sandbox['#finished'] = empty($sandbox['max']) ? 1 : $sandbox['progress'] / $sandbox['max'];
}


"This version is not compatible with Drupal 8.x and should be replaced."

Your regions section is slightly off. It should be:

regions:
  navbar: 'Navigation bar'
  parallax: Parallax
  content: Content

Note the removal of the - in front of each region.


How to alert users that they have a survey / webform to complete

You can achieve this goal using Views Send module.

Create a view and add at least one column containing e-mail    addresses.
[Optional] Expose Views filters to let the user easily build list of    recipients using UI.
Add the "Global: Send E-mail" field to your view. This field provides    the checkboxes that allow the user to select multiple
rows.
Create a "Page" (or "Block") display.
Save the view, load the page, use exposed filters to build the list,    select all or some rows and then click the "Send e-mail"
button.
Fill the message form to configure the e-mail. Use tokens to    personalize your e-mail. The module provide also row-based tokens,
taken from the current row of the view. For example, if the view has
a column with the key users_name (the user name) you can use this
replacement token [views-send-users_name].
Preview and send the mail.

For more information go through the module documentation.


How to print taxonomy term name with views PHP?

Storing PHP code directly on database is not a correct method, it causes many issues. Better you can add the relations on your views - "Content: Taxonomy terms on node". and then add the taxonomy term name field as a "hidden field"

Print the value via "Global: Custom text" field if required any custom wrapper around of it.


How do I alter the file link of an uploaded image in edit/create node form?

You could try implementing your own theme_file_link.

  Returns HTML for a link to a file.

  Parameters

  $variables: An associative array containing:

  file: A file object to which the link will be created. icon_directory:
  (optional) A path to a directory of icons to be used for files.
  Defaults to the value of the "file_icon_directory" variable.

Put this into your theme's template.php file:

function MYTHEME_file_link($variables){
  $file = $variables['file'];
  $icon_directory = $variables['icon_directory'];

  $url = file_create_url($file->uri);
  $icon = theme('file_icon', array('file' => $file, 'icon_directory' => $icon_directory));

  // Set options as per anchor format described at
  // http://microformats.org/wiki/file-format-examples
  $options = array(
    'attributes' => array(
      'type' => $file->filemime . '; length=' . $file->filesize,
    ),
  );

  // Use the description as the link text if available.
  if (empty($file->description)) {
    $link_text = $file->filename;
  }
  else {
    $link_text = $file->description;
    $options['attributes']['title'] = check_plain($file->filename);
  }

  return '' . $icon . ' ' . l($link_text, $url, $options) . '';
}

Clear the cache, and then modify the code.

I would also investigate Amazon S3 Stream Wrapper


How to delete old obsolete terms after node's term field has been updated?

A better description of what you're looking for is "orphaned terms". There exists a module that addresses that use case, called Delete Orphaned Terms.

  This is a utility module for deleting "orphaned" taxonomy terms. By
  default, terms with zero nodes associated with them are considered
  orphans, though administrators can specify the number of nodes
  associated with a term in order for it to be considered an orphan.


Make sure the region variable is getting printed in page.tpl.php which is associated with your block.
Make sure there is content for your block. If $block['content'] is set to empty in hook_block then the block does not appear at all.
Check block visibility condition as well


Your D7 may not remain unchanged forever.  When it change, you will want its sitemap to change in concert with the site. In other words, you need something like XML Sitemap on your site.

You should therefore install the XML Sitemap module (as you suggest yourself).  The module actually has an upgrade path if you used the D6 version of the module to generate the D6 sitemap.

If your D6 sitemap was generated by some other means, or if you don't care about preserving the D6 settings for the sitemap, just install at as a fresh module on D7, and it will create a new sitemap.


How to process a textarea as an html list?

Either use the text-field and choose "list" style. Another way is to simply use filtered HTML as your text-format for your text-area. Once you select filtered HTML. use < ul > or < li > in front of each line of text to turn it into a list-item. This can also be accomplished using "Views"


Although not exactly a duplicate of How to make EntityListBuilder sortable? it is essentially the same answer as Berdir wrote,

  You'd have to implement the query logic yourself.

For instance, BlockListBuilder overrides getEntityIds to add a condition on the theme key.

However as Berdir also notes,

  For content entities, I would strongly recommend to rely on the views
  integration instead. List builders are limited in functionality and
  mostly useful for config entities only.


Separate Domain users get redirected to Default domain upon login and content save

After plenty of fatigue , I ended up removing $base_url from settings.php and the problem was solved. But still I wonder what if I have to ever to use $base_url again, the problem will again creep up.


Cannot override template provided by contrib module in theme

For drupal8 you need to enable twig debug in the service.yml file. Then clear cache. After that, you will see in the browser inspector all templates name suggestion to override a part of the page.


Add comment with Inline Entity Form while adding content

Inline Entity Form doesn't support Comment forms out of the box.

Part of the process of building the IEF widget is a call to inline_entity_form_get_controller() which will retrieve a controller class from the entity metadata. As you can see in IEF's hook_entity_info_alter() invocation, it only adds this controller metadata for node, taxonomy, commerce product, & commerce line item entities.

Theoretically, you could build your own custom module that could:

Invoke hook_entity_info_alter() to add support for comment entities.
Build your own custom class that extends EntityInlineEntityFormController(e.g. CommentInlineEntityFormController) to be evoked for form processing.

Keep in mind this is an unusual use case, a comment entity is predicated on a its parent entity pre-existing before it's created; you're likely to run against logic that might prevent this (e.g. database integrity checks) .

It might be easier just to create your own custom node type entity that's configured just to appear like comments on your nodes.


How to combine several form objects into one?

I've created a working example of a combined form object.
Please read the comments below if you want to understand how it works and the workarounds that were applied.

The gist can be found here

Note: There may still be unforeseen issues with the solution below.

<?php

namespace Drupal\sandbox\Form;

use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormInterface;
use Drupal\Core\Form\FormState;
use Drupal\Core\Form\FormStateInterface;
use Drupal\node\Entity\Node;
use Drupal\user\Entity\User;

class ComboForm extends FormBase {

  /**
   * This constant is used as a key inside the main form state object to gather
   * all the inner form state objects.
   * @const
   * @see getInnerFormState()
   */
  const INNER_FORM_STATE_KEY = 'inner_form_state';

  const MAIN_SUBMIT_BUTTON = 'submit';

  /**
   * @var \Drupal\Core\Form\FormInterface[]
   */
  protected $innerForms = [];

  /**
   * The ComboForm constructor needs to initialize the inner form objects
   * that this form will later use.
   *
   * Because both the user and the node forms are entity forms then an entity
   * object needs to be assigned to them.
   *
   * Because the node entity has bundle, the bundle (type) must be defined
   * before the form is generated.
   *
   * @TODO If the node type is customizable then a custom controller is needed.
   *
   * @TODO should this form allow edits? If so then the form objects should
   *       be assigned with the edited entities.
   */
  public function __construct() {
    $this->innerForms['user'] = \Drupal::entityTypeManager()
      ->getFormObject('user', 'default')
      ->setEntity(User::create());

    $this->innerForms['node'] = \Drupal::entityTypeManager()
      ->getFormObject('node', 'default')
      ->setEntity(Node::create([
        'type' => 'article'
      ]));
  }

  /**
   * {@inheritDoc}
   */
  public function getFormId() {
    return implode('__', [
      'combo_form',
      $this->innerForms['user']->getFormId(),
      $this->innerForms['node']->getFormId()
    ]);
  }

  /**
   * The build form needs to take care of the following:
   *   - Creating a custom form state object for each inner form (and keep it
   *     inside the main form state.
   *   - Generating a render array for each inner form.
   *   - Handle compatibility issues such as #process array and action elements.
   *
   * {@inheritDoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state) {

    $form['#process'] = \Drupal::service('element_info')->getInfoProperty('form', '#process', []);
    $form['#process'][] = '::processForm';

    foreach ($this->innerForms as $key => $inner_form_object) {
      $inner_form_state = static::createInnerFormState($form_state, $inner_form_object, $key);

      // By placing the actual inner form inside a container element (such as
      // details) we gain the freedom to alter the wrapper of the inner form
      // with little damage to the render element attributes of the inner form.
      $inner_form = ['#parents' => [$key]];
      $inner_form = $inner_form_object->buildForm($inner_form, $inner_form_state);
      $form[$key] = [
        '#type' => 'details',
        '#title' => $this->t('Inner form: %key', ['%key' => $key]),
        'form' => $inner_form
      ];

      $form[$key]['form']['#type'] = 'container';
      $form[$key]['form']['#theme_wrappers'] = \Drupal::service('element_info')->getInfoProperty('container', '#theme_wrappers', []);
      unset($form[$key]['form']['form_token']);

      // The process array is called from the FormBuilder::doBuildForm method
      // with the form_state object assigned to the this (ComboForm) object.
      // This results in a compatibility issues because these methods should
      // be called on the inner forms (with their assigned FormStates).
      // To resolve this we move the process array in the inner_form_state
      // object.
      if (!empty($form[$key]['form']['#process'])) {
        $inner_form_state->set('#process', $form[$key]['form']['#process']);
        unset($form[$key]['form']['#process']);
      }
      else {
        $inner_form_state->set('#process', []);
      }

      // The actions array causes a UX problem because there should only be a
      // single save button and not multiple.
      // The current solution is to move the #submit callbacks of the submit
      // element to the inner form element root.
      if (!empty($form[$key]['form']['actions'])) {
        if (isset($form[$key]['form']['actions'][static::MAIN_SUBMIT_BUTTON])) {
          $form[$key]['form']['#submit'] = $form[$key]['form']['actions'][static::MAIN_SUBMIT_BUTTON]['#submit'];
        }

        unset($form[$key]['form']['actions']);
      }
    }

    // Default action elements.
    $form['actions'] = [
      '#type' => 'actions',
      static::MAIN_SUBMIT_BUTTON => [
        '#type' => 'submit',
        '#value' => $this->t('Save'),
        '#validate' => ['::validateForm'],
        '#submit' => ['::submitForm']
      ]
    ];

    return $form;
  }

  /**
   * This method will be called from FormBuilder::doBuildForm during the process
   * stage.
   * In here we call the #process callbacks that were previously removed.
   *
   * @param array $element
   *   The form element.
   * @param \Drupal\Core\Form\FormStateInterface $form_state
   * @param array $complete_form
   * @return array
   *   The altered form element.
   *
   * @see \Drupal\Core\Form\FormBuilder::doBuildForm()
   */
  public function processForm(array &$element, FormStateInterface &$form_state, array &$complete_form) {
    foreach ($this->innerForms as $key => $inner_form) {
      $inner_form_state = static::getInnerFormState($form_state, $key);
      foreach ($inner_form_state->get('#process') as $callback) {
        // The callback format was copied from FormBuilder::doBuildForm().
        $element[$key]['form'] = call_user_func_array($inner_form_state->prepareCallback($callback), array(&$element[$key]['form'], &$inner_form_state, &$complete_form));
      }
    }

    return $element;
  }

  /**
   * {@inheritDoc}
   */
  public function validateForm(array &$form, FormStateInterface $form_state) {
    /** @var \Drupal\Core\Form\FormValidatorInterface $form_validator */
    $form_validator = \Drupal::service('form_validator');
    foreach ($this->innerForms as $form_key => $inner_form) {
      $inner_form_state = static::getInnerFormState($form_state, $form_key);

      // Pass through both the form elements validation and the form object
      // validation.
      $inner_form->validateForm($form[$form_key]['form'], $inner_form_state);
      $form_validator->validateForm($inner_form->getFormId(), $form[$form_key]['form'], $inner_form_state);

      foreach ($inner_form_state->getErrors() as $error_element_path => $error) {
        $form_state->setErrorByName($form_key . '][' . $error_element_path, $error);
      }
    }
  }

  /**
   * {@inheritDoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {
    /** @var \Drupal\Core\Form\FormSubmitterInterface $form_submitter */
    $form_submitter = \Drupal::service('form_submitter');

    foreach ($this->innerForms as $key => $inner_form) {
      $inner_form_state = static::getInnerFormState($form_state, $key);

      // The form state needs to be set as submitted before executing the
      // doSubmitForm method.
      $inner_form_state->setSubmitted();
      $form_submitter->doSubmitForm($form[$key]['form'], $inner_form_state);
    }
  }

  /**
   * Before returning the innerFormState object, we need to set the
   * complete_form, values and user_input properties from the main form state.
   *
   * @param \Drupal\Core\Form\FormStateInterface $form_state
   *   The main form state.
   * @param string $key
   *   The key used to store the inner form state.
   * @return \Drupal\Core\Form\FormStateInterface
   *   The inner form state.
   */
  protected static function getInnerFormState(FormStateInterface $form_state, $key) {
    /** @var \Drupal\Core\Form\FormStateInterface $inner_form_state */
    $inner_form_state = $form_state->get([static::INNER_FORM_STATE_KEY, $key]);
    $inner_form_state->setCompleteForm($form_state->getCompleteForm());
    $inner_form_state->setValues($form_state->getValues() ? : []);
    $inner_form_state->setUserInput($form_state->getUserInput() ? : []);
    return $inner_form_state;
  }

  /**
   * After the initialization of the inner form state, we need to assign it with
   * the inner form object and set it inside the main form state.
   *
   * @param \Drupal\Core\Form\FormStateInterface $form_state
   *   The main form state.
   * @param \Drupal\Core\Form\FormInterface $form_object
   *   The inner form object
   * @param string $key
   *   The key used to store the inner form state.
   * @return \Drupal\Core\Form\FormStateInterface
   *   The inner form state.
   */
  protected static function createInnerFormState(FormStateInterface $form_state, FormInterface $form_object, $key) {
    $inner_form_state = new FormState();
    $inner_form_state->setFormObject($form_object);
    $form_state->set([static::INNER_FORM_STATE_KEY, $key], $inner_form_state);
    return $inner_form_state;
  }

}


How to programmatically set user state to "active"

You can use a combination of user_load_multiple() and user_save() to update the status property of the users:

$uids = db_query('SELECT uid FROM {users}')->fetchCol();
foreach (user_load_multiple($uids) as $account) {
  $account->status = 1;
  user_save($account);
}

It's worth bearing in mind that any mail notifications you have set to inform users of their account status will be invoked using this method.

If you don't want that to happen I think you'll have to go directly into the {users} table and set the status manually (not recommended):

db_update('users')
  ->fields(array('status' => 1))
  ->execute();


These are robot spam registrations. To my eye, they look like they originate from XRumer.  XRumer knows how to complete the registration process of LoginToboggan and knows how to solve simple CAPTCHAs, so these measures will not stop XRumer from registering.

The modules I've found to be most effective against robot spam registrations are MotherMayI and CAPTCHA Riddler.

Both these are based upon the same idea: To register, the registrant should be able to answer a simple question where the answer is obvious to a human, but not to a robot.

If you site's language is not English, almost any question will work, since robots do not have multi-language skills.

CAPTCHA Riddler lets you set up a "pool" of questions (so a returning robot will face a different question on each visit).  MotherMayI only allows one question, but let you set up an RegExp for the answer and also has allows for a longer text to "hint" to a human what is expected.  I currently prefer MotherMayI, but check out both.

PS: So far, no spam robot has managed to register at any of my 20 sites (all that accepts registrations by the public are protected by MotherMayI).


Create a module that add text/image to a specific type nodes

Various ways of doing this. Either edit your tpl file. Create a node--article.tpl.php in your theme folder (copy the syntax from node.tpl.php) and modify the code to add your desired label. If you need to print username then the global $user is available. Just define it as global and access username as $user->name.

Or you could use Panels module. It's very flexible and powerful.

For creating custom module to do this, there are various approaches. One good way is this:

In your custom mymodule.module file, use the hook_node_view like this:

function mymodule_node_view($node, $view_mode) {
    if ($node->type=="article"){
        if ($view_mode == 'full'){
            $node->content['my_extra_content'] = array(
                 "#markup"=> 'Made by me!',
                 "#weight"=> 100
              );
           }
         return $node;
   }
}

After this, Made by me should appear at the bottom of each node. If you want it to appear at the top, then just modify the weight and give it some negative value.


Send report of all changed or updated content in past day?

Have you loooked at message notify?
Have a look at the blog post by gizra
or watch the video, message notify allows you to use view as the body of the email.


I want my users to login through 'Last Name', rather than 'Password'

You can do this by using a module called String overrides to redefine the strings exposed to your users during login and on their profile page.

Navigate to Administration » Configuration » Regional and language  » String overrides and fille in the following and click "Save configuration":

Now, login will look like this to your users:

Note that this just renames the fields.  This means that the last name will not have its own field and it will not be displayed on the user's profile page.  It is not clear from your question whether this will be a problem.

However, if you want a real "Last name" field, and you want to use this field for authentication, you can do this by creating a small module that uses hook_form_FORM_ID_alter() to make a couple of changes to the login form:

Hide the password field.
Add "Last name" as a field.

Now, in the form validation, check that the value of the "Last name" field matches the last name in the user's profile, and if it does, fill in the hidden password field with the correct password.  If you use the same password for all users in this set up, it can be hard-coded in your form validation.  This will make Drupal take care of all the heavy lifting of creating a session, book-keeping of logins, etc.

As for the (in)security of using the last name instead of a real password as a login credential, I'll take your word for security not being an issue here.  However, I am puzzled by why want this, so I have added a question about it as a comment.


How to aggregate results of search engines using drupal

If you have links to RSS feeds, you can use the Aggregator module that comes with Drupal; the alternative is the Feeds module.
Otherwise, if you want to import the content as nodes, you can use the Feed Import module.


How can I add a captcha to this HTML form

I'd say you have two obvious choices :

either you reimplement the form using the drupal webform module and then add some captcha module like recaptcha,
or you keep going the tought html-only route and just see how you can integrate a captcha library within your "html within the content editor" form...

I'd say the first strategy is wiser. Particularly since your form is fairly straighforward.


I finally figured out the answer: the functionality has simply not been coded. Applying the patch from this issue: https://www.drupal.org/node/2792653 (patch #95 is the latest right now) will add a checkout pane for entering coupon codes. It is still not available on the cart page as you would expect in a webshop, but at least visitors can enter a coupon code.

You can place the checkout pane using Commerce->Configuration->Checkout flows->pick your flow by clicking 'edit'->Coupon redemption pane.


Can taxonomy tags/terms be more than one word?

I found Only works with first taxonomy term views3 D7 which is about the same issue you have.

This is what comment #18 and #20 say. You might also look at comment #28.

  This works very well, but it only works with the first tag/taxonomy term applied to a node. For instance, if a post was tagged Cheese, Recipe, Tomatoes, and Pasta, it would show other posts tagged with Cheese, but not those tagged with Recipe, Tomatoes, or Pasta. Is there a way to get it to consider all taxonomy terms, not just the first one?

  I just tried this solution and it seems to work. Just select "Reduce Duplicates" then under "More" select "Allow multiple values." That's it, you should have all the things being printed out and not just things related to the first term. Let me know if this helps.


How to allow all commerce customers to use their billing address as their shipping address, in Commerce Shipping 2.X?

Go to Checkout Settings (admin/commerce/config/checkout). Find Shipping Information pane and click configure.

You'll see setting for copying billing address right there (screen below)


Redirection after certain node type creating

Try putting your destination as GET destination parameter, i:e $_GET['destination']. The GET destination parameter gets the highest preference


Load content without refreshing page in views

What you need is the views load more module

  This module has some very key differences then the other load more
  module.

  Provide ajax/no-ajax views load more
  Works with views default ajax implementation, no hacks (check/uncheck ajax)
  Supports the Waypoints module for loading on various points, Such as when the scroller is visable on the page.
  Supports the Fade effect when loading new content


Facebook like photo gallery with comments, tag photo, share etc

To annotate images in Drupal 7: Imagefield Marker
http://drupal.org/project/imagemarker

See also: Image Annotations in Drupal 7

Very good multiple image uploader in Drupal 7:
Media module
http://drupal.org/project/media
(Quick way to get this is to create a free drupalgardens.com account and export the whole Drupal 7 code)

Comments are built-in in Drupal 7 for many content types.

Consider also:
http://drupal.org/project/disqus
(Drupal support for DISQUS a discussion comment system for integration with various social networking sites)

Also: Facebook Comments module:
http://beacon9.ca/labs/drupal-7-facebook-comments

I would suggest integrating comments with an existing social network as their authentication policies (particuarly Facebook's for example) can discourage trolls, spam and provide you with a centralised means of managing the comments, as well as spreading awareness of your site as their comments on your site are seen by their friends in their feeds).


Translation of a field overwrites the original language value

I suggest looking and experimenting with the following settings:

admin/config/regional/language/detection

You can also check if the checkbox "Enable interface translation to English" is checked. That may cause this problem.
admin/config/regional/language/edit/en

Question : One thing didn't become clear for me:
"It is the same as it was before, but on the web page, I have two nodes with different translations." - what is the url of the web page. Is it a page constructed with views, panels, or just node/nid ?
Regards,
Oleg


$model = entity_load_single('field_collection_item', $model_id);
$node = $model->hostEntity();
echo $node->nid;


You can use Markup module using which you can add text or HTML which will display a picture..

Project page says

  This module adds the ability for site admins to add "Markup" widgets
  to the form. These essentially let designers of cck content-types
  insert additional markup into the node/edit form to display to
  content-authors. This is the equivalent of adding additional elements
  to $form of the type '#markup'.


The module Devel provides a searchable list (/devel/container/service).

For the command line use Drupal Console:

drupal debug:container


Simple&efficient slider module for the following purpose

Views Slideshow isn't a bad way to go. It will probably take some working with css/templates/views to get it to display the way you want, but it is the most used module, so if you find yourself up against a wall using it, there's a good chance someone's already has done it and has written a tutorial, or would answer a question.

There are a few other modules out there you could look at. A quick search I found this page, which has a decent list

Also a very in-depth comparison on the different modules out there from drupal.org


How to tell what filename to select when using twig debugging in drupal 8 theming

It depends on how specific you want to get. If you made a template for block.html.twig it would effect every block. block--system.html.twig would effect all of the system blocks, and block--system-branding-block.html.twig would effect the every branding-block subset of the system-block. And block--octo-branding.html.twig could possibly be every block that is using the octo-branding block plugin.

I'm not positive what template is what in your case since I don't know what is named what in your theme and plugins, but that's my best guess. Regardless the rule of thumb is it goes from most specific to most broad in order. And Drupal will use whatever template is most specific that applies in every case. For example.

I have a basic page located at /node/18.
Near the top it says

<!-- FILE NAME SUGGESTIONS:
   * page--node--18.html.twig
   * page--node.html.twig
   x page.html.twig-->

If I made a template for page.html.twig, it would load that template for every page. If I made a template for page--node.html.twig it would use that template for every page for nodes. If I made a page--node--18.html.twig it would use that template only for that specific node. If I've already made any combination of those templates Drupal will use the most specific one.


What's the new code that you've added to the template.php file? When I run into problems like this, in the 95% of cases I make a mistake and the cache clearing works, but my new code won't be recognized because of errors.

Basically, if you're able to run

drush cc all

without any warnings or errors, the cache clearing succeed and it should tell you that

'all' cache was cleared [success]


Display taxonomy term description when mouse hovers

You could try using beautytips and views. There is an old Drupal 6 video explaining how to do it for feeds, showing a part of the body when hovering the title in a list: http://www.veoh.com/watch/v200239557fzYsENz.
It is still pretty much accurate on the conception of it.


Run a boolean test function on form submit

You should do this in validation handler. In hook_form_alter (or in your form definition function), add $form['#validation'][] = 'mymodule_form_validate';. Then, add this code:

function mymodule_form_validate($form, &$form_state) {
  if (!mymodule_dates_valid($form_state)) { // Return boolean here.
    form_set_error('date_field', t('Invalid dates'));
  }
}


Could anyone suggest a Drupal database versionning tool?

I think the Backup and Migrate module will help you. Here is a quote about it (from the module's project page):

Back up and restore your Drupal MySQL database, code, and files or migrate a site between environments. Backup and Migrate supports gzip, bzip and zip compression as well as automatic scheduled backups.
With Backup and Migrate you can dump some or all of your database tables to a file download or save to a file on the server or offsite, and to restore from an uploaded or previously saved database dump. You can choose which tables and what data to backup and cache data is excluded by default.


let the user choose role upon registration

If you love custom coding and if you already have a custom module, I would recommend to do this with a custom module rather than using Profile 2 and other related modules. I personally prefer to write custom modules because it will let you get exactly what you are looking for.
But you still need to use Auto Assign Role module to let user choose a user role on registration.

My solution is to show/hide the respective profile fields upon user role selection on the registration form. It would not redirect to the respective profile page.
You can create profile fields at admin/config/people/accounts/fields and you can export them to the registration form, but they cannot be created by role. What you would need to do is to show/hide each field by role from hook_form_alter and use #ajax attribute.

Here is an code snippet for this purpose. I did not test the code. Just for example.

function yourmodule_form_alter(&$form, &$form_state, $form_id) {

    if($form_id == 'user_register_form' || $form_id == 'user_profile_form'){

        $form['autoassignrole_user']['user_roles']['#ajax'] = array(
          // #ajax has two required keys: callback and wrapper.
          // 'callback' is a function that will be called when this element changes.
          'callback' => 'ajax_form_alter',
          // 'wrapper' is the HTML id of the page element that will be replaced.
          'wrapper' => 'replace_field_div',
          // Don't show any throbber...
          'progress' => array('type' => 'none'),
         );

        # This profile field will be shown or hidden when the respective "user_roles" is selected
        $form['field_first_name']['und'][0]['value']['#type']       = 'hidden';
        $form['field_first_name']['und'][0]['value']['#required']   = FALSE;
        $form['field_first_name']['und'][0]['value']['#type']       = 'hidden';
        $form['field_first_name']['und'][0]['value']['#prefix']     = '
';
        $form['field_first_name']['und'][0]['value']['#suffix']     = '
';

        // An AJAX request calls the form builder function for every change.
        // We can change how we build the form based on $form_state.
        if(isset($form_state['values']['autoassignrole_user']['user_roles']) && $form_state['values']['autoassignrole_user']['user_roles'] == {rid_here}){
            # when the respective user roles is selected, show this field and set required.
            $form['field_first_name']['und'][0]['value']['#type']       = 'textfield';
            $form['field_first_name']['und'][0]['value']['#required']   = TRUE;
        }else{
            # when the respective user roles, hide this field and remove required.
            $form['field_first_name']['und'][0]['value']['#type']       = 'hidden';
            $form['field_first_name']['und'][0]['value']['#required']   = FALSE;
        }
    }
}
/**
 * Callback for user_roles
 *
 * On an ajax submit, the form builder function is called again, then the $form
 * and $form_state are passed to this callback function so it can select which
 * portion of the form to send on to the client.
 *
 * @return renderable array (the textfield element)
 */
function ajax_form_alter($form, $form_state){
    return $form['field_first_name'];
}

You may notice that you have to use ['und'][0]['value'] for the profile field to tweak its attributes. If you are not sure about this, you can print $form for debugging purpose:

dpm($form); // if Devel module is enabled
echo '
'; print_r($form); echo '
'; // if you don't have Devel module

If there is another better solution, please post it and it will be appreciated.


Is it possible to build a high-traffic Drupal community website without hacking?

Drupal can serve high-load sites without hacking.

You need to use memcache to store Drupal caches not in db but in memory.
For Drupal 6 you need to use Pressflow core.
You need to use Drupal cache mechanism, its configuration much depends on what users do you have most - anonymous or authenticated.

For anonymous users Varnish can dramatically increase site performance.

Don't forget to configure cache for each View and Panel on you site.

Also Drupal 7 can work with MySQL's master-slave architecture.

Don't forget to use cdn for loading static content such as images, css, js and files uploaded by users.

If you will have search on your site - I advise you to use Apache Solr.

I have created several high-loaded sites and haven't hacked any query that was provided by Drupal core. In some cases only queries that were provided by views module were altered - but this is not a hack.

But don't think you can built a high-load Drupal site without deep knowledge of Drupal architecture, API and lot of useful modules.


How to get all the fields defined by a particular module?

hook_field_info() defines field types in Drupal 7, so I think you're actaully interested in field types, not fields?

If so, field types, like any other plugin definition have a provider key, if you want to get the field types of a certain modules, call \Drupal::service('plugin.manager.field.field_type')->getDefinitions() and then filter on the provider key:

$field_types = \Drupal::service('plugin.manager.field.field_type')->getDefinitions();
$field_types = array_filter($field_types, function (array $definition) {
  return $definition['provider'] == 'yourmodule';
});

Code example written in browser and untested.


Getting the image URL from a field_image on a node

Here is an update version of for this answer after 8.0.x. This base on @joelpittet comment.

{{ file_url(node.field_image.entity.fileuri) }}


Any module for user to custom make a schedule from listed options?

I haven't done it persay. But, having attended many Drupal Camp's and 1 Drupal Convention I know the Conference Organization Distribution (COD) has this basic feature-set built it.

COD include the concept of Sessions, and session collections. I know that users can select tracks to register for (typically in a day-calendar view) and then a users session list appears on the users dashboard/account page.

I would recommend either downloading the COD distribution and using it directly, or viewing the install profile of COD and the included content types, Fields, Views, Rules, etc and reverse engineering the functionality you want on a smaller scale.


Is there a way to dynamically resize remote images in drupal 7?

Try out Imagecache External module

  Imagecache External is a utility module to allow you to use
  imagecache(D6)/image derivatives (D7) with external images.


How to know how many elements are processed in the finish callback?

Reading the Batch Process in Drupal 8 and Drupal 8 Batch Example articles I found the answer.

The key is in the

//Message to show during each execution of the callback function
$context['message']
//Array with the total of processed items.
$context['results']

So, the solution is in the operations callback function, now the functions is like this and it works:

function process_line_saint_du_jour($line, &$context) {
  //Custom Code
  $info = str_getcsv($line, ";", '"');
  $context['results'][] = $info[3];
  $context['message'] = t('Migrating Saint du jour @day', array('@day' => $info[3]));
}


How to know where to place a block in the body of my page

If you're new to Drupal 7, I also encourage you to look into placing your blocks using the Context module, rather then hard-coding their location through theming or something like that.  It's also more flexible than what you can just do through the block admin interface.

Here's a simple example of using the Context module to place a block in a certain location on a single page or a specific content type:

Once you've downloaded and enabled the module, go to admin/structure/context
Click the "Add" link to add a new context
Fill in the first few fields as shown below (name, tag, conditions to be met to fire this context)

Before saving, in the "Reactions" section, select which blocks you want displayed and WHERE when the conditions above are met


Remove colons from Drupal form fields/labels

Create your own implementation of theme_form_element().
The offending semicolon is in $t('!title: !required', ...), and would need to be removed in both locations.

Not the easiest thing to change, but at least it's possible without hacking core!


Custom region twig template for region into node twig template

I think your filename is incorrect. It should be:

region--node-col-1.html.twig.

Enable twig debugging to see the suggestions output in the HTML source, which will paint a better picture of what Drupal is expecting to see as template overrides.


Use the trans tag in Twig without escaping HTML

AFAIK the Twig trans tag in Drupal 8 was implemented to ease translations to themers that were already familiar with Twig.

Under the hood, it's working with the same kind of translation strings as the regular Drupal translation function t() or the Drupal Twig filter |t, whereas all variables you are using within the trans block are handled as @variable or %variable placeholder within the translation strings.

These placeholders within the translation function always escape HTML before being inserted to the translation. No matter how you try to not escape the values you pass in, except you pass in a FormattableMarkup object.

Unsanitized variables ({{ variable|raw }} in Twig templates or !variable in translation strings) are deprecated for Drupal 8 translations and won't work in latest 8.x Drupal versions. The translation API description is a little outdated.

For your use case, you may just add the HTML link tag to your translation string and make the link URL itself the variable. Unfortunately, the Twig trans tag doesn't support that kind of variable yet. (Compare this core issue.) So you should use the t filter instead:

{{ 'A link example in a translation.'|t({ ':url': url }) }}

The above example matches the translation strings:

en: A link example in a translation.

de: Ein Beispiel-Link in einer Übersetzung.


I think the easiest way to do this would be to make the key the same as the value.  For instance:

$form['education'] = array(
  '#title' => t('Education'),
  '#type' => 'select',
  '#description' => 'Select your higher education.',
  '#options' => array(
    '_none' => t('-- SELECT --'),
    'B.tech' => t('B.tech'),
    'MCA' => t('MCA'),
    'MBA' => t('MBA'),
    'Graduate' => t('Graduate')
  ),
  '#required' => TRUE,
);

You need to pass values in associative array


Will migrating content types be possible?

I guess the best place to search for upgrade process is UPGRADE.txt file. Here you can find the step-by-step approach to follow in upgrading the site from Drupal 6/7 to Drupal 8.

Drupal 8 core will include a robust data migration API: https://drupal.org/node/2121299, part of the IMP initiative: https://groups.drupal.org/imp . Also you can check the recently updated list of modules that are included in Drupal 8 core: http://blog.merge.nl/2014/01/21/drupal-which-drupal-7-modules-went-into-drupal-core

Few of the links that you check:

Getting your site ready for Drupal 8: http://www.acquia.com/blog/getting-your-site-ready-drupal-8
Drupal 8 - Improved upgrade process: http://www.acquia.com/blog/d8migrate
Converting modules from Drupal 7 to Drupal 8:http://webchick.net/upgrade-modules-d8
Converting 7.x modules to 8.x: https://drupal.org/update/modules/7/8


Try changing

if (isset($row->field_image['und'][0]['value']) == 1) {

to

if (!empty($row->field_field_image)) {


The issue here is that there are probably two form IDs for the form. One is the form_id, and the lesser known one is the base_form_id. If a Drupal form is used more than once on a page, weird things come about. To get around this, form developers can set the form ID to be dynamic, so that each time the form is built, it's given a unique ID. Example:

class FooBarForm implements FormInterface {

  protected $id;

  public function __construct($type) {
    $this->id = $id;
  }

  public function getFormId() {
    return 'foo_bar_form-' . $this->id;
  }
}

class FooRouteController {

  public function fooBarForm(ContentEntityInterface $entity) {
    $form = new FooBarForm($entity->id());

    return \Drupal::formBuilder()->getForm($form);
  }
}

Forms can also implement BaseFormIdInterface, which requires them to implement BaseFormIdInterface::getBaseFormId(). The form ID returned from this hook will be the same for all instances of the form, and NOT dynamic.

class FooBarForm implements FormInterface, BaseFormIdInterface {

  protected $id;

  public function __construct($type) {
    $this->id = $id;
  }

  public function getFormId() {
    return 'foo_bar_form-' . $this->id;
  }

  public function getBaseFormId() {
    return 'foo_bar_form';
  }
}

The relevance of this is that there are actually multiple form alter hooks called, in this order:

hook_form_alter()
hook_form_BASE_FORM_ID_alter()
hook_form_FORM_ID_alter()

Looking at your hook - module_form_views_form_commerce_cart_form_orange_default_42_alter, it would appear you are implementing the third hook. The ID of 42 is being appended as part of the dynamic Form ID.

To find out the base form ID (if one exists), you can call the following in your form:

$form_state->getBuildInfo()

This will give you the build info, which you can dump with kint() or however you do your debugging. In the build info will be the base form ID (assuming it's set). If it is, you can implement the second form alter hook above, using that base form ID.


Why should I not put content in the development environment?

I think that either what you were told was not explained correctly, or that you misunderstood.

You can put content on development environments. And you should, to test.

But that content won't be migrated to production. If you want that content on production, you'll need to create it on production. Or, you can create a migration strategy (using the Migrate UI for example) to migrate content between environments. But this generally takes a good bit of work, and isn't usually done.


Facebook Oauth and sending messages to facebook users

When a user registers or connects with his/her Facebook account, your web application receives that person's Facebook username which you can then store in a field.

On Facebook, you can receive external messages at username@facebook.com.

Now all that's left to for you to do is set up Rules module (maybe Facebook Rules module can help) so that if a user has connected his account on your website with his Facebook account an email is sent to username@facebook.com.


Handle formatting of longtext value for entity wrapper

You just need to specify a format for your text value:

$entity->body->set(array('value' => $body[0], 'format' => 'full_html'));


Running batch API in tests should work just fine, although there is an issue with the testbot.

Make sure you are always using curly braces for your tables, that's the usual issue when something like this happens. So for example SELECT * FROM {node}.

Edit:

Two things wrong with your code, as written in the comments.

You are not calling batch_process() in your code, so the batch is never executed within the tests.
My initial answer was not 100% correct. You can not trigger batch runs directly within your test code. A batch requires direct interaction with the browser and it is not possible to run tested batches (simpletest is already running as a batch run). What you need to do is create a test module, implement hook_menu() with a page callback and then call batch_set()/batch_process() there.


Updating Views Module Not Working 7.x-3.13 --> 7.x-3.15

I checked Views module versions from 7.x-3.13 to 7.x-3.15 and it seems that there are no changes needed to be applied to the database (the views.install file didn't change between the two versions). I think you need just to override the module directory with the new version and clear all caches.


"Unit testing" and "multi-site" are in direct conflict with each other. Multi-site is definitely an integration/functional testing concern.

What you can do in a unit test to help guarantee that things are working correctly for a multi-site setup is to unit test only the logic that is computing different results for each site in the multi-site setup. Use a @dataProvider to test the input for different sites in a multi-site setup.

The result of that logic should vary by the url.site cache context. You can assert the presence of that cache context in the X-Drupal-Cache-Contexts response header in your integration/functional test.

IOW:
- unit test for testing various inputs, with a @dataProvider
- functional test that asserts the presence of url.site cache context

Together, they guarantee things work correctly.


Collection is required in solr configuration. You'll need to create a collection you want to use for your site. Create using below command or by user interface of solr, then use the same name for the collection.

  sudo su - solr -c "/opt/solr/bin/solr create -c COLLECTION_NAME -n
  data_driven_schema_configs" // Only for ubuntu

Replace COLLECTION_NAME with the name of your collection you want.


Services can not create an user with role

Just install Auto Assign Role Module.

Then use this following json code:

{"name":"user3431","pass":"kes35@r4","mail":"user343@sample.com","status":"1", "user_roles":{"6"}}


Use value from buildForm() in submitForm()

Typically, the $form_state object can be used to stash that data. $form_state->getStorage() references a simple array that you can put whatever you like inside, which you can then retrieve in submitForm() the same way.


How to disable the revision feature completely?

Field SQL norevisions actually solves exactly that problem by

  Field SQL norevisions provides a field storage backend using SQL that does not create a revision table for each field.

I haven't tried it, but anything written by Alex Pott can probably be expected to work properly.

I assume however that this also goes for all entites as it changes the storage backend.

Without a new storage engine, the below is the original, less useful, answer:

The revision tables must be available, and they must contain data.
Unfortunately, you just cannot get rid of them without completely breaking Field API, the reason being that the revision, contrary to their name, is the data storage.

Perhaps it's possible, with more database wizardry than I know, that you can set the regular field_data_* tables to be mirrors of each revision table. That might work.

Other than that, I can't think of any solution that would do this.

Edit: While I don't know if this will have, "interesting", side effects, I asked the wizards if this was at all doable. Can I have one table be an alias or symlink to another?.

Edit 2: Actually, it seems like much wizardry isn't needed at all. One could try replacing the field_data_* tables with a View that replicates the corresponding revision tables. Again, I haven't tried this, and my understanding of the interals of field api are a bit lacking, but it certainly could work.

Edit 3: (Yes, this is getting silly), someone pointed out that the above will cause the same data to be written twice, now to the same table. So it probably wont work anyway.


In the Twig documentation, there is an entry that can help you out: https://twig.symfony.com/doc/2.x/filters/nl2br.html

{{ "I like Twig.\nYou will like it too."|nl2br }}

will output:

I like Twig.<br />
You will like it too.

So inside a string, you could use \n or the function nl2br at the end of it.


How do I programmatically set up multiple default flags?

Figured it out. To have multiple default flags you simple do this:

function mymodule_flag_default_flags() {

$flags = array();

$flags[‘FLAG_NUMBER_1’] = array(
    'content_type' => 'node',
    'title' => '',
     // Rest of flag data
);

$flags[‘FLAG_NUMBER_2’] = array(
    'content_type' => 'node',
    'title' => '',
     // Rest of flag data
);

return $flags;

}

where [‘FLAG_NUMBER’] is the machine name for the flag.


Change Port number to 465 or 587 in case of SMTP Server: smtp.gmail.com and 587 in case of SMTP Server: smtp.live.com.

As per : https://www.arclab.com/en/kb/email/list-of-smtp-and-pop3-servers-mailserver-list.html.


Overwrite jquery.ui.slider.min.css generated by jQuery Update module

The solution is to insert in your themes template.php the following:

function mytheme_css_alter(&$css) {
  if (isset($css['misc/ui/jquery.ui.theme.css'])) {
    $css['sites/default/modules/jquery_update/replace/ui/themes/base/jquery.ui.theme.css']['data'] = drupal_get_path('theme', 'mytheme') . '/mytheme_jquery_design/jquery.ui.theme.css';
  }
}