How do I remove the default node path when using a path alias?

Simple answer: You don't have to. We pretty often are asked about disabling the generic URLs to avoid penalties from search engines.

This however is not necessary. Once using URL aliases, the meta tags for both versions of the node rightfully declare the node/[nid] paths as short URL, and the URL alias as canonical URL. So search engines will index the page using the URL aliases.

Penalties would arise only, if you provide the same content at various places and trying to disguise their connection.

If you still are afraid, you can e.g. make use of the rabbit_hole module.


Is it possible to create a calculation field using database abstraction layer?

Yep Haversine should work without a problem. This is slightly modified from a production site which is up and working right now, for example:

$lat = 51.5014;
$lng = 0.1419;

$query = db_select('field_geo_latitude', 'f')
  ->fields('f', array('entity_id'))
  ->orderBy('distance');

$earth_radius = 3959;
$expr = "(
  $earth_radius * acos(
    cos(radians(:lat))
  * cos(radians(field_geo_latitude))
  * cos(radians(field_geo_longitude) - radians(:lng))
  + sin(radians(:lat))
  * sin(radians(field_geo_latitude))
  )
)";
$query->addExpression($expr, 'distance', array(':lat' => $lat, ':lng' => $long));

$query->having('distance <= :radius', array(':radius' => 10));

Resulting query:

SELECT f.entity_id AS entity_id, (
  3959 * acos(
    cos(radians(:lat))
  * cos(radians(field_geo_latitude))
  * cos(radians(field_geo_longitude) - radians(:lng))
  + sin(radians(:lat))
  * sin(radians(field_geo_latitude))
  )
) AS distance
FROM {field_geo_latitude} f
HAVING  (distance <= :radius)
ORDER BY distance ASC

When executed all the parameters are replaced as expected.


What function does Drupal provide to save an array in a file?

Apart from PHP functions for reading/saving data in files, Drupal 7 has file interface functions too; one of those is file_unmanaged_save_data() which saves data in a file. The difference between those Drupal functions, and the equivalent PHP functions is that the Drupal functions can handle the case the module is trying to save the content in a file that already exists. See FILE_EXISTS_ERROR, FILE_EXISTS_RENAME, and FILE_EXISTS_REPLACE.

There are file interface functions that save a reference to the file created in a table. This can be useful in the cases the files needs to be automatically deleted because they are temporary, or programmatically deleted. See for example file_copy(), and file_move().

About using a database to save serialized data, that is what Drupal already does with the table containing the value of Drupal variables defined from modules. Its database table is defined as follow. (I show the definition used from Drupal 7, but Drupal 6 uses a similar definition.)

  $schema['variable'] = array(
    'description' => 'Named variable/value pairs created by Drupal core or any other module or theme. All variables are cached in memory at the start of every Drupal request so developers should not be careless about what is stored here.',
    'fields' => array(
      'name' => array(
        'description' => 'The name of the variable.',
        'type' => 'varchar',
        'length' => 128,
        'not null' => TRUE,
        'default' => '',
      ),
      'value' => array(
        'description' => 'The value of the variable.',
        'type' => 'blob',
        'not null' => TRUE,
        'size' => 'big',
        'translatable' => TRUE,
      ),
    ),
    'primary key' => array('name'),
  );

During bootstrap, Drupal loads all the variables from the database, and saves their values in a global variable. This is the code used by Drupal for this purpose. (The function is variable_initialize(); the Drupal 6 function is variable_init(), called in the same circumstances.)

  // NOTE: caching the variables improves performance by 20% when serving
  // cached pages.
  if ($cached = cache_get('variables', 'cache_bootstrap')) {
    $variables = $cached->data;
  }
  else {
    // Cache miss. Avoid a stampede.
    $name = 'variable_init';
    if (!lock_acquire($name, 1)) {
      // Another request is building the variable cache.
      // Wait, then re-run this function.
      lock_wait($name);
      return variable_initialize($conf);
    }
    else {
      // Proceed with variable rebuild.
      $variables = array_map('unserialize', db_query('SELECT name, value FROM {variable}')->fetchAllKeyed());
      cache_set('variables', $variables, 'cache_bootstrap');
      lock_release($name);
    }
  }

  foreach ($conf as $name => $value) {
    $variables[$name] = $value;
  }

  return $variables;

Drupal doesn't have performance issues, even if that function is called for every rendered page. As you can see, it caches the value of the variables in a cache. If your data is requested frequently enough, you could consider using a cache table too.

As for using persistent variables to store data, keep in mind they are loaded in memory every time Drupal bootstrap; if you are going to store data that could not be used for the currently loaded page, then persistent variables are not what you should use for storing your data. Also, since variable_set() clears the cache used for the persistent variables, it is generally preferable to reduce the number of calls to variable_set() done for a single page.


How to create a raw link in view(with contexual filter) custom text

I'd rather add a 'Custom text' field to the view, give it some text ("Click here"), and under "Rewrite Results" check "Output this field as a custom link", link path is {{ field_abc }} and then check "External server URL"


I agree with '2-Stroker'. Do this:

function HOOK_block_view_alter(&$data, $block) {
  if ($block->module == 'menu_block' && $block->delta == 'DELTA_OF_THE_BLOCK') {
    $data = array('subject' => 'TITLE OF BLOCK', 'content' => '&nbsp;');
  }
}


Exclude a .js file on certain Drupal 6 paths

I think that this module spits out the reference to the JS file inline in the content.  If this is true, then I would use some logic inside template_preprocess_page to determine whether you are on an HTTPS path, and then search/replace $vars["content"] and remove the string.  You may also be able to use template_preprocess_comment_wrapper to do the same thing.

This solution is pretty hackish, but I think it may be your only solution short of patching the module.


How do I know Honeypot is working on my custom module form?

You can enable an option Log blocked form submissions on page admin/config/content/honeypot, set Honeypot time limit to, let's say, 30 seconds and try to submit your form faster than 30 seconds. Then check your log (admin/reports/dblog). You will see Honeypot log message if it worked.

And you probably should include some option in array:

  honeypot_add_form_protection($form, $form_state, array('honeypot', 'time_restriction'));

  Note that you can enable or disable either the honeypot field, or the time restriction on the form by including or not including the
  option in the array.
  (https://www.drupal.org/node/1232638)


Modifying destination directory for imagefield file migrating D6->D7

To avoid future situations like this, here is what I came up with:

  public function prepare($entity, stdClass $row) {
    // Change the destination directory for the field_mainphoto and
    // field_thumbmailphoto files to be /images.
    foreach (array('main_photos', 'thumbnail_photos', 'video_thumbnails') as $dir) {
      if (substr($entity->destination_file, 1, strlen($dir)) == $dir) {
        $entity->destination_file = str_replace($dir,'images', $entity->destination_file);
      }
    }
  }


Drupal: node_load() in php file - load via ajax

Rather than using a custom php file you should attempt to solve the issue "the drupal way" via a custom module or in your template.php... Please see my answer in this question.

It explains how you can add to the original url to change the template (or create a blank template so it is only node data presetned).


There is an issue when views, javascript and caching are used in combination.
Some information that may be of help:

https://drupal.org/node/1873970
https://drupal.org/node/1811828
https://drupal.org/node/1984774

As far a I can understand the cached page or block cause the js to fail. In another answer it is stated:

  This may be a timing issue, flexslider may require the images to be
  loaded when it is called so it can work off their attributes, remember
  that $(document).ready() fires after the DOM has finished loading
  whilst $(window).load() fires after all images on the page have loaded
  - giving you intermittent results if they are cached etc, replace:

  $(document).ready(function(){ ... }); with

  $(window).load(function(){ ... });

I have not found a sure fire answer /solution to the issue and may broaden out the question to see if there is an advised fix for views+cache+js=problem.


Conflicting realm variables when using i18_variable

Found the fix thanks to some help from @piyuesh

  $items['embed-form-configuration'] = array(
    'page callback' => array('get_embed_form_configuration'),
    'access arguments' => array('Embed Form Configuration Permission'),
    'access callback' => TRUE
  );

It was silly in hindsight, as my page callback was a drupal get form, and in the callback function I was returning a drupal get form as well. THat is why multiple realms.


Which is the highest version of Solr that is compatible with the "Apache Solr Search" module?

Given there is an issue in the project issue queue (Solr 7 integration) about allowing to use the module with Solr 7, the module is at the moment only compatible with Solr 5 and eventually Solr 6.

Notice that the README.txt file has not been updated since 6 years ago and that the solr-conf directory contains configuration files for Solr 1.4, 3.x, 4.x, and 5.x. This means the module has been tested with Solr 5.x, at least the 5.x version that was available 4 years ago.


A table was not created by _schema() function

The hook_schema is only run for table creation during module install.

To run it later, you'd need to install the schema from .install file with something like

/**
 * Implements hook_update_N
 */
function cleanetica_advanced_update_7001(){
  drupal_install_schema('cleanetica_advanced');
}

Add, and then run update.php


Disabling authoring information in Omega 3.x does not work from content type; how can I disable it?

Don't know how exactly it looks in your Omega theme, but in Zen you just remove/change the following snippet in templates/node.tpl.php (or templates/node--content_type.tpl.php):

<?php if ($display_submitted): ?>

    <?php print $submitted; ?>

<?php endif; ?>

In Bartik it's equivalent would be:

<?php if ($display_submitted): ?>

    <?php print $user_picture; ?>
    <?php print $submitted; ?>

<?php endif; ?>


How to embed a custom content type in a Drupal 7 theme?

That's correct (answer below) -- you can't embed content types in your theme, however, you can create custom modules that users can install to have a content type you've created available.

If you are new to Drupal, and do not write your own modules yet, you can use the Features module to create custom content types on your site, export them to a feature via the Features module, and import them to any number of sites.

Using the features module can be a little confusing at first, but there's lots of additional documentation and tutorials online.  I'd start with the module's documentation page first: http://drupal.org/node/580026.  :-)


This works perfectly fine:

$query = new EntityFieldQuery();
$result = $query->entityCondition('entity_type','node')
  ->entityCondition('bundle', 'product_display')
  ->propertyCondition('status', 1)
  ->fieldCondition('field_expires','value', '2013-04-30T14:02Z', '>')
  ->execute();


Check out this Page. You can set this using locale module and i18n translation module.


How to use modified (calculated) value of a field in Drupal entity query condition?

To do so you can use LIKE operator in your query like the following:
$host = parse_url($url_entered)['host'];
$result = \Drupal::entityQuery('node')
  ->condition('type', 'ABC')
  ->condition('field_link', "%" . $host . "%", 'LIKE')->execute();

UPDATE
if you want to check that the exact host exist, you should select all values of your field and then compare with the entered host.
$host = parse_url($url_entered)['host'];
// Select all uris of field link.
$database = \Drupal::database();
$query = $database->select('node__field_link', 'nfl')
  ->condition('nfl.bundle', 'page')
  ->fields('nfl', ['field_link_uri']);
$result = $query->execute()->fetchAll(PDO::FETCH_COLUMN, 0);
$hosts = [];
// extract all hosts.
foreach ($result as $item){
  $hosts[] = parse_url($item)['host'];
}
// Check if the host already exist.
if (in_array($host, $hosts)){
  // Do what you want ici !
}


If you're ok with writing a small custom module you could do it very easily using hook_menu_alter():

function MYMODULE_menu_alter(&$items) {
  $items['node']['access callback'] = FALSE;
}

The above will deny access to the page, if you want to remove it completely use this instead:

function MYMODULE_menu_alter(&$items) {
  unset($items['node']);
}

There's a discussion on the subject here with a few other ideas but I think this would be the simplest.


How do I interact with Mautic from a custom module?

I think you're on the right track. Module https://www.drupal.org/project/mautic_api provides a wrapper around Mautic API - see https://git.drupalcode.org/project/mautic_api/-/blob/8.x-1.x/src/MauticApiService.php#L127
You can use it in you module code via \Drupal::service('mautic_api'). The hook you've mentioned looks correct to me.


How do you add information text to a Drupal 7 form?

To add plain text to forms, you use #markup- see the Form API.

$form['rate_the_room']['hello'] = array(
  '#markup' => '
Hello
',
);


Which Drupal versions are affected by the vulnerabilities in advisory PSA-2016-001?

The security team is intentionally a bit circumspect with these warnings. They either have to catch us all flat-footed or give potential attackers a heads up that something worth their time is coming. Currently they are siding with the latter method (and as much as I hated seeing that message today I agree with them).

For the most part it will not be clear until they release the news what modules will be covered. There is already speculation in some circles, but there isn't likely anything to be done before the announcement. Clearly from their announcement multiple modules are effected, and likely at least one is something very common.

Depending on the number of sites you support you should block off enough time to do updates for all of them.

These advisories will no longer cover Drupal 6. There is no formal way to know if Drupal 6 is effected (there will probably twitter comments, blog posts, etc about it after the release of the updates). If D6 is effected the only solution may be to take them offline.


I almost got it....the field i'm looking for is called Content:Path.  Right now, it prints /my-first-news-item.  All I need to do now is have it print the domain name as well.....almost there.

EDIT
Figured out the last part.  To print out the absolute path, make sure the field also has the setting Use absolute link (begins with "http://") checked


Create map that show user Location and last user's post

Once I had to do the very same thing and followed this good video by Drupal Therapy. It uses GMap (API 2) + Location modules instead of Open Layers, but if you're on D6 this is still a good solution. If you enable user-locations and node-locations functionalities in the modules page, you'll find predefined Gmap user/nodes location views. If you need to associate geographic information only on certain content types (and not to all nodes), you'd better enable location-CCK and just add and configure a location field to your desired content type, then create your Gmap view.

Hope it helps you to start with maps in Drupal.


is there any module which gives domain list as content type field

That feature has been developed for the pending Drupal 8 release https://drupal.org/node/1917780 but is yet to be available for D7 (afaik)


Use a custom code and define your own debug function that uses dsm if available or debug if not:

function my_debug($data, $label = NULL, $print_r = FALSE) {
  if (function_exists('dsm')) {
    dsm($data, $label);
  }
  else {
    debug($data, $label, $print_r);
  }
}

But keep in mind that you should avoid any debug code in production.


Exposed filter selectbox dropdown for a textfield

You can use Grouped filters of exposed filters to set unique results for select box in a views. Please see the screenshot given below:


Yes, a product can have two different titles.

You can add fields to products on the product type admin screen (/admin/commerce/config/product-types) by choosing the appropriate product type and selecting manage fields.  I would add a text (plain) field and call it short name or something like that.

Then, you can configure the display settings for the product type to hide the short name field (disable it), ensuring only the full title is shown on the product page.

Then, in your grid product catalog, configure your view (or whatever you use to make the catalog) to show only the short name, not the title field.


If I use node_save() to create a new node, do I need to manually escape user input?

If by escaping you mean using check_plain() or similar functions, then no; escaping is done when outputting something, not when saving it in the database, or in Drupal persistent variables.

Imagine what would happen if you call check_plain() on a node containing "&"; that character would be escaped to "&amp;" that it would be converted in &amp;amp; when Drupal would show the node content. The result is that "&" would be shown as "&amp;" and that is not what it would be expected.

In Writing secure code, you can read the following text:

  Use check functions on output to prevent cross site scripting attacks

  No piece of user-submitted content should ever be placed as-is into HTML.

  Use check_plain() or theme('placeholder') for plain text.
  Use check_markup() or filter_xss() for markup containing text.
  Use the t() function with "@" or "%" placeholders to construct safe, translatable strings.

  See how to handle text in a secure fashion for more details.

As you see, the page about writing secure code doesn't say to escape the text being saved, but only text being output, when the text has been entered from users, in a way or in another. An example of text entered from a user is the username or the signature associated to user accounts, the node title, or the node body.

About SQL injection, you just need to use placeholders in you queries; Drupal database functions escapes the content of the placeholders, which would not be possible if you write a query like the following one, for example:

$query = db_query("SELECT * FROM {node} WHERE title = '$title'");

The "Writing secure code" reports:

  Use the database layer correctly. For example, never concatenate data directly into SQL queries, like this:

<?php
 db_query('SELECT foo FROM {table} t WHERE t.name = '. $_GET['user']);
?>

  Instead, use proper argument substitution with db_query:

<?php
 db_query("SELECT foo FROM {table} t WHERE t.name = '%s' ", $_GET['user']);
?>

  If you have to accommodate a variable number of arguments in your SQL, create an array of placeholders. Don't do this:

<?php
 db_query("SELECT t.s FROM {table} t WHERE t.field IN (%s)", $from_user);
?>

  Instead, do this:

<?php
 $placeholders = implode(',', array_fill(0, count($from_user), "%d"));
 db_query("SELECT t.s FROM {table} t WHERE t.field IN ($placeholders)", $from_user);
?>


$data->field_field_telephone[0]['raw']['value'];

This will give you your value from that field in Views PHP. If you use dpm() from Devel module it will show you that $row->field_telephone is 11. that's the NID.

Try to avoid using Views PHP unless you are doing something too complex for views. And even then you should try to write a custom module to interact with views instead of saving code in the DB.


Entity translation

  Allows (fieldable) entities to be translated into different languages, by introducing entity/field translation for the new translatable fields capability in Drupal 7. Maintained by the Drupal core i18n team.

together with Title module - (making the taxonmy terms translatable)

Title module

  After enabling the module as usual, visit the Manage fields page of the content type, taxonomy vocabulary or "comment type" which you wish to replace fields of and click the replace link. That's all.


How to show Checkboxes with Fulltext Search Filter Exposed?

Currently BEF doesn't support tweaking the display of the filter operator, only the filter itself. But this would be a great addition -- feel free to post a feature request in the BEF issue queue.

Thanks.


You have to use the power of render arrays.

For your example, I would use something like that :

$form_class = 'Drupal\xyz\Forms\XyzActionsForm';
$form = [
  'form' => $this->formBuilder->getForm($form_class, $parameter),
  'custom' => [
    '#type' => 'container',
    'inside' => [
      '#markup' => 'custom html', // Or use the power of render with html_tag type
    ],
  ],
];

return $form;

Then you can manage cache and other stuff on your render array and build your response with it.


How to create the history of particular field of content

Track Field Changes is a module that allows you to easily enable tracking/auditing on changes to fields, and has views integration.

I hope this will make your work.


Services: which hook to use for altering node field values before calling the node retrieve service?

Actually I think it's only hook_node_load() that can be use. As I understand Services module send just data and doesn't do any HTML render of the node and the hook_node_view is actually done only for it : change the HTML render.


How to prevent a View from rendering via a hook?

Wanted to do similar but just $view->executed = TRUE; made the query in the view still run. Looking at view::build(), I understood you need the following code, to prevent anything running further in the view (displays and query).

$view->executed = TRUE;
$view->built = TRUE;

To make it clearer, the code you should use is the following one.

function ding_eresource_views_pre_view(&$view, &$display_id, &$args) {
  if ($view->name == 'eresource_list' && $display_id == 'attachment_1') {
    // Prevent rendering if parent view has some option set.
    if (!empty($view->old_view[1]->barr)) {
      // This does not work. How can it be done?
      $view->executed = TRUE;
      $view->built = TRUE;
    }
  }
}


In the foreach loop of your example, you create multiple buttons and you can set a different/distinct '#name' property property to each submit button, e.g.:

foreach ($result as &$value) {
  ...
  $form['repo']['submit'] = [
    '#type' => 'submit',
    '#value' => $value->name,
    '#name' => $value->name,
  ];
  ...
}

In your validation and/or submit handler you can retrieve the element that triggered the form submission using $form_state->getTriggeringElement()['#name'].


How to generate a Commerce order from a CSV?

Im not sure how to make csv directly to order, but this should work:

create a node type, called "csv order"
use Feeds module to fetch the data from csv to this node type
install module hook_post_action
write a custom module, which after saving node "csv order" would take data from this node, and create commerce order with line items
remove the csv order node if neccesary


Looks like this is currently the canonical answer:

Use Secure Pages

  This module makes sure that the user is running on a secure page when
  they create or edit content, view user details, or administer the
  site.

The other part of my question regarding redirecting assets on a page to a secure connection has actually be integrated into drupal core. It was previously a contrib module: http://drupal.org/project/securepages_prevent_hijack

  #D7CX: This functionality is in Drupal 7 core so this module will not be ported. Please stay tuned for the securepages port.

  This is an add-on to the Secure Pages module that will prevent
  hijacked sessions from accessing SSL pages, yet still allow users to
  stay logged in when browsing non-SSL pages.

Drupalscout looks to have a great site recipe on working with SSL's as well:

  The Secure Pages module is a relatively old module and quite popular.
  It's goal is to only make certain pages of the site use HTTPS by using
  two lists of urls which should either by HTTPS or not. The benefit of
  this module is that you can use regular old HTTP for most of the site
  and only encrypt the traffic where you really need it. By default it
  will encrypt traffic for adding content, editing content, anything
  related to users, and for the admin area.

  SSL processing is taxing on a server. Using SSL on just the most
  important pages helps make sure that the data sent back and forth on
  those pages is encrypted. However, the session cookie is still
  unencrypted so a user who authenticates over HTTPS and then visits a
  non secure page sends their sesssion identifier in the clear which
  allows for an attacker to steal their session and login to the site
  which gives them the access to the very data that was supposed to be
  protected. This is largely "security theater" but it sure makes people
  feel good.

  Pro: Reduces load on server compared to a full SSL solution while
  encrypting important data transmission. Con: Doesn't protect against
  session hijacking so data can still be compromised.


Add field and Exclude from Display.
Add Global: Text area in the header.
Check Use replacement tokens from the first row
Enter the row pattern
Use css to make it look part of the first row

That will output the first row's field in the header.


webform alter default value template.php

Webform is a node module. So editing a node even though it contains form can be altered using hook_nodeapi.


$form_state does not follow same array structure as $form

If you group the fields below $form['fields'] you also have to set #tree at the top of the array:

$form['fields']['#tree'] = TRUE;

Then the values will be structured in the same way as the form elements.


Referencing a paragraph field in a field--node template

I was able to solve this by using the following in the field template:

{% for item in items %}
  {{ item.content['#paragraph'].field_role.0.value|striptags }}
{% endfor %}


I can't translate description of front page in my multilingual site

All major translation issues for metatag module are now fixed (see: https://drupal.org/node/1282620, https://drupal.org/node/1688286)

All you have to do is:

Go to metatag settings page: /admin/config/search/metatags
Override your frontpage (/admin/config/search/metatags/config/global:frontpage) and write
your infos in default language
Save your modifications
Go to your homepage
Flush site cache
Switch site language for every other language (this way all strings can be generated for translations)
Go to /admin/config/regional/translate/translate and search (in default
language) all strings you have to translate and translate them

This should be enough.

If you are using metatag submodules like Context be aware that translations issues are not still full fixed (see: https://drupal.org/node/1986032)

Hope this help


Bitnami Installation forcing me to flush caches while theming

Update for anyone who comes here in the future:

Bitnami comes with Google PageSpeed installed & enabled by default It's a pretty useful tool, but it's tricky to figure out what's caching your css when there's nothing apparent.

To check for it, take a look at the  of your drupal site & look through the <meta> & <style> tags for compressed css files, they'll look like lkjsdhf.gkdfsgklkshr.pagespeed.kljhasdfgk.ljsdhflgk or somesuch.

To disable it, navigate to your installation's apache configuration folder, mine was /home/bitnami/stack/apache2/conf & edit pagespeed.conf

Look for the line ModPagespeed on (mine was line 20) and change on to off

After that, restart Apache. You can also log into AWS and reboot your instance.


Allowed column type names and element type names for creating custom Field Types

All available schema types are listed in the following table:
https://www.drupal.org/node/159605

Here is a list of available types of render elements (first column of the table corresponds to the #type property of the element)
https://api.drupal.org/api/drupal/elements


How do I insert content fields above title in a content type template?

You will have to use the page template instead of node template so you can add fields before the node title.
page--content-type.tpl.php


Updating a field programmatically, hook_node_update

Entity metadata wrappers

The entity API provides some wrapper classes you may use to easily deal with entities and to leverage the entity property information modules provided. With the help of the wrappers you can access the property information, loop over known properties, or just get/set the described data values, etc.

These are some simple usage examples as found in the README:

For making use of this information (metadata) the module provides some
wrapper classes which ease getting and setting values. The wrapper supports
chained usage for retrieving wrappers of entity properties, e.g. to get a
node author's mail address one could use:

$wrapper = entity_metadata_wrapper('node', $node);
$wrapper->author->mail->value();

To update the user's mail address one could use

$wrapper->author->mail->set('sepp@example.com');

or

$wrapper->author->mail = 'sepp@example.com';

The wrappers always return the data as described in the property
information, which may be retrieved directly via entity_get_property_info()
or from the wrapper:

$mail_info = $wrapper->author->mail->info();

In order to force getting a textual value sanitized for output one can use,
    e.g.

$wrapper->title->value(array('sanitize' => TRUE));

to get the sanitized node title. When a property is already returned
sanitized by default, like the node body, one possibly wants to get the
not-sanitized data as it would appear in a browser for other use-cases.
To do so one can enable the 'decode' option, which ensures for any sanitized
data the tags are stripped and HTML entities are decoded before the property
is returned:

$wrapper->body->value->value(array('decode' => TRUE));

That way one always gets the data as shown to the user. However if you
really want to get the raw, unprocessed value, even for sanitized textual
data, you can do so via:

$wrapper->body->value->raw();

More examples:

$wrapper->body->set(array('value' => "content"));
$wrapper->field_text[0] = 'the text';
$wrapper->field_text[0]->set(array('value' => "content"));
$wrapper->field_text2->summary = 'the summary';
$wrapper->field_text2->value = 'the text';

$wrapper->save();
$wrapper->delete();

More docs: http://drupal.org/node/1021556


How do I list all blocks with PHP enabled inside?

If you want to find all custom blocks that have PHP code as their input format, you can query the block_custom table. The format column will contain the key php_code.

$blocks = db_select('block_custom')
  ->fields('block_custom')
  ->condition('format', 'php_code')
  ->execute();
foreach($blocks as $block) {
  // @TODO: Add your own actionable code
}


Turning page titles to links using hook_page_alter()

I don't think hook_page_alter() is the best place to do this (though I may be wrong), it seems like since you're changing the display of the title it should be done at the theme level.

Personally I'd go for a hook_preprocess_page():

function MYMODULE_preprocess_page(&$vars) {
  if ($node = menu_get_object()) {
    $field_items = field_get_items('node', $node, 'field_user_id');
    $first = array_shift($field_items);

    $user_id = $first['value']; // if 'value' is the column name for your field, it might be 'uid' if you're using a references field, 'target_id' for entity reference, etc.

    $link = l($vars['title'], 'path/for/link');

    $vars['title'] = $link;
  }
}


All cookie data is in the PHP superglobal $_COOKIE.  However a typical Drupal site only stores the a random session identifier in the cookie, so it may not be what you're looking for.  If $_COOKIE doesn't answer your question please post more details about what you're trying to accomplish.


Get current language of Drupal 8 in javascript?

In pages with the core/drupalSettings library included, it seems to be pretty reliably available through the path:

var langCode = drupalSettings.path.currentLanguage;


Adding a new separate menu link to /admin/config in page?

Adding link to admin config under development, media, service is easy but creating new separate menu like admin_config_development, admin_config_service , admin_config_media is bit tricky.

As mentioned in

  Create same file with small alteration  modulename.links.menu.yml

modulename.admin_config_modulename:
  title: ' settings'
  description: ' selection.'
  route_name: modulename.settings
  parent: 'system.admin_config'
modulename.second_link:
  title: 'settings'
  description: 'selection.'
  route_name: modulename.settinganother
  parent: 'modulename.admin_config_modulename'
  menu_name: modulename

  By: monkpal


Assuming you put the preprocess code in your theme's template.php, coding this inside a node ought to work  - but in order for it to do so you have to

make sure the Core "PHP Filter" module is enabled and
make sure the node's Input Format is set to "PHP code."

As I noted, this is not the most secure or maintainable way to do things, but it'll let you do what you want without messing about in page or node templates.


Drupal does not support different login forms. User is either logged in or not, and his privileges depend solely on his roles.

You can put a block multiple times on one page using MultiBlock
User has his roles, check them normally. He will have his role no matter what form will he use.
If you want dynamically give roles, yes, you need to write your own module that will act kinda like login handler, but be prepared to live with huge access permissions problems.


<?php print theme('mark', array('type' => node_mark($node->nid, $node->changed))); ?>

this is how it is done on the content overview page. give it a try, it will display read for anonymous users' - probably ..,

here's the code from node_mark, where node_last_viewed is used:

function node_mark($nid, $timestamp) {
  global $user;
  $cache = &drupal_static(__FUNCTION__, array());

  if (!$user->uid) {
    return MARK_READ;
  }
  if (!isset($cache[$nid])) {
    $cache[$nid] = node_last_viewed($nid);
  }
  if ($cache[$nid] == 0 && $timestamp > NODE_NEW_LIMIT) {
    return MARK_NEW;
  }
  elseif ($timestamp > $cache[$nid] && $timestamp > NODE_NEW_LIMIT) {
    return MARK_UPDATED;
  }
  return MARK_READ;
}

so for you maybe this could be used (statistics module needs to be enabled)

 <?php
      if (node_last_viewed($node->nid) == 0) {
        print '<span>' .  theme('mark', array('type' => MARK_NEW)) . '</span>';
      }

best to call this theme function (and any logic) in the preprocess method, and use a variable in the template ..


How to have a field with a select list widget and custom list entries?

For Drupal 8

Yes, is possible, but you will need to implement your own field type.

You should take a look into the Country module as you will need to implement the OptionsProviderInterface interface.

In the getPossibleOptions method, you will query the external site and get the possible options for your field.

For Drupal 7

You can always take a look inside the Examples module even for Drupal 8 you will find a very useful boilerplate code for your projects. If you want to check another example just go to the Countries module.


When should I create a service or a utility function?

Ken Rickard from Slack Drupal #contribute channel says: "I would
  create a service if you expect other modules (or other developers) to
  interact with that code. Utility methods are just private shortcuts
  for yourself."

Yes, a cool thing about services is that anyone can overwrite them. So if you want to give other people the ability to customise a particular piece of code.
See Altering existing services, providing dynamic services.

In addition, you should make it a service if you need to do Mock test for PHP Unit testing. See Services and dependency injection in Drupal 8, see Unit testing more complicated Drupal classes.

Q & A:

Service unit test

Writing unit tests for a method that calls static methods from another class


Have can I have a view grouped by nested hierarchy?

Create a list of all nodes that you want in your Views,
add the field for their taxonomy terms to show where they belong,
add the Parent relatinship for your taxonomy reference field to your Views. You may need to first add the relationship to the taxonomy reference field first, to get the Parent one to show as an option, in which case you'll en up with two relationships, the second one set to use the first one.
Add the Taxonomy Name field and set it to use the Parent Relationship. This field will show the parent term of the one the node is tagged with
Under Format use the "Group by field" option and set the first one to the Parent Field, and the second "Group by field" to the (sub-term) regular taxonomy field.

This should get you fairly close, I can't predict OTOMH where the nodes that have been tagged with only the parent taxonomy.


How to load a file located in core/includes?

You can use a good old fashioned include_once (or require_once):

include_once DRUPAL_ROOT . '/core/includes/install.inc';

Core uses the same method any time it needs to source a file in core/includes. Case in point, ModuleHandler::loadInclude itself does exactly that if the file extension provided is "install":

public function loadInclude($module, $type, $name = NULL) {
  if ($type == 'install') {
    // Make sure the installation API is available
    include_once $this->root . '/core/includes/install.inc';
  }

  ...


Trying to add a column of Mysql timestamp through hook_update

While valid in SQL, there is no data type TIMESTAMP in the Drupal 7 database schema.

The list if valid data types is here.

This means that you cannot add this datatype  to your tables through any function that goes to the Drupal API (such as db_query).  Your SQL console is not subject to these limitations, and will allow it to be added.

So the short answer is: Drupal 7 will not let you do what you try to do.

Also, in case you're trying to add two auto-update timestamps, note the following limitation in MySQL:

  One TIMESTAMP column in a table can have the current timestamp as the default value for initializing the column, as the auto-update value, or both. It is not possible to have the current timestamp be the default value for one column and the auto-update value for another column.


How can I get the form validated with AJAX?

Here is a very basic example that will validate your data. It should give you an idea of how to handle it:

class myForm extends FormBase
{
  public function getFormId()
  {
    return 'my_form';
  }

  public function buildForm(array &$form, FormStateInterface $form_state)
  {
    $form['#prefix'] = '
';
    $form['#suffix'] = '
';
    $form['some_text'] = [
      '#type' => 'textfield',
      '#title' => $this->t('Enter a value'),
    ];

    $form['submit'] = [
      '#type' => 'submit',
      '#value' => $this->t('Submit'),
      '#ajax' => [
        'wrapper' => 'my_form_wrapper',
        'callback' => '::ajaxCallback',
      ],
    ];

    return parent::buildForm($form, $form_state);
  }

  public function validateForm(array &$form, FormStateInterface $form_state)
  {
    if($form_state->getValue('some_text') != 'Awesome')
    {
      $form->setValue('some_text', $this->t('Please enter "Awesome"'));
    }
    parent::validateForm($form, $form_state);
  }

  public function ajaxCallback(array &$form, FormStateInterface $form_state)
  {
    return $form;
  }

  public function submitForm(array &$form, FormStateInterface $form_state)
  {
    drupal_set_message($this->t('The form was submitted'));

    parent::submitForm($form, $form_state);
  }
}

With the above code, the form is built, and the ajax is set. Note that no validation needs to be set, as the validateForm() method will be called automatically if it exists. When the ajax is executed, it will always call the validate form method first. If validation is passed, then the submitForm() method will be called, but if validation is failed, it will not. Finally the ajax callback is called and the form is returned.


Is it valid to use entries in #default_value if they are not in the #options?

Reading through the code of form_process_select it is obvious that the situation where #default_value is set, but the value isn't a valid option, is not being handled properly:

This piece of code may "fail" in that case:

// If the element is required and there is no #default_value, then add an
// empty option that will fail validation, so that the user is required to
// make a choice. Also, if there's a value for #empty_value or
// #empty_option, then add an option that represents emptiness.
if (($required && !isset($element['#default_value'])) || isset($element['#empty_value']) || isset($element['#empty_option'])) {
  $element += array(
    '#empty_value' => '',
    '#empty_option' => $required ? t('- Select -') : t('- None -'),
  );

In your sample code, you don't set #required for the select field. That is why you don't observe any effect.

However, in the general case, you can't supply a bogus value for #default_value and always be sure that theFAPI will treat it just the same as not set or NULL #default_value.

If change your example and set #required to TRUE, and #multiple to FALSE, you should be able to reproduce a situation where having a bogus default value (such as "lizard") behaves different from the default value being NULL or absent.


Display Related Nodes by Taxonomy Terms in Block

Resolved it by using the following method:

Under Advanced
→ Contextual Filter: "Vocabulary Name"
→ Taxonomy Term ID from URL
→ Load default filter from node page, that's good for related taxonomy blocks
→ Select Limit terms by vocabulary
→ Select the appropriate Vocabulary
→ Under "Multiple-value handling" Select the appropriate option as per your requirement (either "Filter to items that share all terms" OR "Filter to items that share any term".
That's it. It worked for me.


Have a look at the rules scheduler module (part of the rules module). You should be able to do most of the things with date calculation and rules scheduler.

If you're missing something in rules you might have to implement your own rules action. Have a look at hook_rules_action_info().


Where are all the controller classes instantiated?

So, first, this is not a controller, it's a form class. Controllers are instantiated by the routing component.

Every route must have a controller. _form and some other special cases are processed after routes were collected and the actual controller is added. For forms, that is \Drupal\Core\Controller\HtmlFormController.

The actual processing happens in \Drupal\Core\Controller\FormController::getContentResult(), which calls \Drupal\Core\Controller\HtmlFormController::getFormObject(), which in turn uses \Drupal\Core\DependencyInjection\ClassResolverInterface::getInstanceFromDefinition() to instantiate the form class.

FormController then hands of the processing of the form to \Drupal\Core\Form\FormBuilder, which uses various other classes in the Form namespace.


So the answer to this was easier than I thought.  I loaded the $other_callout node, and then unset the $key, utilizing the following code:

foreach($other_callout->field_skus as $key=>$value) {
if($value['nid'] == $sku) {
        $sku_rec = $value;
        $sku_rec_key = $key;
    continue;
    }
}

unset($other_callout->field_skus[$sku_rec_key]);

node_save($other_callout);

Thanks for the help guys, I appreciate it.

Drupal on.


How to display specific nodes in an EVA based on common taxonomy

From the EVA project page:

  In addition, the unique ID of the entity the view is attached to -- as well as any tokens generated from that entity -- can be passed in as arguments to the view.

Pass the Taxonomy terms as arguments to the view attachment. You may then add a contextual filter to the view attachment which can make use of these arguments and  require the arguments be of terms within the appropriate vocabulary.


Probably a stupid question but have you tried using the #required setting when you created the field i.e.

'#type' =>
'textfield',
'#title' => t('Subject'),
'#default_value' => $node->title,
'#size' => 60,
'#maxlength' => 128,
'#required' => TRUE,

from Form API reference https://api.drupal.org/api/drupal/developer!topics!forms_api_reference.html/7#required


Only Publish a node in certain languages

First of all lets make sure you have set up Drupal correctly:

Do you have activated the core Content translation module
Do you have activated the core Language module
Do you have set up at least 2 or more languages (of course you have)
Do you have set up detection and selection correctly (I think you have)
Do you have set up content types correctly to allow multiple languages (sure otherwise it won't work)
Now when you start to list your nodes in content/admin overview you should be able to select translate each node
If you choose this and you translate it you should see the button below saying translate and publish which can be switched to translate and unpublish this selection
if you choose the second your translation will not be published automatically. Violá

Hope it helps ...


How to get the number of registrants (RNG module) from the theme layer

You can access the event manager service to grab an event meta object. The event meta object contains a bunch of helpers to manipulate registrations and registrants. In your template preprocess functions add whatever data you want from the event meta object.
function mymodule_preprocess_HOOK(&$variables) {
  $event_entity = $entity; // Provide your entity

  /** @var \Drupal\rng\EventManagerInterface $event_manager */
  $event_manager = \Drupal::service('rng.event_manager');
  $event_meta = $event_manager->getMeta($event_entity);
  $mydata = $event_meta->whatever();
   // See \Drupal\rng\EventMetaInterface for methods. e.g:
   // $event_meta->getRegistrants()
   // $event_meta->getRegistrations()
   // $event_meta->countRegistrations()
   // $event_meta->getCapacity()
   // $event_meta->remainingCapacity()
  $variables['myvariable'] = $mydata;
}

For nodes, replace mymodule_preprocess_HOOK with mymodule_preprocess_node and $entity with $variables['node'].


Passing custom fields as parameters in a REST query

The default functionality only works with node properties, not fields. Fortunately you can use the Services Entity API module to get what you need:

Integration of Services and Entity API.
You can define an endpoint via Services and publish any entity data relying in Entity API.
This module allows to get entities by properties or fields and also paging and related entities that are defined properly.


/README.txt: UTF-8 Unicode (with BOM) English text, with CRLF line terminators

In Settings - User config, you should set

"default_line_ending": "unix",

Also, when saving file, select UTF-8 Unicode without BOM - that's exactly what you were told here:

  the byte order mark at the beginning of UTF-8 files is discouraged

Emphasis mine.

Taken from Fixing Sublime Text 2 line endings?


Access custom block in page.html.twig template

Take away the block from the view header and use twig_tweak module to be able to insert something like this in your twig template

{# No need to configure this block on "admin/structure/block" page. #}

Block:

{{ drupal_block('BLOCKID') }}

Or if you don't want to use an extra module add to your THEMENAME.theme

function THEMENAME_preprocess_page(&$variables) {
  $block = \Drupal\block\Entity\Block::load('BLOCKID');
  $content = \Drupal::entityTypeManager()->getViewBuilder('block')->view($block);
  $variables['my_block'] = $content;
}

and in your twig template just use

{{ my_block }}


Check if Workbench Content Has Published Revision

I'm assuming this question is about D7 ...

Step 1 - Flag published revisions

Use the Flag module to flag Workbench content whenever a published revision gets created. The flag you'd want to use is a global flag. To actually flag such content, use the Rules module.

Step 2 - Check if flagged

Adapt your existing Rule(s) (for advanced Workbench notifications) to take into account if your content has yes or no been flagged. To do so, you have a choice:

Split your current Rules Action (for those notifications) in 2 Rules Components (in which you can use Rules Condition to check the flag).
Use the Conditional Rules module so that you can include the required Rules Condition(s), to check the status of the flag, within the Rules Actions of your existing rule.


How can I add a custom price to a cart as an attribute of product type in Drupal Commerce?

Below these modules will help you with bit of customization or addons

Commerce Product Attributes

  This module provides some enhancements to the Drupal Commerce
  attribute handling.

Commerce Product Option

  This module allows you to add user-customizable options to the
  commerce "add to cart" form. You do this by defining "option sets", to
  which you can attach any field of your choosing. These option sets can
  then be added to your commerce products using entity reference, after
  which the fields in your option set will show up in the add to cart
  form.

Commerce Pricing Attributes

  This module provides some enhancements to the Commerce Product Option
  and Commerce Product Attributes handling by applying pricing rules to
  custom product attributes. So, you can add attributes to products that
  affect the final product price.


How to run commerce_order_save() without triggering any rules?

It's possible, but the change would need to be sitewide (not just in the context of rules). You'd need to override the entity controller class used for commerce_product (which you could do with hook_entity_info_alter()), and re-implement its save() method so it doesn't invoke the entity hooks.

If that is undesirable (probably is), and you just need to update field values, you can use field_attach_update() instead, which will bypass the entity save process altogether:

$order->some_field[LANGUAGE_NONE][0]['value'] = 'foo';
field_attach_update('commerce_order', $order);

Other than those I don't think there's any way to accomplish it using the API.


Product catalog in views that is hierarchical but not mutually exclusive

I would try to achieve this with an exposed filter in views, 'Has taxonomy terms' or 'Has taxonomy terms (with depth)' for example. Use this as an exposed filter (dropdown with multiple select) in a page display.
In the advanced settings in views you can choose to expose the form in a block. You can add this to the left sidebar and activate 'autosubmit'. So everytime they change something the results get filtered.

Since dropdown is not that nice, I would try on basis of this post https://stackoverflow.com/questions/9208997/drupal-7-creating-a-taxonomy-filter-using-checkboxes to change it to checkboxes.


You first have to add the image to the index. Then preferably reindex.
Usually for some reason the image fields are hidden on the page, where you add the fields to the index.
The page in Drupal 7 would be under Search and metadata > Search API > Your index, edit > Fields
/admin/config/search/search_api/index/NAME_OF_INDEX/fields

And your image field you may add from the bottom - the section is called "Add related fields" and then you should choose your field and click "Add field". Afterwards you may click the checkbox to the field - in order to add it to the index.

The approach with node_load is a very bad one because that would load stuff from the database, where the idea of Search Api and in this case the connection with Apache Solr - is to get everything directly from the Solr.


I use a function I've written called ifset for this purpose:

function ifset(&$var, $prefix='', $suffix='', $else = '') {
    return isset($var) && $var ? $prefix.$var.$suffix : $else;
}

It can simply be used like:

$foo = 'test';
echo ifset($foo); // produces test
echo ifset($bar); // produces an empty string

Or you can supply a suffix, prefix or else values:

$foo = 'test';
echo ifset($foo, 'before ', ' after', 'foobar'); // produces before test after
echo ifset($bar, 'before ', ' after', 'foobar'); // produces foobar

So, in your instance you could write:

$edu_completed = ifset($entityform_wrapper->field_education_completed->value());

This is slightly different to your code a $edu_completed will be an empty string instead of not being set at all.


How to rename address labels on Address field module?

This can be done with hook_form_alter:

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

    //drupal_set_message("Form ID is : " . $form_id);

    switch($form_id) {

        case 'MY_FORM_ID':

            // dpm($form);

            // $form['NAME_OF_YOUR_FIELD'] - this is the field you want to edit

            // check that the field is set before looping over values
            if(isset($form['NAME_OF_YOUR_FIELD'][LANGUAGE_NONE])) {
                // loop over each values passing $item by reference
                foreach($form['NAME_OF_YOUR_FIELD'][LANGUAGE_NONE] as &$item) {
                    if(is_array($item) && isset($item['street_block'])) {
                        $item['street_block']['thoroughfare']['#title'] = 'Address Line 1';
                        $item['street_block']['premise']['#title'] = 'Address Line 2';
                    }
                }
            }
            break;
    }

}

I found the path to the variable I wanted to change by outputting the $form array to the message area using devel's dpm function, and then searching though the array for the value "Address 1" using the search krumo module.


Drupal 7: Webform Emails: How to change content based on a condition?

I reckon you can get there just using Webform and applying some Conditions. Here is the recipe I just tested.

Add a 'country' select field, with options NZ and USA
Add a 'usa1' textfield, set as private, and enter default value you want to go in your email when USA is chosen ('love usa').
Ditto for an NZ textfield (nz1) ('go nz').
Now set up a condition that will 'show' (to admins only as it is private) the USA text field when USA is chosen as country,
ditto a condition so if NZ is chosen, the NZ text fields 'shows'.
Now set up your email with eg [submission:values:usa1][submission:values:nz1]

and presto hey!

If i select USA as country I get email saying 'love usa'.
if i chose NZ I get 'go nz'

Is that pretty much what you need?

NB: I thought this route would work as we had done similar when we needed an email to go out to addressX 'only' if a user chose USA as country.
We used webform conditions and
We craeted an email field that was set to private. Then used conditions to 'show' it (to admin only) if USA was chosen.
Then we could just set up a new webform email using that field, and it only fired if the condition was met.


Why is accessing paragraphs slow? Is there a better approach?

Well after fiddling around with it some more, I suppose the best answer here is to just cache the variable  $para_ids using \Drupal::cache() and then update it whenever there is a node/entity update or insert. I could look into database optimization to see what is actually happening with the $item->entity reference, and put an index on the joins/where statements but I am not very confident that is the best way.


Found a great way to do this automatically after comparing the Devel tab on a node before and after manually saving it. I realize this is a somewhat narrow use case, but I think it's pretty strong nonetheless.

Create a CKEditor profile (I called it "Bio Cleaner", machine name bio_cleaner) and limit it to the tags and attributes you want. In my case, it's <a href hreflang> <ul type> <ol start type> <li> <br> <p>.
For any "formatted" text field in your content types, add the new CKEditor profile as an allowed profile.
In your migration, rather than just dumping the raw contents into a field name, set it up like so:

(Sorry for the image - Stack Exchange apparently can't format yaml?)

Anyway, the secret sauce is to to set the /value key of the target field to the value pulled from the migration, and to set the /format key to the new format you created. Drupal will automagically clean up whatever tags aren't included in your profile when it saves the data.

NOTE: this relies on having the Allowed Formats module installed.


You won't be able to get a tab with exactly that path in it, as it won't match the node/% path and the tab simply won't show.

The easiest way I can think of to do it would be to create a proxy page that does match that pattern. Something like:

function MYMODULE_menu() {
  $items['node/%node/manage-ct'] = array(
    'title' => 'Manage content type',
    'access arguments' => array('something appropriate to your install'),
    'page callback' => 'MYMODULE_node_manage_proxy',
    'page arguments' => array(1),
    'type' => MENU_LOCAL_TASK
  );

  return $items;
}

function MYMODULE_node_manage_proxy($node) {
  $type = str_replace('_', '-', $node->type);
  drupal_goto('admin/structure/types/manage/' . $type);
}

That way the tab will appear, but as soon as the user clicks through to the page it will redirect to the node type form.


Modules needed: Flag, Rules, Rules Scheduler (comes bundled with rules)

Create a user flag

Add an integer field to your user fields. Ex: Attendance (this will keep track of the # of days attended)

Create a new Rule

React on A user has been flagged
Actions: Set a data value >> flagged-user:field-user-attendance >> OFFSET : 1

So this will +1 your field every time the user is flagged.

in Rules add a new component.

Component: Rule >> Data Type: User >> Label: att >> Machine Name: att >>
Actions: Unflag a user >> USER: att >> USER ON WHOSE BEHALF TO FLAG: att >> Skip permission check

Go back to your Rule and add action of Schedule Rule Component

Select your component >> SCHEDULED EVALUATION DATE: +5 hours >> Identifier: [flagged-user:name] will be auto unflaged soon >> ATT: flagged-user

so in 5 hours all users that are flagged will be auto unflagged. (this auto resets them for you, so you are ready to flag the next day)

Update

A good solution but the date really needs to get recorded as well – J. Reynolds

Challenge accepted.
In users add a field called "Date Attended" type:text field. In settings Change number of values: Unlimited

In your rule, add Action: Add an item to a list >> flagged-user:field-date-attended >> ITEM TO ADD: click on switch to direct input mode and then put [site:current-date] >> Append item to the end.

This will auto add a new term with a timestamp when you flag a user/student.

You can then use the Field Permissions module if you want to hide this from users so they cant see it and/or edit it.
PS: I think you might know this already, but just in case. To add a flag link to your view, first you need to add a RELATIONSHIP of flag to your view. Then the flag link option will be available to add as a field in fields.
IMPORTANT NOTE: The Scheduled rule will be triggered in the next cron run.


how to print value of a taxonomy field to headline with node.html.twig?

That's because a taxonomy field has no values. It contains entities, which are the referenced terms. You get the first term with .entity and then you can get the values inside of the term, for example if the term would have a field_test2:
{{ node.field_test1.entity.field_test2.value }}

Or simply the term label (no .value needed for this):
{{ node.field_test1.entity.label }}

If you need translation use the |translation filter of the module Twig Tweak.


How to set a $_POST var value as default value for a textfield webform component?

Webform 4 no longer uses so much of its own custom code.

It now uses drupal tokens like you would expect anywhere else.

Under the text area is a link "Browse available tokens." that will give you a javascript token browser to help you find the tokens you want.

You can access submission tokens like this: [submission:values:FIELD_KEY]

The special tokens you are after though like %post are no longer supported in webform 4.x.

For more information see https://www.drupal.org/node/1001798

Your best bet for such token support would be for them to be added to the main token module or another third party token module in the global token space.

$_GET tokens have an issue https://www.drupal.org/node/550164 however I don't think there is one for $_POST at this stage.

Alternatively you can write a hook_form_alter() in a custom module and set the default value there using $_POST.
That would be your easiest option I would say.


D6/views - Multiple nodes in one slide grouped by taxonomy

You might add an argument to your view.

The url of your view should looks like: "my_site/my_views_url/11"
(#11 is the tid of "fruits")

This url will list all terms depth to "fruits" (so apples, pears, bananas)

To add a depth in your argument term in the view follow the views UI :


how to open desktop node link shared on facebook onto mobile device (mobile website version)

the solution is very simple, I just don't see it.

its in advanced sitting for mobile switch module, Multisite shared content must be checked.


How do I check the content of variables passed to a template file?

You can follow document.

  To dump only the available variable keys use:

{{ dump(_context|keys) }}

In this case you can use:

{{ kint(node|keys) }}

Or you can follow topic

  Create a /modules/contrib/devel/kint/kint/config.php file and add /
  modify the line $_kintSettings['maxLevels'] = 3; (by @mdrummond on
  Slack)

The best way: install module twig_tweak and using twig function

{{drupal_dump(node)}} to dump variables.


What is the equivalent of "Referential Integrity for CCK" in drupal 7?

There is a sandbox project for a D7 port that performs cleanup on cron.

Otherwise drupal supports databases that do not enforce referential integrity, so it has not (to my knowledge) been a core issue.


Retrieve create node form. Why cant save send values?

I think you're confusing Drupal by having a form within a form so-to-speak. I think it would be a lot easier to define a proxy function for the node form so you don't need to worry about doing so:

function module_menu() {
  $items['user/%/edit/blog/add'] = array(
    'title' => 'Add blog post',
    'page callback' => 'module_blog_form_proxy',
    'page arguments' => array(1),
    'access arguments' => array('createBlog'),
    'type' => MENU_CALLBACK,
  );

  return $items;
}

function module_blog_form_proxy($uid) {
  // Validitiy checks etc...

  $user = user_load($uid);
  $node = array('uid' => $user->uid, 'name' => $user->name, 'type' => 'blog');

  module_load_include('inc', 'node', 'node.pages');
  return drupal_get_form('blog_node_form', $node);
}


Adding custom meta tags to nodes, dependent on author name?

I don't know of a metatag module which gives you that level of granularity; you might have to do it in code.

Fortunately, it's pretty easy. You'll need a custom module, in which you should implement hook_node_view(), and use drupal_add_html_head() to add the meta tag based on custom logic.

Very brief example:

function MYMODULE_node_view($node, $view_mode, $langcode) {
  if ($node->type == 'foo' && $view_mode == 'full') {
    if ($node->name == 'admin') {
      $tag = array(
        '#type' => 'html_tag',
        '#tag' => 'meta',
        '#attributes' => array(
          'name' => 'robots',
          'content' => 'follow,noindex',
        ),
      );
      drupal_add_html_head($tag, 'MYMODULE:robots:noindex');
    }
  }
}


If you want to basically prevent hotlinking images, you can try the following in your .htaccess file

RewriteEngine on
RewriteCond %{HTTP_REFERER} !^http(s)?://(www\.)?yourdomain.com [NC]
RewriteRule \.(jpg|jpeg|png|gif)$ - [NC,F,L]


How do I create a HTML link from an internal path using the core Link class?

Getting the route can be tricky. Sometimes I'll just do a code search for the path.

Routes are defined in [MODULE].routing.yml files. You can often look for a route you need if you can guess the module that supplies it. For example, the user login page is provided by the user module, so I look in user.routing.yml, in which I find this for the user login route:

user.login:
  path: '/user/login'
  defaults:
    _form: '\Drupal\user\Form\UserLoginForm'
    _title: 'Log in'
  requirements:
    _user_is_logged_in: 'FALSE'
  options:
    _maintenance_access: TRUE

The route name here is user.login. Now, that route name can be used to do the following:

$url = Url::fromRoute('user.login');
// Get the URL string:
$url_string = $url->toString();
// Build a link:
$link = Link::fromTextAndUrl(t('Log In'), $url);
// Get the link string:
$link_string = $link->toString();

Note that $link->toString() returns an object of type Drupal\Core\GeneratedLink. This class has the magic method GeneratedLink::__toString(). This magic method is invoked when the object is treated like a string. That means you can treat the result of $link->toString() as if it were a string, even though it's an object. So in context where you can print values, this will work:

print Link::fromTextAndUrl(t('mylink'), Url::fromRoute('user.login'))->toString();


Sounds like the problem is that clean URL's are enabled in Drupal but not supported by your Apache configuration (make sure that mod_rewrite is enabled and the folder/vhost has AllowOverrides enabled) or the .htaccess file is missing.

You can verify that this is the problem by accessing the non-clean version of the URL. For example, instead of example.org/something, try example.org/?q=something.

See http://drupal.org/getting-started/clean-urls for more information.


To answer your specific question; clearly $TitleImage is not empty, views_embed_view is returning wrapper elements or a space. in the view settings make sure "no results" returns nothing using the no results behavior of the field and the view (under advanced).

Why use a view? If that image is on that piece of content then there is no need for a view at all, just use the field:

<?php hide($content['field_title_image']); // So it does not render elsewhere ?>
<?php if (!empty($content['field_title_image'])): ?>

      <?php print render($content['field_title_image']); ?>

<?php else: //Display regular title ?>
  <?php print render($title_prefix); ?>
  <?php if ($title): ?>

<?php print $title; ?>

  <?php endif; ?>
  <?php print render($title_suffix); ?>
<?php endif; ?>

(if you are on node.tpl.php the filed will be as above, if you are on page.tpl.php it will be inside $page['content'] array)


Why doesn't the pager appear in page--taxonomy.tpl.php?

I tried with the Bartik theme, and it works.

The steps I followed as the following ones:

I copied the page.tpl.php file the Bartik theme has in its templates directory in the page--taxonomy.tpl.php file
Right before <?php print render($page['content']); ?>, I copied the following code.

<?php
  $query = db_select('node', 'n');
  $query = $query->condition('n.type', 'article', '=')
    ->fields('n', array('nid', 'title', 'uid'))
    ->extend('PagerDefault')
    ->limit(1);

  $result = $query->execute();
  foreach ($result as $node_obj) {
    echo $node_obj->title . "
";
  }

  echo theme('pager');
?>

I selected another theme instead of the Bartik theme, disabled the Bartik theme, and then selected the Bartik theme as default one. (This step is probably not necessary, but I did it to be sure Drupal would notice I added a new template file.)
I visited http://tero.local/dr72/taxonomy/term/2.

If it doesn't work for you, I suggest trying with another theme, possibly one that comes with Drupal, for example the Bartik theme. Be sure you are adding the template file to the theme Drupal is using. If the theme selected for the current user is another one, the template file is not being used, and that would explain why you are not getting any output.

This is what I suspect, as the code doesn't depend from arg(2). You just need to visit a page whose path starts with taxonomy, for example http://example.com/taxonomy/term/2, or http://example.com/taxonomy/term. (Replace example.com with the domain you should use for your site.)

Update

It works, but using the following code.

<?php
  $query = db_select('node', 'n');
  $query = $query->condition('n.type', 'article', '=')
    ->fields('n', array('nid', 'title', 'uid'))
    ->extend('PagerDefault')
    ->element(10)
    ->limit(1);

  $result = $query->execute();
  foreach ($result as $node_obj) {
    echo $node_obj->title . "
";
  }

  echo theme('pager', array('element' => 10));
?>

Apparently, there is a conflict between the pager added from Drupal, and the pager added from my code. This is the reason why such code should not be added to a template file. Rather than using this method, it is better to override the taxonomy term page with other methods, such as the Views module, or implementing hook_menu_alter() in a custom module.

Using the Bartik module this is the output I get:

When there aren't nodes using that taxonomy term

When there are nodes using that taxonomy term

Any different result could be caused from the code used for the specific theme used on the site. Understanding what exactly causes the different behavior seems a little outside the purpose of this site, as it is too localized to be helpful for future readers, considering that similar code should not written in a template file.


You can use this in the terminal

drush sa

For example on my dev server:

- drush sa
@8080
@commons_3_dev
@none
@w2

The aliases are set in file called aliases.drushrc.php. For me this is located in /usr/local/share/drush/. Depending on how you installed Drush and on which distro you're on this may differ.

You can set up aliases in this fashion inside that file

$aliases['8080'] = array(
'uri'=>'server.com:8080',
'root'=>'/var/www/html_webtest2',
);

$aliases['w2'] = array(
'uri'=>'webtest2.server.com.edu',
'root'=>'/var/www/html_webtest2',
);

$aliases['commons_3_dev'] = array(
'uri'=>'yourserver.com/c3d7/',
'root'=>'/var/www/html_commons_3_dev',
);

For more fun, you can chain these together for server wide backups. For example, I do a big back up to all aliased sites like this

 drush sa | egrep "(@|default)" | egrep -v "(@none|@self) | xargs -L1 drush arb

Taken individually

 drush sa  # list site aliases
 | egrep "(@|default)"  # include default and any line containing a @ mark
 | egrep -v "(@none|@self)" # remove any lines with @none or @self
 | xargs -L1 drush arb # with each line run drush archive-backup

To find path and other info, use a bit o' pipping:

drush sa | xargs -I {}  sh -c "echo {}; drush {} st"

To narrow it down to finding paths:

    drush sa | xargs -I {}  sh -c "echo {}; drush {} st" | egrep "(@|path)"
@8080
 Site path                     :  sites/8080.webtest2
 File directory path           :  sites/8080.webtest2/files
 Private file directory path   :  /var/www/drupal_private_files
@commons_3_dev
 Site path              :  sites/default
 File directory path    :  sites/default/files
@none
@w2
 Site path              :  sites/default
 File directory path    :  sites/default/files

update

A bit late but I wanted to say don't forget about drush @sites st. I believe the @sites parameter will act on everything found under the sites folder. Think

drush @sites cron -y # runs cron on each root/sites/site
drush @sites rf


You have domain aliases with Domain Access, so you can edit your www.domain-d.com.au domain and add aliases that you need with redirection rule.

When you edit the domain you'll notice Aliases tab, there you can find explanation how to create the pattern and you just add the pattern that you need.

So, you don't need .htaccess for this.


Google Analytics module is not tracking site search

The problem is that Google Analytics only supports site search tracking if the path is "search/something", not "sitesearch" as we use on my client's site.

Line 138ish from googleanalytics.module:

if (module_exists('search') && variable_get('googleanalytics_site_search', FALSE) && arg(0) == 'search' && $keys = search_get_keys()) {
  $url_custom = '(window.googleanalytics_search_results) ? ' . drupal_to_js(url('search/'. arg(1), array('query' => 'search='. drupal_urlencode($keys)))) . ' : ' . drupal_to_js(url('search/'. arg(1), array('query' => 'search=no-results:'. drupal_urlencode($keys) .'&cat=no-results')));
}


Declare a #theme starting with the base hook of the input element and a double underscore:

  $form['my_field'] = [
    '#type' => 'textfield',
    '#theme' => 'input__custom',
    '#icon' => 'my_icon',
    '#title' => $this->t('My title'),
  ];

Prepare additional variables in a preprocess hook:

function mytheme/mymodule_preprocess_input(&$variables) {
  if ($variables['theme_hook_original'] == 'input__custom') {
    $variables['icon'] = $variables['element']['#icon'];
  }
}

Then you can use the added variables in the input template:

{{ icon }}


Getting body of a node to display in a block using PHP code

I found out how to do this:

$node_id = basename($_SERVER['REQUEST_URI']);
$node = node_load($node_id);
echo $node->body['und'][0]['value']

I have also found out that there is probably a better way to do this using field_view_value(),
but I am not quite sure how that works.


Solved. The issue was arising from a change I'd made to the KernelRequestSubscriber where I was redirecting users that hit the homepage that wasn't on the actual root of the site (to stop the homepage from being accessible from multiple routes - duh).


How to make the autocomplete term widget (tagging) case-sensitive?

You are looking for Termcase module, It will do that.

  It prevents users to use different cases on terms. With termcase you
  can make sure all terms in a vocabulary begin with an uppercase or
  that they are all formatted to lowercase.

There are five options available:

No formatting
Ucfirst: convert the first character of the term to uppercase
Lowercase: convert all characters of the term to lowercase
Uppercase: convert all characters of the term to uppercase
Propercase: convert the first character of earch word to uppercase

You can define these settings per vocabulary. The module even enables you to update all existing terms in a vocabulary and select whether or not you want to convert synonyms as well.


I had to do a query like that once, here is how I achieve this with EFQ:

$matches = array();
yourmodule_mini_query('12-DEC-14', $matches);
yourmodule_mini_query('null', $matches);

function yourmodule_mini_query($value, &$matches) {
  $entityQuery = new EntityFieldQuery();
  $query = $entityQuery->entityCondition('entity_type', 'product');
  $query->fieldCondition('product_expiry_date', 'value', $value, '=');
  $query->fieldCondition('availability', 'value', 'Yes', '=');
  $results = $query->execute();

  if(count($results)) {
    foreach ($results['product'] as $p) {
      // By using product_id as array key, you deal with the duplicates
      $matches[$p->product_id] = $p->product_id;
    }
  }
}

Where $matches contains an array of product_id's that are available and for which product_expiry_date is null OR 12-DEC-14.

Hope it helped.

EDIT: As said in the comments below, the evaluation of the NULL value may require a second distinct query instead of calling twice the same function.


First four free - changing product pricing based on cart quantity in Commerce using Rules

You can add a custom rules condition for line item which will check next:

if the amount of items in cart is more than 4
if the current line item position is greater that 4 (load cart, sort cart line items by created date)

Use the custom condition in pricing rules for line item.


Image upload not working for "AUTHENTICATED USER"

Do not give your authenticated users the Import media files from the local filesystem permission. It's actually different functionality that could open you up to security risk.

Looking at media_media_browser_plugin_info(), we can see that in order to use the upload plugin, the user has to either have the Edit media or the Administer media permission. Likely you'll want to assign the former.

I'll file an issue to correct that the import permission is misleading, and improve the description of the Edit media permission to be clear this is necessary to upload files in the browser.


Slow "Add another item" with unlimited valued fields

building on the answer by Charlie, I found that it takes about the same amount of time to reload the block if you are adding 1 or 100 items, so here is a trick to add a select list of numbers in the form next to 'add more' so you can choose how many you are adding. This saves a lot of time and is still flexible.
Could be wrapped in to a little module

<?php
/**
* Implements hook_field_attach_form()
*/
function village_field_attach_form($entity_type, $entity, &$form, &$form_state, $langcode){
  $options = array('language' => field_valid_language($langcode));
  // Merge default options.
  $default_options = array(
    'default' => FALSE,
    'deleted' => FALSE,
    'language' => NULL,
  );
  $options += $default_options;
  list(, , $bundle) = entity_extract_ids($entity_type, $entity);
  $instances = _field_invoke_get_instances($entity_type, $bundle, $options);
  // Iterate through the instances.
  $return = array();
  foreach ($instances as $instance) {
    // field_info_field() is not available for deleted fields, so use
    // field_info_field_by_id().
    $field = field_info_field_by_id($instance['field_id']);
    $field_name = $field['field_name'];
    //If we are looking at our field type and specific widget type, and we are multiple entries
    if($field['cardinality'] == FIELD_CARDINALITY_UNLIMITED){
      //Check just in case the button is here, and add another #submit function
      if(isset($form[$field['field_name']]['und']['add_more'])){
        // add a simple select list, this defaults to numb 3
        $form[$field['field_name']]['add_more_number'] = array(
          '#type' => 'select',
          '#title' => t('Add more no.'),
          '#options' => drupal_map_assoc(range(0, 50)),
          '#default_value' => 2,
        );
        $form[$field['field_name']]['und']['add_more']['#submit'][] = 'village_field_add_more_submit';
        $form[$field['field_name']]['und']['add_more']['#value'] = 'Add more rows';
      }
    }
  }
}
function village_field_add_more_submit($form, &$form_state){
  $button = $form_state['triggering_element'];
  // Go one level up in the form, to the widgets container.
  $element = drupal_array_get_nested_value($form, array_slice($button['#array_parents'], 0, -1));
  $field_name = $element['#field_name'];
  $langcode = $element['#language'];
  $parents = $element['#field_parents'];
  // Alter the number of widgets to show. items_count = 0 means 1.
  $field_state = field_form_get_state($parents, $field_name, $langcode, $form_state);
  //get the number from the select
  $numbtoadd = $form[$field_name]['add_more_number']['#value'];
  if($numbtoadd){
    $field_state['items_count'] += $numbtoadd;
    field_form_set_state($parents, $field_name, $langcode, $form_state, $field_state);
    $form_state['rebuild'] = TRUE;
  }
}
?>

I also posted the suggestion on Drupal.org at https://drupal.org/node/1394184#comment-8252701
where the op had a similar issue.


Why would an error persist after after uninstalling the module?

This is 'normal' as your Twig files are being cached by Drupal. The easiest way to fix the issue is to run $ drush cache-rebuild (with Drush 8 which is the only release compatible with Drupal 8) which will handle all cache rebuild, including Twig cache. Alternatively, under sites/default/files/php you can safely delete the twig directory. If you're not in a multi web server environment, you can delete the php directory altogether, which will both delete the Twig cached files and the Service Container.


Sometimes a clear cache solves the issue.  Don't know if yours is the same issue but it happened to me and i cleared cache and it resolved the issue.


How do I update a site after its installation profile is updated?

I don't know if you have any problem using Drush to update the installation profile, but I use git and everything is fine.

If you have code (in the installation profile) that writes on the db and push this to production nothing will happen. So all your changes must done manually.

Finally, the installation profiles aren't the best way to maintain a site, after Drupal install nothing will happen.

About the 40sites take a look at Aegir. It's a hosting platform for Drupals.


Unable to install the XYZ module since it requires the A module

Adding the yaml_editor to core.extension.yml solved the issue.
It perhaps were removed due to a complex git merge, and that's why my install process started to fail all that sudden.


customizing an info window with geolocation views

Having clarified this with the developer, you need to alter the  ip_geoloc_gmap_multi_loc.js file at line
165.  This relates to the infoWindow maxWidth setting.  Essentially I have
tried to increase this massively.

This sorts out the problem for me, and the developer advised me that this should not cause a problem.

I couldn't work out how to do this with css.  Might be possible...but I couldn't work it out...

...hope this helps someone in the future, as it caused me quite a headache!

Thanks again for your posts,

Mark.


SWF Tools install/ setup of media players

Figured it out.  As you said chellman the version matter greatly.  I had to go under:
/admin/settings/swftools/flowplayer3 and under plugins I had to change the Player File from the default to flowplayer-3.0.7.swf.  Than you have to manually create the directory /sites/all/modules/swftools/shared/"flowplayer3" where you add the plugin.  So, there it is!


How can I add Zurb Foundation as a library?

You created the library, alright, but you need to call the library.

In [theme_name].info.yml add the following:

libraries:
  - '[theme_name]/foundation'

Also you need to modify your [theme_name].libraries.yml file and add dependencies:

foundation:
  version: 6.x
  css:
    base:
      includes/foundation/css/app.css: {}
      includes/foundation/css/foundation.css: {}
      includes/foundation/css/foundation.min.css: {}
  js:
    includes/foundation/js/app.js: {}
    includes/foundation/js/jquery.js: {}
    includes/foundation/js/foundation.js: {}
    includes/foundation/js/foundation.min.js: {}
    includes/foundation/js/what-input.js: {}
  dependencies:
    - core/drupal
    - core/jquery
    - core/jquery.once

As per Adding stylesheets (CSS) and JavaScript (JS) to a Drupal 8 theme


I have a solution for this.

First: I have just created one product type, with the field 'somethingTermReference'(term reference), wich will be the base of the production switcher.

Second: I created content types for every product category, for displaying them. Each content type has a type field with distinct values.

Third: I created views for every product category and there are 3 filter criterias for each view: published content, content type(actual product category), and one exposed filter on a product reference 'somethingTermReference' field.


How to subscribe a user to a group when the OG context is in the commerce order?

Try out following these steps

1) Using the Entity Reference module, I've created an entity reference on my product type. It's target type is "Node", and the Target Bundle is the content type of my Organic Group. In my case, that's called "Classroom".

2) I create a piece of content of type "Classroom".

3) I create a new product and a drop-down will show a list of all my Classrooms. I select one of them.

4) Now comes the time to make the rule to automatically add the user to the correct group.

Conditions
Event: Completing the checkout process

Conditions
Entity has field: commerce-order:commerce-line-items:0
.. Name of the field to check for: commerce_product

Entity has field: commerce-order:commerce-line-items:0:commerce-product
.. Name of the field to check for: field_og_reference (this is the name of my entity reference that I put on the product in Step #1).

Actions
Fetch entity by property.
.. Value: User
.. Property: Email
.. Value: commerce-order:mail
.. Limit result count: 1
.. Variable Label: Fetched Account
.. Variable Name: account_fetched

Subscribe User to Group
.. User: account-fetched:0
.. Group: commerce-order:commerce-line-items:0:commerce-product:field-og-reference:group

Solution 2
See tutorial about this, have a look:


Apply settings to all display overridden and default in views 3

Once its overridden there is nothing you can do to affect it globally.

I guess you could export the view and just add the field to the export code and then import the code.


How to filter nodes by role (Content Access for nodes activated)?

Data related to access permissions per node settings are stored in content_access table created by content access module along with acl module tables like ace and acl_node

It is stored in serialized format.. For example

Content access doesn't have any views integration to list content filtered by roles based on settings...

I am afraid you need to read serialized array and then filter nodes using code...

To read values per node see per node settings page code below implemented in content access module..

/**
 * Per node settings page.
 */
function content_access_page($form, &$form_state, $node) {
  drupal_set_title(t('Access control for @title', array('@title' => $node->title)));

  foreach (_content_access_get_operations() as $op => $label) {
    $defaults[$op] = content_access_per_node_setting($op, $node);
  }

  // Get roles form
  content_access_role_based_form($form, $defaults, $node->type);

  // Add an after_build handler that disables checkboxes, which are enforced by permissions.
  $form['per_role']['#after_build'] = array('content_access_force_permissions');

  // ACL form
  if (module_exists('acl')) {
    // This is disabled when there is no node passed.
    $form['acl'] = array(
      '#type' => 'fieldset',
      '#title' => t('User access control lists'),
      '#description' => t('These settings allow you to grant access to specific users.'),
      '#collapsible' => TRUE,
      '#tree' => TRUE,
    );

    foreach (array('view', 'update', 'delete') as $op) {
      $acl_id = content_access_get_acl_id($node, $op);
      acl_node_add_acl($node->nid, $acl_id, (int) ($op == 'view'), (int) ($op == 'update'), (int) ($op == 'delete'), content_access_get_settings('priority', $node->type));

      $form['acl'][$op] = acl_edit_form($form_state, $acl_id, t('Grant !op access', array('!op' => $op)));
      $form['acl'][$op]['#collapsed'] = !isset($_POST['acl_' . $acl_id]) && !unserialize($form['acl'][$op]['user_list']['#default_value']);
    }
  }

  $form_state['node'] = $node;

  $form['reset'] = array(
    '#type' => 'submit',
    '#value' => t('Reset to defaults'),
    '#weight' => 10,
    '#submit' => array('content_access_page_reset'),
    '#access' => count(content_access_get_per_node_settings($node)) > 0,
  );
  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Submit'),
    '#weight' => 10,
  );

  // @todo not true anymore?
  // http://drupal.org/update/modules/6/7#hook_node_access_records
  if (!$node->status) {
    drupal_set_message(t("Warning: Your content is not published, so this settings are not taken into account as long as the content remains unpublished."), 'error');
  }

  return $form;
}


How do you get a node ID from an order in ubercart?

I should have been clearer, its ubercart marketplace.

I got it to work this way:

$items = uc_cart_get_contents();
foreach ($items as $item) {
$product = node_load($item->nid);
      }


Make PDF,XLSX,DOCX,PPTX output for drupal REST server

Yes it's definitely possible, but you'll need to write a formatter class for each type of file as the bundled REST server only has support for XML, JSON, JSONP, serialized PHP, bencode, and optionally YAML.

To start, you need to implement hook_rest_server_response_formatters_alter to let the REST server know about your new type, e.g.:

function MYMODULE_rest_server_response_formatters_alter(&$formatters) {
  $formatters['pdf'] = array(
    'mime types' => array('application/pdf'),
    'formatter class' => 'MyModuleServicesPDFFormatter',
  );
}

Then add your formatter class, which needs to implement ServicesFormatterInterface and provide the render method:

class MyModuleServicesPDFFormatter implements ServicesFormatterInterface {
  public function render($data) {
    return some_function_to_convert_data_to_pdf_string($data);
  }
}

Then make sure that class is auto-loaded by putting this in your module's .info file:

files[] = relative/path/to/MyModuleServicesPDFFormatter.php

Repeat the process for all of the new formatters you wish to provide, clear the cache when you're done.


Form problem : calendar pop up overriden by an autocomplete field

Try:

input{
  position: relative !important;
  z-index: 0 !important;
}

You can change the "input" selector to meet your needs and try this without "!important" also.


Saving the module configuration form data

The form elements saved above will all be stored in the variables table.

Are you wanting to move this data or store it somewhere else? If not, then your answer is already in your code with the variable_get() default value.

system_settings_form()

  Add default buttons to a form and set its prefix.

System settings form will store your form data in the variables table and key it with the name of the form element.  For example, a form element defined as $form['foo'] will be retrievable by using variable_get('foo', NULL).  Because of this I always figure it's a good idea to namespace your form elements as you would functions (i.e. $form['mymodule_foo'])


Can I register an additional namespace to point to the modules folder

Splitting my comment over there into a separate answer then ;)

You can, yes, see system_register() and drupal_classloader_register(). Those helper functions hardcode "Drupal\" as they are all about modules, but you could get the class_loader service directly.

As @Clive said there, I would not recommend doing it for your own classes, there isn't really a reason to do so, unless you're including an external library.

External libraries is a different story, that can be useful. As already commented in How to autoload classes from a 3rd party PHP library in Drupal 8, if you do not want to depend on Composer Manager, then you can implement your own autoloader service and register them either by loading a composer-style autoload.php, or if you have it available in a different way, by directly registering it in the cloassloader service.


How to get the View Object from ViewsBlock?

I think there is no way to get the the view Object directly it's protected property and there is no method to get it:
From ViewsBlockBase

  /**
     * The View executable object.
     *
     * @var \Drupal\views\ViewExecutable
     */
    protected $view;

But there is a way first get the view id from the DerivativeId and then load the view here is a code snippet below:

  use Drupal\views\ViewExecutable;

  $blockManager = \Drupal::service('plugin.manager.block');
  $contextRepository = \Drupal::service('context.repository');
  // Get blocks definition.
  $definitions = $blockManager->getDefinitionsForContexts($contextRepository->getAvailableContexts());
  $views_blocks = [];
  foreach ($definitions as $id => $definition) {
    $id_type = explode(':', $id);
    if ($id_type[0] == 'views_block') {
      /** @var \Drupal\views\Plugin\Block\ViewsBlock $viewsBlock */
      $viewsBlock = $blockManager->createInstance($id);
      $derivativeId = $viewsBlock->getDerivativeId();
      $derivativeId_exploded = explode('-', $derivativeId);
      $view_id = $derivativeId_exploded[0];
      $view = Views::getView($view_id);
      $views_blocks[] = $view;
    }
  }

I hope that helps.


Twig date function not working on custom field within node

Before you need convert field field_my_date form 2021-10-01 to timestamp

You can use hook_ENTITY_TYPE_view_alter to be convert it to timestamp

use Drupal\Core\Entity\EntityInterface;
use Drupal\Core\Entity\Display\EntityViewDisplayInterface;

/**
 * Implements hook_ENTITY_TYPE_view().
 */

function hook_ENTITY_TYPE_view_alter(array &$build, EntityInterface $entity, EntityViewDisplayInterface $display) {
  if($display->bundle()=='node_type'){
    $field_date_timestamp = strtotime($entity->get('field_my_date')- >value);
    $build['field_my_date'] = \Drupal::service('date.formatter')->format(
    $field_date_timestamp, 'custom', 'M.d.Y');
  }
}

in file twig node tempalte {{field_my_date}}


How to change the draggable icon of new theme

I suspect it's similar to a problem I had with draggable table rows in a zen subtheme: the icon was just a bit mis-placed. Using Firebug or similar tools you can see what's going on – on my site it looked like this:

Using firebug I could see the reason for this:

The icon was mis-placed. So I suppose you probably don't have to change the draggable icon itself, but you'll have to adjust the position of the icon.

The css responsible for the position should look like this:

a.tabledrag-handle .handle {
background: url("../../misc/draggable.png") no-repeat scroll 6px 9px rgba(0, 0, 0, 0);
height: 13px;
margin: -0.4em 0.5em;
padding: 0.42em 0.5em;
width: 13px;
}

and you should find it in this system css file:
/modules/system/system.base.css

Instead of changing it in that system css file you should however override the settings in your theme's css file. You probably don't have to change much – just have to play around with the settings for margin and padding according to your theme… Hope this helps somehow?


drupal_mail() sends two emails, second email is empty

The drupal_mail() function you call will send an email.

Then when you call $system->mail($message); that will send a second email.

Here is an example of how to use drupal_mail (taken from here):

/**
* Implements hook_entity_insert().
*
*/
function dummy_module_node_insert($node) {
  $module = 'dummy_module';
  $key = 'dummy_key';
  $language = language_default();
  $params = array(
    '@url' => url('node/' . $node->nid, array('absolute' => TRUE)),
    '@title' => $node->title,
  );

  drupal_mail($module, $key, $mail, $language, $params);
}

/**
* Implements hook_mail().
*/
function dummy_module_mail($key, &$message, $params) {
  $message['subject'] = t("@title event registration confirmation", $params);
  $message['body'] = array();
  $message['body'][] = t("Hello", $params);
  $message['body'][] = t("Node has been created @title (@url).", $params);
}

The user who posted this code originally labeled it as "The propper way to use this:" and I've had success using this code before.


The module Draggableviews could be a solution here. It adds a table drag handler and a order field that is saved after you have rearranged the view. The same order field can then be used in another display if you want.


How do I find the Delta of a CCK Multivalue Field

I would suggest putting this in a node-TYPE.tpl.php instead of node.tpl.php unless this is your only content type, but anyway, here is a quick start to accomplishing what you asked for using a simple for loop:

<?php $max = max(count($node->field_before), count($node->field_after)); ?>
<?php for ($i = 0; $i < $max; $i++): ?>

Before <?php print !empty($node->field_before[$i]) ? $node->field_before[$i]['view'] : ''; ?>

After <?php print !empty($node->field_after[$i]) ? $node->field_after[$i]['view'] : ''; ?>

  <?php if ($i != ($max - 1)): ?>

------

  <?php endif; ?>
<?php endfor; ?>

This can obviously be tweaked to add a default value if a field lengths are different, or skip the checking if you know that each "before value" will have a corresponding "answer value".

Also, if using default "unlimited fields", a user could rearrange them via drag and drop and potentially screw up your data.  If this is a concern for you, you may want to look at Multigroup for CCK3.


How do I remove the "where" clause from a structured query object in hook_query_alter()?

That's pretty much all there is to it: in hook_query_alter() you only have access the query object from "outside" and, since there is no public API to remove conditions, it's kinda confusing.

However, there's some clever php hackery going on so if you call $where =& $query->conditions(); or any of the other examples in the documentation you linked it will return a reference to that corresponding variable.

So, in the where example above, you gain access to $query->where protected class variable.  If you inspect them you will see they are just basic php arrays containing all of the information and you can literally just unset something on that reference and be done.

So:

$where =& $query->conditions();
// Remove the second condition.
unset($where[1]);

Finally, specifically with where queries, you want to be mindful of the #conjunction and eventual more complex and/or grouping stuff.


trigger event before content is parsed after ajax

Are you using AJAX API? All the Ajax commands have the same return, for example

array(
    'command' => 'insert',
    'method' => 'html',
    'selector' => $selector,
    'data' => $html,
    'settings' => $settings,
);

And if you open the file misc/ajax.js, you will find insert() function in Drupal.ajax.prototype.commands. I think now you got the idea right? You just need to define a new ajax command by extending standard library, for example

Drupal.ajax.prototype.commands.lightbox = function (ajax, response, status) {
    // Do something with response.
};

And on server side, you just need to return

array(
    'command' => 'lightbox',
);

You can put more options in the command like what core does.