I'm working on Entity API documentation here: https://drupal.org/developing/api/entity.

The question is too big to answer in detail, and it depends on whether you need content or config entities. Assuming you want content entities (stored in database, can be fieldable/revisionable/..., details in the link above), you need to do something like this, the documentation linked above will eventually cover each step, including tutorials, right now, it only covers the first steps.

Provide an entity class and add the necessary annotations to expose it as an entity.
Provide the necessary table(s), you don't have to change much if you already have your 7.x schema, but you want to add a uuid and possibly langcode column if your entity can have a language/be translatable. See the node example linked in step if you want to make some base fields (properties) translatable or revisionable, you currently need to provide the necessary tables yourself.
Provide the base field definitions in your baseFieldDefinitions() method.. Note that the way this works will change in https://drupal.org/node/2047229 (from arrays to classes).
Implement the necessary pre/post Save/load/Delete methods if you have custom logic that needs to happen e.g. before saving an entity (like updating the changed timestamp).
Implement an access controller if you have non-trivial access logic and override the checkAccess() and checkCreateAccess() methods or specify the admin_permission in your annotation if you just have a single permission that allows full access.
It is recommended although not technically required to provide an interface for your entity class (e.g. NodeInterface for Node) that includes useful (usually get/set/isSomething()) methods for your base fields, so that you can type hint on the interface and get auto-complete for those methods.

Depending on what you need, there will also be further steps, like defining the necessary forms, possibly a render controller and so on, but those should probably be separate questions if you need more information.

Notes:

Config entities are basically similar, except you need to use the config storage controller (https://drupal.org/node/2119905 will make this easier), you don't need to define table schemas (obviously) but you need to provide a config schema file, see e.g. those for taxonomy vocabularies or node types.
Content entities don't have their base fields defined as public or protected properties, instead, they are automatically managed in the values and fields properties. Access them either through get()/set() or the corresponding magic methods. ($node->title is equal to $node->get('title')).
Help on the documentation there would be very welcome. I've created a basic outline for the content/structure I'd like to have, so just create a new page and get started on e.g.  I'm also interested in having simplified tutorials, for config entities, there's one here already that I will move over to the entity documentation when ready: https://drupal.org/node/1809494
Core has quite a large number of content entity implementations, if you want to see working examples: Node, User, Term, Comment, CustomBlock, ... as the article linked in step 1 explains, you can always find the entity types provided by a module in the Entity namespaace.
@fago just gave a presentation about Entity API at the DrupalCamp Vienna this weekend, covers a lot of what I wrote here and more.


path_to_theme() goes to parent theme not subtheme

I had this problem too. Solution here, applied to node instead of page, worked for me: copy node.tpl.php to your custom theme templates directory. Once I did that, path_to_theme() behaved correctly.


Is it possible to use a condition set component as a parameter for another component?

This answer provides a way to capture the following common pattern for Rules: "If conditions A and conditions B, then do actions" for fixed conditions A and actions. Instead of creating a separate condition set component for every conditions B (and then use those components inside some kind of "abstract" Rules component as a variable), the following approach is way easier:

Create a condition set component for conditions A, say My component for conditions A.
Create an action set component for actions, say My component for actions.
For every conditions B, create a new Rule.
For every new Rule, add My component for conditions A to the conditions, and My component for actions to the actions. Then, complement the conditions with conditions B.

Result: we fixed the never-changing conditions A and actions in 2 Rules components. That saves us a lot of redundant repetitive work. If we want to implement 10 cases of the general pattern, then we end up with 10 Rules + 2 Rules components = 12 Rules in total.

Let's compare this approach with the initial idea. We would have to create 10 Rules components for the conditions B + 1 "abstract" Rules component + 10 Rules that contain this "abstract" Rules component in their actions = 21 Rules in total.

The advantage of the proposed alternative approach is less Rules in total. The disadvantage is that every Rule needs to include the same action set and condition set components. But to be honest, adding those 2 components to the Rules takes much less clicks and time than creating new Rules... I think this problem nicely illustrates the power of action sets and condition sets in the Rules module (a feature that might seem somewhat obscure for beginners).


Actually you need to different keys one for the browser (client side) and one for the server . You already have configured your server key but you need to get a new key from google developer dashboard for the browser side .
then go to google_store_locator.module line 441 and change it to :

'js' => array('//maps.googleapis.com/maps/api/js?sensor=false&libraries=places&key=' . variable_get('geocoder_apikey_google_client') => array('type' => 'external')),


Pre-HTML5 way

Sorry no, it is not easy nor stable. Footer is a part of HTML structure, and HTML is send with each request. You would need to remake a lot of Drupal to make it's navigation AJAX based to leave footer in place and reload just changes. I did it, once.

First problem is - if you change anything before #, browser will reload, it's mandatory. So you would need to send HTTP 204 No Content and hope user's browser really understands it. Then, JavaScript would need to detect answer like that, generate proper AJAX query. Or you could use js to insert # into every link and then send AJAX.

Either way, in PHP you would need to be able to serve stripped version of HTML structure. I did it by appending ?ajax=true and in theme stripping everything before and after my #main-container and sending only it's content. Of course if you use "# way", you cannot just paste content. You need to treat links inside.

Long story short, it was complicated, dirty, and worked like a magic. But worked all right.

HTML 5 way

Use <audio> tag like this:

<audio autoplay loop>
  <source src="ambient.mp3">
</audio>

And let the browser care.


Taxonomy search block - Search for e.g. "mac" -> Go to URL /tags/mac

You can use Custom Search module. This module allows you to manipulate search functionality.

It has sub module called custom search Taxonomy which allows you to search according to taxonomy terms.

This allows you to configure path also.

If you want to use custom search paths, enter them here in the form path|label,
one per line (if only one path is specified, the selector will be hidden).

The [key] token will be replaced by what is entered in the search box, and the [terms] token will be replaced by the selected taxonomy term id(s).

Ie: mysearch/[key]/[terms]|My custom search label.


how to update the form values after pressing the submit button

You're mixing up #value and #default_value. If you want to show information in the form but let the user change it, you need to use #default_value. If you want the information to always be the same, and never let the user change it, use #value.


How do I display a view content for a specific user?

You can set permission for the specific role in view. Check the access in page/block settings

Change the access permission to role, then check the access for the specific roles for view content.

For example, Restrict View for the authenticated user. So, the users who are belonging to the authenticated user roles can able to access the content, other roles cant access it.


What is the purpose of _services_controller_execute_preserve_user_switch_anonymous()?

The user register action (which is essentially just an alias of the user.create resource) executes the user register form. Doing so affects the global $user object, which overwrites any existing $user object. Other resources related to the user will also do the same thing.

This is undesirable, as it replaces the global user that you're using to authenticate against the endpoint. So the Services module saves your session before executing any callbacks, and restores it afterwards. This ensures the integrity of the original session.

I think the misunderstanding is simply that you're expecting the user register resource to automatically invalidate the current session, and replace it with a session for the newly created user. I can't see anything in the code that would suggest that's supposed to happen, and it makes sense that it wouldn't...

Imagine your app needed to register 10 users in a batch; if your session was invalidated each time you made a call to user.register, and replaced with a session for the new user, you'd have to logout and potentially re-authenticate before each subsequent registration. Not an ideal situation to be in.


Custom field widget form - Multiple values

You can use drupal form api attributes like

 case 'select':
        $widget += array(
          '#type' => 'select',
          '#prefix' => '
',
          '#suffix' => '
',
          '#options' => $options,
          '#delta' => $delta,
          '#element_validate' => array('_entityreference_hierachy_option_limit_validate'),
          '#default_value' =>  $saved_target_id,
          '#multiple' => $multiple,
          '#size' => $multiple ? min(12,count($options)) : 0,
        );
        break;

https://api.drupal.org/api/drupal/developer!topics!forms_api_reference.html/7#multiple


How do I use it only in the frontend theme?

With jQuery Update 7.x-3.0-alpha2 and later, there is a setting that allows to change the jQuery used for a specific theme; you can select:

The site default version (set with the jQuery Update module)
The version that comes with Drupal
Any version supported by the jQuery Update module


In the Encrypt module, can I switch between phpseclib and mcrypt assuming I keep the Key Provider Settings in place?

No. You cannot just switch out the encryption methods. Mcrypt AES (CBC Mode) pads the input and also prepends two salts and an IV as well other information like the HMAC for authentication in it's output. phpseclib does none of this. Here are some examples:

encrypt('all your base');
// $text = "TUsE3Fwzvj6MT41ritVO/zUuJ/qWNmZJIBU3euDEX9iDMb3IqMyTJEFwssW/SI/GZ8ce/HxqrqPFWGzTNC0d7UZUtRjr2JReoqaCqw18GHyGhbjqr1zZbr/MCIT1rENM";

encrypt('all your base', array(), 'phpseclib');
// $text = "1r/WWYiCW9icZ93iUxStMQ==";

You can actually rewrite the existing mcrypt plugin to use phpseclib instead. You wouldn't necessarily need the HMAC stuff—it's there for added benefit but you can just skip it. But you likely could make a pain-free transition.

For example, replacing the existing decryption code in _encrypt_encryption_methods_mcrypt_aes_cbc():

// Initialize for decryption.
mcrypt_generic_init($mcrypt, $ekey, $iv);

// Decrypt the data.
$processed_text = mdecrypt_generic($mcrypt, $text);

// Terminate decryption.
mcrypt_generic_deinit($mcrypt);

// Remove any padding.
$pad = ord($processed_text[strlen($processed_text) - 1]);
$processed_text = substr($processed_text, 0, -$pad);

// Close the Mcrypt handle.
mcrypt_module_close($mcrypt);

With this rewrite:

$path = libraries_get_path('phpseclib');
require_once $path . '/Crypt/AES.php';
$aes = new Crypt_AES();
$aes->setIV($iv);
$aes->setKey($ekey);
$processed_text = $aes->decrypt($text);

Returns the correct plain-text given the original mcrypt encryption ciphertext. At least, it should. I've got mcrypt on my system and so phpseclib is probably using it, but it should "just work" for you.

Oh yeah, FYI, use phpseclib 1.x. As the 2.x branch will not work.


Yes it is possible to use only context module to override layout.

When you first add context @ admin/structure/context/add, you need to select condition as "path" and reaction can be whatever you want. For ex. choose reaction as "Regions" and then go ahead disable region for the sleected "path" (the one you chose above in condition).

Just remember context module will use your existing theme layout and regions (.tpl.php files) unlike in panels where it allows you create your own regions and layout.


How to remove (not verified) status in anonymous comments?

You can implement hook_preprocess_username and remove the extra variable:

function THEME_preprocess_username(&$variables) {
  $variables['extra'] = '';
}


How to create internal and external links

To be honest, I don't know anything about Drupal 4.  I don't regard it as a platform to build on in 2014.

In Drupal 7, out of he box, you create links using plain HTML:

internal link
external link

There are a bunch of modules for Drupal 7 you can install that gives you other syntaxes for adding links to content. To mimic the square brackets around tags syntax you cite as example. Install the Bbcode module.  It uses markup based upon BBCode.  For a more modern style, similar to StackExchange, install the Markdown filter module. It let content authors use markup based upon John Gruber's Markdown.


Add additional information to a field of a content type

Some solutions you have:

1) create field Product with multi values to content type Order bases on a table field. Module : https://www.drupal.org/project/tablefield

In this table you can attached the prices and with a custom module do the counting.

2) Create content type Order, create content type Product. In content type Product add a field price. Make a relation to entity from Order to Product.

3) Make use of ubercard. This will define products, cards and as far I can remember the recalculation of the card can be refreshed easily

4) Make use of Drupal Commerce, I know it is possible in there but never used it.

Let me know if you need more details.


Show all taxonomy terms on taxonomy term page

There are couple of modules to solve this purpose

Taxonomy Block
Taxonomy Menu Block

Here is the config page of taxonomy menu block module


It appears that this can't be done using the standard webform module. It defines a limited list of tokens that hasn't been updated for the new user fields. They are included as tokens (if you use field_nnn) but they will be an empty value.

After initially looking at building a custom module, it seems that the Tokens module does make user fields available in the form [user:field_nnn].


Hide dates in the present in .tpl.php files

Presuming you are using the Date module. In the Manage Display settings for the content type, modify the setting for the Date output and put 'now' in the 'starting from' box.


What is the difference between hook_menu(), hook_menu_alter(), and hook_menu_link_alter()?

hook_menu() -> Define menu items and page callbacks.

hook_menu_alter() -> Alter the data being saved to the {menu_router} table after hook_menu is invoked.

hook_menu_link_alter() -> Alter the data being saved to the {menu_links} table


Search user by field value using Drupal Search Api

On the first hand, can you check if your content is being indexed properly ?
If yes, then I would recommend using the default search box provided by drupal, and see if you get results.

Assuming you are using search api solr module.


How to change permissions to a role when a content is set as published

You could use the following code.

use Drupal\Core\Access\AccessResult;
use Drupal\node\NodeInterface;
use Drupal\Core\Session\AccountInterface;
use Drupal\user\Entity;

function mymodule_node_access(NodeInterface $node, $op, AccountInterface $account) {
  $type = $node->getType();
  // Is it published?
  $nodeIsPublished = $node->isPublished();
  if ($type == 'news' && $operation != 'view' && $nodeIsPublished == 1) {
    if($account->hasRole('rolename')) {
       return  AccessResult::forbidden();
    }
    else {
      return AccessResult::allowed();
    }
  }
  return AccessResult::neutral();
}

Also, the Override Node Options module allows permissions to be set for each field within the Authoring information and Publishing options fieldsets on the node form.


Try with the String Overrides module. Here is a quote about it (from the module's project page):

Provides a quick and easy way to replace any text on the site.
Features

Easily replace anything that's passed through t()
Locale support, allowing you to override strings in any language
Ability to import/export *.po files, for easy migration from the Locale module
Note that this is not a replacement to Locale as having thousands of overrides can cause more pain then benefit. Use this only if you need a few easy text changes.


How to use different value from select options vs what's displayed? Name vs Realname

Having changed it to $account->name I managed to find out what's going using devel command dpr($variable) which contained the users uid.

Then I just needed to replace the user lookup query accordingly to cross check from realname table with that of the users based on uid.

$query = db_select('realname','rn');
$query->join('users','usr','usr.uid=rn.uid');
$query->fields('rn', array('uid'));
$query->condition('rn.realname',$mail,'=');
$result =$query->execute()->fetchAll();

if (!empty($result)) {
$uids =array($result[0]->uid);
$account = user_load_multiple($uids);
$account = array_shift($account);
}


hook_services_request_postprocess_alter() looks like a good candidate. I don't have an installation to test with right now but something like this ought to work:

function MYMODULE_services_request_postprocess_alter($controller, $args, &$result) {
  if (isset($result['form_errors'])) {
    array_walk($result['form_errors'], function(&$error) {
      $error = strip_tags($error);
    });
  }
}


Deleting modules from the database that aren't on the filesystem

Try the Schema module.

This module compares the live database structure with the schema structure declared by all enabled modules, reporting
on any missing or incorrect tables

  The Schema module provides additional Schema-related functionality not provided by the core Schema API that is useful for module developers. Currently, this includes:

  Schema documentation: hyperlinked display of the schema's embedded    documentation explaining what each table and field is for.
  Schema structure generation: the module examines the live database    and creates Schema API data structures for all tables that match the
  live database.
  Schema comparison: the module compares the live database structure    with the schema structure declared by all enabled modules, reporting
  on any missing or incorrect tables.


The Google Ad Manager module uses a filter for the tokens, not the Token module. You could call its internal function $content=_google_admanager_substitute_tags($text); to do the substitution for you, where you replace $text with [google_ad:ad_slot] but I am not sure if it will know enough to put all the google js in your page. Try it out, I guess.

Otherwise, you can do something like $content=theme('google_admanager_block', $gid, $google_ad); where $gid=variable_get('google_admanager_account',''); and $google_ad is your ad slot. That I've done all over the place myself with reasonable success.


Allow to filter (in a view) on a datetime field of a custom entity

As there are so many difficulties with base fields (sorting, displaying, filter etc in views), I decided to remove all of them and I re-created them back in the field UI.
To allow this, I set fieldable = TRUE, and field_ui_base_route = some_path in the annotations of my entity.
This is of course poor design because each field will create a table on its own but I had no time to spend on this...
Feel free to provide a better answer... I think we need a real how-to to provide the same functionalities we have for fields created in UI then for base fields
Edit to add: I have created an issue to create an help item on this topic: https://www.drupal.org/project/drupal/issues/3213021


How to add class to field--item element generated by paragraphs

It depends a little on how your Paragraph is structured. Is it a single paragraph type with multiple generic fields in it or a paragraph with multiple other paragraph types inside of it?

If it's the latter, you have to create two twig files (For the parent and the child) but you can control output for each row and the contents of each row.

Alternatively, if you are just trying to style each item what's wrong with just selecting the field--item elements, eg:

 .field--whatever-parent-is-called .field--item { style here. }


How do I deal with discounts/refunds and a payment gateway to achieve accurate reporting for accounting?

Step 1 - Enable Commerce RMA
First of all, you need to get something in place to enable the tracking/registration of such refund requests within the Drupal Commerce ecosystem. For that, the Commerce Return Merchandise Authorization module appears to be the best alternative available today. Some more details about this module (from its project page):

This module aims to extend Drupal Commerce with the Return Merchandise Authorization functionality. It's built on top of the nice Entity API library and using its own Entity Type (CommerceReturn).
Feature list:

Exposes a return of goods workflow on customer side.
Ability to separate products that can and cannot be returned
Ability to specify a return period, after which the ability to create an RMA is not available.
Provide an Admin UI to manage customer returns. Admin can remove or add product and change the prices of returned product.
Ability to customize the customer reasons on both product and product type levels.

Step 2 - Create custom Rules reacting to Rules Events about a CommerceReturn
By using the Commerce Return Merchandise Authorization module, you'll get the CommerceReturn entity types available. And because of those entity types, it opens up all sorts of custom business logic you may want to implement by using the Rules module. That will allow you to build custom rules that react on the typical entity-related Rules Events, such as:

After deleting a CommerceReturn.
After saving a new CommerceReturn.
After updating an existing CommerceReturn.
Before saving a CommerceReturn.

Step 3 - Create custom Views about CommerceReturn entities
As per those CommerceReturn entities, you also get out-of-the-box reporting (and even charting ...) capabilites by simply using the Views module. So for anything that is not already covered by Commerce Reporting, just create the required custom Views.
Step 4 - Create work-arounds for payment gateway limitations
I'm not aware of any solutions to also automagically take care of the payment gateway processing for such refunds. Especially because I think that there is no way to refund part of a transaction.
However, if you have the Rules module available (see above), you might create custom rules with Rules Actions that (eg) transform such CommerceReturn entities in (e.g.) User Points (piece of cake), so that they can be used to get discounts on future transactions.
Summary
The above is not a perfect/complete solution, but at least an improvement as compared to the  "requests of a refund via good old fashioned email" (as in your question). Actually it would at least keep track of such outstanding refunds to be processed.
PS: I'm assuming this is about D7.


No, there is no reliable comparison, because doing that is almost impossible. There are various reasons for that, one is that D8 vanilla is like D7 vanilla + a whole bunch of modules, especially views.

If you compare a single request on a vanilla installation, then D8 is clearly slower than D7 (even if you add views), quite a bit actually. That might still improve more or less until the release, but it's not going turn around completely.

D8 is just running a lot more code, our own and vendor code like symfony underneath, so that takes more time. The service container also adds quite a bit of overhead.

However, D8 has a number of things that are hopefully going to make more than up for that on real sites

Javascript by default runs in the footer, which improves front-end performance, as pages build up faster and you can see and use them earlier.
The highly improved caching, especially render caching with cache tags and contexts, means that caches on real sites with changing content will perform much better. In D7, every time a node was changed or created, the complete block and page cache were invalidated. In D8, thanks to cache tags, D8 knows where that node shows up and might show up and only has to invalidate the relevant pieces. There's still a lot of work going on to improve that, but D8 provides a lot more tools to build faster big sites.
There's also the argument that you would have to run D7 on hardware that is as old as that version while running D8 on modern hardware, which is considerably faster. Also, early benchmarks show that vanilla D8 runs up to 50% faster with PHP7, because that version is much better at running a lot of code fast. (You can also run D7 on modern hardware and with PHP7 (probably), so that argument only works so far...)
Thanks to those decoupled services and better API's, which in a first step make things slower, is D8 going to have much better support for running partially/completely (depending on how daring you are I guess) with MongoDB and other alternative backends (like redis for the key value store). Again, for big sites, that allows to take at least part of the load away from MySQL, and store parts of your data (or, again, everything) elsewhere, which in turn helps to distribute the load across multiple servers.

Also keep in mind, if you care about performance, then you're very likely not running vanilla D7/D8 sites, you have large sites with a lot of content. And as mentioned above, D8 brings a lot of tools to help you to make those kind of sites faster. Some things will require work as a developer and need to be done right (just like in D7), but if you do, then I think that D8 can perform pretty well in real world scenarios.


How to create notifications like Facebook about pending workflow approvals?

Have a look at one of the answers to "Notification + Subscription: Can this combination recipe be used to create notification system similar to Facebook's?", which explains how the Menu Badges module can be used for this. The result of using it looks as in this example:

The current status of this module for D8 is like so:

  The 8.x-1.x-dev release includes all the functionality of the Drupal 7 version. However, it is not yet completely working with the new caching that Drupal 8 does. Badges are getting cached and don't change when they should. Once that is fixed, a stable release will be created.

To implement it for supporting what you decribed in your update, you only have to create an appropriate view (using views) with as results the updated content that the editor should be notified about.


The first sentence you quoted is wrong. "file path" is not a must, if you set "file"; in fact, by default Drupal will take its value is the directory containing the module implementing the menu. If you want to use a different directory, such as drupal_get_path('module', 'mymodule') . '/includes'), then you can set "file path."

_menu_router_build() contains the following code.

// Calculate out the file to be included for each callback, if any.
if ($item['file']) {
  $file_path = $item['file path'] ? $item['file path'] : drupal_get_path('module', $item['module']);
  $item['include file'] = $file_path . '/' . $item['file'];
}

$item['module'] is set by menu_router_build() using the following code.

  foreach (module_implements('menu') as $module) {
    $router_items = call_user_func($module . '_menu');
    if (isset($router_items) && is_array($router_items)) {
      foreach (array_keys($router_items) as $path) {
        $router_items[$path]['module'] = $module;
      }
      $callbacks = array_merge($callbacks, $router_items);
    }
  }

A module could implement hook_menu_alter() to alter $item['module'].


You should set in the content type translation settings, to show no fallback language, and set all english nodes to English, rather than Language neutral (if they are such).


How can I embed the content of a field into the content of another field?

You can combine two fields in hook_ENTITY_TYPE_view()

function mymodule_node_view(&$build, $entity, $display, $view_mode) {

  if (isset($build['field_source'][0]['#markup']) && isset($build['body']['0']['#text'])) {

    $build['body']['0']['#text'] =
      '<strong>(' . $build['field_source'][0]['#markup'] . ')</strong> ' .
      $build['body']['0']['#text'];

    unset($build['field_source']);

  }
}

and unset the added field to avoid double content.

You can also add html tags if they are allowed in the text format.

This is an example. You have to look into the build array after you've configured the display mode in ui and adjust the array keys.


Displaying all values of a List (text) field, whether checked or unchecked

You can easily generate a field formatter to output what you need in drupal 8 (generate field formatter => drupal gpff with drupal console) and get the result into a view.

Getting the field definition will allow you to get all possibles values (selected or not) for your list and display items as check or not considering the current node value.

$defs = \Drupal::service('entity_field.manager')->getFieldDefinitions('{ENTITY_TYPE}', '{BUNDLE}');
$field_definition = $defs['{FIELD_NAME}'];

Your custom formatter will be available in views (and everywhere it is usable, node display etc.).


Webform field options missing Entity Reference?

This module might do what you want, webform references.

From description,

  Provides a webform component that can reference a node/term/user in webform. It provides "Select List", "Autocomplete", "Checkbox" and "Radio" as widget.
  A view with entityreference display can also be used to get the list as options.


The multiping module will provide this feature in Drupal 7, since the ping module is not part of core anymore. The D7 branch hasn't been started, but there is a patch that you can test that ports the module to Drupal 7. If you test it and it works for you, please comment on that issue, the more people that review that patch the closer the module will get to a full D7 release.


Is it possible to reference a field to a node, and also to a user?

I found an answer. The modules entity_reference and field_collection are what I needed. field_collection makes a collection that has a reference to the node, and also to the user_reference. An awesome module!


Please check hook_menu() documentation.

You need to specify page callback arguments like:

'title' => 'Example Page',
'page callback' => 'drupal_get_form',
'page arguments' => array('my_form_id'),
'access arguments' => array('access content'),
'type' => MENU_SUGGESTED_ITEM,


How to resolve the MySQL error Duplicate entry 'comment_publish_action' for key 'PRIMARY'?

From the information provided in the question so far, it is hard to tell what is causing your problem (consider refining your question by editing it).

However, as an alternative, you may want to consider using the Backup and Migrate module like so:

install that module on both Drupal sites (where you want to export from, and where you want to import to).
use this module to create a backup in the originating Drupal site (and save it somewhere to a local file), of the relevant tables in the MySQL database.
use this module to restore that "local file" (= backup) to import it in your target site (which is where you're currently encountering the problem.

Does this help somehow?


How to escape a string so it does not get replaced by Token::replace()

Token::replace() allows you to use a callback to replace extra tokens no module define, but that is called after the tokens have been replaced; plus, it gets a array as array($original_token => $replacement) which makes things slower since you would need to replace each token one by one.

I would rather set 'clear' to FALSE, and then replace all the tokens that have not been replaced with an empty string. Since the strings you need to keep follow a specific pattern, it would be easier to remove the unreplaced tokens with preg_replace().


How to enable highlighted search functionality?

You can use the Highlight module:

  Highlight the keywords from referrer search engine
  Highlight the keywords from local search

If you need more information you can read this posts:

Highlight searched keyword using exposed filter views?
Add Keyword Highlighting using Search API in Drupal 7


Automatic Google translation when there is no real translation

I have an idea that we can achieve using gtranslate language dropdown (hidden) and drupal langauge dropdown

Steps
in hook_preprocess_page check node has translation if yes make the page is not google translatable using class "notranslate"
if it has not translation then pass the language code to javascript and call google translate function

For Exampel:
/**
 * Implements hook_preprocess_page().
 */
function hook_preprocess_page(&$variables) {
  $variables['attributes']['class'] = [];
    $language = \Drupal::languageManager()->getCurrentLanguage()->getId();

$variables['attributes']['class'][] = 'node-' . $nid;

if(isset($variables['node'])) {
    $nid = $variables['node']->id();

    if($variables['node']->hasTranslation($language)) {
        $variables['attributes']['class'][] = 'notranslate';
    }
    else {
        $variables['#attached']['drupalSettings']['language'] = $language;
    }
}

}

In Custom.js

doGTranslate('en|' + drupalSettings.language);


Creating and updateable block on home page of site

Drupal allows a node to be marked as "Promoted to front page" when editing the page (it's at the bottom, under "Publishing options").
You can make your block from a View

Enable the Views module.
Add a new view admin/structure/views/add
Create a block (untick create a page)
Click "Continue & edit"
Add a filter by "Promoted to front page"
Alter "Use pager" to display 1 item.
You should already have a sort by post date.
Save changes.
Add the block to your home page (it sounds like you already know how to do this, but ask if not).

This view will show the most recent item with promoted to front page set.


Don't display block title on some content types

Do you have Ctools installed? Then you have two visibility plugins for content types. One from Ctools and one from core. Better use that from core, because Ctools is still alpha. If you install the module Block Visibility Groups, then you get the option to negate the condition also for the core plugin.

A core only workaround would be to use the path of the content type and negate this.


How to remove "authenticated-user" from this [user:roles:join-path]/[user:name]

You can implement hook_pathauto_alias_alter(), which is invoked from pathauto_create_alias(). The function passes the pattern used from the Pathauto module before the tokens are replaced in $context['pattern']. You probably want to check the pattern contains "[user:roles:join-path]" to avoid "authenticated-user" is removed where the pattern explicitly uses "authenticated-user".

The alternatives would be:

Implement hook_tokens_alter() to alter the output of that token, but that would change it in any place the token is used, not only in alias created from the Pathauto module
Implement hook_tokens(), and hook_token_info() to implement a token similar to [user:roles] but that doesn't include the string for the authenticated user role

Notice that it is the Pathauto module that handles the :join-path part of the token, in pathauto_tokens().


Send Email upon Registration to Author of node

So after getting the base set I needed to connect to the table for the users profile information.

So for first name it would be:

[registration:entity:author:profile-main:field_first_name]

So for phone number it would be:(field_office is what they called the Office Phone field.)

[registration:entity:author:profile-main:field_office]

Hope it helps someone else.


Custom save message for site information form

It seems you have success with displaying the message but not with saving the value? For this you need to load the editable version of the config, set the value and save:

function api_key_form_submit($form, FormStateInterface $form_state) {
  $config = \Drupal::service('config.factory')->getEditable('api_key.settings');
  $config->set('siteapikey', $form_state->getValue('siteapikey'));
  $config->save();
}

By the way it's also a good idea to get the value from the editable version because the config might be overridden and you want to fill the form with the original value:

$site_api = \Drupal::service('config.factory')->getEditable('api_key.settings')->get('siteapikey');


How do I customize hierarchical breadcrumbs?

In D8 the hierarchy of breadcrumbs is by default path based, so you have to change the path for the second level from /service1 to /services/service1

Or install a module to build the hierarchy based on menus or taxonomy terms:

https://www.drupal.org/project/menu_breadcrumb
https://www.drupal.org/project/taxonomy_breadcrumb


How to trigger module install file ad hoc

You can do different things depending on your use case.

If you really need to test your install script again you need to uninstall your module rather than just disabling it. You can do that by running drush dis mymodule && drush pm-uninstall mymodule followed by drush en mymodule again. As @Clive mentions if you have the Devel module installed you can also drush dre mymodule (Devel reinstall). Or disable the module at http://example.com/admin/modules and then uninstall the module at  http://example.com/admin/modules/uninstall . You should probably have a hook_uninstall function set up to clean up after your install. For example you may need to drop some tables or delete temporary files. See the link below for hook_uninstall.
If you have an update to already the installed module you should use hook_update_n instead of hook_install. Then you can visit http://example.com/update.php or run drush updb
Link below.
Lastly, you can probably change the database table that records the installation. I don't recall exactly how to do that but I don't think its preferable.

Here are the docs on writing uninstall hooks.
https://api.drupal.org/api/drupal/modules%21system%21system.api.php/function/hook_uninstall/7

Here are the docs on writing update hooks. Basically the way I do it is make sure that hook_install runs the update functions after it runs itself.
https://api.drupal.org/api/drupal/modules%21system%21system.api.php/function/hook_update_N/7

eg:

/*
 * Implements hook_install
 */
function mymodule_install() {
// do some things

// then run the updates
    mymodule_update_7000();
    mymodule_update_7001();
}

/*
 * Implements hook_install
 */
function mymodule_update_7000() {
// do some other things
}

/*
 * Implements hook_install
 */
function mymodule_update_7001() {
// do some more things
}


Why jquery menu collapse on all pages except front page

Doing

<script src="sites/all/themes/custom/mytheme/js/main.js"></script>

is bad Drupal practice. As per the docs you should be doing
my_theme.libraries.yml
menu-collapse:
  version: 1.x
  js:
    js/main.js: {}
  dependencies:
    - core/jquery
    - core/jquery.ui
    - core/jquery.once

page--node--2.html.twig
page--node--3.html.twig
page--node--6.html.twig
page.html.twig
{{ attach_library('theme_name/menu-collapse') }}

inside the template file(s).
Note: If this functionality is meant to be for every single page, rather then having to always add this to every variation of page.html.twig, add this in html.html.twig instead.

If after doing the above, the issue still persists

Why would the front page not operate like the other pages in accessing
the JavaScript and jQuery?

Possibly due to jQuery being loaded twice.
Go to /admin/config/development/performance and uncheck Aggregate JavaScript files (remember to turn back on after your're finished debugging)
Then on your front page, right mouse click, and select inspect
Go to network, and select JS, then refresh the page with the inspector open. You'll be able to see all the JS files that are loaded.

If there are no jQuery duplicates, in the inspector go to the "Console tab" and see if there is a JS error.


Drupal 8 status code set 301 instead of 302 for urls with out lang code

That redirect isn't a drupal standard feature, it is done by the redirect.module.

It is currently using the default response header of the redirect configuration in \Drupal\redirect\EventSubscriber\RouteNormalizerRequestSubscriber::onKernelRequestRedirect(). That is a bit weird as that is the default for new manually created redirects which usually should be cached.

I think there is an issue in the redirect module to change that to a different configuration or always using 302, if not, feel free to create one.


Flexslider only showing to logged in users

I was having the same problem with Flexslider.

After checking all the permissions issues, I remembered that the content for my slides was "unpublished". I switched it to "Published" and, VOILA! It worked.

It's a common practice to have the slides "unpublished", so I don't know why this makes a difference, but it did.


Proper backup procedure for remote site?

You set a path for manual and automatic backups in Backup & migrate module. You get the resulting tar.gz file using ftp to your local machine for backup. If you want to restore, from within the module you choose file to upload.
For the db backup just the generated file, for the files the /my_drupal_site_1/sites/ directory
See #2
You can create a new profile in Backup & Migrate module and select which tables to backup (restore only restores what was backed up so you are ok there). Partial backup requires a lot of caution as to not forget necessary tables.
If you are restoring to an existing site NO, if it is a migration you are after YES
See #5

I think you are better of using i rather than ii, as using drush is a lot more "technical" and mistake prone.

As for you last question, yes... use Backup & Migrate to create a DB backup file on the server and then get everything using FTP. Even better use CPanel or Plesk and backup Home and mySql alltogether.


Why are field widgets not form elements?

It seems logical to me that a field widget could be a form element, that also happens to map directly to some underlying storage

Widgets are form elements; they just have additional capabilities a form element doesn't have. The documentation about the field widget API describe the widgets using the following words:

  Widgets are Form API elements with additional processing capabilities. Widget hooks are typically called by the Field Attach API during the creation of the field form structure with field_attach_form().

Every widget is implemented using at least one form element, but a module implementing a widgets needs to implement some hooks that are not required from a form element:

hook_field_widget_info()
hook_field_widget_form()
hook_field_widget_error()

While the first can be considered the equivalent of hook_element_info(), the other two are additional hooks necessary for the widgets to work. It's thanks to the information passed to hook_field_widget_form() that a widget is rendered.

Drupal could have implemented widgets expanding the properties returned from hook_element_info(), but the truth is that a widget and a form element are two different things that are used in different cases; consider a widget a more specialized type of form element.
If hook_element_info() were used also to return information about widgets, the code looking for widgets would need to filter out the form elements to keep the widget information; vice versa, the code looking for form elements should filter out the widget information. Considering how ofter that information is required, that is the reason why two different hooks are necessary.

Drupal could have used a "base element" property returned from hook_field_widget_info(). If such property has not been implemented, it means nobody proposed it, or it has been proposed, but it has been though to be useful on few limited cases.

As for Drupal 8, things changed a little, and form elements are objects of classes implementing FormElementInterface, while field widgets are objects of classes implementing WidgetInterface. The interface that is common between those interfaces is PluginInspectionInterface, which doesn't define any method for rendering a form element, which are instead defined from RenderElement, an abstract class.
Since now widgets are implemented with classes, the base widget is essentially the base class from which a widget class is derived; there isn't the need of a property to define the base widget of a widget.


To inject the database service add/alter the following methods in your controller class:

use Drupal\Core\Controller\ControllerBase;
use Drupal\Core\Database\Connection;
use Symfony\Component\DependencyInjection\ContainerInterface;

class PetmdController extends ControllerBase {

  protected $database;

  public function __construct(Connection $database) {
    $this->database = $database;
  }

  public static function create(ContainerInterface $container) {
    return new static(
      $container->get('database')
    );
  }

  public function foo() {
    $this->database->insert(...)->fields(...)->execute();
  }
}


How can I get my WYSIWYG editor to stop *#@&%^ing up my HTML?

I had just run into this problem of wysiwyg editors reformatting the html source into a minimized blob of contiguous html.

The solution I found was to use TinyMCE editor with WYSIWYG and to add an additional module called wysiwyg-codemagic.  With this module, you place the codemagic plugin for TinyMCE in the TinyMCE library's plugins (Follow the instructions in module's Read.Me).

Now, when the author of the node content drops into the html source, as occasionally needed, the source is very readable and presented correctly.

This was an old post, but I thought this new info would help for the others of us that still run into this problem


Errors when trying to install adaptive theme on D8 from backend GUI method

First thing is you don't install it.

All you have to do is make sure adaptivetheme is somewhere in the /themes/ directory.

Then download and install the AT Tools module and it's AT Theme Generator sub-module, then create a sub-theme via the UI (a tab in the Appearance section). The at_core base theme will install automatically when you enable your sub-theme.

Also, this theme will never show up on the Appearance page, it's hidden deliberately, because it's just a collection of scripts and libraries that support features in sub-themes. It's never intended to be interacted with via a UI, or be set as default etc.


Why is the expire header set to some time in the past ('Sun, 11 Mar 1984 12:00:00 GMT') in Drupal 6/ PressFlow and Drupal 7?

See http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.9.3.

  If a response includes both an Expires header and a max-age directive,
  the max-age  directive overrides the Expires header, even if the
  Expires header is more restrictive.  This rule allows an origin server
  to provide, for a given response, a longer expiration  time to an
  HTTP/1.1 (or later) cache than to an HTTP/1.0 cache.

And if you look at the following code, you can see that the reason they do that is to prevent caching and allow you to do your own caching. This disables the internal page cache but returns headers allowing downstream caches (such as Squid, Varnish, and other reverse proxies) to cache full pages.

function drupal_page_cache_header_external() {
  // Get headers set in hook_boot(). Keys are lower-case.
  $hook_boot_headers = drupal_get_header();

  $max_age = variable_get('page_cache_max_age', 0);
  drupal_set_header('Cache-Control', 'public, max-age=' . $max_age);
  drupal_set_header('Last-Modified', gmdate(DATE_RFC1123, $_SERVER['REQUEST_TIME']));

  // HTTP/1.0 proxies do not support the Vary header, so prevent any caching
  // by sending an Expires date in the past. HTTP/1.1 clients ignores the
  // Expires header if a Cache-Control: max-age= directive is specified (see RFC
  // 2616, section 14.9.3).
  drupal_set_header('Expires', 'Sun, 11 Mar 1984 12:00:00 GMT');

  // Allow HTTP proxies to cache pages for anonymous users without a session
  // cookie. The Vary header is used to indicates the set of request-header
  // fields that fully determines whether a cache is permitted to use the
  // response to reply to a subsequent request for a given URL without
  // revalidation. If a Vary header has been set in hook_boot(), it is assumed
  // that the module knows how to cache the page.
  if (!isset($hook_boot_headers['vary']) && !variable_get('omit_vary_cookie', FALSE)) {
    drupal_set_header('Vary', 'Cookie');
  }
}


After Module updates got "Warning: require_once() "

It would be interesting to see if your problems could be related to the "memory limit", which might not be high enough (anymore), especially because of the "... have also added Workbench Media module ...".

Assuming this is NOT a multi site, consider editing your /sites/default/settings.php, and change the line to set the memory limit. If it is a multi site, then edit the settings.php file related to the site where you are experiencing the problem.

That line in settings.php should look similar to this:

ini_set('memory_limit', '100M');

The '100M' in it might be some other number. Whatever the number is, try to increase it with like 50%, or maybe even double it to see what happens after you do so (of course do not forget to save the file after increasing that number).

Another possibility that you may want to verify, is to "perform a clear cache" (it doesn't hurt, and occasionally helps solving various issues).

Curious to hear if that helps somehow ...


Why isn't the #ajax property available for more Form API elements?

In Drupal 8 render elements are plugins and you can define a custom render element in a module without modifying core.

The scenarios you describe probably don't need a custom render element. A #markup with an event attached to it is like a link or a button, where you remove the styling with css.

Additionally you can hook into ajax js and react on events with your own javascript. See ajax.js, the hooks are called prototypes.


How useful is it to use the latest Composer version to maintain my sites?

drupal-project has a composer version check built in that currently requires 1.0, so you're fine with 1.1 for now:

https://github.com/drupal-composer/drupal-project/blob/94404dcbed7fe9eb9ea8d95016b661ae6d4f9e3f/scripts/composer/ScriptHandler.php#L75

That said, more recent versions have performance improvements I think and sooner or later, there might be a problem that will force you to update, and then it will be easier if you already are using a custom more recent version. On the other side, your hosting provider might also update that version from time to time, you might want to check that with him. E.g. in case of a security issue.

But no, for now, you're not required to do this.


Instead of using different select boxes for month, date and year, you could use date_popup type.

$form['start'] = array(
    '#title' => t('Arrive'),
    '#type' => 'date_popup',
    '#default_value' => 'YYYY-MM-DD 00:00:00',
    '#date_year_range' => '0:+3',
    '#size' => 12,
    '#required' => true,
  );

Which comes with time field, so you will have the timestamp. Thats it, now you can compare the timestamp input to the database value.


I find the Automatic Entity Label module to do that.
After making a backup of your Drupal database and folders, require it with composer and enable it.
Now you will see a new 'Automatic label' tab in the comment type management, and by clicking 'Automatically generate the label and hide the label field' you will be able to use tokens to auto fill it.


Blocks are an important part in Drupal, but you don't model a theme with them.
Blocks are implemented from modules, using hook_block_info() and hook_block_view() (together other hooks); what themes implement are regions where those blocks are rendered. A theme cannot decide not to implement regions, since there are some regions Drupal requires from themes.

Eventually, a theme can alter how a block is rendered, but themes are not modelled around blocks.


How do I redirect to a certain page from user profile page

Maybe this module user_default_page, might be what you are looking for.

From the description,

  Fill the 'Redirect to URL' field and 'Message' field for both Login
  and Logout fieldset.


EFQ propertyCondition Doesn't work in Simpletest

It turns out that the status of my node was, in fact, being set to '1' immediately prior to this query running, but that despite the fact that the node_save() that was called immediately after node_publish_action() should have cleared the cache, node_load() was in fact calling a cached version of the node.

I got around this by adding the TRUE parameter to node_load().

NOTE: You can't skip the middle parameter, á la node_load($nid, TRUE). This is annoying, because it will fail silently and it will just return a boolean FALSE. To get a node without caching, and also without specifying a VID, you must use node_load($nid, NULL, TRUE).

In a simpletest, you can also use a TRUE parameter like so:  drupalWebTestCase::drupalGetNodeByTitle($nid, TRUE).


display question content type and a referenced node answer

You will have to create a relationship.

Click the [+] next to Relationships in Views, and select the field that contains your node reference
Make sure your Row Style is set to fields
Select Node: Title - do not use the relationship yet.
Next, select Node title again, but this time tell it to use the relationship (the field should be listed in your field listing as (Relatioship name) Node: Title).
Filters should be set to whatever your content type for questions is called.


I suspect you need to configure your search view modes.

For each of your content types, visit the Magage Display page, eg admin/structure/types/manage/page/display

Unfurl Custom Display Settings, check Search Index and Search Result, and save.

Then for each, configure the search view modes.  Search Index will be used to build up the text that gets indexed.  Add / remove fields as needed.  The Search Result will be used to display the search results.


Look at HTML5 tools it enables you to preprocess the HTML element for manifest insertion.

  HTML5 Tools is a module that allows Drupal sites to be built using
  HTML5 ... smartly.

  One of our goals is to provide as much support for HTML5 markup in a
  set of Tools provided by a module so that you can use this module with
  any HTML5 theme you'd like.


How do I hide buttons like the "delete" one in a node form?

You can use hook_access().
Super simple example will hide button "Delete" automaticaly and disallow deletion of some nodes in any other places in Drupal.

Important note:

  The administrative account (user ID #1) always passes any access check, so this hook is not called in that case.

function MYMODULE_access($op, $node, $account) {
   if ($op == 'delete') {
      if ($node->something != 'something') {
          return FALSE;
      }
   }
}

For Drupal 7 there is hook_node_access() for this stuff.


Search form escaping characters and spaces?

That wasn't entirely it - it was escaping with a %25 and passing it to the search form, causing no results.  It was an issue with my htaccess, it's fixed.


You could also create a process plugin to create the Paragraph inline with the record you are migrating. I can't do piecemeal migrations in my case. The project has about 100,000 nodes and no data structure to 'create' Paragraphs out of. Even if I could, I don't want to have to run that dozens of times to get a full set of data.

Anyway.

Here is a real example:

<?php

namespace Drupal\mymodule_migration\Plugin\migrate\process;

use Drupal\migrate\ProcessPluginBase;
use Drupal\migrate\MigrateExecutableInterface;
use Drupal\migrate\Row;
use Drupal\paragraphs\Entity\Paragraph;

/**
 * @MigrateProcessPlugin(
 *   id = "published_author_paragraph_item",
 *   handle_multiples = TRUE
 * )
 */
class PublishedAuthorParagraphItem extends ProcessPluginBase {

  /**
   * {@inheritdoc}
   */
  public function transform($value, MigrateExecutableInterface $migrate_executable, Row $row, $destination_property) {
    $paragraphs = [];

    foreach ($value as $item) {
      $paragraphs[] = $this->createParagraphItem($item);
    }

    return $paragraphs;
  }

  /**
   * {@inheritdoc}
   */
  public function multiple() : bool {
    return TRUE;
  }

  /**
   * Generates a paragraph item entity.
   *
   * @param array $value
   * @return array
   * @throws \Drupal\Core\Entity\EntityStorageException
   * @throws \Drupal\migrate\MigrateException
   */
  protected function createParagraphItem(array $value) : array {
    $paragraph = Paragraph::create([
      'type' => 'paper_authors',
      'field_paper_author' => [
        'target_id'  =>  $value['user_id'],
      ],
      'field_paper_published_name' => [
        'value'  =>  $value['name'],
      ],
      'field_paper_disclosure' => [
        'value'  =>  $value['disclosure'],
        'format' => 'basic_html',
      ],
    ]);

    $paragraph->save();

    return [
      'target_id' => $paragraph->id(),
      'target_revision_id' => $paragraph->getRevisionId(),
    ];
  }
}

In my migration definition yaml:

  _authors_shim:
    plugin: generate_authors_array
    source: author_array
  field_paper_published_authors:
    plugin: published_author_paragraph_item
    source: '@_authors_shim'

generate_authors_array is another process plugin I use to massage the data for the plugin code above. This paragraph type has a user reference, a plain text field and long text field. The passed value is an array of arrays, so this will in fact create multiple paragraph deltas for the paragraph field I am filling. It also rolls back properly.

I had tried to get this to work with sub_process at first, but could not get the paragraph field to populate at all until I went this route. I believe this is due to paragraph fields hold references to their stored entities (target_id, target_revision_id).


Regular session table crashes, on a large multi domain, multi site Drupal set-up

I would convert the user & session tables to InnoDB. I would also check the memory limits for MySQL. It's not the most ideal tool, but if you're in a shared environment you can install a copy of Drupal Tweaks (http://drupal.org/project/drupal_tweaks) and see if you are able to alter any of the MySQL configuration directive such as memory limit.


D8 doesn't create .htaccess for private file system path

This is a better .htaccess to use:

# Turn off all options we don't need.
Options -Indexes -ExecCGI -Includes -MultiViews

# Set the catch-all handler to prevent scripts from being executed.
SetHandler Drupal_Security_Do_Not_Remove_See_SA_2006_006
<Files *>
  # Override the handler again if we're run later in the evaluation list.
  SetHandler Drupal_Security_Do_Not_Remove_See_SA_2013_003
</Files>

# If we know how to do it safely, disable the PHP engine entirely.
<IfModule mod_php5.c>
  php_flag engine off
</IfModule>
<IfModule mod_php7.c>
  php_flag engine off
</IfModule>

This .htaccess is the one that should have been placed in your private files directory by Drupal 8 (or 9) core. (Perhaps permissions on the private directory prevented Drupal from creating the file.)

The accepted answer above is adequate to quiet the warning from Drupal status report, but does not actually prevent the remote script execution exploit addressed in the original core security advisory from 2013.


Encoded strings in hook_menu wildcard case menu item to lose access

I've assumed this needs fixing in core, so logged it here - any insights welcome!

http://drupal.org/node/1822004


From your question

  Is there another ways to make the login more safe?

Yes,try one of the following modules

Login Security

  Login Security module improves the security options in the login operation of a Drupal site. By default, Drupal introduces only basic access control denying IP access to the full content of the site.

Secure Login

  Secure Login module enables the user login and other forms to be submitted securely via HTTPS, thus preventing passwords and other private user data from being transmitted in clear text. Secure Login module locks down not just the user/login page but also any page containing the user login block (or other forms that you configure to be secured).


How do I force my nodes to all show up at a given path, without adding them to a menu?

There are two ways I know, and both are based on Menu block module.

Add all elements to the menu all right, but in the blocks that show menus, limit maximum depth so they are never shown to the end user in menu. Additional benefit is that you will have them properly placed in a tree for SEO modules like Site map or SiteMenu. And breadcrumbs will work out of the box.
Keep all nodes that should "appear" like they are in one menu in one path "directory", using Pathauto or similar solution. Add a Menu block set to show menu you need, and set it's display settings to only appear under the path you need and everywhere deeper. For breadcrumbs, you would need something like Breadcrumbs by path or Easy Breadcrumb - both claim to provide breadcrumbs based on URL aliases, so they are menu independent.

Personally, I would go with first way.


How to Associate Drupal content type with CiviCRM groups?

With the CiviCRM Entity module, many CiviCRM API entities are exposed as proper Drupal entities. You can then create Entity Reference fields to reference particular entities. So on your node types, create an entityreference field, target CiviCRM Groups, and you will be able to reference the groups this way


Migrating a Drupal 6 site to Drupal 7 can I copy the D6 database as a local source?

Yes, you can source the migration from a copy of the D6 database running on the same database server as the D7 site's database. Be aware: the migrate D2D wizard will ask you for a "File prefix". In the "File prefix" field, you must specify a path to the uploaded files directory of the D6 site. Those could be a local copy also.

If in addition, you are asking how to copy a MySQL database from one server to another, that may be out-of-scope for Drupal Answers. There are tons of resources on the Internet for that—your own hosting provider may provide tools to do this. But I won't stop someone else from answering if they please. Apologies if that is not an aspect of the question posed.


Show the value of a node-form field inside an AJAX field added via hook_form_alter()

function myresa_callback($form, $form_state) {
  $element = $form[‘box’] ;
  $element[‘#markup’] = «The price for » . $form_element

No wonder this doesn't work, where does $form_element come from? Also fields tend to be structured like $form[field name][$node->language][columname] (the latter being value in your case IMO)


Re-enable System theme file within a child theme

One way of getting this to work is to add the CSS file as a part of your global-styling in custom_theme.libraries.yml

global-styling:
  css:
    theme:
      /core/modules/system/css/components/ajax-progress.module.css: {}

Hope this helps anyone who has come across this problem.


How to create menu link to an individual field within a node in Drupal 7

The quickest might be with a MENU_LOCAL_TASK in a custom module, e.g.:

function YOURMODULE_menu() {

  $items=array();

  $items['node/%node/avatar'] = array (
    'title' => 'Avatar',
    'page callback' => 'YOURMODULE_node_avatar',
    'page arguments' => array(1),
    'access callback' => TRUE,
    'weight' => 64,
    'type' => MENU_LOCAL_TASK,
  );

  return $items;

}

function YOURMODULE_node_avatar($node) {
  // drupal_goto($node->field_avatar[0]['filepath']); // Drupal 6
  drupal_goto($node->field_avatar[LANGUAGE_NONE][0]['filepath']); // Drupal 7 (I think :)
}

which would create an Avatar tab for you that when clicked on would display the image in field_avatar.  Obviously you'd have to change that up to your exact field (and I think I got the D7 language stuff right in there if you are on D7).

It could also be called directly, e.g. www.YOURHOST.com/node/1/avatar would display the avatar of node with nid 1.  If this is going to be how you access it, you could change MENU_LOCAL_TASK to MENU_CALLBACK and then the Avatar tab wouldn't show up on the page.


What is the difference between an entity in Drupal 7 and a content entity in Drupal 8?

I'm not sure what you are asking.

Example modules are named after what they're an example of, it's not for them to pick a name, really.

Drupal 8 has Content Entities, which evolved from the field structure of Drupal 7's entities and Config Entities, which are based on concepts from ctools exportables, entity.module's exportable entities and various other things.

Both share the same base class and a few comments and concepts but beyond that, they're quite different. Both are typed classes, Content entities have a strict although somewhat complex structure but are very extensible within that structure (That is, Entity -> Field Item List > Field Item > Property). They can have revisions and translations which are conceptually similar to field translations in 7.x but have a different API.

While there isn't that much documentation yet, https://www.drupal.org/developing/api/entity has some, there are also plenty of presentions from DrupalCons and other events about the concepts, API's and so on, including a recent one that I co-presented: https://2015.drupalcamp.at/session/entities-drupal-8.


Adding a block to a page build with a call to theme (Drupal 7)

inflatable_icons_canvas_page() is the callback function for your hook_menu page,  therefore in your hook_menu you will define a route as:

  function inflatable_icons_menu() {
    $items['abc/def'] = array(
      'page callback' => 'inflatable_icons_canvas_page',
    );
    return $items;
  }

Then you can use the route 'abc/def' to determine the visibility of your blocks either in the admin blocks UI or in your module code. In later case it will be something like:

$blocks['example_empty'] = array(
    'info' => t('Example: empty block'),
    'status' => TRUE,
    'region' => 'sidebar_first', // Not usually provided.
    'visibility' => BLOCK_VISIBILITY_LISTED, // Not usually provided.
    'pages' => 'abc/def', // Not usually provided here.
  );

Then configure the block as usual from blocks admin UI. If you go to configure the block you will find the configuration of visibility settings to "show block in specific pages" option "only the listed pages" and your hook_menu route in text area. You could change it now if desired, as you will with a block created through UI.


The variable $user should probably be the parent entity of the field:
$user = $items->getEntity();

Which then when used as cache dependency should solve the caching issue:
$result->addCacheableDependency($user);

BTW you find the current user already in $account. If your access check depends on it then don't add it as object but use this predefined method for caching:
$result->cachePerUser();

But most times access code depends only on the current user roles and the resulting permissions, then you could use instead
$result->cachePerPermissions();

which is much better for cache performance.


How to facilitate meetings / events with participant registration, agenda and documents?

There are many options in Drupal allowing you to add registrations to content. So if you add a content type of 'meeting', you can add file fields, dates and an agenda text field. Add a taxonomy field for grouping by type.

Then with any of the registration modules you can register users.

Entity Registration
Node registration
RNG (Drupal 8)

Basically it is not one module, but a combination of fields and modules to get the desired functionality.


The problem is with volunteers_field_widget_form and volunteers_field_widget_form_alter. volunteers_field_widget_form_alter was preventing updates. If I set the default_value of the relevant elements appropriately in volunteers_field_widget_form, Drupal both allows updates and displays correctly.

$element['position_title'] = array(
  '#type' => 'textfield',
  '#length' => 255,
  '#title' => $t('Position name'),
  '#default_value' => isset($items[$delta]['position_title']) ? $items[$delta]['position_title'] : null,
  '#weight' => 0,
  '#delta' => $delta,
  '#size' => 'big'
);


If scheduler is using hook_form_alter() on a form, and your module is also using hook_form_alter() on the same form, the order of execution of these two hook_form_alter() functions matters. Evidently, your module's hook_form_alter() is getting called before scheduler can add the new form elements you're trying to modify.

Drupal executes these hooks in order of module weight. If you do not set the module weight, then I believe they all default to the same value and hooks with the same weight will get called in alphabetical order (but this is not guaranteed).

To ensure that your module gets called after scheduler, you need to set your module's weight to be greater than the scheduler's module weight. This is how you do that in your module's install file:

/**
 * Implements hook_install().
 */
function my_module_install() {
  // Because we need to alter a form that is also altered by the scheduler
  // module, we need to ensure this module gets loaded AFTER the scheduler.
  $weight = db_query('SELECT weight FROM {system} WHERE name = :name', array(':name' => 'scheduler'))->fetchField();
  db_update('system')
    ->fields(array(
      'weight' => $weight + 1
    ))
    ->condition('name', 'my_module')
    ->execute();
}


How to disallow certain strings in signatures?

In drupal, whichever field you are taking input as, you need to make sure that only plain text is inserted by the user. This way, drupal will run check_plain function to the text added, and no links, xss attacks can be made.


Modify a variable before it saves to database

I don't think your approach is the best. You need to do the following:

Add a custom module.
Implement hook_form_alter in your module and and alter the user
profile form. Form id: user-profile-form.
Add a validation function i. e. $form['#validate'][] =
'my_module_custom_form_validate';.
add an implementation for the function in your module and modify the form values as you wish.

Also, you don't need to use the $_POST variable if you are following the drupal form api.


On Drupal, the node title is always required. On books, the title is even more important, since it is used for the links to the other pages of the book, shown after the page content.

I took the screenshot on Drupal 7, but the same is true for Drupal 8.

The only way to avoid entering a title would be having a module that automatically adds a title to nodes, like the Automatic Nodetitles module, or the Automatic Entity Label (which has a version for Drupal 7 and Drupal 8).

  Automatic Nodetitles is a small and efficient module that allows hiding of the content title field in the form. To prevent empty content title fields one can configure it to generate the title by a given pattern.

  "Automatic Entity Label" is a small and efficient module that allows hiding of entity label fields. To prevent empty labels it can be configured to generate the label automatically by a given pattern.


How can I show a block only on the edit page for a specific content type?

You could implement hook_block_list_alter() to alter the status of the block. (Replace $bid with the block ID, and $content_type with the content type you are interested to.)

function mymodule_block_list_alter(&$blocks) {
  if (!empty($blocks[$bid]) && ($node = menu_get_object()) && arg(2) == 'edit' && $node->type == $content_type) {
    $blocks[$bid]->status = 1;
  }
}


See what path aliases are set up with Drush?

You have to either be within a drupal doc_root (aka apache verbiage) or have properly configured drush site aliases for commands to work:

Eg, if your site lives at /var/www/

cd /var/www/
drush cc all

Or if you have setup a drush site alias of @local, then from anywhere on your system:

drush @local cc all


preventing access to php files using htaccess doesnot allow ajax to use php files

I've no idea what you're trying to accomplish, but I believe you're seriously misguided about how a PHP-based website works.

If you set up .htaccess-rules to stop the browser from accessing any PHP-file, it is not only ajax that will be affected.  Every page on your Drupal website will return 403 to any visitor, including index.php in the root directory.  I doubt that you want this.

If you've got Apache configured correctly for PHP, the contents of a PHP-file are never transmitted to the client - only the result of processing it server side.  Just point your browser to sites/default/default.settings.php to see how this works.  Unless you've really munged your Drupal configuration, you should not need to do anything to stop the PHP-files from being browsed.


What is the correct way to save checkboxes values on form submission?

The arrays aren't of compatible formats, you need to prepare them yourself:

foreach (array_filter($form_state['values']['audio_options']) as $selection) {
  $node->field_audio_options[LANGUAGE_NONE][]['value'] = $selection;
}


How do I implement bootstrap's panel component for a specific block / block region in my bootstrap (sub) theme?

Quick-and-dirty way: Uncheck all the boxes to display default classes in Views, and then use a twig template specifically for that views block to write the CSS exactly as you want.
You can find the Views twig templates in /core/modules/views/templates.
It depends on how you configured the view, but if it's an unformatted block, you want the unformatted template, views-view-unformatted.html.twig.  Copy that file from the Views template directory into your subtheme's directory.
Next, you have to rename the file so that it only applies to the block. In Drupal 7, Views was nice and gave you the suggested theme hooks, but in Drupal 8, you have to figure them out yourself.
The rule is TEMPLATE_NAME--VIEW_MACHINE_NAME--DISPLAY_MACHINE_NAME.
If you go to edit the view in the admin UI, you can get this info from the URL.
/admin/structure/views/view/VIEW_MACHINE_NAME/edit/DISPLAY_MACHINE_NAME.
Once you rename the file, you will need to rebuild the cache to get Drupal to use it.
Sometimes you may need to customize other views templates as well (a single view can use multiple templates); you can do that in the same way as described above..


Content moderation - workflows / weird behavior

What I did was create a new state called Needs Review to mimic draft state at /admin/config/workflow/workflows.

The one thing to note is to check default revision. Then set the permissions and you should be able to go from publish to unpublish.

After the change here is what your configuration should look like.


Redirect to previous non drupal page after login

Drupal doesn't react by default to a URL parameter called redirect; it does however react to the parameter destination. The destination parameter pretty much trumps any other internal redirect so this should override the default redirect.

When you send your users through to the Drupal login form try using a URL like this:

http://azeem.com/user/login?destination=qa


Getting rid of password_confirm labels in module

I agree with @Clive that it is not a good idea to remove those labels, but there is a way to make them invisible, without to remove them. Drupal 7 has a CSS class for that purpose: element-invisible.

The code I would write is similar to the following one.

function mymodule_form($form, &$form_state) {
  $form['password'] = array(
    '#type' => 'password_confirm',
    '#maxlength' => 20,
    '#size' => 10,
    '#process' => array('form_process_password_confirm', 'code_testing_process_password', 'user_form_process_password_confirm'),
  );

  return $form;
}

function mymodule_process_password($element) {
  $element['pass1']['#title'] =  '' . t('Password') . '';
  $element['pass2']['#title'] =  '' . t('Confirm password') . '';

  return $element;
}

The process functions I am using are the same used from the "password_confirm" form field, except the second one, which is my custom process function I use to make the label invisible.

You could also replace the reference to form_process_password_confirm() if you want to radically change the output for the form fields. The last process function I am using is the one that adds the JavaScript code which checks when the password entered in the two form fields is the same, among other things.


How do you add a conditional to check if the Node object exists?

If you are on a non-node page, menu_get_object() returns NULL.


Can original text be edited in translate interface or elsewhere?

You can use the String Overrides module to change the original strings.
Here is a quote about it (from the module's project page):

Provides a quick and easy way to replace any text on the site.
Features

Easily replace anything that's passed through t()
Locale support, allowing you to override strings in any language
Ability to import/export *.po files, for easy migration from the Locale module
Note that this is not a replacement to Locale as having thousands of overrides can cause more pain then benefit. Use this only if you need a few easy text changes.


You can migrate users with roles without migrating roles using migrate static_map

In migrate set

  process:
  uid: null
  name: name
  pass: pass
  mail: mail
  status: status
  created: created
  access: access
  login: login
  roles:
    plugin: static_map
    bypass: true
    source: roles
    map:
      5: new_role_name
      3: editor

and in the source plugin you have to set the roles in prepareRow

  /**
   * {@inheritdoc}
   */
  public function prepareRow(Row $row) {
    $uid = $row->getSourceProperty('uid');

    $query = $this->select('users_roles', 'r');
    $query->fields('r', ['rid']);
    $query->condition('r.uid', $uid, '=');
    $record = $query->execute()->fetchAllKeyed();
    $row->setSourceProperty('roles', array_keys($record));

    return parent::prepareRow($row);
  }


How to allow users who have cancelled their accounts to re-activate / re-enable them?

There are two URL which can help you in achieving this. First you will have to use Advance User module & then you can extends some hooks of it according to your need for account re-activation.
There is a blog written on similar issue which may help you - Enable/Disable User.

I hope you find your solution.


How to display DB data from Custom module using custom HTML markup?

There are 2 ways of doing it.
First one is to define your own theme function using hook_theme and then either create a theme function of a template file inside of your module or theme folder.
example code is given here

/**
 * Implements hook_theme().
 */
function MYMODULE_theme($existing, $type, $theme, $path) {
  $custom_theme = array();
  $custom_theme['my_new_theme'] = array(
    // example theme template register
    // for
    //sites/all/modules/mymodule/templates/my_new_theme.tpl.php
    'template' => 'my-new-theme',//dash will convert to underscore in template name.
    'path' => drupal_get_path('module', 'mymodule') . '/templates',
    'variables' => array('header' => null,'rows'=>null),
  );

  return $custom_theme;
}

You can then use

theme('my_new_theme', array('header' => $header, 'rows' => $rows));

instead of your theme function call.
And then inside of your my_new_theme.tpl.php you can access $header and $rows variables.

Second method is not recommended but a possible way of doing this.
So you can just create your HTML output in your callback function where you are creating that list. Store your full html to be out-puted in some variable and finally just return that variable at the end. Drupal will render your HTML as it is.


how to print 'add term' taxonomy form into block

A couple things:

The function taxonomy_form_term() expects the $vocabulary parameter to be an object with a "machine_name" property
You should wrap the vocab name in quotes
More elegant to use module_load_include() instead of include_once()

So:

if ($vocabulary = taxonomy_vocabulary_machine_name_load('jenis_dokumen')) {
  module_load_include('inc', 'taxonomy', 'taxonomy.admin');
  $edit = array();
  $taxonomy_form = drupal_get_form('taxonomy_form_term', $edit ,$vocabulary);
  return drupal_render($taxonomy_form);
}


PDOException: SQLSTATE[42S22] When adding quiz content

The error was somehow related to the UUID module, which couldn't be disabled without derailing the entire website. Here's how I fixed it.

uninstalled the feature that held the affected quiz module

drush pm-disable <my_feature>
drush pm-uninstall <my_feature>
uninstalled the quiz module and all the modules dependent on it:

drush pm-disable quiz
drush pm-uninstall quiz
moved the quiz module files to my temp backup outside the drupal root:

mv sites/all/modules/contrib/quiz ../<temp_backups>/quiz

downloaded the quiz module fresh and reenabled it and all the dependent modules and reenabled the feature that contained it:

drush dl quiz

drush en quiz

That took care of this particular error.

Please note: I did not yet have any quiz data or content set up; this guideline is only safe for a dev environment. I have not tested it with any actual content or user data.


Do new routes require a static first portion?

In the routing system you can't do this. What you can do is path aliasing.

Inbound: /{bar}/foo/{baz} -> /foo/{bar}/{baz}

Outbound: /foo/{bar}/{baz} -> /{bar}/foo/{baz}

You need a pattern to apply a regular expression on the path inbound, so /{bar}/{baz} is only possible if the parameters themselves have a distinctive pattern.

I didn't find a tutorial how to build a path processor, but you can use the
PathProcessorFront class as example.

Register both as tagged service in the .services.yml file for the module.

services:
  path_processor_front:
    class: Drupal\Core\PathProcessor\PathProcessorFront
    tags:
      - { name: path_processor_inbound, priority: 200 }
      - { name: path_processor_outbound, priority: 200 }
    arguments: ['@config.factory']


Unable to upload files. Though the maximum file size limit is 80 MB, can't upload even 50 kb files

Some things that can break file uploads:

upload_max_filesize and post_max_size ;
memory_limit ;
Unwritable tmp directory.


I'm trying to make a module that searches LDAP for users

I think you'll find that LDAP modules for Drupal are primarily for allowing LDAP users to use Drupal.

My understanding of what you're saying is that you just want to display the LDAP users, sort of like a directory system?

If Drupal doesn't have to really interact with your LDAP users,  you should be able to create your own module for this pretty easily.

There are quite a few LDAP functions in PHP:  http://ca2.php.net/manual/en/ref.ldap.php

Create a module that makes use of them, and then passes the data over to a node for display purposes.


Pass multiple sets of variables to theme function

And, the general rule of "post a question and that helps you figure it out yourself" applies here yet again.

All I did was modify my theme hook like so:

/**
 * Implements hook_theme().
 */
function my_module_theme($existing, $type, $theme, $path) {
  return array(
    'my-module-mail' => array(
      'variables' => array(
        'openings' => array(
          'service_name' => NULL,
          'time' => NULL,
          'therapist' => NULL,
          'booking_link' => NULL,
        ),
      ),
      'template' => 'templates/my-module-mail',
    ),
  );
}

and fill my $variables array like so:

  // Loop through all openings for this category.
    foreach ($available_openings[$tid['tid']] as $mail_opening) {
      $variables['openings'][] = $mail_opening;
    }
    $body = theme('my_module_mail', $variables);
    // Define mail parameters.
    $params = array(
      'subject' => t('Your Available Openings'),
      'body' => $body,
    );
    // Send the mail.
    drupal_mail('my-module-mail', 'featured_openings', $entity->mail, language_default(), $params);

and it works like a charm.


Edit content type > comment field > edit > change the text


How do I add a specific meta-tag to all the pages of a site?

You can use the Metatag module for this, in order to add meta tags to every page of your site:

If you want to do it by coding, it is possible to implement the theme_preprocess_html hook to add the meta tag manually:

function theme_preprocess_html(&$variables)
{

    $noindex = [
            '#tag' => 'meta',
            '#attributes' => [
                'name' => 'robots',
                'content' => 'noindex',
            ],
        ];
    $variables['page']['#attached']['html_head'][] = [$noindex, 'noindex'];
}

(more details here: https://stackoverflow.com/questions/35913739/add-meta-tag-to-head-in-drupal-8)


How do I insert a view into an article based on filters that are only defined at node publish?

So if I understand correctly you have a node edit page, with a view provided by the views module with exposed filters, probably in a block in block somewhere on the page.

Your copywriter will then put some parameters into the exposed filters and get some results.

If this is a custom view that you have made then there are not going to be any pre-made modules that suit your needs so to put the content that is returned into the body your options are:

1) Copy and paste

2) Write some jQuery that runs upon clicking the view row that insert the copy into the body

Here is some information on adding js in Drupal.


Since Devel 4 you have to add Kint youself:
composer require drupal/devel kint-php/kint

You can read through this epic issue to learn more: Unknown "kint" function. in Twig\ExpressionParser.

Also important to read the release notes. On all 4.0.0+ releases the following is written. You have to do this before upgrading:

If you have Kint module enabled, please run these commands before
upgrading:

drush pm:uninstall kint or uninstall Kint using the Drupal UI
composer require kint-php/kint

To fix any Kint-missing-module-error, simply downgrade Devel composer require 'drupal/devel:^2.1', uninstall Kint drush pmu kint and then upgrade again composer require drupal/devel kint-php/kint.


I had a requirement once like this where, using web service I have to create a node that will also save image. The following code uploads and saves image using web service.

// File validator.
$validators = array(
  /**
   * Defaults already allow png, jpg etc. If more needed to be supported,
   * edit here.
   */
  'file_validate_extensions' => array(),
  'file_validate_size' => array(),
);

foreach ($_FILES['files']['name'] as $field_name => $file_name) {
  // Save the file and get file object.
    $file = file_save_upload($field_name, $validators, file_default_scheme() . "://");

  // Check whether image is uploaded.
  if ($file->fid) {
    $node = new stdClass();
    $node->type = 'CONTENT_TYPE';
    $node->title = 'TITLE';
    $node->language = LANGUAGE_NONE;
    $node->uid = 'USER_UID';
    node_object_prepare($node);

    $node->field_custom[$node->language][0]['value'] = 'SOME_VALUE';
    // File upload here..
    $node->field_image[$node->language][0] = (array)$file;

    $node = node_submit($node);
    node_save($node);
  }
  else {
    return services_error(t('File upload failed'), 406, t('File upload failed'));
  }
}

NOTE: Following code was tested using services 3. Also it was an iOS app that was consuming this web service, and it worked there.

NOTE: File uploaded with POST request.

I tested the above code using a Google Chrome plugin called REST Console. To install the plugin search for "rest console" in Chrome Web Store and install the first plugin you get in result (with up green and down blue arrow)

Hope this helps!


Facet Blocks are not appearing in indexed views

I figured out what the problem was... I rendered that block in sidebar region.. That was it..

When your search isn't the main content on the page then the facets does not appear now I rendered the block view it in Content Region.

Now the facets appear!!!


Indeed, #markup only allows string, but you can by using a block type

$view_output = views_embed_view($view_name, $display_id, $uid);

$page['profile']['bio_mobile'] = array(
  '#type' => 'block',
  'content' => [
    'system_main' => $view_output,
   ],
  '#prefix' => '
',
  '#suffix' => '
',
);


how to make previously entered values appear for multistep forms after validation errors

I was bitten by a similar case in a multistep form scenario, though in my case it was use of the "Previous" button that didn't preserve user entered values.

Initially I was under the impression that D7's form_builder() would automatically merge user data in $form_state['values'] back into the '#value' property of the form elements on previous step's subform, but this never happened!

After reading carefully through examples module, form_example/form_example_wizard.inc, I realized that I had to use:

'#default_value' => !empty($form_state['values']['my_elem']) ? $form_state['values']['my_elem'] : '',

on all form elements that I wanted to "remember" their user input!


Issue with options in ICME file uploader missing

I have the same issue. This is a big headache.
We want to make all off-site (external) links have target = _blank.

Solution: The CKeditor Anchor Link module, anchor_link, adds the other link properties (as it existed in Drupal 7). You have to edit the text formats and include the new buttons that anchor_link creates. However, these buttons are identical to the ones created by the Link module (in core D8), so make sure to remove them and drag the new ones (from anchor_link) in.


How to view nodes that only you have published?

I've found the content_access module to be pretty helpful for this kind of thing.

Just enable this on the content type you want to control, and make sure that "view any content" is unchecked for authenticated users, and that "view own content" is checked for authenticated users.


What is the D6 equivalent of D7's hook_filter_info?

In Drupal 6, filter modules just implement hook_filter(). In particular, to process text from a filter, you should use code similar to the following one.

$result = module_invoke('markdown', 'filter', 'prepare', 0, -1, $input);
$result = module_invoke('markdown', 'filter', 'process', 0, -1, $result);

I assume the delta for the input filter is 0, which means selecting the first input filter implemented by the module.
The first call to module_invoke() could be not necessary, but most input filter prepare the text that is going to be preprocessed, mostly to avoid conflicts with other filters, including the ones implemented by Drupal core. In fact, check_markup() uses the following code.

// Give filters the chance to escape HTML-like data such as code or formulas.
foreach ($filters as $filter) {
  $text = module_invoke($filter->module, 'filter', 'prepare', $filter->delta, $format, $text, $cache_id);
}

// Perform filtering.
foreach ($filters as $filter) {
  $text = module_invoke($filter->module, 'filter', 'process', $filter->delta, $format, $text, $cache_id);
}


Drush sql-dump but exclude multiple tables with a pattern

Drush has a number of options to exclude tables from sql-dump. These all now support wildcards (thanks @MPD for pointing this out), so for example you can do this:

drush sql-dump --skip-tables-list='result-*'

This will completely exclude any tables matching the pattern result-* - that is, beginning with result- - from the dump. You can pass multiple patterns (or individual table names) by separating them with commas. The quotes are necessary to prevent your shell from expanding the pattern.

If you want the tables' structure to be included but just not the data in them, use --structure-tables-list instead.

The other options are --skip-tables-key and --structure-tables-key which work similarly, but instead of providing the table names or patterns directly on the command line, you add them to an array in drushrc.php and specify the array key on the command line. This is useful if you have a set of tables that you routinely exclude, such as 'cache_*'. The example.drushrc.php provided with drush gives the following example:

/**
 * List of tables whose *data* is skipped by the 'sql-dump' and 'sql-sync'
 * commands when the "--structure-tables-key=common" option is provided.
 * You may add specific tables to the existing array or add a new element.
 */
# $options['structure-tables']['common'] = array('cache', 'cache_*', 'history', 'search_*', 'sessions', 'watchdog');


Submit is not working for contact form which was embedded by AJAX

I just had this issue myself. Try this:

use Drupal\Component\Serialization\Json;
use Drupal\Core\Render\BubbleableMetadata;

function somemodule_form_conditional_ajax($form, FormStateInterface $form_state) {
  $output = [];
  $values = $form_state->getValues();
  $conditional_form_id = $values['somefield'][0]['value'];

  $contact_message = \Drupal::entityTypeManager()
    ->getStorage('contact_message')
    ->create([
      'contact_form' => $conditional_form_id,
  ]);

  if (!is_null($contact_message) && $contact_message instanceof Drupal\Core\Entity\EntityInterface) {
    $form = \Drupal::service('entity.form_builder')->getForm($contact_message);
    $output = render($form);

    $data = BubbleableMetadata::createFromRenderArray($form);
    $attachments = $data->getAttachments();
    $settings = '';
    if(!empty($attachments['drupalSettings'])) {
      $settings .= '<script type="text/javascript">jQuery.extend(drupalSettings, ';
      $settings .= Json::encode($attachments['drupalSettings']);
      $settings .= ');</script>';
    }

    $output .= $settings;
  }

  return $output;
}

The only thing I'm unsure about is if the $output requires an array - what I've given you is a string. So it may not work.


How do I test that a text field in $form_state has been populated by the user?

This depends on the field in question and what values could possibly be entered into it.

In most cases an empty string would mean that the field has had no value set.
If zero is a valid value then check like this:

if ($form_state['values']['my-field'] !== '')

That will check that the value is an empty string, whereas != '' would also match zero and false etc.

Also, depending on your set-up and requirements, if the field has a default value you have to decide what happens in the case the the value in form state equals the default value, because in that case you don't know if the user has left the field default on purpose or not.


Upload new item (node gallery) link not showing with a user of different permission - Drupal 7

Now it worked. Previously its was beta version of node gallery. Now I changed it into Node gallery-7.x-1.0. In the permission tab i had checked "Node Gallery API". In the case of beta version of node gallery these was not showing.


hook_entity_base_field_info() vs. creating a new entity

There isn't a 'right' or 'wrong' method of this. It really depends on your business requirements.

Are the fields you are thinking you need related to the user object? If they are, then I would use the User object. However, that shouldn't involve extending it, you can just add fields to it.

Without more information it's hard to be more specific.


Ajax callback not working with 'language_select' in drupal 8 forms

Try adding a container. It works for me:

public function buildForm(array $form, FormStateInterface $form_state){
    $current_user = \Drupal::currentUser();
    $user_preferred_langcode = $current_user->getPreferredLangcode();

    // The status messages that will contain any form errors.
    $form['status_messages'] = [
     '#type' => 'status_messages',
     '#weight' => -10,
    ];

    $form['title'] = [
      '#type' => 'html_tag',
      '#tag' => 'h2',
      '#value' => t('Change Language'),
    ];

    $form['preferred_langcode'] = [
      '#type' => 'language_select',
      '#languages' => LanguageInterface::STATE_CONFIGURABLE,
      '#default_value' => $user_preferred_langcode,
      '#ajax' => [
        'callback' => [$this, 'languageCallback'],
        'event' => 'change',
        'wrapper' => 'language-wrapper',
      ],
    ];

    $form['language_wrapper'] = [
      '#type' => 'container',
      '#attributes' => ['id' => 'language-wrapper'],
    ];

    $preferred_langcode = $form_state->getValue('preferred_langcode');

   if(empty($preferred_langcode) || $user_preferred_langcode ==
$preferred_langcode) {
      $form['language_wrapper']['default_language'] = [
        '#type' => 'html_tag',
        '#tag' => 'p',
        '#value' => $this->t('Your Current Language'),
      ];
    }

    $form_state->setCached(FALSE);

    return $form;
  }

  public function languageCallback(array $form, FormStateInterface $form_state) {
    return $form['language_wrapper'];
  }


Programmatically get the results of a view

You can not get the value of field directly from row result.
You can get it by accessing to the entity like the following:
Option1

  foreach ($view->result as $id => $result) {
    $node = $result->_entity;
    // Get the full name value.
    $name = $node->get('field_user_full_name')->value;
    // check the result output for testing only.
    \Drupal::messenger()->addMessage(t($name));
  }

Or by loop through the fields like the following:
Option2:

foreach ($view->result as $id => $row) {
      foreach ($view->field as $fid => $field) {
        if ($fid == 'field_user_full_name') {
          //Get the full name value.
          $name = $field->getValue($row);
          // check the result output for testing only.
          \Drupal::messenger()->addMessage(t($name));
        }
      }
    }


Turn off responsive behavior for Bootstrap 3

You can reset Media queries breakpoints, it will not work.
Here is path: bootstrap/bootstrap_subtheme/less/variable.less
at line number 209.

Check it.


How to view several Colorbox images simultaneously after click on wide screen?

You need to choose per page gallery in colorbox formatter settings like in screenshot :