Finally, it works :D, I'll just put this answer here to help how still don't know how to login user via my custom Web Services API, i had to manage the cookies from the frontend, I use symfony, after sending a POST request to /{endpoint}/user/login, and receive the response that will look like this:

{
    "sessid": "ZkJ26dMEQQ-K3VkE9zv2Cni2lWergSOOnPlF3jkiF-Q",
    "session_name": "SESS948facaca231cedd9a2a526239dcb6dc",
    "token": "icfD3CNT4r4QAlEGiYmqzez0MVmsPbAowVR8HtfaD4Y",
    "user": {
        "uid": "1",
        "name": "admin",
        "mail": "contact@headless.com",
        "theme": "",
        "signature": "",
        "signature_format": null,
        "created": "1459037019",
        "access": "1459439836",
        "login": 1459440402,
        "status": "1",
        "timezone": "Europe/Paris",
        "language": "",
        "picture": "0",
        "init": "contact@headless.com",
        "data": false,
        "roles": {
            "2": "authenticated user"
        }
    }
}

i create a cookie with (any name) and the value will be "session_name=sessid", don't forget the "=".
and finally to see if the user is logged in, you need the token and the cookie that you created, send a POST request to {endpoint}/system/connect WITH this HEADERS:

X-CSRF-Token: token from the login response
Cookie: SESS948facaca231cedd9a2a526239dcb6dc=ZkJ26dMEQQ-K3VkE9zv2Cni2lWergSOOnPlF3jkiF-Q (session_name=sessid)

and voila :D, you get a response like this:

{
    "sessid": "ZkJ26dMEQQ-K3VkE9zv2Cni2lWergSOOnPlF3jkiF-Q",
    "session_name": "SESS948facaca231cedd9a2a526239dcb6dc",
    "user": {
        "uid": "1",
        "name": "admin",
        "mail": "contact@headless.com",
        "theme": "",
        "signature": "",
        "signature_format": null,
        "created": "1459037019",
        "access": "1459440402",
        "login": "1459440402",
        "status": "1",
        "timezone": "Europe/Paris",
        "language": "",
        "picture": "0",
        "init": "contact@headless.com",
        "data": false,
        "sid": "ZkJ26dMEQQ-K3VkE9zv2Cni2lWergSOOnPlF3jkiF-Q",
        "ssid": "",
        "hostname": "127.0.0.1",
        "timestamp": "1459440402",
        "cache": "0",
        "session": "",
        "roles": {
            "2": "authenticated user"
        }
    }
}

i hope my answer help any one how is looking for how to login users via Drupal Services.


Related Terms Block Based on Terms Fields

I was able to get this done by adding my code in into my contextual filter which would be Taxonomy Term:[You term field name].

This is the code I used.

$path = drupal_get_path_alias($_GET['q']);
$path = explode('/', $path);
$termname = array_pop($path);
$termname = str_replace("-", " ", $termname);
$terms = taxonomy_get_term_by_name($termname );
$term = reset($terms);
$term->tid;
$term_list = taxonomy_term_load($term->tid);
return $term_list->field_companies_industry['und']['0']['value'];


The summary value will only be set if someone has actually filled out the summary textfield when editing the node. You'll need to do the trimming yourself in code. Drupal has functions such as https://api.drupal.org/api/drupal/modules%21field%21modules%21text%21text.module/function/text_summary/7.x or views has https://api.drupal.org/api/views/views.module/function/views_trim_text/7.x-3.x

So you'll need to do a check to see if the summary value exists, if it doesnt use the main text and trim it with the functions or something similar above


No block to display at block settings in any contributed theme

Go to the Block Layout page at /admin/structure/block, then Place a Block in the selected region and select Simplenews subscription. Once saved, the block should be available.

Source: Simplenews on Drupal 8 - subscription block.


How do I overwrite the variables in my theme?

If you are wondering why the <span> tags don't appear in the button output from rate_preprocess_test(), that is probably because mytheme_preprocess_test() is called after rate_preprocess_test().
I take rate_preprocess_test() is defined inside a module; in that case the preprocess function defined inside the module is invoked before the implementation of the preprocess function contained in the theme, as reported in the documentation for theme(), which lists the preprocess functions in the following order:

template_preprocess(&$variables)
template_preprocess_HOOK(&$variables)
MODULE_preprocess(&$variables)
ENGINE_engine_preprocess(&$variables)
ENGINE_engine_preprocess_HOOK(&$variables)
ENGINE_preprocess(&$variables)
ENGINE_preprocess_HOOK(&$variables)
THEME_preprocess(&$variables)
THEME_preprocess_HOOK(&$variables)


What is the proper condition to check for a select list value of none?

Make sure to add a Rules condition Entity has field (related to your field field-client as shown in your first Rules Condition). For a video tutorial that illustrates the importance of this Entity has field condition, refer to Data types and data selection, especially what is shown between about 13:30 and 17:30 in it.

If that doesn't help, you may want to do some Rules debugging, as explained in the answer to "How can I display the value of a variable inside a condition?".


Hide flag field from certain nodes in view

Install the Views PHP module and enable it. This will allow you to
embed php into a view cell.
Add a new nid/node id field to your View. Make sure to check the
“Exclude from display” checkbox.
Add a new Content: Published field to your View. Make sure to check the
“Exclude from display” checkbox.
Rearrange your fields so that your hidden nid field and published
field  at the top of all fields. This is important. It needs to be
“available” as an element to the custom php field we are about to
add, and if it’s after, the custom php field won’t see it.
Add a new Global: PHP field.
add the following code to the Output Code section of the field (in
php):

if ($row->status) {
  print flag_create_link("the_machine_name_of_your_flag", $row->nid);
}

 Use  delimiters to enclose PHP code.
Click the apply button

use flag field in Sort criteria for sorting content mean flagged content on top
this is a tested solution.
hope this solve your problem.


It's classy/base:

libraries-override:
  classy/base:
    css:
      component:
        css/components/form.css: false

Which is defined in the classy.info.yml.


If you use the function fboauth_fbid_load() you get facebook id or FALSE.
With the facebook id you can obtain profile picture.


Ubercart alter product price when product added to cart

Here is another hook you can play with hook_uc_add_to_cart

Parameters:
$nid - the node ID of the product
$qty - the quantity being added
$data - the data array, including attributes and model number adjustments

Here is how to work with hooks

  Drupal's module system is based on the concept of "hooks". A hook is a
  PHP function that is named foo_bar(), where "foo" is the name of the
  module (whose filename is thus foo.module) and "bar" is the name of
  the hook. Each hook has a defined set of parameters and a specified
  result type.

function hook_uc_cart_item($op, &$item) { the work hook should be replaced with your modules name like

function YOURMODULENAME_uc_cart_item($op, &$item)

See Hooks


How to make a form with latest nodes listing with checkboxes same as in 'admin/content' page?

First off all you can see how this realize in /admin/content page.
The file /modules/node/node.admin.inc has a function node_admin_nodes()
This function returns form which contain list of nodes. The file has clear description and you can read and copy-paste code from this function to your module with necessary modifications.


Difference between drupal_write_record and db_insert

drupal_write_record doesn't know by itself whether to do the insert or the update, but this is determined by the existence (or not) of the 3rd parameter: $primary_keys which defaults to array() while db_insert is to insert new record to database.

according to drupal_write_record API documentation

  $primary_keys: To indicate that this is a new record to be inserted, omit this argument. If this is an update, this argument specifies the primary keys' field names. If there is only 1 field in the key, you may pass in a string; if there are multiple fields in the key, pass in an array.

Also

  Do not use drupal_write_record() within hook_update_N() functions, since the database schema cannot be relied upon when a user is running a series of updates. Instead, use db_insert() or db_update() to save the record.


Storing anonymous user information in a cookie

Since Drupal 7, there are two functions to store data in a cookie: user_cookie_save(), and user_cookie_delete(). Despite the function names, the functions work also for anonymous users, since they don't get information from the $user object or any information that is related to the user ID.

comment_form_submit() uses user_cookie_save() in the following code lines:

if (user_is_anonymous()) {
  user_cookie_save(array_intersect_key($form_state['values'], array_flip(array('name', 'mail', 'homepage'))));
}

If you are using a version of Drupal that doesn't define that functions, you can implement similar functions in a module you use.

function mymodule_cookie_save(array $values) {
  foreach ($values as $field => $value) {
    // Set cookie for 365 days.
    setrawcookie('Drupal.visitor.' . $field, rawurlencode($value), REQUEST_TIME + 31536000, '/');
  }
}

function mymodule_cookie_delete($cookie_name) {
  setrawcookie('Drupal.visitor.' . $cookie_name, '', REQUEST_TIME - 3600, '/');
}

Keep in mind that setrawcookie() is only available in PHP 5. If you are developing a module that could be used with PHP 4, then you should use setcookie(), and the code of the functions should be accordingly changed: the parameter needs to be declared as $values (not array $values), and the call to rawurlencode() needs to be removed as the cookies are already URL encoded from setcookie().


How to restrict completion of only one field within a field group

I have not expressly done the exact use case you've requested. I recommend you look at the following blog post describing the Drupal States API, including newer additions made to that API for ORing and XORing conditions:

http://www.metaltoad.com/blog/drupal-7-form-api-using-states-multiple-conditionals-and-or-and-xor

For simple multiple-condition clauses the States API follows this convention:

'[field-selector]' => array('[evaluate]'),
'[field-selector2]' => array('[evaluate]'),

For more complex conditional logic you can write the following array structure:

array('[field-selector]' => array('[evaluate]')),
'[OR/XOR]',
array('[field-selector2]' => array('[evaluate]')),

Be aware that the version of jQuery being used on your site could be important for these conditionals to work (again see the blog post).

If the above does not meet your needs I recommend you look at the Field Conditional States module:

  The working states that are supported by FCS are:

  visible / invisible - Hides/Shows a form element
  enabled / disabled - Grays out a form element
  required / optional - Makes a form element required to be able to submit the form
  checked / unchecked - Checks/Unchecks a checkbox (of course only applicable to checkboxes)

  Fields to which these states will be applied, are called target fields
  or controled fields.

  To trigger these states there is a different set of trigger states
  (not to be confused with the states described above) that will trigger
  a state when applied to a control field:

  empty - Triggers when the control field is empty
  filled - Triggers when the control field is not empty
  checked - Triggers when the control field is checked
  unchecked - Triggers when the control field is not checked
  value - Triggers when the control field's value is equal to a given string
  !value - Triggers when the control field's value is NOT equal to a given string

  All of them are supported as long as they make any sense for the
  widget of the used control field. For example it doesn't make any
  sense to wait for a text field to be checked or for a checkbox to have
  the value "Hello World". So most (if not all) fields will only use a
  subset of these trigger states.

Note: that the states api and the field condition module are clientside modules -- they don't enforce the validation on the server. You'll likely also want to use a custom form validation function to assure that only 1 field is provided upon form submission.


Safe change of field type from text to email or link

A different approach  could be - Why try to change field type ? Why not copy old to new ?

You could possibly use something like views data export or other similar module to create a dump of your nodes as node ID and text field to csv file.

Then create your new field.

Then use feeds to import your csv and assign the old text field column to your new field. Make sure you tick the box to update nodes !

Then delete your old field.


Drupal 8: Build "visitor history" using Flag/Rules

Honestly I gave up pretty quickly since it seemed unnecessarily complicated.  I created a very basic module that handles the marking/unmarking via the Flag API.  It has a single hook that looks like this:

function mymodule_node_view(array &$build, \Drupal\Core\Entity\EntityInterface $entity, \Drupal\Core\Entity\Display\EntityViewDisplayInterface $display, $view_mode) {

  //UPON VIEWING 'mytype' NODES
  if($entity->getType() == 'mytype'){

    //CREATE HISTORY FLAGS
    $uid = \Drupal::currentUser()->id(); //current user
    $flag_id = 'history'; //flag type is named history
    $flag_service = \Drupal::service('flag');
    $flag = $flag_service->getFlagById($flag_id);

    if($flag->isFlagged($entity) == '1'){
        //unflag then reflag to update date
        $flag_service->unflag($flag, $entity);
        $flag_service->flag($flag, $entity);
    } else {
        //flag it for the first time
        $flag_service->flag($flag, $entity);
 }
 }
}


Change display order of a content type fields in the view tab

The fields are sorted by weight, which is hidden by default, because you can reorder the rows by dragging. You can switch off dragging and input the weights by hand with Show row weights.

Doesn't matter if the fields are used in multiple content types, you can arrange them in each content type individually.


How to implement template file that would reside in database?

You can register a loader, see Drupal\Core\Template\Loader for the implementations that drupal core uses and their parent classes/interfaces.

See also how they're registered in core.services.yml, for example:

twig.loader.filesystem:
    class: Drupal\Core\Template\Loader\FilesystemLoader
    arguments: ['@app.root', '@module_handler', '@theme_handler']
    tags:
      - { name: twig.loader, priority: 100 }

So, it's certainly possible to do it, if it's a good idea is another question ;)


Using as shipping address the value entered as billing address

Yes, you can try to custom jquery event.
1.To create a custom js file in your theme folder (/themes/theme-name/js)
Triger Function Like:
$("select[name='panes[delivery][select_address]']").change(function()
{
//your code
//.....
});

Thanks


Install i18n and enable the Translation Redirect module within.

Install Globalredirect and go to admin/config/system/globalredirect and check "Language path checking".

You can then take the user to either source or translated node, and Globalredirect will take the user to the page which is in the currently active language.


If the Page display name of the view is page, then it prints the path

$view = views_get_view($view_name, TRUE);
print $view->display['page']->display_options['path'];


For me this sounds pretty simple to solve. In your custom module just set a requirement:

name: Foo Bar
description: 'Lorem ipsum.'
package: Custom

type: module
core: '8.x'

dependencies:
  - dynamic_entity_reference:dynamic_entity_reference

By that you ensure that dynamic_entity_reference exists and is enabled when your module gets installed. That's it. Except I misunderstand you and you are instead looking for hook_module_implements_alter to change the order of modules calling a certain hook.


Migrated content type fields not showing

It sounds like the fields might be disabled on the entity form.

Goto Structure -> YOUR CONTENT TYPE -> Manage form display

Then move the fields you are expecting to see in the form from Disabled (bottom) to Content.  You can also control the display order from there.


How do I display all terms of nodes created by user in a user view field

It's not likely you have it working the way you describe it, even for one node.

You need to first connect the users to the nodes, before you can make further connection to terms on those nodes.

The easiest to create such views is through Taxonomy term type, not User type, since it's the terms you want to list in the end:

Create Taxonomy term Views with 0 Pager (to show all items)
Under Fields add Taxonomy term: Name if you don't have it already
add Relationship Content using field_[name], require it
Add another Relationship Content author, require it (it will automatically use the first Relationship)
Add a Contextual filter User ID, it will automatically use the author Relationship, and configure it:
When the filter value is NOT available
Provide default value
User ID from route context
When the filter value IS available or a default is provided
Specify validation criteria
User ID
Single ID
Hide view
Turn Aggregation on.

To test the views enter a user ID into the Preview field, it should show a list of terms associated with the user's node's field you added the Relationship for.

Aggregation takes care that there are no duplicates in the results.


I've achieved this using a view to pull nodes that share the same taxonomy as your current node.

Basically create a view that uses the 'Has taxonomy term' contextual filter. And also include a content NID contextual filter to exclude the current node (in the list appearing in that view).

Follow the example here to create the view ('Views 3' steps at top):
http://www.metachunk.com/blog/adding-related-content-view-drupal-7

I've also taken it a bit further and ticked 'Reduce Duplicates' and 'More > Allow multiple values'. That way you can specify multiple terms from your current node and only get a node once if it appears in more than one term.

Make sure you select the fields you'd want to see in your template.

My view is also filtered to one content type  'news' so i've named it 'related_news'. I use the following code in my template.php to grab the views content and pass the template an array. Add your custom fields to the $terms array to then use their ID to find related content.

/**
 * Return result of Related News view for a specific node.
 * TO-DO: Add default functionality.
 * @param object $node
 * @return array
 */
function [template]_get_related_news($node) {

    $terms = array();

    //Get terms from fields.
    $terms = array_merge($terms, $node->field_field_term_1);
    $terms = array_merge($terms, $node->field_field_term_2);

    //Build array of ids
    $termIDs = array();

    foreach ($terms as $terms){
        $termIDs[] = $terms['raw']['tid'];
    }

    //Load view
    $relatedView = views_get_view('related_news');

    //Execute view with term ids as argument. Include node id to exlude it from results
    $relatedView->set_arguments(array(implode('+', $termIDs), $node->nid));
    $relatedView->execute();

    return $relatedView->result;

}

You could also get the view to produce a block and use this to display the content within your theme.


Can I safely delete auto-created Postgres Indexes?

I used the following PSQL query to identify all the indexes not being used and to sort by biggest first:

SELECT nspname || '.' || C.relname AS "relation",
  pg_relation_size(C.oid) AS "size",
  idx_scan,
  idx_tup_read,
  idx_tup_fetch
FROM pg_class C
LEFT JOIN pg_namespace N ON (N.oid = C.relnamespace)
LEFT JOIN pg_stat_all_indexes stat ON C.relname = stat.indexrelname
WHERE nspname NOT IN ('pg_catalog', 'information_schema')
ORDER BY pg_relation_size(C.oid) DESC

I deleted several dozen indexes. So far, no issues. It seems performance may be improved as I am noticing less CPU resources needed. Likely because there are fewer indexes to be updated.


Multiple dates token for auto node title

You could use the following code snippet in your auto_nodetitle configuration.
Don't forget to select the option "Evaluate PHP in pattern.".
And replace the field_date_multiple with your own field's machine name.

Hope this helps!

<?php

$dates = array();
foreach($node->field_date_multiple[LANGUAGE_NONE] as $date){
  $dates[] = date('j-m-Y', strtotime($date['value']));
}
echo implode(', ', $dates);

?>


How can I show the flag field using Twig?

I found it.

Flag machine name: bookmark

Then we can use {{ content.flag_bookmark }} in node.html.twig to show bookmark flag .


This was a compatibility issue with the Location module moving over to geofield
module allowed me to add the coordinates to the search api index


Why don't {{ product.body }} and {{ product.field_specifications }} return values in custom commerce-product.html.twig file

why does
{{ product.body }} display nothing while {{ product_entity.body.value
}} displays something.

This is because {{ product.body }} returns an array not a single value. Body has other properties such as summary so you need to specify what you want from that field.

why does
{{ product.field_specifications }} display nothing while {{
product_entity.field_specifications.value }} displays something.

I'm not sure what field type you set field_specifications to, but I'm guessing you set it to a formatted text field. If that's the case it would return an array just like Body would. If field_specifications was simply a textfield, {{product.field_specifications}} would have worked.


How to get the form field label of a multi-value field

What is the proper way of obtaining the title, and what causes the
  difference?

The cause is this code in the field widget:

  // For multiple fields, title and description are handled by the wrapping
  // table.
  if ($is_multiple) {
    $element = [
      '#title' => $this->t('@title (value @number)', ['@title' => $title, '@number' => $delta + 1]),
      '#title_display' => 'invisible',
      '#description' => '',
    ];

This t($string, array $args = [], array $options = []) function returns a TranslatableMarkup object.

You can cast the translatable markup as string to obtain the title, but normally you don't have to. See both answers here  How to get the string value from the function CountryManager::getStandardList()?


This code should create the placeholder:

function mytheme_form_search_block_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {
  $form['keys']['#attributes']['placeholder'] = t('The new placeholder');
}

So if that does not work for you, it might be because you need to clear the cache.


you can use Pathauto contrib module.

  The Pathauto module automatically generates URL/path aliases for various kinds of content (nodes, taxonomy terms, users) without requiring the user to manually specify the path alias. This allows you to have URL aliases like /category/my-node-title instead of /node/123. The aliases are based upon a "pattern" system that uses tokens which the administrator can change.

https://www.drupal.org/project/pathauto


Why disable non-core modules when doing a core update?

Contributed modules are not always robustly built and can fall victim to changes made in core. This is particularly an issue if the contributed module has not made proper use of Drupal's API or relies on a database structure in core that may change with the upgrade (even if it is just a minor update). It is therefore safest to disable all the contributed modules before updating in case one of the modules causes the site to fail on completion of the upgrade process. Admittedly this is rare, but it does happen. It happened to us once, but thankfully just on a dev version of a site.


How can I make my menu children display horizontally below my main menu?

There are two ways I know of to achieve this. The first is configuring Drupal core's primary and secondary links functionality and some theming, the second is the Menu Block module.
Primary and Secondary links core functionality + theming
If your theme utilizes the primary and secondary links variables you can configure the behavior you're looking for in the Menu Settings area.
From the Primary and Secondary Links documentation page:

Drupal also provides two default system menus called "Primary links" and "Secondary links". ... A powerful feature of this primary/secondary system is when you choose the same menu as the source for both theme variables. In this case, the two menus magically couple together, and the Secondary links shows you the second level of items from the menu for the page that you are on.

Here is a free Drupalize Me Video that shows the process in Drupal 6, it's very similar in Drupal 7.
You would set up your menu with the sub-pages as children of the main page links:

Home
News
Help

Basics
Content
Digital Dialog
Exams, etc

For this example I used the Main Menu that is default in core, but you can use any menu.

On the menu settings page (Admin > Structure > Menus > Settings or http://example.com/admin/structure/menu/settings) set both the 'Source for the Main links' and 'Source for the Secondary links' to your menu.

When you visit your Help page the secondary links displayed will be the children of the Help menu link. And the child links will stay open while you are on either the parent page or on one of the child pages. In the Bartik theme the secondary links are located in the top right of the page.

To match the layout of menus in your screenshot, you would most likely need to make theming adjustments as the Primary and Secondary links are not blocks configurable on the Admin > Structure > Blocks page. At the theme layer the variables are $main_menu and $secondary_menu.
Menu Block Module
If you foresee needing deeper levels of menus or want your menus to be in configurable blocks, or would just rather use a module than adjust your theme, there is the Menu Block module. From the project page:

[P]rovides configurable blocks of menu trees starting with any level of any menu. ... if you’re only using your theme’s Main menu links feature, you can add and configure a “Main menu (levels 2+)” block. That block would appear once you were on one of the Main menu’s pages and would show the menu tree for the 2nd level (and deeper) of your Main menu and would expand as you traversed down the tree.


Commerce Product generate Preview on Add Product page

You can try rendering the product entity and attaching it to the form.

To render the product entity (see entity_view):

// Extract the referenced product from the node.
$node_wrapper = entity_metadata_wrapper('node', $node);
$product = $node_wrapper->field_product->value();

$product_view_mode = 'full'; // Set the view mode you want to use to display this product.

// This will return a render array.
$rendered_product = entity_view('commerce_product', array($product->product_id => $product), $product_view_mode);

Finally, alter the form so that it also contains the rendered product.

// Now add the markup to the form.
$form['product_preview'] = array(
  '#markup' => render($rendered_product);
);


Attach javascript library and settings to a node page

try hook_entity_view or hook_node_view_alter:

/**
 * Implements hook_entity_view().
 */
function mymodule_entity_view(array &$build, EntityInterface $entity, EntityViewDisplayInterface $display, $view_mode) {

  if ($entity->bundle() == 'background_carousel_page' && $view_mode == 'full') {
    $build['#attached']['library'][] = 'mymodule/mylibrary';
  }

}

or

/**
 * Implements hook_ENTITY_TYPE_view_alter().
 */
function mymodule_node_view_alter(array &$build) {
  // @see \Drupal\Tests\embed\Functional\EmbedPreviewTest::testPreview
  $build['#attached']['library'][] = 'mymodule/mylibrary';
}


Output both form and generated image (imagejpeg) onto same page

If you put $form_state['rebuild'] = TRUE in your submit handler then the form's redisplayed and you have access to $form_state['values'] in the form constructor. This is typically how multi-step forms are done. So in this case something like:

if (empty($form_state['values']['user_name'])) {
  $form['user_name'] = array(
    '#title' => t('Your Name'),
    '#type' => 'textfield',
    '#description' => t('Please enter your name.'),
  );
  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Submit')
  );
}
else {
  $form['image'] = array(
    '#theme' => 'image__nameform',
    '#path' => $path,
    '#width' => $width,
    '#height' => $height,
    '#alt' => $form_state['values']['user_name'],
  );
}

To pass the name to your image generation function you want to change its entry in hook_menu(): the path should be image/% (which says there's an argument), page callback create_textimage (because that's what generates the content) and page arguments array(1) (because the text is the second argument, and you start numbering at 0). There are more details in the documentation for hook_menu().

A few other points not directly related to the Q:

Currently the image generation function is a bit of a DOS vector (because it's a bit CPU intensive, isn't cached, doesn't require auth, and doesn't require a form submission).
You should use drupal_set_message(t('Thanks for adding your name, %name.', array('%name' => $name));. This is secure and translatable - see t() and format_string().
The function names are a bit all over the place. If your module's called frameyourname then all your functions should start with that (with a few exceptions). Also I'd suggest avoiding a path like image/% in favour of something more specific like frameyourname/%.


Install Placeholder module. Using this module you can convert any label of any elements of any form in your site in to a placeholder. Just add the CSS style of the form element in to this module configuration and it will do the rest of the jobs

You can also try this

$form['search_form']['#attributes'] = array('placeholder' => 'Search ...');


Plugin Derivatives For Queue and Migration Plugins

The annotation cannot be derviated, but the class itself yes.


Left and Right region is not showing on ZEN sub theme

I finally found the solution for this problem. That is the put 'zen' folder under the same location of the sub-theme folder. Actually, the site I've been working on is a multi site setup and there is also an entity there that is also using zen as it's theme. I thought putting just my sub-theme is enough since the site still recognized the main theme, which is Zen.

The reason why the two region of the theme I uploaded is not being recognized, is because it's info file is not being read properly. The info file that is being read by the site is found, on the other zen sub-theme I mentioned above.


Error while trying to install drupal commerce kickstart

Go to your php.ini file. Search and change values for the following:

post_max_size = 500M
upload_max_filesize = 500M
max_execution_time = 2000
max_input_time = 2000
memory_limit = 512M

and save file

In apps config

C:\wamp\apps\phpmyadmin3.3.9/config.inc.php (whatever your server is)

add the below code

     //maximum execution time in seconds (0 for no limit)
     $cfg['ExecTimeLimit'] = 300;

and save the file.

Restart your WAMP Server.

For more details go there.


Filter node by custom_field in admin panel

You need to install Admin views module. It will replace administrative overview/listing pages with actual views for superior usability. Now, you can override your views for admin panel for filter content by field_list.


Form validation after drupal_build_form in hook_node_view

You do need a form alter. You're modifying the form array after it's already been built, which includes caching the form and processing the input.

  Form is nicely displayed, fields are hidden, submit button value is changed

Those are handled at render time, whereas the input processing (and therefore handler execution) are done at form build time. Or to put it another way, consider the form returned by drupal_build_form() as nothing more than a render array that happens to render a form. If you want a form array proper, you need to get the form via an alter (ie before drupal_process_form() is called on it).

You can use hook_form_FORM_ID_alter() if you want to target just one content type form, or hook_form_BASE_FORM_ID_alter() if you want to target multiple types or be dynamic. If you need to know within the form alter whether the form's embedded via a hook_node_view() you can pass that state via $form_state.


Not able to import images using feed image grabber module in content image field

Finally with a struggle for more than a day, I finally get succeeded in importing images in Drupal Content type.

I used Feed Image Grabber Module with feed but not works for me might be my image path is from external server.

Then I used Media, File Entity and Media Feeds module which gives me ability to import images from external URL too.

After all the above modules get enabled.
I have added one more mapping "source->target" in my Feeds Importer under Mappings and Select "Target Field" appended with "(media_internet)(field_image)" and then save.
Then upload CSV file and finally my images start getting saved in
image field.

Hope this will help someone.


How to sort nodes per domain with the Views module?

You are right: Best ot achieve ordering in views-lists is indeed draggableviews. But beware that this doesn't work with all styles. I am not sure, since it is half a year ago I have needed it for a project, but I think draggableviews is made for tables in mind. But as far as I remember there was an additional module making it possible also for other listing styles.

But the rather real problem is not how to order the views list items. The problem is that you need 2 almost same but a little bit different views (page-views? or block-views?), and how to let the 2 views show up on 2 different domains. I assume you would like to have the kind of same page on the same path but on two different domains in two different orders. The problem here is, if you try to achieve this with overriding paths by 2 different views and different domain conditions, the filtering or conditioning of the view depending the domain will make some trouble... It will always try to load both views and will always take the first arriving and if the condition doesn't fit, it will not change to the other. This is not a bug. It is because of how overriding paths works.

Let me know if you have any idea how to achieve this last part. Maybe I can help then on some further steps on it. But in the moment I see the end of the road here.


ImageFlow module doesn't find its library in Drupal 7

Try using the dev version of the module. I was having the same problem, found this issue: https://drupal.org/node/2042787
Seems the maintainer fixed it in dev but did not in the point release.

If you find documentation on getting this to work after installation, please link!


Entity:media doesn't exist error when searching for url in "add link" in wysiwyg

I had a similar problem, but not with entity:media, but with entity:shortcut

I ended up by deleting the matcher from the database.

It is in the datatable config under the name "linkit.linkit_profile.ckeditor"

SELECT * FROM config WHERE name= "linkit.linkit_profile.ckeditor";

The data is stored in a serialized string. To remove it, you must be confident in editing serialized strings, which is a bit dangerous.

I used (UN)Serialize.me to convert the unserialized string to a JSON string, then edited the JSON in JSON Editor Online and back again.

I first tried to use drush to export the config, editing the config YAML file and then importing, but it yielded the same error.


How can I list only modules which need an update?

Drush puts that [ok] information out on stderr. So you can actually just dump that by using:

drush ups 2>/dev/null

which for me gave:

 $ drush ups 2>/dev/null
 Name    Installed Version  Proposed version  Message
 Drupal  8.2.5              8.2.6             Update available


Drupal 8 page manager and panels contextual filters for views_block

Alternative, you can use Views to pick up the tax term id's

If your node has multiple tax terms, you need to allow multiple values for your contextual filter


Requiring a package doesn't find a dependency

As reported in Composer fails when installing a dependency of a dependency, but not when the dependency is installed directly. that probably happens because the root composer.json file doesn't set a minimum stability, or doesn't accept a less stable package.

Try with composer require drupal/commerce:@dev as suggested in that issue report.


How can I apply logic in user registration welcome emails?

Pretty ugly, but I have a solution. Please post if you have a better one that can be applied for more use cases.

So I installed the https://www.drupal.org/project/computed_field module.

I added a hidden computed filed to my user registration form with my logic.

Then I used the token module to include the value of that computed field in my user welcome email.

It does the job, but again, it is pretty ugly.
Hopefully this helps someone until someone posts a more direct solution.


Finally, I found how to do it. I don't understand why I got lots of errors previously.
 function sully_ad_import_views_query_alter(ViewExecutable $view, QueryPluginBase $query) {
if ($view->id() == 'document_list' && in_array($view->current_display,array('block_1','block_3'))) {

  $query->addField(
    'taxonomy_term_field_data_media__field_standard_termref_1__node__field_categorie',
    'delta',
    'delta'
  );
  $query->addOrderBy(
    NULL,
    NULL,
    'asc',
    'delta'
  );

}

}


Children of children not appearing in book navigation menu

book_children(), which is used in the preprocessor for the "book_nagivation" theme hook (template_preprocess_book_navigation()) only retrieves the immediate children of the current book item, so you wouldn't expect the default "Book navigation" block provided by the Book module to show all children of the current book item recursively.

If you wanted to modify the behavior of this block in your theme, you could clone the template_preprocess_book_navigation() from book.module, placing the function in the template.php file for your theme and renaming it to yourthemename_preprocess_book_navigation(), and then create and call a modified clone of book_children() that recursively collected all links in the book beneath the passed link.

If the behavior you wanted was to display the standard tree for all interior book pages, but display book's entire outline only when you are viewing main page of the book, you could alter your yourthemename_preprocess_book_navigation() function so that it only calls the "get recursive tree" function when the $book_link doesn't have a parent ($book_link['plid'] == 0), and call book_children() for all other cases.


If you want to install Drush via composer require rather than git clone followed by composer install (which is slightly easier), then I would recommend:

Use the stable version of Drush, ~8
Install with cgr


There's 2 areas you need to check this is included.  It's common to have applied to the search and not realise it needs to applied in views also.

I take it so far you have made the fields in

configuration > search api > Operations 'EDIT'

"Fields" tab > 'Add Related Fields ' at the bottom.

Now you also need to add the Fields in

structure > views > your view

Filter Criteria >

On the right hand side look for 'Searched Fields'  - make sure all the fields your searching are in here.

I hope that solves it for you .


Looks like 128M of memory is still not enough, try more. If that still fails there's probably a memory leak or endless loop somewhere, or a too bloated configuration (e.g. too many fields, trying to debug a structure that has too many entries and so on).


It turns out that "Clean URLs" need to be turned on for OpenID...  I added "AllowOverride All" to the  section under VirtualHost in my Apache config file.  This allowed me to turn on Clean URLs and the error is now gone.


After moving a module to another folder , i cannot clear reminiscent module paths

i have ended up putting in local.settings.php

   /**
 * Class Loader.
 *
 * If the APC extension is detected, the Symfony APC class loader is used for
 * performance reasons. Detection can be prevented by setting
 * class_loader_auto_detect to false, as in the example below.
 */
$settings['class_loader_auto_detect'] = FALSE;


How to enable block "overlay" with a gear

You just need to turn on the core Contextual Links module, and make sure that all roles that should be able to see those links have the "Use contextual links" permission.

If it's still not showing, check to see if your theme has a custom block.tpl.php file. If so, make sure that the $title_prefix and $title_suffix variables are being printed out (see the original template file).

The contextual links output is contained in one of those vars (I think it's $title_suffix actually) so the links won't be printed unless the correct one of those vars is also printed.


Link field to node content only with Colorbox

Go to admin/config/media/colorbox and at the bottom there is a settings called 'Colorbox Node Integration' uncheck Enable Regions and save it.
After that colorbox shows only main content of node.


How to change Date format without diving to core?

I think your best bet is Calendar_Systems module that will not do the core changes but everything else needed on the frontend.


How to switch logo and menu links based on subdomain?

I am unaware of any contrib modules that do this (well, other than Domain Access), but it would be pretty trivial to write a little custom code to accomplish it.

Essentially, you would add something to your theme preprocess to detect the domain and tack on body classes.  How to do this depends on whether you are using Drupal 6 or Drupal 7.  Either method, though, would use $_SERVER["HTTP_HOST"] to detect the theme.

Then, in your CSS you would preface your logo rules with body.whatever to choose the correct one.

The menu thing is a little trickier.  You would use essentially the same logic, but set a variable containing the proper menu and print this out in your theme.  To be honest, though, I really would use Domain Access for this if you are using Panels.  The domain shows up as a panel selection rule, so you can do all of this from the UI.


How to always show Poll results on most recent poll block?

From memory you can configue poll blocks using the Views module. At any rate, using Views you will be able to create a new block that displays votes. You can then add a footer to the block with a link to the poll node so users can vote.

There's plenty of documentation about using Views:

http://drupal.org/project/views


Is there a field type that offers structured entry that gets rendered as a table?

Take a look at these modules:

TableField
CCK Table Field


Is this a good way to make fields accessible for an empty entity object?

I too was looking for an answer to this question, however you question has provided me with the best answer so far.

My implementation of your solution was to call your function in my entity create function and then loop over the values attaching the fields as empty arrays:

function MY_ENTITY_create($values = array()) {
    $entity = entity_get_controller('MY_ENTITY')->create($values);
    foreach(_get_fields_for_entity('MY_ENTITY') as $field) {
        $entity->{$field} = array();
    }
    return $emtr_safe_check;
}

function _get_fields_for_entity($entity) {
    $result = db_select('field_config_instance', 'f')
        ->fields('f', array('field_name'))
        ->condition('entity_type', $entity)
        ->condition('bundle', $entity)
        ->execute()
        ->fetchAllAssoc('field_name');

        return array_keys($result);
}

As my entity does not have a bundle, but my module does define several different entities I modified your function slightly to handle loading fields for different entities with bundles of the same name.

I would still be interested to see other peoples solution to this problem.


Exportable and Fieldable Blocks in Drupal 7

The answer is simpler than you could possibly imagine: check out the Bean module, it does exactly what you want! :)


This is how we are working:

Keep as much as possible in code. Features strongarm and other modules are helpfull here. Often we figure out the configuration variables of the modules and put them into settings.php by hand.
Things like enabled modules are left to the DB. We maintain a central copy of our db in GIT. If someone adds a new module, he is responsible for taking this DB, adding the module and pushing a new copy to git together with the new module code. The backup & migrate module is very handy here.

An other alternative would be to develope against a single central DB. The disadvantage of this is that you will likely face situations where one developer trashes the DB and therfore the work of his colegues as well. You could set up a cron job taking a DB dumps at regular times to make sure you don't loose to much in such a situation.


When the quiz is completed I guess you need to email the job creator. You could do this using hook_node_insert().

E.g.

function hook_node_insert($node) {
  if($node->type == 'quiz') {

    // Get the job nid from the quiz nid
    $job_nid = db_select('field_data_field_quiz', 'q')
      ->fields('entity_id')
      ->condition('field_quiz_target_id', $node->nid)
      ->condition('entity_type', 'node')
      ->condition('bundle', 'job')
      ->condition('deleted', 0)
      ->execute()
      ->fetchField();

    $job = node_load($job_nid);

    $job_author = user_load($job->uid);

    drupal_mail (
      // The name of your module
      'my_module',
      // An arbitrary mail key, that you decide (used in hook_mail())
      'new_quiz_submission',
      // The destination mail address
      $to->mail,
      // The language that the mail should be sent in (requires translation if not English)
      $to->language,
      // Some parameters we can use in hook_mail()
      array (
        'account' => $job_author, // Pass the user account to hook_mail
      )
    );

  }
}

function my_module_mail($key, &$message, $params) {
  // The key allows for a module to define multiple mails. This
  // key needs to be the same as the first parameter in drupal_mail() above
  if($key ==  'new_quiz_submission') {
    $message['subject'] = t('New Quiz submission');
    // Each element of the body array becomes a new line in the email.
    $message['body'][] = t('Hello @user', array('@user' => format_username($params['to'])));
    // Adding an empty string to the body array adds an extra line in the email
    $message['body'][] = '';
    $message['body'][] = t('A user submitted a quiz. To see the results click here.');
  }
}

I pretty much just copied and pasted the code for sending simple emails from here.

I would create a view with a contextual filter that shows all of a particular authors quizzes that need scoring and then the link the in the email could just link to that view.

When they marked the quiz then I would also use a boolean field to mark the quiz as scored.


I can't access private files in CKEditor

If I'm understanding the situation correctly, then the issue is that, by virtue of bring a private file, they would need the right permissions in order to view the file in their browser.

On the sites I work on, we use elFinder, and the permission to allow access is called Access private files.

If you're not using elFinder, then there is probably a similar permission that you'll need to enable.

Hope that helps!


Change Content region width when Sidebar has content?

$page['sidebar_first'] is an empty array when you have no content in that region. So it is defined and the condition

if ($page['sidebar_first']):

is true even if you have no block in the sidebar. So

print render($page['sidebar_first'])

gets executed and, after the rendering, $page['sidebar_first'] will look something like

array(
  '#printed' => true,
  '#children' => '',
)

meaning that it's no longer empty and the condition if (!empty($page['sidebar_first']): will be met in any case. You may want to rewrite your code to something like

      <?php if (!empty($page['sidebar_first']): ?>
       <aside id="sidebar-first" role="complementary" class="sidebar clearfix">
         <?php print render($page['sidebar_first']); ?>
       </aside> <!-- /#sidebar-first -->
       <div class="content-region-sidebar-sibling">
         <?php print render($page['content']); ?>
       </div>
     <?php else: ?>
       <?php print render($page['content']); ?>
     <?php endif; ?>


search_update_totals() is not invoked / or search_cron() is not invoked

In some circunstances, you need to call search_update_totals() after indexing. The reason is that you need to make sure that it runs from the same location that you ran search_index, and after it.

In theory it is always called when you index using a cron job, but I am indexing with a drush command and I had to call it manually at the end. If the cron run failed it won't be called.


Try this from admin panel. Create hierarchical menu for this. See the screenshots


In Pager options There is a field named Pager ID. Setting a different value for each view should solve the problem.


SA-CORE-2013-003 - Files directory Not fully protected

quote from SA-CORE-2013-003 - Drupal core - Multiple vulnerabilities | Drupal.org:

  Additionally, the .htaccess of the temporary files directory and
  private files directory (if used) should include this command:

  Deny from all

instead of using .htaccess inside of /tmp directory (which can be wiped), I placed following rule inside of my pressflow.conf:

<Directory "/tmp">
    Deny from all
</Directory>


notice after entering a function in template.php

That notification is displayed because the node key of the $vars array is not always defined in hook_preprocess_page() function.

Use the following code, which first checks if the node key exists and then continues. It also uses the switch statement, which is easier to read if you only need to check the node type and use one condition:

function myZen_preprocess_page(&$vars) {
  if (isset($vars['node'])) {
    switch ($vars['node']->type) {
      case 'mappe':
        $vars['theme_hook_suggestions'][] = 'page__mappe';
        break;

      case 'fatti_e_risorse':
        $vars['theme_hook_suggestions'][] = 'page__fatti_e_risorse';
        break;
    }
  }
}


You can try with 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.


How to edit and delete entityform submissions?

use entityform hook_form_alter with devel module in this case i suggest to view your data before submit button ... and entityform hook_form_insert to view your data after submission button using devel module or drupal_set_message. You can actually alter in hook_form_alter button to  store entityform submission to particular content type.


Adding custom Text changes the horizontal alignment in Content type

Why dont you just do the following:

   $form['field_section_grid_image']['#suffix'] = '

 OR';

   $form['field_section_grid_image_path']['#prefix'] = '

';


how to map fields in feeds module with csv that has no headers?

The Feeds module support CSV files without column headers.  On admin/structure/feeds/foo_importer/settings/FeedsCSVParser, you just need to select "No Headers".  Then on admin/structure/feeds/foo_importer/mapping, you use the column numbers for the source.

Be careful when entering the Name of source field. Your first column is named '0', the second '1' and so on.


It is likely that something in the sub theme is wrong. There are several steps to go through. They are detailed in  starter kit readme.


How to add fields in Drupal Registration Form?

After you have enabled the module there will be a new content type called Profile available. Add fields to the content type Profile under admin/content/types.

The fields you add here will show up when the user registers.


I was having the same problem with D7.  The solution for me was to use field_get_items(...) for reading the node data.

$year_items = field_get_items('node', $variables['node'], 'field_year');
$year = $year_items[0]['value'] + 1;

I found the post on Rendering Drupal 7 fields (the right way) very helpful.  It does seem strange that we shouldn't use the $variables provided to the preprocessor and template to read and modify the template variables.  I must be missing something.


Views show fields is set, but only "Content" options are available to select - why?

The Content: Body field should be there as long as it exists in the content type.

A couple things you can try in this order:

Ensure all permissions are set properly
Flush all caches
Flush the views cache at /admin/structure/views/settings/advanced
Disable views cache just to see if that's an issue
Update Views

Here's a current issue of the problem


Saving a data to two different nodes with same node id?

As Paul commented, there is already a system to keep track of changes. You can enable node revisioning through the UI by going to Config > Structure > Content types > [Content Type] > Edit and select the Create new revision option under Publishing options. Now every on-site node edit will be registered as a revision and the previous values are logged in the Revisions tab (next to edit).

If you need to programmatically create a new revision, you can do it as follows:

$node = node_load($nid);

$node->field_call_response['und'][0]['tid'] = $call_response;

$node->revision = 1; // Save new revision
$node->log = "Explain what you changed";
node_save($node);


Why does JsonResponse keep returning a <?php tag at the beginning?

I was having trouble with this same bug.

At the top of my response there was a php short open tag

<?
<aside data-entity-id="392" data-entity-type="node" class="sidenote">

That was breaking my jQuery ajax call.

It was working locally but broken on the QA server.  Ultimately, after researching the problem, I knew that there was some corrupt PHP file outputting to the page before Drupal explicitly output the page.

After discovering from my php.ini file that short tags were disabled on QA and enabled locally, I was able to grep the codebase for documents in my theme and custom modules that started with a php short tag.  Sure enough, my theme's .theme file was empty with just a php short open tag in it:

<?

Changing this to a regular php open tag and a newline fixed the bug.

<aside data-entity-id="392" data-entity-type="node" class="sidenote">

The qa server was outputting this to the page, but only on this one page (that I know about).  I guess because I was calling

\Drupal::service('renderer')->renderRoot($data);

If I removed that, the controller could return clean json or output.  But when I got the theme layer involved, the bug crept up.


Is there a way to create a Text Format on install of a Drupal Module? And enable a Filter for my module?

Using Features you can export your Text Formats in code and have it automatically configured.

You can configure the filter used for a text format and their order. You can also configure the HTML filter used in the default Filtered HTML text format to allow more HTML elements. So by either allowing the HTML element produced by your filter, and by moving your filter after the HTML filter, you can get your custom filter to work.


hook_taxonomy_term_update(), where does it get invoked in drupal's core code?

It's invoked from taxonomy_term_save().

The reason you can't find it is because the hook gets invoked via an interpolated string, depending on the current operation (insert or update):

module_invoke_all("taxonomy_term_$op", $term);


How do I add a hyper-link as a content type field?

For this case you should use one of these (or both) hooks hook_node_view and hook_view


A form directly can not be posted to Drupal. But a general callback can receive post request data and can process it to store it somewhere.

For this, a hook_menu entry is required to register a callback with a newly created URL . This callback can access $_POST.

On the other hand post request to Drupal can be invoked with form data either by CURL or jQuery.ajax()

Your custom module:

function hook_menu(){
  return array(
     'path/to/submit/post/values' => array(
        'title' => 'Catch Post Data',
        'access arguments' => array('access content'),
        'page callback' => 'catch_post_data',
        'type' => MENU_CALLBACK,
     )
  );
}

function catch_post_data(){
   $values = $_POST;
   // Get post values and store where you like.
   // Do not break the system. Do it carefully using proper entity functions.
   if($success)
       drupal_json(array('status' => 'SUCCESS'));
   else
       drupal_json(array('status' => 'FAILURE'));
}

Form can be posted via jQuery.

$.post('path/to/submit/post/values', $('#form').serialize(), function(response){
    response = $.parseJSON(response);
    if(response.status == 'SUCCESS')
        alert('Congrats!');
    else
        alert('Something went wrong');
});


Failed to find the Facebook client libraries

It's looking for the file in sites/all/libraries/facebook-php-sdk/src/facebook.php, while your file exists in publichtml/sites/all/libraries/facebook-php-sdk-master/src/facebook.php and www/sites/all/libraries/facebook-php-sdk-master/src/facebook.php. The difference is between facebook-php-sdk and facebook-php-sdk-master.

Change the folder name from facebook-php-sdk-master to facebook-php-sdk.


The pager on a form doesn't update upon first submit of the form

Seemingly, I have fould the solution.
Namely, to avoid it, I set the Element property for the pager explicitely.

Here are fragments of code.

$nodes = $q->sort('created', 'DESC')->pager(10, 0)->execute();

/// code here

$form['nodes_container']['pager'] = [
  '#type' => 'pager',
  '#element' => 0,
  '#parameters' => $pager_params,
];

Unfortunately, I didn't have a time to debug and find out why it didn't worked before but it works now. Newertheless, it works.


How to fix special characters in node titles?

Drupal does check_plain on titles which removes all html and does some conversion of chars (& -> &amp;). Depending on how the migration went, that could be part of the problem (escaping escaped content). But it's hard to say what the problem is without knowing what you actually got in the database.

Drupal uses the philosophy to store everything raw in the database, and escape it on output. If the legacy system did it differently, you could have the data stored differently than what Drupal expects, and would then need to fix it at the database layer.


Views: get the fields from a Paragraph without duplicate records

When working with views and entity reference revisions, which is what paragraph fields are essentially, it is preferred (in my opinion) to use rendered entities instead of relationships because of the exact issue of duplication.
Rendered entities lets you add/remove fields per view mode of the entity in a separate form.
First you must add the field of the paragraph (the one you placed on the node) to the view, choose 'Rendered Entity' and select the view mode you want (the choice of view mode depends on if you use it in other places and wouldn't want to affect appearance in these other places, or the opposite if you want to reuse appearances):

Then go to the paragraph management page, manage displays, and select your view mode (you can add additional view modes at the bottom)

From here you can configure the appearance of the paragraph like you would a content type, such as adding/removing fields.
The end result will have a view with your node titles and the paragraphs with the fields you configured in the paragraph's view mode.

Edit
In the case that a single paragraph type is needed from the field, then relationship would be appropriate here, you just need to add a filter. Add 'Type' filter and choose your paragraph type.


This sounds a little like it's due to your contextual settings. Not sure if you set these based on some info you found on the net, but the settings given online can lead to your view block not rendering content because you are currently looking at that exact content to begin with.

The thought behind this is for example if you load a bunch of articles of the same content-type, that it will not list the same article in that list etc.

What you CAN try is to go into your views block (which is causing trouble) and under "advanced" set a simple "Global Text" under NO VIEW RESULTS BEHAVIOUR saying something like "Cannot load" or similar, to look if the block loads now with that message. If that is the case then the issue is more than likely in your contextual filters or in the field filter settings.


How do I get Captcha to reappear in my registration form if an error was detected after submission?

It's in module settings. Under Persistence , you can set CAPTCHA to appear:

always,
once per form,
once per session.

It used to default to always, but as far as I remember there was an issue to change default. Probably now it defaults to once per form or once per session. It should be enough to manually change it to always.


Administrator notification on user registration

First, go to /admin/config/system/actions. In the section "Create an advanced action", choose "send an email" and click on "create". It takes you to a page where you need to enter a recipients email address, (enter the Administrator's email address here), subject and message. Click Save.

Second, go to /admin/modules and enable the Trigger module.

Third, go to /admin/structure/trigger/user. In the Section "Trigger: After creating a new user account" Choose "Send e-mail" in the select box. Click Assign.

Example Message:

A user has created an account.

Details:
 - Username: [user:name]
 - Email: [user:mail]
 - Time: [user:created:long]

Activate their account by going here: [user:edit-url]


If this is a listing of taxonomy terms, you could giva a try to the Term Reference Tree module. At any rate you could just carefully theme a view, tossing out all markup that is unnecessary or even could mess up with jQuery plugin.


clientside_validation (drupal-6 and drupal-7) performs some additional client-side checks, including checks on uploaded file extensions (but not MIME Types).  (And, as @tim.plunkett mentioned in the comments, mimedetect is useful for server-side MIME Type validation, but the file must be uploaded to the server in order to be validated.)

For uploading multiple files, consider the following:

swfupload (drupal-6; Flash)
plupload (drupal-6 and drupal-7; Flash and several other technologies supported; new/under development)

For uploading multiple images, additionally consider these:

image_fupload (drupal-6; uses swfupload above)
jifupload (drupal-5 and drupal-6; free; uses Java applet)
aurigma (drupal-6; software purchase / service subscription required)


Form Builder module not working in Drupal 7

I was finally able to activate it. If you read well the requirements to install formbuilder you will find one of the options is to install Options Element. Please refer to this link http://drupal.org/project/form_builder and see the requirements.


How to get devel content generate module to only include one image per dummy content creation

you can set the image upload limit in field setting itself.

-Anas


admin/reports/dblog will show you the last messages logged by Drupal. To see the menu, you need to enable the "Database logging" module, which is a core module present also in Drupal 6.


How can I calculate product price based on product attributes?

The pricing rules give you the basic mathematical functions to manipulate a price (add, subtract, multiply), but they also give you the ability to set it to a specific amount. The rub just comes in calculating that amount you want to set it to first. : )

Rules allows you to calculate a value and then use that in subsequent actions, so that would be the course of action you might take ... you could, for example, ensure the rule knows about the fields you need to access on the product to make the calculation, multiply it out into a calculated value, and then set the price amount to that calculated amount.

However, this is a scenario where I'd typically expect a custom action to be created. Complex mathematical operations should be handled in code where they can be tracked, tested, etc.


How can I combine a product attribute with a subset of another one in Drupal Commerce?

Required steps

Step 1

Create 2 taxonomies:

Background color, with terms white, black, green, blue, yellow
Surface, with terms glossy or matte.

Step 2

For each prod type, add field "Background color", which is a field "term referenace" (and refer to the Background color taxonomy).

Attentionn: make sure to check the option "attribute field settings" (enables this field to function as an attribute field on the add-to-cart-form).

Then add a similar term reference field "Surface".

Step 3

Use store / products / add product to add individual products, with a specific SKU, and for which you pick the right values for each of both taxonomies.

So for "Matte surface", you should create 5 individual products (one for each background color). But for "Glossy surface", you only create 2 individual products (1 with a white background color, and 1 with a black background color)

Video tutorials

For a more detailed video tutorial of the steps described above, refer to Drupal Commerce - Pruduct Attributes (16:13). Before doing so, you may want to first view these related videos:

Drupal Commerce - Pruduct Types (9:11).
Drupal Commerce - Pruduct Displays (11:36).

By only reviewing/studying these 3 videos (total time = about 37 mins), you'll have a very good foundation to get started with the fundamentals of Drupal Commerce.

Commerce Backoffice

Managing products (and orders) can be confusing. However, the Commerce Backoffice module helps with that. For more details about that module, refer to my answer to the question about
Correct way for Attributes in Commerce


How to add a Custom Operation in the Book Admin Edit Form's Operations?

You can override the bookAdminTableTree() method in the BookAdminEditForm class by extending core/modules/book/src/Form/BookAdminEditForm.php with your own custom form class. You can copy the bookAdminTableTree() method's code and then add an item to the $form[$id]['operations']['#links'] array for 'add-sub-page' (or whatever you want to name the new operation.)

Then alter the existing /admin/structure/book/{node} route (book.admin_edit) in book.routing.yml with a route to your new custom form class.  See www.drupal.org/docs/8/api/routing-system/altering-existing-routes-and-adding-new-routes-based-on-dynamic-ones and the setDefault() method in the Route class: api.drupal.org/api/drupal/vendor%21symfony%21routing%21Route.php/class/Route/8.2.x

This is a helpful tutorial that describes the overall approach: https://www.jaypan.com/tutorial/drupal-8-extending-core-configuration-extending-core-forms-and-overriding-core-routes


what's Taxed line items in the ubercart tax module?

Line items are the items in an order. They can include products, shipping, and tax. The taxed line items are the line items you apply the tax rate to. Generally that would just be the products.


You have to switch on the Locale module, which is part of Drupal  core. There you can search for the strings you want to translate.

If you  want to translate an entire module from scratch, I suggest that you read about translation on drupal.org and make yourself familiar with the toolchain. It's fairly straightforward.


Although your question seems a bit less detailed than it should be, I assume that you need some way to connect a node type (article) to another node type (book). For this you can use References module or Entity References will be even better.

You can add an entity reference field to book content type. Then, when you create a book, you can select relevant articles. If you want to have two-way relationship (book <--> article) then you can also use this module: drupal.org/project/cer
A good addition can be this module also: http://drupal.org/project/inline_entity_form which allows you to create or select your articles when you create a book.

Then in your view, you can show book's titles as fields.
Add a relationship with your entity refrence field.
Add a field "title" but select relationship you just added.
Group the results by first field (title only)


Using the back button after logging out shows you pages from the authenticated user's session

You can implement hook_init() in any of your custom modules

<?php
/**
* Implements hook_init().
*/
function YOUR_MODULE_NAME_init() {
     drupal_add_http_header('Cache-Control', 'no-cache, no-store, max-age=0, must-revalidate, post-check=0, pre-check=0');
}
?>


Using PHP 5.2.17 in Acquia Dev Desktop 2

They dropped PHP 5.2 support with DevDesktop 2. It has hit EOL so you really shouldn't be developing against it.

That said, if you really want to do this, you can find old versions of DevDesktop that used PHP 5.2. I would guess you might hit problems if your end goal is to deploy to AcquiaCloud.


You could try a wishlist or gift registry module. Here's one. I haven't tried this but it should disable or remove items from the list once people select them.

https://www.drupal.org/project/wishlist

Please note that this question has multiple or too many possible answers, so it might get disabled.


Downloading from private directory corrupting some file types

We have finally solved the issue and in case it is of use will put the answer here.

Based on this php issue we realised the issue could be a closing php tag somewhere else on the site.

In the end we found three small modules - one animated a set of banner images on the site; one made some api calls for a search feature; and another created some custom blocks from an external api call.

Each of these had ?> at the end of their .module files. Removing them fixed the problem.

Why this problem went on to affect all files served I do not know.


Not sure, but this sounds like it could be a job for the Field Collection module.


Programmatically add a translation with proper content moderation state

What is the problem you're seeing with the moderation state table? What I think I'm seeing is:

Revision 15 is the initial save of the node.
Revision 16 is the second save, where fr has changes and en does not.

I can't see anything too unusual here, but if you are running into errors later in the lifecycle of the node, that would be helpful information.
One red flag I can see in the code is manually calling setRevisionTranslationAffected and addTranslation. Many of the Content Moderation tests use the following methods to add translations and to create revisions, because that's how additional bits of metadata like the revision_translation_affected column are set:
$storage = \Drupal::entityTypeManager()->getStorage('node');
// You may try either of these two methods for creating a revision or a translation.
$storage->createRevision($node);
$storage->createTranslation($node, 'fr', $node->toArray());


How to maintain and update a Drupal installation and its modules?

I'm not sure about a guide but you will want to look into Features for change management between instances and Drush for updating Drupal and it's modules.

Anything you can't do for the database in features should be placed in an install file and applied as updates to maintain the db between instances.


How to configure mysql database connection with a different socket

According to this Drupal issue, setting the socket in the UI is just not possible right now: (at least in 8.6.10)

https://www.drupal.org/project/drupal/issues/793200

I also could not figure out how to set the socket in sites/default/settings.php.

I had to resort to hardcoding my socket in this file:

core/lib/Drupal/Core/Database/Driver/mysql/Connection.php

This block of code:

    // The DSN should use either a socket or a host/port.
    if (isset($connection_options['unix_socket'])) {
      $dsn = 'mysql:unix_socket=' . $connection_options['unix_socket'];
    }
    else {
      // Default to TCP connection on port 3306.
      $dsn = 'mysql:host=' . $connection_options['host'] . ';port=' . (empty($connection_options['port']) ? 3306 : $connection_options['port']);
    }

I could not find any way to set "unix_socket" value on $connection_options, so I resorted to hardcoding it before this block like:

$connection_options['unix_socket'] = '/path/to/my/mysql/socket';


How to edit Team Members from Drupal site

You can probably find what you need at /admin/content. What you are looking at is the views interface to build a list - the list doesn't exist anywhere but in your database, and it won't exist in the database as a list, it will just be separate rows in the database table, so don't bother looking there. The list is build from the database, using the interface that you have shown a screenshot of.

You should be able to find the various items you want at /admin/content. You may have to filter by a content type, depending on how much content is on your site.


How to get node id on hook_page_build(&$page)

Still comes through the URL indirectly, but this is the easiest way to get it: menu_get_object.

<?
if ($node = menu_get_object()) {
 $nid = $node->nid;
}
?>

Note that if there is a node, it was already loaded by the menu system anyway and this is loaded from the static cache.

Refer this discussion for more detail.


How to configure programmatically a unique constraint on several fields of a custom entity?

As suggested by elstevenson, I used the validation API.

Here the steps.

Create a repository in your module repo.
/src/Plugin/Validation/Constraint
Create a constraint (name = Unique)

namespace Drupal\module_name\Plugin\Validation\Constraint;
use Symfony\Component\Validator\Constraint;

/**
* @Constraint(
*   id = "Unique",
*   label = @Translation("Unique ", context = "Validation"),
*   type = "entity:entity_name"`
* )
*/

class UniqueConstraint extends Constraint {
   public $message= 'Unique entity!';
   }

Create a constraintValidator, and we populate the validate method with an entity query to make sure that there is no record having the same value of field1 and field 2:

 namespace Drupal\module_name\Plugin\Validation\Constraint;
 use Symfony\Component\Validator\Constraint;
 use Symfony\Component\Validator\ConstraintValidator;

class UniqueConstraintValidator extends ConstraintValidator {

/**
 * {@inheritdoc}
 */
public function validate($entity, Constraint $constraint) {
 $field1 = $entity->field1->value;
 $field2 = $entity->field2->value;
 $entity_type_id = $entity->getEntityTypeId();
 $value_taken = (bool) \Drupal::entityQuery($entity_type_id)
  ->condition('field1',  $field1)
  ->condition('field2',  $field2)
  ->range(0, 1)
  ->count()
  ->execute();
if ($value_taken)
{
$this->context->addViolation($constraint->message);

}

}
  }
Then configure our constraint in our entity (annotations part):

/**

* Defines the entity_name entity.

*

    * @ingroup entity_name
    *
    * @ContentEntityType(
    *   id = "entity_name",
    *   label = @Translation("entity_name"),
    *   handlers = {
    *     ...
    *     "form" = {
    *     ..
    *     },
    *  ....
    *
    *   constraints = {
    *     "Unique" = {}
    *   }
    * )
    */

Then you should uninstall your module and then reinstall it . (if your entity is populated with data, you have to delete all the date).
In your code (for example in your form) , you have to ensure the validation :

$violations = $entity->validate();
if ($violations->count() > 0)
{
 $violation = $violations[0];

 drupal_set_message($violation->getMessage(),'warning');
}

Hope it will help.


Special characters in form element #title

Based on the version of drupal you are using, you can use one of functions below :

decode_entities($text) for Drupal 7

or

Html::decodeEntities($text) for Drupal 8

so in case of using drupal 7, Your code will looks like this:

$form['facets'][$current_property] = array(
  '#type' => 'select',
  '#title' => decode_entities($current_property),
  '#multiple' => TRUE,
  '#options' => $myoptions,
  '#default_value' => $widget->buildDefaultValue($element),
  '#attributes' => array('class' => array('facetapi-multiselect',
    $form_state['facetapi_multiselect']['facet_class'])),
  '#post_render' => array('_facetapi_multiselect_modified_disable_options'),
);


This is how I resolved this issue:

I set up my view to only print the URL of the flash file.
THen I created a views template for that specific field.
In that template file i added the HTML above and printed the output - which is the flash files path - as src.
Done!


How to create a test configuration that can called in a test class?

You are missing a couple of basic ideas of unit testing. I try to show them to you:

What is a unit?

Unit is most cases (95%+) a single class. This unit has some dependencies, using them and adding some extra logic to the whole.

In a unit test you only want to test the logic you provide in your class, but you want to make the dependencies as black boxes. A change to the implementation of the dependencies should NEVER make any difference to your unit test.
Only their interfaces what matters.

Clear Dependencies

One of the dependency injection main role is to make your class testable.
By injecting all the dependencies through the constructor you not just giving a nice list what services you class is relying on, but also make it easy to test.

Static methods should not be harder to test than object methods but they have a big drawback: you can't handle calling another static method inside them. Here is a nice explanation:

  Unit-Testing needs seams, seams is where we prevent the execution of normal code path and is how we achieve isolation of the class under test. Seams work through polymorphism, we override/implement class/interface and then wire the class under test differently in order to take control of the execution flow. With static methods there is nothing to override. Yes, static methods are easy to call, but if the static method calls another static method there is no way to override the called method dependency.

About your case

Either you need to eliminate the dependency by providing the value you need via argument, or you will have to give up unit testing on this one.
You still can write a kernel test tho. That will be of course slower, but you can also have a wider scope of functionality / integration to be tested.


Convert address to multi value during migration

I was able to accomplish this by creating a custom process plugin for the address field.

  field_address:
    -
      plugin: myaddress
      source:
        locality: city
        administrative_area: state
        postal_code: postalcode

<?php

namespace Drupal\my_migration\Plugin\migrate\process;

use Drupal\migrate\MigrateExecutableInterface;
use Drupal\migrate\ProcessPluginBase;
use Drupal\migrate\Row;

/**
 * Maps values for address.
 *
 * @MigrateProcessPlugin(
 *   id = "myaddress"
 * )
 */
class MyAddress extends ProcessPluginBase {

  /**
   * {@inheritdoc}
   */
  public function transform($value, MigrateExecutableInterface $migrate_executable, Row $row, $destination_property) {

    $parsed = [];
    // If city name has `and` or `or` it will create multiple address items.
    $cities = preg_split("/ (or|and) /", $value[0]);
    foreach ($cities as $city) {
      $data['country_code'] = 'US';
      $data['locality'] = $city;
      $data['administrative_area'] = $value[1];
      $data['postal_code'] = $value[2];
      $parsed[] = $data;
    }

    return $parsed;
  }

}

My plugin checks to see if there is a string and or or and if there is it converts it multiple values.  Of course, this works out for me because all are US and the cities are for the same state.


How to add a redirection at the end of Delete entity process?

Finally, this code works:

<?php
namespace Drupal\sel\Form;
use Drupal\Core\Entity\ContentEntityDeleteForm;
use Drupal\Core\Form\FormStateInterface;

/**
 * Provides a form for deleting Service entities.
 *
 * @ingroup sel
 */

class ServiceDeleteForm extends ContentEntityDeleteForm {

  public function submitForm(array &$form, FormStateInterface $form_state) {
    $entity = $this->getEntity();

    $entity->delete();
    $form_state->setRedirect('elsewhere', [some argument]);
    drupal_set_message($this->getDeletionMessage());

  }

  protected function getDeletionMessage() { some code }

  public function getQuestion() { some code }

}


You can use Search API with Facet API to create search pages with dynamic filters like here but you can use another modules like Ajax facets if you need checkboxes or select lists as filter widgets.

Search API needs also a database backend (Search API Database Search).


No orders in user profile with custom state of order-status

The Order History page (user/%user/orders) retrieves orders that are general in scope.

If you created a custom Status through /admin/store/settings/orders/edit/workflow/create, this scope excludes Canceled & In Checkout statuses. If you've created a custom state through hook_uc_order_state(), you need to the scope to general for it show up.


How to get "User ID From URL" with contextual filter in Pfofile2 page

If the url schema is alway the same, you can use the default value "Raw value from url" instead of "User Id from URL" and set the 'path component' in your example to '3' to get the user id.


privatemsg and services fully integration

There exist a sandbox project pm services clone comand

git clone --branch 7.x-1.x    https://git.drupal.org/sandbox/deminy/2413647.git privatemsg_services

cd privatemsg_services

also  pm services(profile2) but it needs profile2 to be enabled beore


How can I get the translated path to the current node?

The problem is the lack of a language string / prefix for polish. By this URL detection is skipped.

Look into locale_language_from_url() line 275

<?php
 case LOCALE_LANGUAGE_NEGOTIATION_URL_PREFIX:
   // $_GET['q'] might not be available at this time, because
   // path initialization runs after the language bootstrap phase.
  list($language, $_GET['q']) = language_url_split_prefix(isset($_GET['q']) ? $_GET['q'] : NULL, $languages);
  if ($language !== FALSE) {
    $language_url = $language->language;
  }
 ?>

If there is no language found in the URL is skips. Now the language detection is by session and so on. The only real option is that all languages you use have a prefix. The only real problem that than occurs is that the homepage would always redirect wich is not that nice for bots. But still better than fall back to language detection you don't want.

Besides that you could mode "default" just below "URL (prefix)" so Drupal won't use the session or the browser. But even this is not reliable from my experience.


I want to call ajax callback function from another module's controller in Drupal 8. is it possible?

If anything, this should be:

'callback' => ['\Drupal\common_functions\Controller\CommonFunctionsController', 'ajax_load_boiler_size'],

That's only if it's going to work though. No guarantees.


Draggable table: drupal_render, render, both yield an empty string for "#weight" types?

Weight objects can be rendered with form_process_weight()

    $weight = array(
        '#type' => 'weight',
        '#title' => t('Order'),
        '#default_value' => $i,
        '#delta' => 1,
        '#attributes' => array('class' => array($table_id . '-weight'))
    );

    $weight = form_process_weight($weight);


How to expose to users filter for changing views items limit for pagination?

I have done this manually.  I typically edit views-view.tpl.php file to build up a "items per page" list w/ links and tack on a perpage= GET argument.  You can do the same with a preprocess for the view, but I am spacing on what it is called.

I then implement a hook_views_pre_build:

function mymodule_views_pre_build (&$view)
{
  if ($_GET["perpage"]) {
    $perpage = check_plain($_GET["perpage"]);

    if (is_numeric($perpage) && (int) $perpage > 1) {
      $view->pager["items_per_page"] = (int) $perpage;
    } else if ($perpage == "all") {
      $view->pager["use_pager"] = false;
      $view->pager["items_per_page"] = 0;
    }
  }
}

The last time I remember doing this was with Drupal 6 and Views 2, so you may need to adjust the hook for Views 3.


Can we add the destination query parameter to a link from yml configuration?

Yes, you can add the destination query directly in the yml file.
@see : \Drupal\Core\Menu\LocalActionDefault::getOptions

ie: mymodule.links.action.yml

my_module.my_entity.add:
  route_name: node.add
  title: 'Add My Entity'
  route_parameters:
        node_type: 'my_entity'
  options:
    query:
      destination: '/path/to/redirect'
  appears_on:
    - my_module.my_entity.admin_content


Initially unchecked radio boxes in a form on load

#checked is not a property used from radios form fields, nor radio form fields. It was not even used from Drupal 6.

I used the following code, and none of the radio buttons were selected.

/**
 * Form builder.
 */
function custom_module_form($form, &$form_state) {
  $form['r_8'] = array(
    '#type' => 'radios',
    '#options' => array(
      '1' => t('Yes'),
      '0' => t('No')
    ),
    '#title' => t('Test'),
    '#default_value' => NULL,
  );

  return $form;
}

In this case, if the user doesn't select one of the radio buttons, the form field would not have a a value associated. Your code could handle it as if the user selected a third value (such as "undecided") or what your code considers the default value (e.g. "yes"); if the latter is the case, users should see a note about that.

It makes sense to use the following code, at least in a case: When you want the users voluntary select a value for the field, and not use the default one selected by the module. For example, it would make sense if the user is expressing an agreement, and you want to be sure the user noticed that field, and clicked on one of the radio buttons.

function custom_module_form($form, &$form_state) {
  $form['r_8'] = array(
    '#type' => 'radios',
    '#required' => TRUE,
    '#options' => array(
      '1' => t('Yes'),
      '0' => t('No')
    ),
    '#title' => t('Test'),
    '#default_value' => NULL,
  );

  return $form;
}


Apply the timezone offset to my date field

This took me a hot minute to figure out...
Use the format_date function, but be sure to specify how the date is stored in the db - usually UTC, and then offset by your date field's stored timezone - usually your drual admin specified default timezone.

foreach ($node->field_date['und'] as $date) {
  $unixdate = strtotime($date['value'].' '.$date['timezone_db']);
  print format_date($unixdate,'medium','',$date['timezone']);
}


Hide taxonomy term in specific node form

Use hook_form_FORM_ID_alter

/**
 * Implements hook_form_FORM_ID_alter.
 */
function my_module_form_views_exposed_form_alter(&$form, &$form_state, $form_id) {
  $vocabulary_machine_name = 'my_vocabulary'; // Makes the search faster.
  $term_names = array(
    'Term 1',
    'Term 2',
    'Term 3',
  );

  foreach ($term_names as $term_name) {
    $term = taxonomy_get_term_by_name($term_name, $vocabulary_machine_name);
    unset($form['my_field']['#options'][array_pop($term)->tid]);
  }
}


How do I change the value of a Hidden element?

Based on @mradcliffe suggestion, I've implemented hook_form_FORM_ID_alter() and I do:

$form['elements']['hidden_element_name']['#value'] = 'New value of the hidden element';

It works for me! I hope it helps someone!


Responsive Image Module is only selecting fallback image style

The posted responsive image configuration seems correct. Remember that you also need to change the image field formatter to "Responsive image". If you are using image fields on node entities, you can do this at

/admin/structure/types/manage/MY_NODE_TYPE/display/MY_VIEW_MODE

(If you are using image media entities instead of image fields, use the "Rendered entity" field formatter on the node, and switch to the "Responsive image" field formatter on the media entity at /admin/structure/media/manage/MY_MEDIA_TYPE/display/MY_VIEW_MODE )


Custom view sort plugin not working only when used in table sorting

The problem is that for click sorting it seems that not the view sort plugin is used but the field handler which holds a method clickSort
So here is the solution:
1.) I defined a custom field handler. This can be done in hook_views_data or hook_views_data_alter. I did it in my custom views EntityViewsData extending class:
$data['custom_entity']['committee_role']['field']['id'] = 'committee_role';

2.) Then I defined the field handler class where clickSort can be overwritten.
use Drupal\Core\Database\Database;
use Drupal\views\Plugin\views\field\EntityField;

/**
 * @ingroup views_field_handlers
 *
 * @ViewsField("committee_role")
 */
class CommitteeRole extends EntityField {

  public function clickSort($order) {
    // No column selected, can't continue.
    if (empty($this->options['click_sort_column'])) {
      return;
    }

    $this->ensureMyTable();
    $field_storage = \Drupal::service('entity_field.manager')->getFieldStorageDefinitions('committee_membership')[$this->field];
    $allowed_values = array_keys(options_allowed_values($field_storage));
    $formula = 'FIELD(' . $this->tableAlias . '.' . $this->field . ', ' . implode(', ', array_map(array(Database::getConnection(), 'quote'), $allowed_values)) . ')';

    $this->query->addOrderBy(NULL, $formula, $order, $this->tableAlias . '_' . $this->field . '_keys');
  }
}

After clearing the caching the results in the table are sorted the same way as in the other view. Strange that there is an additional sorting logic in views when a table display is used and the sorting is done via column headers.


Undoing Content Changes Made with Admin Panel

Your ability to undo changes depends on what you changed and how your site was set up. Some components of Drupal can be reverted, like if you have revisions enabled on your nodes. A more advanced set-up may have "Features" which allow you to revert all sorts of things. It really depends.

For most changes you make in the admin panel, you need to find the setting you adjusted and change it back to its original value. It would help if you described your issue in more detail, like what settings were being adjusted and what version of Drupal you were using.


How can I modify the advanced search form when my hook runs too early?

Changing the module weight will work, but sometimes that can cause problems with the order in which other hooks in your module are invoked.
Drupal provides hook_module_implements_alter() for exactly this sort of situation, so that you can target the order a specific hook is run in:

Alter the registry of modules implementing a hook.
This hook is invoked during module_implements(). A module may implement this hook in order to reorder the implementing modules, which are otherwise ordered by the module's system weight.

The code might look something like
function MYMODULE_module_implements_alter(&$implementations, $hook) {
  if ($hook == 'form_alter') {
    // Move MYMODULE to the end of the list.
    $group = $implementations['MYMODULE'];
    unset($implementations['MYMODULE']);
    $implementations['MYMODULE'] = $group;
  }
}

Once you clear the cache your module's implementation of hook_form_alter() will be invoked last (unless of course another module is implementing hook_module_implements_alter() and altering the order again. But that's a different story).
I personally prefer this method as it's just a simple code change, no need to maintain any changes to the system table in the database.
I'm not sure how well that works with a form_FORM_ID_alter hook (never tried it), but with this method you can at least make sure that only the weight for hook_form_alter() need be updated.
Actually looking at the code for drupal_alter(), changing the conditional to if ($hook == 'form_search_form_alter') would probably work.


Actually if you are doing field translation then there is no point of having translate now link at Node level. For this there is always translate primary tab for this. see in screenshot.

Still if you want to achieve this functionality, loop through this array within node object.

$node->translations->data

Do this in module file in hook_preprocess_HOOK here it will be hook_preprocess_node and pass a variable to node.tpl.php


The Embedded Image Field module supports third party image content and also you can integrate with views.

Also look into below module

Remote stream wrapper Provides the ability to use external files with file fields without saving the files to your local files directory. Also provides a 'Remote URL' browser plugin for Media. see DEMO


Drupal 7 theme('pager') -> PDOException: SQLSTATE[42S02]: Base table or view not found

The error is down to the:

// Show pagination in output
$output .= theme('pager');
// echo output to screen
echo $output;

being above db_set_active();

Not sure why this is but it fixes the problem.

Thanks


Customizing Search File Attachments result page

Finally I ended up with some advanced search modules, Which made the search so much better. I used Apache solr and Apache solr attachments modules. This gave me ability to make my search results in a customized way via hooks. I use hook_apachesolr_process_results() to change my results.

First I add a extra field to the file type entities in the solr index, which contain the node title.

/**
 * Implements hook_apachesolr_index_document_build().
 */
function mymodule_apachesolr_index_document_build(ApacheSolrDocument $document, $entity, $entity_type, $env_id) {
    //dsm($entity_type);
    //if the type is file
    if($entity_type == 'file'){
        //add a field node title
        $title = code for getting the node tile of this file
        $document->addField('ts_field_node_title', $title);
    }
}

Now this extra field will be available in your search results. So you can directly use the title instead of file name.

/**
* Implements hook_apachesolr_process_results().
*/
function mymodule_apachesolr_process_results(&$arg) {

    for($i = 0, $l = count($arg); $i < $l; $i++) {
        //if entity type is file change the title
        if($arg[$i]['node']->entity_type != 'node'){
           $arg[$i]['title'] = $arg[$i]['fields']['ts_field_node_title'];
        }
    }

}

Peace! :)


Add class to "link to content" view field

Along with Wims suggestion, I would suggest (as I usually do) to bypass fields in views, and render the view mode of the entity in question. Usually, this is sufficient in most cases if this is a presentation based view, and not a 'report' style view (where records are in table format and fields serve as cell data).

Then, supply the twig template for view modes, where the title is linked, and you can add the class(es) there. Now when you use that view mode to render in Views, it uses one template and is consistent, and Views that rely on rendering entities become easier to maintain and quicker to setup.

Here is an article that explains the difference and the benefit: https://www.amazeelabs.com/en/blog/views-field-rewriting-to-views-modes

That said, no, links themselves do not have a twig file (where you would see the anchor tag markup). I have seen the |merge option before that Wim linked to, though I have been unsuccessful in getting that to work in 8.2.5.

You could also implement theme_preprocess_field and supply the class to the attributes before it is rendered, though as you can imagine, if you have a lot of these, it'll be some work.


Which event should we subscribe to if we want code to be triggered when a new user registers?

AccountEvents::SET_USER isn't the event for user registration. Per the docs:

  This event allows modules to perform an action whenever the current user is
  set. The event listener receives an \Drupal\Core\Session\AccountSetEvent
  instance.

The event is fired when Drupal initializes the user object for the current request, not when new users are created.

For responding to new user creation, you can still use hook_user_insert().


How to load all field values from multiple entities?

EFQ will return an entity stub, if you want the fully loaded entities, you can try something like:

// Build query
$query = new EntityFieldQuery();
$query->entityCondition('entity_type', 'user');
$query->fieldCondition('field_my_field', 'value', $values);
// Execute for result
$result = $query->execute();
// If has data
if (!empty($result['user'])) {
  // Load users
  $accounts = entity_load('user', array_keys($result['user']));
  // If using devel
  // dpm($accounts);
}else{
  // No results
}