Another option is to use Rules on new content creation then run the php code.

  The Rules module allows site administrators to define conditionally
  executed actions based on occurring events (known as reactive or ECA
  rules). It's a replacement with more features for the trigger module
  in core and the successor of the Drupal 5 workflow-ng module.

EDIT:

Enable the module 'PHP Filter'
In Rules, use the 'After Saving New Content' React on Type - this will trigger each time content is published for the first time
Optionally, add a condition Restrict by Type, choose the content type in which you want this to appear
Add a new action 'PHP: Execute custom php code' with your own code


I found the answer from this Link. So Internet Explorers never accepts element value as integer. I changed my code as follows it's working for me,

$price['#states'] = array(
  'visible' => array(
    ':input[id="edit-field-paid-event-und"]' => array('value' => '1'),
  ),
);


Make a div clickable using a render array

It sounds like you want to create an Accordion, I would look at Views Accordion because it sounds like what you want. I would try to stay away from custom javascript and html and attempt to theme views_accordion as you want it to look.


How to make the Admin interface language switch based on node content?

On D7 you'll find a language detection and selection page at admin/config/regional/language/configure:

If you enable and put "URL Determine the language from the URL (Path prefix or domain)" on top the system will show the interface in French for nodes (and other content) in French and it will be English for English content.


How to display vocabulary terms and their descriptions with their tagged content in a view?

If you don't mind using some other contrib modules with views, Views Field View can be the best solution.

Create content views

First, create a content views to list the content title which contains the taxonomy term, add field Content: Title and add the taxonomy term field as contextual filter. (e.g. Content: Tags (field_tags) in screenshot)

  Use aggregation is to remove the duplicated content because same term can be attached on one content more then once.

Create taxonomy term views

Second, create a taxonomy term views to list the Taxonomy term: Name and Taxonomy term: Term description under a vocabulary, which is similar to the one you have created.

  BUT, you don't need to add the relationship Content with Term neither the field Content: Title

Field Taxonomy term: Term ID is used as contextual argument, so exclude it from display.

Attach views field view

Add a views field, select the taxonomy term view you created and place [!tid] as the argument of Contextual filters.

Result

All required data is ready now, you may need to override the views template files for modifying the output.

Performance

  This method involves multiple views, the performance may become an issue if there are many contents and terms. You should enable the time-based cache on the content views.


Drupal Static HTML content not rendering

Looks like it worked out after Upgrading Mysql (from 5.1.. to 5.5..) had php (5.4.17) now its 5.4.22 (guess there's no big difference there..). Thought i'd put it here incase anyone runs into such a weird problem in the future.

Thanks everyone for trying.. Really appreciate it!


How do I get the MIME type of a file basing on its content and not its extension?

You can easily get the MIME type of a file using mime_content_type() function.
$mime_type = mime_content_type($path_to_the_file);

I've just tested it on my local machine; placed a test.pdf file in my home folder and renamed it giving it no and an incorrect extension. In both cases I got the right MIME type:

$ ls
test.pdf

$ drush eval 'var_dump(mime_content_type("/home/elin/test.pdf"))'
string(15) "application/pdf"

$ mv test.pdf test
$ drush eval 'var_dump(mime_content_type("/home/elin/test"))'
string(15) "application/pdf"

$ mv test test.jpg
$ drush eval 'var_dump(mime_content_type("/home/elin/test.jpg"))'
string(15) "application/pdf"

$ mv test.jpg test.png
$ drush eval 'var_dump(mime_content_type("/home/elin/test.png"))'
string(15) "application/pdf"


How do allow an exposed filter to override another filter in Views?

You can modify the view paramteres implementing hooks_views_pre_build. There you can examine received data (for example, checking $_GET) and modify view filters, deleting the "Posted Date: Relative 'today'"filter.

function mymodule_views_pre_build(&$view) {
  if ($view->name == 'my-view') {
    if (must_delete_filter()) {
      unset($view->filter['posted_date_relative_filter_name']);
    }
  }
}

So Views is executed without that filter. In example code must_delete_filter is the function that decides if filter must be deleted or no.


Why are we getting anonymous account creation on a site where this is turned off?

Does your drupal version is up to date ?

Versions before 7.32 need a fix to protect your Drupal from SQL injection ...

https://www.drupal.org/SA-CORE-2014-005

Theres a link to a patch if you cant do the full update


Webform is not submitting after 1st submit?

This piece of code helped to solve the issue.
Clearing the cache for every submission of a webform which is protected by honeypot.
    function MODULE_NAME_form_alter(&$form, FormStateInterface $form_state, $form_id) {
      $advanced_validation = \Drupal::config('honeypot.settings')->get('advanced_validation');
      if ($advanced_validation) {
        $form['#cache'] = ['max-age' => 0];
      }
    }


different views for different taxonomy vocabularies at taxonomy/term/%

Best Solution is using  the : Taxonomy Views Integrator  allows you to choose which view to associate with which taxonomy through a very handy and intuitive drop down menu.

More Detail are Found here:


how to create a new node of a content type when a new node created of another content type?

As said by @drupality

function hook_node_insert($node) {
 if ($node->type != 'job_posting') {
   return;
 }
$node = new stdClass(); // Create a new node object
$node->type = "test";
node_object_prepare($node); // Set some default values

$node->title    = "YOUR title";
$node->language = LANGUAGE_NONE; // Or e.g. 'en' if locale is enabled

$node->uid = 1; // UID of the author of the node; or use $node->name

.
.
.//Enter your other field values
.
node_save($node);
}


Embedded video thumb has been displayed on all overlay windows

You could try CSS z-index Property

  Definition and Usage

  The z-index property specifies the stack order of an element.

  An element with greater stack order is always in front of an element
  with a lower stack order.

  Note: z-index only works on positioned elements (position:absolute,
  position:relative, or position:fixed).

Try setting a higher value to the overlay or a lower value to the youtube player.


Best way to delete all variables when uninstalling module

Variables are cached, so deleting manually is fine so long as you invalidate that cache, e.g.

db_delete('variable')
  ->condition('name', 'mymodule_%', 'LIKE')
  ->execute();

cache_clear_all('variables', 'cache_bootstrap');


How to programmatically duplicate a node reference field during rendering?

You have total control over the layout of nodes within your theme via the node.tpl.php file and its variants and overrides. Check out a lot of information about node.tpl.php here and template files in general here.

By creating a specific template, you can customize it to your purposes along these lines:

function YOURTHEME_preprocess_node(&$vars) {

  if ( /* whatever condition you have that returns true for printing */ ) {
    $vars['template_files'][]='node-printing';
  }

  // any other node preprocessing goes here

}

Then, you put a node-printing.tpl.php file in your theme directory next to the default node.tpl.php for your theme, and in there, customize it as you like.

The key variables to be looking at are $content and $node. If you goto admin/content/node-type/NODE_TYPE/display on your system you can see how $content is built and customized,  while the latter is it as an object containing all of its fields that you can rework and so forth.

Putting a drupal_set_message('<pre>' . print_r($node, TRUE) . '</pre>'); at the top of your new template file will show you what you have to work with.

And, as always, just remember to clear caches after creating this new template so that the theme registry picks it up, but now you should be able put anything anywhere you want in your node display.


I believe that functionality is provided by the Inline Entity Form module

Provides a widget for inline management (creation, modification, removal) of referenced entities.
The primary use case is the parent -> children one (product display -> products, order -> line items, etc.), where the child entities are never managed outside the parent form.

Edit: In fact it definitely is, this is an image from the module page:


Cloudflare Clear Cache For One URL, Convert Curl Command to Drupal::httpClient() Or php

https://api.cloudflare.com/#zone-purge-files-by-url
I found the solution, so this command:
curl -X POST "https://api.cloudflare.com/client/v4/zones/abcdefghijklabcdefghijkl/purge_cache" \
     -H "Authorization: Bearer abcdefghijklabcdefghijkl" \
     -H "Content-Type: application/json" \
     --data '{"files": ["https://example.com", {"url": "https://example.com/url"}]}'

It will be in Drupal like:
      $client = \Drupal::httpClient();
      $options = [
        'headers' => [
          'Authorization' => 'Bearer abcdefghijklabcdefghijkl',
        ],
        'json' => [
          'files' => ['https://example.com/url']
        ],
      ];
      $response = $client->request('POST', $url, $options);
      $data = $response->getBody()->getContents();
      $data = json_decode($data, TRUE);
      if ($data['success']  == TRUE){
        return TRUE;
      }


Custom permissions for unpublished content

The code you are showing is not completely ported to Drupal 8. In particular:

hook_permission() is not used anymore from Drupal 8; what you need is describing the module permissions in view_unpub.permissions.yml
user_access() has been removed
Constants like NODE_ACCESS_ALLOW have been removed

As example of hook_node_access() implementation, see node_node_access(), which also shows what replaces user_access() in Drupal 8.

function node_node_access(NodeInterface $node, $op, $account) {
  $type = $node->bundle();
  switch ($op) {
    case 'create':
      return AccessResult::allowedIfHasPermission($account, 'create ' . $type . ' content');
    case 'update':
      if ($account->hasPermission('edit any ' . $type . ' content', $account)) {
        return AccessResult::allowed()->cachePerPermissions();
      }
      else {
        return AccessResult::allowedIf($account->hasPermission('edit own ' . $type . ' content', $account) && $account->id() == $node->getOwnerId())->cachePerPermissions()->cachePerUser()->addCacheableDependency($node);
      }
    case 'delete':
      if ($account->hasPermission('delete any ' . $type . ' content', $account)) {
        return AccessResult::allowed()->cachePerPermissions();
      }
      else {
        return AccessResult::allowedIf($account->hasPermission('delete own ' . $type . ' content', $account) && $account->id() == $node->getOwnerId())->cachePerPermissions()->cachePerUser()->addCacheableDependency($node);
      }
    default:

      // No opinion.
      return AccessResult::neutral();
  }

The rest of the code seems fine, to me. Check all the files you are using, and see if they need any change to make your modules work in Drupal 8.


You can try this code:

function MODULE_NAME_node_presave(Drupal\node\NodeInterface $node) {
  $node->setTitle('new Title');
  $node->set('body', 'this is body');
}


Is there a tpl.php file generated by Drupal 7 for custom content types

No; Drupal doesn't ever create template files dynamically.

For new content types the default node.tpl.php, or the one provided by the enabled theme, will be used.


What is public static function create() in plugins for?

create() is a factory method for dependency injection.

Plugins which implement ContainerFactoryPluginInterface are instantiated by create() of the plugin class:

ContainerFactory::createInstance

public function createInstance($plugin_id, array $configuration = []) {
  ...
  // If the plugin provides a factory method, pass the container to it.
  if (is_subclass_of($plugin_class, 'Drupal\Core\Plugin\ContainerFactoryPluginInterface')) {
    return $plugin_class::create(\Drupal::getContainer(), $configuration, $plugin_id, $plugin_definition);
  }

  // Otherwise, create the plugin directly.
  return new $plugin_class($configuration, $plugin_id, $plugin_definition);
}


Visit next: Administration » Structure » Views » Orders (admin/structure/views/view/commerce_orders/edit/admin_page)

FORMAT > Format:Table | Settings
Click Settings. In radios buttons select own default order field.


Taxonomy Terms More than one level and Clean Class throws error

The error message:

  Recoverable fatal error: Object of class
  Drupal\Core\Field\FieldItemList could not be converted to string

Unfortunately the field object FieldItemList can't be casted to a string, it doesn't have a magic __toString() method, but it does have a magic __get() method. So you can provide a property name, which is for most field types value, to get the field value as string:

  class FieldItemList

  Represents an entity field; that is, a list of field item objects.

  An entity field is a list of field items, each containing a set of
  properties. Note that even single-valued entity fields are represented
  as list of field items, however for easy access to the contained item
  the entity field delegates __get() and __set() calls directly to the
  first item.

Source: https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Field%21FieldItemList.php/class/FieldItemList/8.7.x


Customizing a View with Taxonomy, color coding and icons

First, to have the associated icon show up with the taxonomy term, do the following:

add field: image field from taxonomy
add field: Global: custom text, set it to [name] [field_your_image_field]
exclude label from display
exclude these two fields from display
change your table grouping from taxonomy name to Custom text ( or whatever you named it )

To style the output, you'll use two settings:

under Format: table | settings, set the row class here

to style individual fields, click on the field in the fields list, click on style settings, and customize field HTML / create a CSS class

There are lots of options here for setting field and label classes, and html elements

Good luck


Why does the Webform disappear after changing Submit button text in Form settings?

Difficult to know what's going on based on the limited information you've provided, but it could be permissions. If you don't have permissions to view the webform then you won't see it.

The scenario you've described might occur if you are configuring the webform while logged in, then testing it while logged out (or in another browser) as an anonymous user that does not have permissions to view.


How do I incorporate a browser file search into a Drupal form?

To output a file select form element in a Drupal form, you simply add a file or managed file element.

$form['upload'] = array(
    '#type' => 'file',
    '#title' => t('Choose a file')
  );
)


Send newsletter with list of users with specific field value

There is the simplenews module which will do the newsletter sending part of your question but similar interests is up to you to define. Drupal can't predict what "similar interests" are!

If you already have a list of users with similar interests, simplenews will enable you to create individual groups/mailing lists which you could add your users to.


Run feeds importer crons one after another

Your approach is already heading in the good direction. If you don't want to schedule the import of both importers, then you should only schedule the first one in mymodule_cronapi().

Then, in mymodule_feeds_after_import(), you'll schedule the next one by calling startImport() on the second source object (or by doing something similar as you did in mymodule_import_feeds_one()). If you configure your importer to import in the background, then startImport() will result into the source being imported during cron. If your import task is large, it may be divided in multiple chunks (depends on the implementation of the parser) so PHP wouldn't exceed the maximum runtime. In this case the import may take multiple cron runs to complete.

/**
 * Implements hook_cronapi().
 */
function mymodule_cronapi($op, $job = NULL) {
  $items = array(
    'cron_one' => array(
      'description' => 'import feeds one',
      'rule' => '4 0 * * *',
      'callback' => 'mymodule_import_feeds_one',
    ),
  );

  return $items;
}

/**
 * Implements hook_feeds_after_import().
 */
function mymodule_feeds_after_import(FeedsSource $source) {
  if ($source->id == 'import_feeds_one') {

    feeds_source('import_feeds_two')->existing()->startImport();
  }
}

I'm not sure why you want to start an import in mymodule_enable(). This code is only called once, when enabling your custom module (unless you disable the module and enable it again).


How do I dump a variable that is too big for dump(var)?

As a workaround, until Kint will be configurable via UI see #2405179, edit modules/devel/kint/kint/config.default.php and set $_kintSettings['maxLevels'] to a lower number (the default is 7).

Try using 4. This will limit the depth of the array that gets dumped.


It was a strange flow of events, but the question was relevant to Ubercart, which I was wrong not to mention in the original post. It took doing research for a Drupal Commerce install to find the path to the answer for Ubercart!

The answer was the Price per Role module. Part of the project requirements were that the "member" viewer should be able to see the original price. As a workaround, we actually had to set up a special fields so that both prices could show! Yes, this could have been done with coding, but the client doesn't have a budget for coding.


Okay for the noobies looking for tooltips like me...  The documentation for qTip (Stylish jQuery Tooltips) is a bit misleading and on first read you might think that must implement the tooltip via input filter.  While implementing via input filter is "quick & dirty", it doesn't allow you to enter any html in the tooltip and also inside your wysiwyg editor you see the tooltip text displayed in the textarea, which destroys the W-Y-S-I-W-Y_G experience.

From the project page if you want to see demos, you are taken to the qTip2 plugin page, which shows great demos, which are programmatically implemented are 100% NOT useful to implement qtip styled tooltips on your page.  You can implement programmtically, but then you have to CSS style the tip on your own.

My Solution:

1.) Install the qTip (Stylish jQuery Tooltips) and create an instance (style) of tooltip that you want to use.

2.)After you save your style, you will be taken back to landing page of the module, which lists the qtip instances (styles) that you have saved.

3.) right-click on this page and select "view-source". In the source code of the page find the name of your saved qtip instance (for example, "test_tip_top_left"). It should look something like this:

Sample textThis is an example of how this qTip instance will look and function throughout the website.

4.) attach the class="qtip-link" attribute to your desired page element, then immediately following the element add a div with the attributes class="qtip-tooltip" data-qtip-instance="test_tip_top_left" and add your desired html content inside the div.

5.) Via theme's style.css (assuming it is used inside your wysiwyg content editing area), create a style to hide the display of the div containing your html tooltip content (if you don't, your tooltip will work, however in your wysiwyg editor the div html tooltip content will be displayed again destroying the WYSIWYG experience), something like:

.qtip-tooltip { display: none; }

6.) Attach the tooltip to an element in your page:

Text Users See
HTML Contentinserted here

7.) BANG - cool tooltip ;-)


Empty field value showing in webform email content

Similar question was recently answered by the Webform module developer at drupal.org:

"You might just need to append the :clear prefix.

[webform_submission:values:element_value] => [webform_submission:values:element_value:clear]"

https://www.drupal.org/project/webform/issues/2982562

So, in your case use replacement pattern: [webform_submission:values:attach_file:clear]


Why do I get a syntax error on this query?

I changed the code to the following one, and I don't get the error anymore.

$query = \Drupal::database()
    ->select('simpleads_impressions', 's')
    ->fields('s', array('nid'));
$query->addExpression("FROM_UNIXTIME(timestamp, '%Y-%m-%d')", 'utime');
$query->addExpression("UNIX_TIMESTAMP(FROM_UNIXTIME(timestamp, '%Y%m%d'))", 'date');
$query->addExpression('COUNT(*)', 'all_count');
$query->addExpression('COUNT(DISTINCT ip_address)', 'unique_count');
$query->where("FROM_UNIXTIME(timestamp, '%Y-%m-%d') BETWEEN CURDATE() - INTERVAL 1 DAY AND CURDATE() - INTERVAL 1 SECOND");
$query->groupBy('date');
$query->groupBy('nid');
$query->groupBy('timestamp');
$result = $query->execute()->fetchObject();


What is the best way to make some content only available to authenticated users?

You can use the combination of ACL and Content access modules to achieve this. ACL + Content access give you better control over access to content: You can make certain types accessible to certain roles, or even specific nodes accessible to specific users.

Now here comes the tricky part:

Both the Acl and Content Access modules have no D8 release yet and have patches in their issue queues, which convert them to D8. For some reason the maintainers have not created D8 branches yet, but I'm using the patched versions of both the modules on my company site - they work perfectly.

ACL patch can be found here.

Content access patch can be found here.


Searching for "brit drupal" produced:

BIRT Open Source Engine integration as a Drupal module for dynamic, BIRT data-driven content pages. Allows multiple BIRT designs to be integrated as its own Drupal content type.
BIRT vs Custom Drupal Module
BIRT OS Drupal Module
BIRT Module for Drupal 6 (video)


Setting up responsive content within a responsive theme

If you are using Zen theme, best way(i hope so) to do responsive design is - Zen grids,
First u need to install ruby gems, after you installed u need two more things, as root install sass and compass and ofc. zen-grids

gem install sass
gem install compass
gem install zen-grids

Then go to your theme folder, and write compass watch now all your css yo need to write in sass folder it will produce css in same files in your css folder. To do blocks responsive, in Layouts folder(ofc if you are using Zen sub theme) u will see responsive-sidebars.scss  or similar, now u need to import @import "zen";// Import Zen Grids with this statement. and write zen-grids code in your responsive-sidebars.scss. Read more about Zen grids - here.
I hope it helps.


In the form submit handler, look in the form state. The values array will contain submitted values.

So for a form element, 'foo', generated like this:

$form['foo'] = [
  '#type' => 'textfield',
  '#title' => t('Foo'),
];

You get the value like this:

function MYMODULE_form_submit($form, &$form_state) {
  $value_of_foo_field = $form_state['values']['foo'];
}


How to reset admin password if account is blocked

Drush is ideal but if you don't have that installed, you'll need to do more than just a sql query because you'll need to get a hash of the password you want to use.

First find your core drupal main directory and run

php core/scripts/password-hash.sh "your_new_password"

In phpmyadmin or your sql db manager of choice find the admin user in users_field_data and replace the pass value with the hash you got from the command above.

Then truncate the 'cache_entity' table. If you were locked out from too many failed login requests also delete instances of your IP in the 'flood' table.

Then you should be able to log in with your new password.


Programmatically building a Quicktabs instance

Yes, programmatically created instances are not registered with those created trough the UI, but at least they are more flexible.


How to check if entity's property has a value

If you look at the entity module, specifically the EntityMetadataWrapper class, there is no method of checking whether or not something has a value.  If a value returns empty you are essentially checking whether or not the value exists by getting an empty value.

For example a single value uses the EntityValueWrapper and only has one method and that is to return the value.  The EntityMetadataWrapper class has few public methods and none that returns whether or not a value is set.  If you wanted to extend one of the classes you could probably build your own method.

/**
 * Wraps a single value.
 */
class EntityValueWrapper extends EntityMetadataWrapper {

  /**
   * Overrides EntityMetadataWrapper#value().
   * Sanitizes or decode textual data if necessary.
   */
  public function value(array $options = array()) {
    $data = parent::value();
    if ($this->type == 'text' && isset($data)) {
      $info = $this->info + array('sanitized' => FALSE, 'sanitize' => 'check_plain');
      $options += array('sanitize' => FALSE, 'decode' => FALSE);
      if ($options['sanitize'] && !$info['sanitized']) {
        return call_user_func($info['sanitize'], $data);
      }
      elseif ($options['decode'] && $info['sanitized']) {
        return decode_entities(strip_tags($data));
      }
    }
    return $data;
  }
}


Taxonomy term name alias in taxonomy term autocomplete

Two options to maybe investigate (neither are easy...):

You could create a custom module using hook_field_widget_form() to define a custom widget. There are several good tutorials on hook_field_widget_form out there, here's one I found quite useful, and the Form API Reference will help too. You might also want to look at Autocomplete Deluxe as a possible base.
You could create a Views table with autocomplete exposed filters, and some custom javascipt that binds a click event to each row controlling the form element, and you could use the 'Node edit' override in Ctools page manager to customise the form page and add it in. If you want one autocomplete box to filter both 'Name' and 'Synonyms', you might need some custom javascript again: maybe hide one input box and control its input with a jquery keyup event on the other box, and set the contextual filters to 'Or' in Views

Of these I'd recommend the first way - much cleaner and probably less work!


Slow Search on Drupal 6.x site with 60.000+ nodes

60,000 nodes in the search index is definitely a lot. Not only is it slow and suboptimal to use Drupal's default search with such a large number of nodes, but it is going to progressively put more pressure on your infrastructure as you continue adding nodes.

The solution would definitely be to offload your search to another tool. Two options:

Solr: 60,000 is child's play for Solr. It could suffice you for a lot more even on a commodity machine.
Elastic search: Another tool built on top of Apache Lucene. This one's newer and does not have as many supporting modules for it as Solr does (for Drupal). But it is faster than Solr and can handle concurrent commits much better.

In both these cases, I'd recommend installing the search tool on another server.


You can index taxonomy terms with this module:
https://drupal.org/project/apachesolr_term

There is a hook that allows you to specify a custom field for the solr index:
hook_apachesolr_index_document_build_' . [entity type]

Then you can add this field to the solr query by using:
hook_apachesolr_query_prepare

There is a more detailed article on how to do this here:
http://rapiddg.com/blog/adding-customized-fields-apache-solr-index-drupal


You could delete the field collection records from there – either through custom Drupal code, or through direct database access if you have that.

Since you have devel enabled and you are generating content, I'm assuming you're not working on a production site, but it's worth saying that deleting records from the database is a risky proposition.

I'm also assuming that you want to delete all of the field collection data for this field collection and not cherry pick just the content that was generated by devel.

You didn't mention what your field collection or its fields were named, but let's say that you have a field collection with the machine-name testcollection and in that collection you have two fields with machine-names collectionfield and collectionfield2.

The data for these will be stored in several tables. In my example, collectionfield1 and collectionfield2 are text fields. Therefore the data will be stored like so:

{field_data_field_testcollection}        // the field collection
{field_revision_field_testcollection}    // the field collection (revisions)
{field_data_field_collectionfield}       // field attached to "testcollection"
{field_data_field_collectionfield2}      // field2 attached to "testcollection"
{field_revision_field_collectionfield}   // revisions
{field_revision_field_collectionfield2}  // revisions

You could remove the fieldcollection content by running the following queries:

DELETE FROM field_data_field_collectionfield WHERE bundle = 'field_testcollection';

DELETE FROM field_data_field_collectionfield2 WHERE bundle = 'field_testcollection';

DELETE FROM field_revision_field_collectionfield WHERE bundle = 'field_testcollection';

DELETE FROM field_revision_field_collectionfield2 WHERE bundle = 'field_testcollection';

If you have data in the testcollection field even after deleting the generated nodes, you should delete that too:

DELETE FROM field_data_field_testcollection;

DELETE FROM field_revision_field_testcollection;


How to detect if a user is in a specific directory/accessing a specific path?

For example I need to know if a user is in this directory http://example.com/directory

If "directory" is a filesystem directory, then it's not possible for a Drupal function to know when a user is visiting that directory, for the simple fact Drupal is not invoked to serve the content of a directory. One of the Rewrite directives present in the .htaccess file that comes with Drupal is the following one:

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} !=/favicon.ico
RewriteRule ^ index.php [L]

If "directory" is the path for which a module defines a menu callback, and there isn't a directory with that name, then it is possible for a function to return TRUE when the user is visiting a specific path.

function check_path(array $directories) {
  $path = $_GET['q'];

  foreach ($directories as $dir) {
    if ($dir == $path) {
      return TRUE;
    }
  }

  return FALSE;
}

This function doesn't consider the path aliases. If http://example.com/path-alias is the path alias for http://example.com/real-path, $_GET['q'] will contain real-path when the user visits http://example.com/path-alias; the same is true for arg(), which will return an array containing real-path.
If the function needs to consider also the path aliases, then it needs to be rewritten as:

function check_path(array $directories) {
  $path = $_GET['q'];

  foreach ($directories as $dir) {
    if (drupal_get_normal_path($dir) == $path) {
      return TRUE;
    }
  }

  return FALSE;
}


how to filter taxonomy vacobulary using views contextual filters

You can refer Hierarchical Select module, which allows you to create taxonomy structure like your requirement and also allows to filter accordingly your requirements in view.


Send notification E-Mail to x when x’s content is commented

Use Rules module. Create the following Rule:

Event: after saving a new comment. You will probably want to restrict this by content type as well.
Add action: send mail. Arguments:

To: switch to data selection and choose comment:node:author:mail
Subject: whatever you want, for example "A comment has been posted to your blog post"
Add the message
Condition: NOT comment:node:author:uid and comment:author:uid so that the user does not receive emails for his own comments.

Here's how to insert the name of the node author:

Formatted username:

Dear [comment:node:author:name], [...]

Specific field (e.g. if you have first and last name fields and you want to use only first name):

Dear [comment:node:author:field-first-name], [...]


How to add class in title div for specific block?

function themename_preprocess_block(&$variables) {

if($variables['block']->bid == 'views-front-block') {

     $variables['classes_array'][] = 'container';
 }

}

add this function in your template.php file of your theme.


Delete selected comments of a particular node?

You can do this with Views Bulk Operation module. Follow the steps:

Install Views and Views Bulk Operation modules and enable these modules.
Create a View of Type "Comment".
Change the Views Format show from 'Comment' to 'Fields' under Format section.
Change the Views Format from 'Unformatted list' to 'Table'.
Add Bulk Operation:Comment, Comment:Title and Content:title fields under Fields section.
In step 5 When you chose Bulk Operation: Comment select Delete Item under SELECTED BULK OPERATIONS setting.
Add Content: Title filter criteria and expose this filter So that you can filter comments of a particular node.


How do I enable recording option in the BigBlueButton module?

My problem is resolved. I have pass record=true in setting array of bbb.module file. Please see below code

function bbb_init_meeting($node = NULL, $params = array()) {
  $welcome     = variable_get('bbb_content_type_welcome_'     . $node->type, '');
  $dialNumber  = variable_get('bbb_content_type_dialNumber_'  . $node->type, '');
  $moderatorPW = variable_get('bbb_content_type_moderatorPW_' . $node->type, '');
  $attendeePW  = variable_get('bbb_content_type_attendeePW_'  . $node->type, '');
  $logoutURL   = variable_get('bbb_content_type_logoutURL_'   . $node->type, '');
  $settings = array(
    'nid'          => $node->nid,
    'name'         => $node->title,
    'meetingID'    => bbb_create_meeting_id($node->nid),
    'attendeePW'   => !empty($attendeePW) ? $attendeePW : user_password(),
    'moderatorPW'  => !empty($moderatorPW) ? $moderatorPW : user_password(),
    'welcome'      => !empty($welcome) ? $welcome : t('Welcome to @title', array('@title' => $node->title)),
    'dialNumber'   => $dialNumber  ? $dialNumber  : NULL,
    // TODO: This is limited to 90000 voice bridges and may
    // collide sooner, as rand() may return x twice in a row
    'voiceBridge'  => rand(10000, 99999),
    'logoutURL'    => $logoutURL, //TODO: make absolute, as soon as supported
    'initialized'  => 0,
    'created'      => time(),
    'record' => 'true',
    'duration' => '10',
  );
  $params = array_merge($params, $settings);
  return $params;
}


How do I print out a specific node to my page?

Looking with the Devel module to the structure of a loaded node, I notice that "body" contains the following values:

The first array index is the language ID for the language set for the node; it could be also LANGUAGE_NONE (the string "und") for nodes for which the language is set to "neutral." That array index contains an array with the following indexes:

"value": the content of the "body" field
"summary": what set as summary (or teaser) for the node
"format": the input format associated with the "body" field

In the node I used as example, if you try accessing $node->body['und'][0]['value'], you would access an undefined value. You should use $node->language to know the language set for the node; you code should be similar to the following one:

$node = node_load(127);
$body = $node->body[$node->language][0]['value'];

As for printing the body content, the "body" field contains the text before the input filter is applied; you should use code similar to the following one, to print the "body" field:

$node = node_load(127);
$language = $node->language;
print check_markup($node->body[$language][0]['value'], $node->body[$language][0]['format'], $language);


How to select all the field in content type

If you don't mind my saying, you don't want to do that manually. Drupal has a rich API which you should use.

The standard method to load a node and all of its fields/extra data, is node_load():

$node = node_load($nid);

If you're trying to avoid the overhead of the 'extra' (non-field) data, then you can use field_attach_load() along with a basic DB query to get a reasonable node object with all fields attached.

// Get base node data (aka 'properties')
$node = db_query('SELECT * FROM {node} WHERE nid = :nid', array(':nid' => $nid))->fetchObject();

// Attach the fields
field_attach_load('node', array($node));

It is possible, of course, to query the database manually for all of this data, but when the functionality has already been written for you there doesn't seem any point.


The contributed modules are in web/sites/all/modules/contrib/.

So, the suggested directory for the custom modules is web/sites/all/modules/custom/.

The other way to manage custom modules is to separate repository for the custom modules.

You can add your custom repositories to your composer.json in project root directory. Composer will look in all your repositories to find the packages your project requires. See Use PHP composer to clone git repo. Add your repositories under default Drupal.

After you add your repository to composer.json you have to tell Composer to install your custom modules to web/sites/all/modules/custom/. Add this line to installer-paths

"web/sites/all/modules/custom/{$name}/": ["type:drupal-custom-module"],

When you create your custom module, you must set type of your custom module in composer.json  to drupal-custom-module.


You can return a BinaryFileResponse from a controller, or as 4k4 has added:
$response = new BinaryFileResponse("public://cal/211443-event.ics");
$form_state->setResponse($response);


Custom form to modify only some fields of an EntityForm

Based on the comments on the question, I fixed my issue.

I created the routing path to call the controller:

mymodule.manage_detailed:
  path: '/mes-detailed/cp/{eid}'
  defaults:
    _controller: '\Drupal\mymodule\Controller\DetailedController::manageAction'
    _title: 'Detailed'
  requirements:
    _permission: 'access content'

Controller:

class DetailedController extends ControllerBase implements ContainerInjectionInterface {

public function manageAction($eid) {

    $entityForm = \Drupal::entityTypeManager()
        ->getStorage('main_entity')
        ->load($eid);
    $finalform =  $this->entityFormBuilder()->getForm($entityForm);

    $render['form'] = $finalform;

    $render['#theme'] = 'manage_detailed';
    return $render;

}

}

Then I put inside the template all the form with:

{{ form }}

Because using only some fields inside the template didn't allow to save data.
And finally I create the submit function to define the redirect:

public static function manage_form_submit(&$form, &$form_state) {
        $url = \Drupal\Core\Url::fromUri('internal:/link-to-go');
        $form_state->setRedirectUrl($url);
    }

To call the submit function I used the alter form function inside the module file:

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

 //drupal_set_message($form_id); //to show id of the form

 if ($form_id == 'name_of_entity_form'){

    $form['name']['#type'] = 'hidden';
    $form['status']['#type'] = 'hidden';
    $form['new_revision']['#type'] = 'hidden';
    $form['revision_log_message']['#type'] = 'hidden';
    $form['field_n1']['#type'] = 'hidden';
    $form['field_n2']['#type'] = 'hidden';
    $form['field_email_']['#type'] = 'hidden';
    $form['field_nd']['#type'] = 'hidden';
    $form['actions']['delete']['#type'] = 'hidden';

    $form['actions']['submit']['#submit'][] = 'Drupal\mymodule\Controller\DetailedController::manage_form_submit';

  }
}


How would I monitor if a new entity had been saved?

If you need it to run for all entities, then your module can implement hook_entity_insert() for new entities and hook_entity_update() for changes to existing ones.

If you just need to target specific ones (node, user, etc), then most of the modules that implement entities also have insert and update hooks.


Webform with element that has logged in user's username

You can create a Value element with a token to capture and store the current user's name.

name:
 '#title': 'User Name'
 '#type': value
 '#value': '[current-user:name]'


Setting exposed filter default value from query string

The #default_value parameter should be set to the key of the select list array.

Example:

$form['category_id']['#default_value'] = $category_id;


How to add others libraries such as Zenpen to WYSIWYG profiles?

You'll need to write a WYSIWYG module plugin. Here is an example module you could follow.

Here is a simple .inc from the WYSIWYG module itself. Wrap your Zenpen one in a module like Ueditor (above) and you're done.


Looks like you are using better exposed filter module, it has option to configure the sorting label

so instead of Sort By
Sort by
 it will not replace the label but give you a nested div if that works for you.


Drupal 8: drush sset system.maintenance_mode TRUE

Drupal 7: drush vset maintenance_mode 1

Drupal 6: drush vset site_offline 1


Rules - How can I put a link into an email sent by a rule

You can use the following: [site:url]user/login?destination=node/[node:nid]/edit.

This will show login form to the users who are not authenticated and then redirect them to the node edit page.

If the user is already logged in, he/she will be immediately taken to the node edit page.


Solution:

$birthdate_object = date_make_date(
   $p->field_szuldat[0]['value'],
   $p->field_szuldat[0]['timezone'],
   $p->field_szuldat[0]['date_type'],
   $granularity = array('year', 'month', 'day'));

$birthdate_formatted = date_format_date($birthdate_object, 'custom', 'Y. F j.');

This yields incorrect value in the DST period of the year (1 day difference), so very dangerous:

$wrong_birthdate = format_date($p->field_szuldat[0]['value'], 'custom', 'Y. F. d.');


Content Type with Add comment, Post New Article, Share Links

To add Add comment link in view, follow below steps.

Add another field to your view i.e. Content: Nid
In field configuration, remove the title.
Select "rewrite the output of this field" and enter "Add comment" in the text area.
Now select "output this field as a link" and enter comment/reply/[nid]#comment-form in the Link Path field.

To add Share link,

Install ShareThis module.
Now add share field into your view.


Displaying Content Flagged by User Name with Flag Module

I had the same issue where I wanted to show the title of the content flagged with a certain flag by each user. I solved it as follows:

Created 2 views - 1 of users and another of content
In the user view, add 'Flags: User's flaggings' relationship (Refer attachment user_view)

In the content view, add 'Flags: Node flag' relationship and 'Flags: User uid' contextual filter (Refer attachment content_view)

Select 'Display contents of "No results found"' for 'WHEN THE FILTER VALUE IS NOT IN THE URL' in the contextual filter added in step 3
Set the format of the content view as 'Unformatted list' and uncheck 'Create a label' option for the 'Content: Title' field
Install Views Field View module
Embedd the content view inside the user view as a field by passing uid as a contextual filter to the content view

Hope this helps someone.

Regards,

Supriya Rajgopal


Can two nodes have same URL using Pathauto?

a registered user creates and submits an article as an unpublished node and assigned an URL by pathauto based on its title. At the same time another user creates an article with same title in unpublished form. Will it too have same url?

No. pathauto by default will append a number to the end of the URL to differentiate between them.


Create different user profiles with drupal 7

I don't know if you are still interested or not. I've got the same problem and I solved in this way:

In the User account you can put an option "Tenant" - "Landlord".
Then use the Rules module to create a rule that gives automatically the role dependent on the option chosen.

Or you can also redirect straight to the edit profile after the registration.


Drupal Signup: how to signup to multiple events at once?

Someone put together a hacky solution for "Signup" module (which is apparently similar to "CCK Signup"). Maybe it's a good starting point: http://drupal.org/node/151898.


Editing Image of Media Type Image in Drupal

Check your Field Mapping for the Media type you created.
Set them all to - Skip field - and you should be able to edit the media content without errors.


Implement Push Notification in my iOS App with a Drupal backend

Three module you need to require to accomplish notification one is rules second is services and push notification modules.

On cofiguration of push notifications you need to configure APNS certificate for IOS by put on private folder and set path to configuration.

By services module you need call register and deregister push token services.

By rule module you can set action of send push notification to particular token.


Scheduler changes node language on publish

Find the difference between your low level site and the big ones. Perhapsyoushouldcompare their node tables once before and once after you have published content onthem. Make shure, that the modules and settings are the same while running these tests.


page "/node/add" that I would like to programmatically limit the links that are displayed based on the users role

If you set node creation permission (Node Module on www.yourhost.com/admin/user/permissions) to specific roles, the existing form should take care of this automagically by itself, eg, if the user accessing www.yourhost.com/node/add can't create a specific node type, it won't be presented on that page.

Based upon commentary, node/add is built via:

function node_add_page() {
  $item = menu_get_item();
  $content = system_admin_menu_block($item);
  return theme('node_add_list', $content);
}

/**
 * Display the list of available node types for node creation.
 *
 * @ingroup themeable
 */
function theme_node_add_list($content) {
  $output = '';

  if ($content) {
    $output = '
';
    foreach ($content as $item) {
      $output .= '
'. l($item['title'], $item['href'], $item['localized_options']) .'
';
      $output .= '
'. filter_xss_admin($item['description']) .'
';
    }
    $output .= '
';
  }
  return $output;
}

so you most certainly could create a new YOURTHEME_node_add_list() function that filters the links based upon a user's role realizing that if the user entered the link directly it would nonetheless still work.

You could also create a node-add-list.tpl.php in your theme's directory with basically this in it as a start:

<?php

  $output='';

  if ($content) {
    $output = '
';
    foreach ($content as $item) {
      $output .= '
'. l($item['title'], $item['href'], $item['localized_options']) .'
';
      $output .= '
'. filter_xss_admin($item['description']) .'
';
    }
    $output .= '
';
  }
  print $output;

and then modify it however you wanted.

Just flush caches after either to make drupal's theme system see and pick up the changes.


You can use the user.data service

\Drupal::service('user.data')->set('mymodule', $uid, 'some_key', 'some_value');

You can then retrieve it with the same service:

$some_key = \Drupal::service('user.data')->get('mymodule', $uid, 'some_key');


How to get exposed filter dropdown option selected value in drupal hook

First of all, look up the exact filter's name. To do that open your view's builder UI and go to this exposed filter's settings page; look for the "Filter identifier" text field.

After that, you can get the filter's currently selected value in hook_form_alter():

function myModule_form_alter(&$form, $form_state, $form_id) {
    if ($form_id == 'views_exposed_form'){
        $view = &$form_state['view'];
        if ($view->name == 'your view name' && $view->current_display == 'page_1') {
            var_dump($view->exposed_input['your filter identifier']);
            // OR
            var_dump($form_state['input']['your filter identifier']);
        }
    }
}


Pager should start from last page instead of first one

At the view, you can use SORT CRITERIA. It can help you arrange in post date, title page or even content field.


oh dear lord.. Didn't dawn on me to make the field visible so I could see it.

The answer is "on"


Don't let user register without role/profile2 profile?

Best way to close all ways of creating users without that profile is adding a custom validation function for the user_register form.

In that validate handler just make sure that the form values are right and a user with a profile2 node will be created when form is processed (submit handlers are executed).

Use a form alter to add your validate.

This way you enforce the creation of valid user only where all user creation happen, the the user register form (except admins).


Getting the value of taxonomy field in a node.html.twig template (Drupal 8.x)

I found the problem. The 'news' field is a multi-value selectable field. The correct way to access the field would be:

{{ content.news.0 }}

Of course, this will only print the first value in the collection, so I created a for loop in the twig template to loop over the different values.

I needed the 'title' and the 'url' of the taxonomy term. This could be retrieved by:

{{ content.news.0['#title'] }}
{{ content.news.0['#url'] }}


It is a build in function in drupal views. When you add a contextual filter there would a section called more. You can put the case to lower case and check "Transform spaces to dashes in URL"


No 'read-more' to specific content type (eg page)

You can do this by removing the "teaser" mode and tweaking node--your_content_type.tpl file.

To remove the teaser mode: Go to "Structure > Content types > your content type";
click on "Manage display"  and "Custom display settings"; uncheck the "Teaser" checkbox.
This will display the content in the front page as is.

Now to remove the "read more" link, unset it in your node--your_content_type.tpl.

unset($content['links']['node']['#links']['node-readmore']);

This way you will not have "read more" link in your home and the whole content will be displayed for your content type.


Drupal 8 migrating image from local folder per XML file

Thanks to quietone, I figured it out. The settings for skipping row didn't work as expected. Instead of repairing, it's much easier for me to modify the XML-file and remove all rows without image node.

So I don't need the skipping plugin anymore and can change the process part to this (and it's working):

process:
  file_source:
  -
    plugin: concat
    delimiter: /
    source:
      - constants/file_source_uri
      - clio_cover
  file_dest:
    -
      plugin: concat
      delimiter: /
      source:
        - constants/file_dest_uri
        - clio_cover
  uid:
    plugin: default_value
    default_value: '1'
  uri:
    plugin: file_copy
    source:
      - '@file_source'
      - '@file_dest'
  filename: clio_cover_name


Multilingual article should display 404 when a translation is not available

It can not be done using core or contrib
To present 404 page not found (bad UX)
You could do something like this in your own module MODULENAME.module file
function MODULENAME_entity_view(array &$build,
  \Drupal\Core\Entity\EntityInterface $entity,
  \Drupal\Core\Entity\Display\EntityViewDisplayInterface $display, $view_mode) {

    $lang = \Drupal::languageManager()->getCurrentLanguage()->getId();
    $ent_lang = $entity->langcode->value;
    if($view_mode == "full" && $lang != $ent_lang){
      throw new \Symfony\Component\HttpKernel\Exception\NotFoundHttpException();
    }
}

but once you go to the not found page the language switcher will not be able to take you back to the translated page though
To Hide untranslated languages in language switcher
There is a core issue about this and solutions are worked out but until it is solved you could create your own module
/**
 * @file
 * Hide language switcher links for untranslated languages on an entity.
 */
use Drupal\Core\Entity\ContentEntityInterface;

/**
 * Implements hook_language_switch_links_alter().
 */
function MODULENAME_language_switch_links_alter(array &$links, $type, $path) {
  if ($entity = MODULENAME_get_page_entity()) {
    $new_links = array();
    foreach ($links as $lang_code => $link) {
      try {
        if ($entity->getTranslation($lang_code)->access('view')) {
          $new_links[$lang_code] = $link;
        }
      }
      catch (\InvalidArgumentException $e) {
        // This language is untranslated so do not add it to the links.
      }

    }
    $links = $new_links;

    // If we're left with less than 2 links, then there's nothing to switch.
    // Hide the language switcher.
    if (count($links) < 2) {
      $links = array();
    }
  }
}

/**
 * Retrieve the current page entity.
 *
 * @return Drupal\Core\Entity\ContentEntityInterface
 *   The retrieved entity, or FALSE if none found.
 */
function MODULENAME_get_page_entity() {
  $params = \Drupal::routeMatch()->getParameters()->all();
  $entity = reset($params);
  if ($entity instanceof ContentEntityInterface) {
    return $entity;
  }
  return FALSE;
}

Above solution is taken from this post
To Hide untranslated menu items
You can use menu_multilingual which gives option when you create/edit a menu block to hide untraslated items.


Same node to show using different themes

The Switch Page Theme module not supported "switching by aliases" yet.

See details here Theme switching not working with aliased paths?


Title field input textbox way too long in firefox browser

I had the same css issue.
you need to address the input field correctly with the inputtype "text":

e.g.

.mywrapper-form input[type="text"] {
   width: 100px;
}


How do I save and retrieve CKEDITOR media (images and video) on a CDN?

Until CKEditor developers implement the functionality, you could create a custom module that:

on node add/edit you loop thru all fields using CKEditor and crawl each images/videos
detect if the images are already on the CDN
if not, upload the images/videos on the CDN
replace the images links with your new CDN links
save the node

I hope it will help you.


How to change image size and position when uploading to article in tb_rave_starter

To edit the size of the image:

Go to /admin/structure/types/manage/YOUR_CONTENT_TYPE/display and click the edit image style button shown in the image below.

This will open a drop down and then you can choose the image size you want:

To change the location of the image you have several options...

You can edit your themes CSS file, however this will require understanding the underlying HTML and CSS.

An alternative is to use a module like Panels that allows you to create custom layout and apply them without actually doing any coding. I've not actually used it before myself but have heard good things about it and there are lots of tutorials online - just Google it.


For the content: Use an approriate content type or view.
For the URL use an URL alias to get something like www.mysite.com/landingpage .
If you want to hide some blocks on the landing page add a PHP snippet in the block configuration which queries arg() or $_GET['q'] for the URL.
If you need an other theme have a look at the ThemeKey module.
Use the Nodewords: D6 Meta Tags module to add meta tags for SEO or Facebook open graph tags.
Use the statistics or Google Analytics module to track the succses of your page.


This is a huge question.

I just can share my experience

First i export mysql data from live site with Backup and Migrate module.

I do restore it in my dev site. In this dev site, i beware to not send infortunetly emails, so i install Reroute email module. (great because the settings are not in database but in settings.php file)

Then i make my own dev on localhost with real datas

Depends if your have the abilities to do that, and if the datas are not so confidential to do so.

But to stick with your question, db diff is impossible is guess. And you have to upload the new module files and enabled them manually (or with drush). Settigs in drupal are totally encapsulated in db


If I understand your question correctly, and you are using Drupal 7, you need the Entity reference and Entity connect module.

The Entity reference module provides a field type with which you can reference other entities. When attached to your 'article' content type, your users can select an instance of the 'creator' content type.

To allow your users to dynamically create instances of the 'creator' content type, the Entity connect module comes in handy. Two buttons will be provided next to the Entity reference field, one to create a new instance and the other to edit existing content.

Please let me know if you need more information/help.


What's the preferred method of creating different page templates

This should by there by default.

For example, the body classes on my test site look like this for a simplenews node:

<body class="html not-front logged-in one-sidebar sidebar-first page-node page-node- page-node-90 node-type-simplenews toolbar toolbar-drawer i18n-en" >

As you can see, there is node-type-simplenews, among many other things.

Those classes are defined in template_preprocess_html() and are using in html.tpl.php (not page.tpl.php, unless you've overriden that. If so, you need to duplicate the logic in that function for your page.tpl.php.


How can I export all users in a CSV format?

Stick the following in a file named expusers.module

<?php
/**
 *  Implementation of hook_menu()
 */
function expusers_menu() {
  $items['expusers'] = array(
    'page callback' => '_expusers_select',
    'access arguments' => array('administer expusers'),
  );
  return $items;
}

/**
 * Callback
 */
function _expusers_select() {
  //
  $csvfile_name = 'expusers.csv'; // the file to save to
  $users = array();
  $result = db_query('SELECT * FROM {users}');
  foreach ($result as $record) {
    unset($userarray);
    foreach ($record as $key => $value) {
      $userarray[] = (empty($value)) ? '' : '"' . $value . '"';
    }
    $user = implode(',',$userarray);
    $users[] = $user . PHP_EOL; // Remove this if file_save_data don't work.
    // Use PHP statement below to append to file here if file_save_data don't work.
    // file_put_contents(..path to file.., $user, FILE_APPEND);
  }
  $file = file_save_data($users,'public://' .$csvfile_name); // Remove this if file_save_data don't work.
  return '
CSV dump of {users} table written to file "' . $file->uri . '".
';
}

Stick the following in a file named expusers.info;

name = Export users
description = "Exports the {users} table to a CSV file in the public file area."
core = 7.x

Create a directory named expusers in your in your modules directory, and place both files in it.

Enable the custom module "Export users" on the site's module page.

Navigate to the path expusers (e.g. http://example.com/expusers).

The message:

CSV dump of {users} table written to file "public://expusers.csv".

Should appear.

Go to your public file area and pick up your file.

The above tiny custom module should be far less resource hungry than Views data export, so, hopefully, you will get your CSV without hitting a memory limit .

However, it first collects all the user data into an array in memory, before dumping into the file.

If you still hit a memory limit, you can't use Drupal's very convenient file_save_data to save to a file.  Instead, you must save the data one line at a time.  There is no built-in Drupal function to do this, but you should be able to use PHPs file_put_contents instead.

I've used comment to indicate how to change the code to replace Drupal's file_save_data  with PHP's file_put_contents.


Using the web interface or using Drush cause different result?

From the technical perspective, the PHP configuration can be different for web server (Apache) and when running from CLI (drush), since different php.ini is loaded, therefore different limits are applied, sometimes your PHP could be different.

If you're non-technical person and it's one time (simple) process, it's better to use web interface, which is recommended way to upgrade your Drupal. The size of database doesn't make any difference, since the batch operation can perform long operations, but it may fail in the middle if you lost your connection.

On the other hand if you're repeating the process many times in order to test it properly, Drush may be a better solution, since you can test the process in more efficient and consistent way especially across multiple environments, this is especially useful if you've continuous integration in place (such as deployments).

So it's really depending on your needs.


Drush bootstrap fail - wrong MySQL username

You don't happen to have a ~/.my.cnf file (which sets the user to root)? MySQL will read that file after the file specified by --defaults-extra-file, and "If multiple instances of a given option are found, the last instance takes precedence".


How to create a view displaying a list of users who have logged-in user's preferences

I had same issue but solved by using this custom code in view. I was using profile2 module for registration so as per sex field, I was done this :

global $user;
$profiles = profile2_load_by_user($user);
foreach ($profiles as $profile) {
  if ($items = field_get_items('profile2', $profile, 'field_seeking')) {
    break;
  }
}
   return $items[0]['value'];

Please check my Post HERE.

As per my post I was do this :

global $user;
    $profiles = profile2_load_by_user($user);
    foreach ($profiles as $profile)
    {
        if ($items = field_get_items('profile2', $profile, 'field_sex'))
      {
            break;
          }
    }

    $i_am=$items[0]['value'];

    if($i_am=='sdmale' || $i_am=='sbmale')
    {

    $looking='smfemale+sbfemale';
    }

    if($i_am=='smfemale' || $i_am=='sbfemale')
    {
    $looking='sdmale+sbmale';
    }
    return $looking;


How to hide a block based on content type?

Sadly, it is not yet part of Context to negate the context (that I am aware of).

You have 2 options (slightly different than the link mentioned by @Mołot):

Write your own context.  It's actually not that hard, and you can follow the general flow suggested in (this post)[http://dtek.net/blog/extending-drupals-context-module-custom-condition-based-field-value].
Use the built-in visibility settings on the block configuration page to enable the block on all content types but the one you want, and all pages desireable (e.g, user/*, views pages, etc.).


You might consider one of two methods:

Define another status/branch in the checkout logic (approved shopping cart -> checkout) wherein Rule 5 would redirect to the approved cart step instead of the standard shopping cart.

or

Implement an "admin approved" flag on the Order that you could set in your actions for Rule 5 and then test in your conditions for Rule 3, redirecting the user only if that flag was false. That flag could be implemented as a new field on the Order entity (assuming Order is an entity).

Method 1 might be somewhat redundant and more work than method 2, but I think it's the better of the two because it extends the current shopping cart/checkout/Rules logic and workflow. I think there's merit in that.

In addition, method 2 would bury a critical aspect of that logic into a field on the Order. I think the state of an Order in a checkout process should be defined separately from the Order itself.

Perhaps there's a third way that uses a little bit of both methods.

Hope this is helpful.


How can I make a link from content profile node to it's user account page?

Quick and easy/dirty on the view page at least, in your node template for your content profile type, let's assume it is node-profile.tpl.php, you could add something like

<?php if (user_access('administer users') && $page): ?>
  <?php print l('User Account For This Profile', 'user/' . $node->uid);
<?php endif; ?>

wherever you wanted that link.  If you want it on the teasers of the node as well, eg, if the profiles are listed in a view or on the front page, etc, just take out the && $page otherwise this will only show up in the full node pages.  You can also pick any permission you want, I just grabbed the first one that made sense to me :)

ADDITION:  if you actually have a role called 'Admin' you can check for it like this:

 <?php
   global $user;
   if (in_array('Admin',array_values($user->roles)) && $page) {
      print l('User Account For This Profile', 'user/' . $node->uid);
   }
 ?>


Subscriptions does not send out "update" notifications

First you need to check your email sending capacity of your website.
Second check that you did the correct configurations for subscriptions module.
Finall you must run the cron (or set the timer for cron) for sending email updates for subscriptions

If you want to test at the final step, just run cron manually


I used this two classes in modules/custom/my_ckeditor/src/Plugin/CKEditorPlugin:

<?php

namespace Drupal\my_ckeditor\Plugin\CKEditorPlugin;

use Drupal\ckeditor\CKEditorPluginInterface;
use Drupal\Component\Plugin\PluginBase;
use Drupal\ckeditor\Annotation\CKEditorPlugin;
use Drupal\Core\Annotation\Translation;
use Drupal\editor\Entity\Editor;

/**
 * Defines the "templates" plugin.
 *
 * @CKEditorPlugin(
 *   id = "dialog",
 *   label = @Translation("CKEditor Dialog"),
 *   module = "ckeditor"
 * )
 */
class Dialog extends PluginBase implements CKEditorPluginInterface
{

  /**
   * Implements \Drupal\ckeditor\Plugin\CKEditorPluginInterface::getDependencies().
   */
  function getDependencies(Editor $editor)
  {
    return array();
  }

  /**
   * Implements \Drupal\ckeditor\Plugin\CKEditorPluginInterface::getLibraries().
   */
  function getLibraries(Editor $editor)
  {
    return array();
  }

  /**
   * Implements \Drupal\ckeditor\Plugin\CKEditorPluginInterface::isInternal().
   */
  function isInternal()
  {
    return false;
  }

  /**
   * Implements \Drupal\ckeditor\Plugin\CKEditorPluginInterface::getFile().
   */
  function getFile()
  {
    $plugin = drupal_get_path('module', 'my_ckeditor') . '/js/plugins/dialog/plugin.js';

    return $plugin;
  }

  /**
   * Implements \Drupal\ckeditor\Plugin\CKEditorPluginInterface::getConfig().
   */
  public function getConfig(Editor $editor)
  {
    return array();
  }
}

<?php

namespace Drupal\my_ckeditor\Plugin\CKEditorPlugin;

use Drupal\ckeditor\CKEditorPluginInterface;
use Drupal\ckeditor\CKEditorPluginButtonsInterface;
use Drupal\Component\Plugin\PluginBase;
use Drupal\ckeditor\Annotation\CKEditorPlugin;
use Drupal\Core\Annotation\Translation;
use Drupal\editor\Entity\Editor;

/**
 * Defines the "templates" plugin.
 *
 * @CKEditorPlugin(
 *   id = "templates",
 *   label = @Translation("CKEditor Templates"),
 *   module = "ckeditor"
 * )
 */
class Templates extends PluginBase implements CKEditorPluginInterface, CKEditorPluginButtonsInterface
{

  /**
   * Implements \Drupal\ckeditor\Plugin\CKEditorPluginInterface::getDependencies().
   */
  function getDependencies(Editor $editor)
  {
    return array('dialog');
  }

  /**
   * Implements \Drupal\ckeditor\Plugin\CKEditorPluginInterface::getLibraries().
   */
  function getLibraries(Editor $editor)
  {
    return array();
  }

  /**
   * Implements \Drupal\ckeditor\Plugin\CKEditorPluginInterface::isInternal().
   */
  function isInternal()
  {
    return false;
  }

  /**
   * Implements \Drupal\ckeditor\Plugin\CKEditorPluginInterface::getFile().
   */
  function getFile()
  {
    $plugin = drupal_get_path('module', 'my_ckeditor') . '/js/plugins/templates/plugin.js';

    return $plugin;
  }

  /**
   * Implements \Drupal\ckeditor\Plugin\CKEditorPluginInterface::getConfig().
   */
  public function getConfig(Editor $editor)
  {
    return array();
  }

  /**
   * Implements \Drupal\ckeditor\Plugin\CKEditorPluginInterface::getConfig().
   */
  public function getButtons()
  {
    return array(
      'Templates' => array(
        'label' => t('Templates'),
        'image' => drupal_get_path('module', 'my_ckeditor') . '/js/plugins/templates/icons/templates.png',
      ),
    );
  }
}

The CKEditor plugins (Dialog & Templates) are placed in modules/custom/my_ckeditor/js/plugins

You also need a custom JS-file for your templates:

(function ($, Drupal, CKEDITOR) {
  "use strict";

  Drupal.behaviors.myCkeditor = {
    attach: function (context, settings) {
      var templates_path = '/modules/custom/my_ckeditor/templates/ckeditor/';

      var templates = [
        {
          title:       Drupal.t('Title'),
          description: Drupal.t('Description'),
          image:       'preview.gif',
          html:        'My Template'
        }
      ];

      // Remove default templates
      CKEDITOR.on("instanceLoaded", function () {
        CKEDITOR.config.templates_files = [];
      });

      // Load tempaltes
      CKEDITOR.on("instanceReady", function () {
        if (CKEDITOR.plugins.get('templates')) {
          CKEDITOR.config.templates_replaceContent = false;
          CKEDITOR.addTemplates('default', {
            imagesPath: templates_path,
            templates:  templates
          });
        }
      });
    }
  };

})(jQuery, Drupal, CKEDITOR);

This talk can help you: https://www.youtube.com/watch?feature=player_detailpage&v=h9KV_VRvIG8#t=1965


Field values sometimes do not show up in grid view or node view for non admin users

Did you try to embed view in your template file?   $embed = views_embed_view('name_of_view','display_id'); . You need also to check permissions


Issues with Term Reference and Multilingual Taxonomy

Turns out we needed to unselect 'Select taxonomy terms by language' - found admin/config/regional/i18n/select - hope this helps someone. More reading at: https://drupal.org/node/1868418 #2


VBO custom action: get the list of selected items

You don't do it at once, you generate the document page by page (item by item).
The document gets created on first run, and on the last run you do whatever cleanup you need.

See archive.action.inc that ships with VBO for an example of this approach.

You can mark your action as "aggregate", and get all rows, but that's going to significantly limit the number of items you can add to the document (depending on your memory limit). VBO is designed to work item-by-item.


How to assign multiple author names for one article?

My workaround for this would be to enable a user reference field with multiple allowed values on the content type you want to put multiple authors on. Then just disable display of authoring info on that content type and instead display the user reference fields.

There are some things that you can't do with this but if you just want to display or categorize posts by multiple authors I think this will work fine.


Make a "Taxonomy Term" Appear in search field

If you have Views installed, use the Views to create a new searchable page. Views has the "Expose", which allow user to change them. All you have to do in View, is to add the "Taxonomy term: Name" on "Sort Criteria" and check the "Expose this sort to visitor, to allow them to change it". See below screenshot for details.


Using Google Store Locator module you can solve your query.

  This project uses Google's Store Locator Utility Library and Google
  Maps to create a 'Store Locator' page that your site visitors can use
  to find and get directions to one of your physical stores. It was born
  out of a need for a simple to install and easy to use locator feature
  for Drupal 7. This module is different from other 'locator' type
  modules (e.g. OpenLayers Locator) in that it doesn't require you to
  have any knowledge of it's dependant modules, and it allows developers
  to focus on implementing personal customizations quickly because the
  installation process is so light.


how to display the list of unread nodes and read nodes

Using the Flag module seems like a no brainer to me to get this to work: introduce a flag that is used to flag relevant nodes as "read". To actually do so, just use the Rules module (using a Rules event like "When viewing content", a kind of getting started with Rules).

With the above in place, you've reduced your question to creating an appropriate view (using Views) which shows the node(s) for which their flagging status corresponds to "read", or "NOT read", or "all of them". If you want, you can created 3 tabs in your view to show these all / read / not read nodes.

Ps: I'm assuming this is about D7.


Why am I urged to include my source files via files[] instead of using include_once?

From Writing .info files (Drupal 7.x):

  Drupal now supports a dynamic-loading code registry. To support it, all modules must now declare any code files containing class or interface declarations in the .info file (...). When a module is enabled, Drupal will rescan all declared files and index all the classes and interfaces that it finds. Classes will be loaded automatically by PHP when they are first accessed.

So it only makes sense to add a file to the files[] array, if that file contains declarations of classes or interfaces and is not included manually (e.g. by calling module_load_include()).


How can I use drupal_static() to save an element in an associative array?

You can use drupal_static to store an array of object.

You can then define a method, lets call it 'getmyobj', to get your data like this :

function getmyobj($obj_name) {
  $objects = &drupal_static(__FUNCTION__);

  if (! isset ($objects[$obj_name])) {
    // Here you load your obejct
    $objects[$obj_name] = method_to_load_your_object($obj_name);
  }
  return $objects[$obj_name];
}

Then you will be able to get you object with the above code :

$obj_a = getmyobj('object_a');


Drush or Drupal console command to list modules with security updates?

drush pm:security should be fine in listing Drupal modules with security updates.

There was a bug from the drupal-composer/drupal-security-advisories project that resulted in not listing the forms_steps module and some other modules.  It was promptly fixed and now it works!


How to use latest jquery version on specific page or code?

There are several ways to do it. If you want to update  jquery, you can use jquery update moudle.

Second thing is you can use, drupal_add_js() function to include the jquery file to particular node.

Third thing is you can use the js, that is used in all the page in template.php or in theme.info file. I hope you are looking for second method. Also, this question will help you much.

Updating jquery


What is the purpose of url('', array('prefix' => &$prefix)) in drupal_add_js()?

Modules can implement hook_url_outbound_alter() to change to change generated URL's. The most typical example of that are language prefixes.

If you have two languages enabled with path prefixes, english at /en and german at /de, then pathPrefix will either be /de or /en. Since there is no actual API to get that prefix, it uses that trick.

The hook invokes locale_url_outbound_alter(), which in turn invokes the defined url_rewrite callbacks of the enabled language negotation types. In case of the path prefix, that is locale_language_url_rewrite_url which changes the prefix at the end of the function.

The reason for doing this is that it allows ajax calls and other javascript requests (for example the admin overlay) to do that request in the current language, so that strings returned by those requests are in the expected language.


Find user profile page link from database

The path "/users/admin" is actually an "alias" for something like "user/1", where 1 is the user id. In Drupal 7, these aliases are stored in the {url_alias} table along with the real path that they point to.

So if you want to figure out what user the alias "users/admin" points to, look in the {url_alias} table and you will see a column called "source", which should have something like "user/1". "1" in this example is the user id.


Is it possible to define default config entities in a single yml file?

According to Configuration Storage in Drupal 8:

  Configuration Entities must each be put into their own YAML files, and they should be generated by having the module write out its configuration (don't try writing them by hand).

So it sounds like what you're experiencing is indeed the expected behaviour, and for the time being at least, you'll need to separate each default entity into its own YAML file.


Go in admin/user/permissions and check if the "access content" [and "search content"] is checked for the    anonymous user


What is the fastest way to get node title from nid?

You said fastest.

If you can compromise two things, this should be the fastest one. Now, note that you have to compromise:

If you are only trying to get the node title, and if you are sure that there are no other hook_node_load implementations (basically module handlers that would alter the node load at the time they are loaded), you can skip using the node_load() or node_load_multiple() functions and go for this solution.
When loading a node from the database, it's advised that you use a query tag to make sure that the user has access to those nodes. If you don't use any node access modules, you can go down for this solution.

With both above points in mind you can uses something like this:

function MYMODULE_node_get_title_fast(array $nids) {
  $titles = &drupal_static(__FUNCTION__, array());
  $return = array();
  $unavailable = array();
  foreach ($nids as $nid) {
    // Lookup static cache of self.
    if (array_key_exists($nid, $titles)) {
      $return[$nid] = $titles[$nid];
    }
    else { // Set NULL, so unavailable nodes will have NULL as their return value.
      $unavailable[$nid] = NULL;
    }
  }

  if ($unavailable) {
    $results = db_query("SELECT nid, title FROM {node} WHERE nid IN (:nids)", array(':nids' => array_keys($unavailable)))->fetchAllKeyed(0, 1);
    if ($results) {
      $return = $results + $unavailable;
      $titles = $return + $titles;
    }
  }

  return $return;
}

You can pass an array of node IDs, and the above function will return their titles without the overhead of node_load, field_attach, or entity_load overheads. It also skips node access checks, so do not use this in sites that you want any sort of access restrictions.

Usage example:

 $titles = MYMODULE_node_get_title_fast(array(256, 258, 54898));

You would return an array, with all given array values as keys, and the title as their value. NULL if the node is unavailable.


What is the most performant method to run many UPDATE statements?

UPDATE statements alter data and are therefore by definition not fast. They might be relatively fast if you a small data set but the bigger you table gets, the slower an UPDATE will become, especially if it involves updating indexes and stuff.

So I doubt it would matter much if you execute them separately or in a single call. Instead, I would look into ways to "optimize" them in a more general way:

Maybe you can rewrite it so that you need to execute less queries, e.g. use a subquery to get the value. Make sure to actually profile it to be sure that it is faster. A complex query could also be slower than a number of simple ones.
Use db_transaction() to execute all queries in a single transaction. Not only will this enforce consistency (all or nothing, if you have an error in the 500. query the others changes will be reverted as well) it will also be considerably faster on many systems because (in the default configuration) MYSQL enforces a write to the file system after each transaction (and if you don't use transactions explicitly, every UPDATE/INSERT/DELETE query is considered a separate transaction).
Maybe your table structure can be optimized so that you need less queries.
If there is no way around executing hundreds of UPDATE queries, I would go for reliable instead of performant/fast. Have a look at how node access table rebuilds are done for example ( which can result in hundreds of thousands of INSERTS if you have many nodes). When one is necessary (e.g. a node access module is installed), it usually just sets a flag to inform the admin and then the actual rebuild is executed in the backend with a batch.

If you provide more details on what you are actually trying to do, I might be able to give you some actual advice as well.

EDIT:

Some more hints now that you posted what you are doing exactly.

If you don't need to keep old data, you could try if you can first calculate the metrics for a number of nodes, then delete them and then do a multi-insert. Maybe that's faster, maybe not.
Generally, I would implement what you're doing in a hook_cron(). You could process N nodes per cron run, store the highest node id and on the next run, process the next N. If a query returns less than the requested N, you reached the end of your data set and are done for the day, set a flag to today and can start by zero at the next day. If you need to process all nodes at the same time, I'd create a simple drush script that you can start through system cron, but still group the processing into groups of nodes, to avoid memory issues.
You could look into using a different backend for storing your metrics if you're on your own server and can install something. For example, there is http://oss.oetiker.ch/rrdtool/, which is specifically built for storing "time series data" (quote from the website). I have never used it though. And if you're in for big, then there are systems like Hadoop which is among others used by Facebook to process their enormous amount of daily metrics.


If you want to update your field when user was deleted you should put your update query into your sms_user_delete. Because userfieldmobil_user_update will only works if u update user data, not delete it.

function sms_user_delete($uid, $number = FALSE) {
  userfieldmobil_user_update($account->uid); // my custom field about users i call this manually.
  $query = db_delete('sms_user')
    ->condition('uid', $uid);
  if ($number) {
    $query->condition('number', $number);
  }
  $num_deleted = $query->execute();

  $num_updated = db_update('field_data_field_mobilnumber')
     ->fields(array(
     'field_mobilnumber_value' => '',
     ))
     ->condition('entity_id', $uid, '>=')
     ->execute();
  }

Its not like in drupal 6 where u can use hook_user, read about hook_user_update and hook_user_delete for more info.


Custom made blocks not getting displayed in Blocks page

Did you try to (steps in order):

use a minimal hook_block_info() definition for your block (such as
the one below or even without 'cache' option!) the very first time?
manually remove your block's entries in block table, if any?
then clean all caches?

Longer version of why these steps may help:

Using a minimal block definition such:

function sso_block_info() {
  $blocks['applinks'] = array(
    'info'   => t('Single Sign On'),
    'cache'  => DRUPAL_NO_CACHE, // this can also be left out!
  );
  return $blocks;
}

Would not list my block in the "Disabled" pseudo-region of admin/structure/block!

Troubleshooting revealed that block had been inserted in block table, but its value for the region column was blank and not the usual '-1' that every other currently disabled block contained!

Tip: updating this value to -1 directly within DB made block 'Single Sign On' show up in block admin's Disabled zone instantly!

Then I manually removed my block's entries from DB and cleaned caches to effect Drupal calling again hook_block_info. This time my block showed up correctly in block admin UI the first time!

My hunch is that existing config entries in DB for blocks will sometimes interfere with what is indeed correct block registration code! Cache clearing will not affect entries in block table! I guess that certain perhaps invalid combinations of options in hook_block_info() will cause D7 to register a block with a blank value for the region (a block appears in) instead of -1 (a disabled block).


How to create a preconfigured block/view.

Yes I could work with a specific content type and views.
an alternative way is to create a module with a specific form to change the content block, and to add the content to the block API.

1 _ add your admin path

function my_module_menu() {
 $items['content_block'] = array(
  'menu_name' => 'main-menu',
  'type' => NORMAL_MENU_ITEM,
  'title' => 'My content block',
  'page callback' => 'drupal_get_form',
  'page arguments' => array('my_module_form'),
  'access arguments' => array('admin_content_block'),
 );
 return $items;
}

2 _ Set your permission

function my_module_permission() {
 return array(
  'admin_content_block' => array(
      'title' => t('Can change content block'),
  ),

}

3 _ A form dedicated to your admin, allowing to change the content :

function my_module_form($form, &$form_state){

$form['block_content'] = array(
   '#type' => 'textarea',
   '#title' => t('Block Content'),
    '#default_value' => variable_get('my_module_block_content', ''),
);
$form['submit'] = array(
      '#type' => 'submit',
      '#value' => t('Submit'),
);

return $form;
}

function my_module_form_submit($form, &$form_state) {
   variable_set('my_module_block_content', $form_state['values']['block_content']);
}

4 _ your block view

function my_module_block_info() {
$blocks['block_content'] = array(
  'info' => t('Block Content'),
);
return $blocks;
}

function my_module_block_view($delta = '') {
if ($delta == 'block_content') {
    $block['subject'] = t('Your block title');
    $block['content'] = variable_get('my_module_block_content', '');

    }
return $block;
 }


Can we use one product for multiple display nodes in Commerce D8?

Drupal 8 Commerce does not need product display nodes anymore. When we create a product, we get a page automatically for this product.

But if you need, like me, to keep a "node environment"  on your website then you will have to create as much products as nodes and link them through an entity reference field (Type : Reference > Other...)

To create products, variations and links between nodes and products, I use Feeds, Commerce Feeds and Feeds Tamper. In my case, each feed type is based on upload file technique with CSV file created from Excel.

First, you build a Variations Feed type to create product variations with simple data (sku (unique), price, your_attribute). In my case, customer type was the attribute.

Second, you build a Products Feed type to create products using variations imported before (title (unique), variations (skus), store (required, ID=1 if you have only one). Here goes Feeds Tamper with List explode to get multiple variations for one product.

Third, you build a Nodes feed type to link nodes and products with two data (node title (unique), product title (in entity reference field)).

Finally, you get display nodes with specific products and variations and when you add to cart, products are well separated.

Hope this helps.


How to link Images of one node to other node?

Whichever way you look at it I would say that these images should be a field on the entity that they are linking to ( you are going to have a validation nightmare having a multiple image field and an entity reference field that can't be forced to have x number of values easily ). The easiest way to then render these would be to use the views module, create a block displaying fields and selecting he image field and clicking the box to link the image to the original piece of content. You can also have a filter to select only entities where this field is filled.

In reality though a better approach would be to create a menu ( this is what you are doing after all ) and put in the images using css.
example:

#block-system-main-menu li a {
  display:block;
  width:100px;
  height:100px;
  background-repeat:no-repeat;
}
#block-system-main-menu li:nth-child(1) a {
  background-image:url('../images/icon_1.png');
}
#block-system-main-menu li:nth-child(2) a {
  background-image:url('../images/icon_2.png');
}


How do I rename a field name of a table?

Using db_change_field.

Under the parameter section:

  $field Name of the field to change.

  $field_new New name for the field (set to the same as $field if you
  don't want to change the name).


What is the correct thing to do when reusing code from an old, abandoned project?

Request to become the new maintainer, and push your changes as the continuation of the old project.

That is the correct thing to do.


Move label to RIGHT of checkbox in Webforms

Drupal is spitting out the markup as [title][field] and what you want is [field][title] so to accomplish this you need to override Drupal's default theme implementation of your field. To do this copy example.com/modules/field/theme/field.tpl.php to your theme template folder(if one does not already exist in there ...sites/all/themes/my_theme/templates) and modify the template file to your desired markup.
When naming your template file you can restrict it to the webform fields, Drupal will use the most specific template it finds in the following order:

field--field-name--content-type.tpl.php
field--content-type.tpl.php
field--field-name.tpl.php
field--field-type.tpl.php
field.tpl.php (in your theme)
field.tpl.php (in drupal's field module)

Take a look at this link, Drupal documentation on field.tpl.php

Hope this helps.


How to override Entity Autocomplete required validation error message?

In HOOK_form_FORM_ID_alter() add #element_validate attribute to the form element

$form['field_your_field_name']['#element_validate']

Reference: https://api.drupal.org/api/drupal/developer!topics!forms_api_reference.html/7.x#element_validate


Using php command to pass custom php.ini values into drush phar

You did it exactly right -- just add the additional Drush command, options and arguments after the part you already typed in.  For example:

php -d memory_limit=256M /usr/local/bin/drush --php-options=memory_limit=256M --root=/path --uri=example.com status

That's kind of a lot of typing, so you might want to make an alias:

alias drush='php -d memory_limit=256M /usr/local/bin/drush --php-options=memory_limit=256M'

Then:

drush --root=/path --uri=example.com status


Show all nodes with the same term, the current user is assigned to

There are a lot of answers you can search for "sibling taxonomy" or some other wording.

Here's one answer you can follow: Filter taxonomy term attached to user field

The only difference is you always want your views to show the current user's matches, and not create, for example, profile pages for everyone separately as it is in that answer.

To make your Views show only the current user's matches in the User ID Contextual filter you have to choose User ID from logged in user instead of User ID from route context.


How do you use hook_form_FORM_ID_alter() to alter the USER EDIT form?

Try:

function MYMODULE_form_user_form_alter(&$form, $form_state, $form_id) {
  // Your code...
}

Inspecting element, I see the form id is user-form, which needs to be translated to the machine-readable name user_form

Otherwise, you can always do a standard HOOK_form_alter():

function MYMODULE_form_alter(&$form, $form_state, $form_id) {
  if ($form_id == 'user_form') {
    // Your code...
  }
}

And always clear cache after adding/changing hook names.


Why are there two default image options in an image field

One is the default image information for that field as a global entity, while the other is specific to that instance of the field. Fields can be re-used across different content types, so the global default would apply to every content type that used that field, unless those content types override that behaviour with their own specific default.


How to make sure that drupalSettings value gets updated on the JavaScript end?

In this case instead of returning HTML (aka the form render array) your AJAX callback method needs to return an AjaxResponse object (see API docs). The AjaxResponse object should contain at least 2 commands, one for updating your HTML (the processed form) and other to update the drupalSettings object. A possible response could be like

public static function ajaxCallback(array $form, FormStateInterface $form_state) {
  // Assuming the $form variable is either the updated render array or rendered output.
  $response = new AjaxResponse();
  $response->addCommand(new ReplaceCommand('#wrapper-id', $form));
  // The $data variable is an assoc array with he same keys you passed during the build under #attached key.
  // If you don't want to merge the settings but instead replace it, remove the second argument.
  $response->addCommand(new SettingsCommand ($data, TRUE));
  return $response;
}


How to desactivate jquery_update logic for the homepage

The reason why your theme_preprocess_page function isn't working, is because the jQuery update module uses a clever implementation of hook_theme_registry_alter to ensure it's implementation of hook_preprocess_page is called last.

What I recommend you do is create a new module and implement your own hook_theme_registry_alter and hook_preprocess_page functions. See a simple example below which has taken some code snippets from the jquery update module:

function mymodule_theme_registry_alter(&$theme_registry) {

  if (isset($theme_registry['page'])) {
    if (count($theme_registry['page']['preprocess functions']) > 0) {
      if ($key = array_search('mymodule_preprocess_page', $theme_registry['page']['preprocess functions'])) {
        unset($theme_registry['page']['preprocess functions'][$key]);
      }
    }

    // Now tack it on at the end so it runs after everything else.
    $theme_registry['page']['preprocess functions'][] = 'mymodule_preprocess_page';
  }
}

This hook implementation tells Drupal to invoke our custom hook_preprocess_page function after all other modules have run their hooks.

Then we need to define our own custom implementation of hook_preprocess_page which will alter the scripts included on the front page:

function mymodule_preprocess_page(&$vars) {

  // Only do this for pages that have JavaScript on them.
  if (!empty($vars['scripts'])) {

    $template_files = $vars['template_files'];
    $scripts = drupal_add_js();

    if (in_array('page-front', $template_files === TRUE)) {
      // Here I unset all the javascripts that I don't want to be loaded in the homepage
      unset($scripts['theme']['themes/"theme_name"/js/jquery.jcarousel.min.js']);
      // Once cleaned up all unncessary javascripts, I load them into $var['scripts']
      $vars['scripts'] = drupal_get_js('header', $scripts);
    }
  }
}

Using this approach in your own custom module will make sure that any alterations you want to make to your javascript includes will happen very last.

Good luck! :)


Search Taxonomy Term pages containing entity referenced nodes

I stumbled upon a module called Search by Page Paths which swerves the above issue by indexing the front end of the site. This approach means that regardless of the source of my data and where it is placed, it will see anything rendered out onto a page as part of that page.

The main caveat is that one must specify paths to index, but in terms of my particular build this isn't a bad thing and means I have complete control over where a user ends up after searching.


Load current node from block and from display suite field

You can load the node id from node page using arg function...

  Returns a component of the current Drupal path.

  When viewing a page at the path "admin/structure/types", for example,
  arg(0) returns "admin", arg(1) returns "structure", and arg(2) returns
  "types".

node pages always has path 'node/nid' so arg(1) gives node id...

$nid = arg(1);
$node = node_load($nid);


Change region/block content based on current node

Try the context module.

  Context allows you to manage contextual conditions and reactions for
  different portions of your site. You can think of each context as
  representing a "section" of your site. For each context, you can
  choose the conditions that trigger this context to be active and
  choose different aspects of Drupal that should react to this active
  context.

  Think of conditions as a set of rules that are checked during page
  load to see what context is active. Any reactions that are associated
  with active contexts are then fired.

Refer the module page for documentation links.


How can I restore the security of an old site with a sql injection vulnerability which was probably exploited?

Theoretically, that SQL query could be used to do anything on that database server, including changing the password for a Drupal  account not used so often, or creating a new account in the users table.

Suppose that $_POST['title'] contains the following.

"ddddd', 'comment', 127.0.0.0.1, 1469987843, 0, 3, '01/', 'Tintin', NULL NULL); DELETE FROM {users} u WHERE u.uid > 0; -- "

This would change ""INSERT  INTO {comments}  VALUES($cid2, 0, $nid, $uid, '$title', '$comment', '127.0.0.1', $timestamp, 0, 3,'01/', '$name', NULL, NULL)" into the following.

"INSERT INTO {comments} VALUES($cid2, 0, $nid, $uid, 'ddddd', 'comment', 127.0.0.0.1, 1469987843, 0, 3, '01/', 'Tintin', NULL NULL); DELETE FROM {users} u WHERE u.uid > 0; -- ', '$comment', '127.0.0.1', $timestamp, 0, 3,'01/', '$name', NULL, NULL)"`

I added a query to delete the users table, but I could have added any query, including the one to alter the password of an existing account, or creating a new user.

How that type of attack is effective depends only from how much the attackers know about your site: which software you are running, which version, etc. Once they have access as administrator, they could do enable the PHP input format, and execute arbitrary code. I would say that spam is the last of your problems.

As side note, as Clive said, template files should never contain SQL queries; eventually, those could be in preprocess functions, but in most of the cases, they should be in a module.
Also, in Drupal SQL query, you should wrap the database table names in {}. This allows Drupal to use prefixes in the table names, and even use tables from different databases.