How to render formatted text field from paragraphs as is in twig?

This is the code I'm using inside one of my field templates to output a text field, which is used as an HTML/JS widget input box

{% for item in items %}
  <div{{ item.attributes }}>{{ item.content['#context'].value|raw }}</div>
{% endfor %}

Should work for you, I guess you'll have to remove the |raw filter for your case. (But usually it is not the recommended way to output fields this way.)


The code would go in hook_block_info(). You can use the pages property to define the list of pages the block should be shown on. e.g.

$blocks['recent'] = array(
  'info' => t('Recent content'),
  'pages' => 'dashboard',
  'visibility' => BLOCK_VISIBILITY_LISTED
);


How to add in-line styles to addressfield field?

Check out the CSS Injector module. It won't do inline styles, but you could always write a selector (which is the best practice anyway).


Aegir different site folder from site name

Using a different sitename would be your best option. You could then add an alias for the real sitename.


How do I add custom pages or view pages to search index?

Yes, it's possible to provide a custom search index for either the Core/Search API module. Both modules are using the D8 plugin API to create their own plugin types for providing new indexing.

In Core, the SearchPlugin plugin type allows you to define the methods that you will need to implement for all aspects of search. To see how this works, look at the core UserSearch & NodeSearch plugins to see how it interfaces with queries and indexing.
For SearchAPI, there are many different plugin types for interfacing with its different aspects of search. For brevity, you should start looking at the SearchApiDatasource plugin type to start providing a new indexable source.

In regards to an "abstract manner where the implementation would work using core database search or search api with solr," you're going to have to get clever with OOP and the plugin classes you're providing in your module if you want to do something like that. You're better off implementing each first, then abstracting later (if it provides benefits).


Choose a facet using the search form and then show filtered results

Here's my solution:

Add the select menu to the form and append a custom submit function

  function ucb_parking_form_alter(&$form, &$form_state, $form_id) {
  switch ($form_id) {
    case "search_block_form":
      // Add the audience select list
      $form['search_audience'] = array(
       '#type' => 'select',
       //'#title' => t('Choose Audience'),
       '#options' => array(
      47 => t('Faculty/Staff'),
      36 => t('Student'),
      ),
       '#description' => t('Focus your search on an audience.'),
      );
      //Add a custom submit function to the end of the array of functions.
      //(This function will run after apachesolr_search_form_search_submit().)
      array_push($form['#submit'], 'ucb_parking_front_page_search_submit');
      break;
  }

}

In the custom submit function construct the solr url with a query string representing the facet that should be applied and redirect the user there:

function ucb_parking_front_page_search_submit($form, &$form_state) {
  /*
   * Simply construct the solr url for the search.
   * Note the querystring for the facet must be passed via an array with the 'query' key
   * to ensure correct urlencoding.
   */
  $form_state['redirect'] = array($form_state['redirect'], array('query' => array('f[0]' => 'im_field_audience:' . $form_state['values']['search_audience'])));
  //drupal_goto is probably equivalent
  //drupal_goto($form_state['redirect'], array('query' => array('f[0]' => 'im_field_audience:' . $form_state['values']['search_audience'])));
}

I think that this is the correct approach because apachesolr does pretty much the same thing with $form_state['redirect']:

/**
 * Added form submit function to retain filters.
 *
 * @see apachesolr_search_form_search_form_alter()
 */
function apachesolr_search_form_search_submit($form, &$form_state) {
  $fv = $form_state['values'];
  // Replace keys with their rawurlencoded value
  if (isset($fv['search_block_form'])) {
    $raw_keys = str_replace("/","%2f",$fv['search_block_form']);
    $form_state['redirect'] = str_replace($fv['search_block_form'], $raw_keys, $form_state['redirect']);
  }
}


When programmatically adding views, what is a more efficient way to add them other than include them in mymodule.views_default.inc?

I'm not 100% sure if it'd help performance-wise, but it is possible to separate the Views into different files. In your case, this is probably useful anyway as that's a LOT of Views.

If you create a folder in your module called "views" (or whatever you want), then you can just add the following to your implementation of hook_views_default_views.

function MYMODULE_views_default_views() {
  $files = file_scan_directory(drupal_get_path('module', 'MYMODULE'). '/views', '/.view/');
  foreach ($files as $filepath => $file) {
    require $filepath;
    if (isset($view)) {
      $views[$view->name] = $view;
    }
  }
  return $views;
}

DISCLAIMER/CREDIT:

This code was taken from this blog post, and this comment, so make sure you pop over there and say thank you :)


take some time and watch these very informative new videos: Modules Unraveled Kudos to Brian Lewis aka bjlewis2


Alright so here's what I did, with help from MegaChriz.

The dev dependencies for Drush need to be installed and the phpunit version that comes with Drush should be used instead of a 'general' phpunit. So not the one I installed through composer.

Git clone of Drush from my home folder (/users/wim.mostrey)

git clone https://github.com/drush-ops/drush.git
cd drush
git checkout 8.1.9

Install Drush with dev dependencies using Composer while being inside the Drush folder

composer install

Execute built-in tests pointing to the phpunit version from Drush:

UNISH_NO_TIMEOUTS=1 /users/wim.mostrey/drush/vendor/bin/phpunit --configuration /users/wim.mostrey/drush/tests --filter=ImageCase

or for Drupal 7 tests:

UNISH_NO_TIMEOUTS=1 UNISH_DRUPAL_MAJOR_VERSION=7 /users/wim.mostrey/drush/vendor/bin/phpunit --configuration /users/wim.mostrey/drush/tests /users/wim.mostrey/Sites/drupal7/sites/all/modules/feeds/tests/drush


The load event in jQuery doesn't work with elements without URL. This is not a Drupal issue. You can't use it this way.


How to add a custom row class or ID to type table render elements

Can you try code the below.

$row = array('data' => 'some data');
$rows[] = array('data' => $row, 'class' => 'some class');
);

Or maybe

$row = array('data' => 'some data');
$rows[] = array('data' => $row, 'class' => array('some class'));

Reference answer https://www.drupal.org/forum/support/post-installation/2016-04-21/add-class-in-row-with-theme-table


Content is not a variable of a field template. This is the reason kint(content) does not produce any output. The content of the field is in items:

  {% for item in items %}

{{ item.content }}

  {% endfor %}

Did you try twig debug to find the right template?

Debugging Twig templates

Edit: (Template in question was edited to node template)

This is no problem to add divs and classes to the node twig. Here is an example:

        {{ content }}

I've added two container inside and outside the article tag and one class to the article tag itself.


Paging the list of comments, and getting the comment count

Paging on comments is provided in Drupal Core without any contribute modules.

If you go to your content type configuration screen:

D6 Path: admin/content/node-type/[node-type-name]
D7 Path: admin/structure/types/manage/[node-type-name]

You will see there's a Comment field-set/tab(d7) with some options. The option you want to check out is the comments per page setting. Select the number you'll like for when a page should break and save your settings. Once you're comment have pass that threshold you will see a pager for your comments.

Now for the comment counts there a variable available to you in both Drupal 6 and 7 in the node template. The name of that variable is $comment_count.


Under the Rules module add the event that fires After new user is created, then under conditions add a Data comparison, on the first step you should select your checkbox field, on clicking continue you will be presented with the options of this field, that is checked or unchecked.

Now add your action/s under the actions section.

If you want to also check when a user is modified, you should add a rule for the event Existing user is updated.


How do we configure SElinux to not break Drupal?

Looks like you are connecting to a remote host. You may need to allow httpd to make remote connections. Run these commands as root to set the SELinux variables.

setsebool -P httpd_can_network_connect 1
setsebool -P httpd_can_network_connect_db 1

http://alexbilbie.com/2013/02/selinux-php-mysql/


You can try Custom Breadcrumbs module.

  Many new features have been added including support for Views, Panels,
  Taxonomy vocabularies and terms, paths, and a simple API that allows
  contributed modules to enable custom breadcrumbs for module pages and
  theme templates. These are implemented using optional, independent
  submodules that depend on the main Custom Breadcrumbs module.

  In addition to breadcrumb visibility, this version provides an option
  permitting PHP code snippets to be used in forming the breadcrumb
  titles and paths. Multiple languages are also supported.

Another option is Panels Breadcrumbs module.

  Panels Breadcrumbs allows you to set your breadcrumbs directly from
  Panels configuration, and also allows you to take advantage from
  Panels arguments and contexts as placeholder tokens.


How to override the default image style for displaying user picture?

Use hook_preprocess_user_picture(). See template_preprocess_user_picture().

Here a sample code:

/**
 * Implements hook_preprocess_user_picture().
 *
 * @see template_preprocess_user_picture().
 */
function example_preprocess_user_picture(&$variables) {
  $style = 'your_style';

  $account = $variables['account'];
  if (is_numeric($account->picture)) {
    $account->picture = file_load($account->picture);
  }
  if (!empty($account->picture->uri)) {
    $filepath = $account->picture->uri;
  }

  if (isset($filepath)) {
    $alt = t("@user's picture", array('@user' => format_username($account)));
    $variables['user_picture'] = theme('image_style', array('style_name' => $style, 'path' => $filepath, 'alt' => $alt, 'title' => $alt));
  }
}


You can add your own CSS classes to the images via the WYSIWYG editor. The code provided on https://stackoverflow.com/questions/48474/how-do-i-position-one-image-on-top-of-another-in-html should do what you are looking for:

.parent {
  position: relative;
  top: 0;
  left: 0;
}
.image1 {
  position: relative;
  top: 0;
  left: 0;
}
.image2 {
  position: absolute;
  top: 30px;
  left: 70px;
}


You can achieve this in two ways

1) Add following style in your CSS

tr.view-subfooter-number{ display: none; }

OR

2) Go to  views-calc-table.tpl.php file under views_calc module directory and find the following code (PAGE SUM row code)

    <?php foreach ($row as $field => $content): ?>
      <td class="view-subfooter views-field views-field-<?php print $fields[$field]; ?>  <?php print $options['info'][$field]['align'] ?>">
        <?php print $content; ?>

    <?php endforeach; ?>

You can comment/remove the above code to hide 'PAGE SUM' row at view output.


Display Content with Taxonomy on User and content matching with Multiple Vocabularies

If I understood correctly you are trying to eliminate duplicates from your view.
Display only one title by content.

When I'm in a case when even Aggregation or Query Distinct settings don't seem to work (most of the time this is caused because the query left/inner joins),  I use a small script that does the trick to do an easy group by using the query comment field. In your case you could group by node.id

/**
 *  Found this trick on theoleschool.com.
 *
 *  Description: Allows the view developer to specify the query
 *  group by action in the query comments. Great way to force the
 *  removal of duplicates.
 *
 *  Just go into your query comments and type in "groupby:" with
 *  that colon followed by the field you want to group by.
 *
 *  Examples...
 *  groupby:node.nid
 *  groupby:file_managed_file_usage.fid
 *
 *  Ref-Comment: http://theoleschool.com/comment/496#comment-496
 *  Ref-Article: http://theoleschool.com/blog/using-hookviewsalter-add-group-statement
 */
function mymodule_query_alter(QueryAlterableInterface $query) {
  if ($query->hasTag('views')) {
    static $count;
    $view =& $query->getMetaData('view');

    if (strstr($groupby = $view->query->options['query_comment'], 'groupby')) {
      list($action, $field) = explode(':', $groupby);

      if (strlen($field) > 0) {
        $query->groupBy($field);
      }
    }
  }
}


Get directories & files of a theme in module

You are mixing filesystem path and URL path:

base_path(): Returns the base URL path (i.e., directory)
of the Drupal installation.
drupal_get_path(): Returns the path to a system item (module, theme, etc.).

The second argument for file_scan_directory() is the preg_match() regular expression of the files to find. You are using '0' which only match a single file named '0'.

file_scan_directory(DRUPAL_ROOT  . '/' . drupal_get_path('theme','sandesh') . '/' . 'layouts'); is all you need to do. Use base_path() only when building URL for which an existing helper function (url(), file_create_url(), etc.) cannot be used.


Possible solution of separating your caches, by regions, in Varnish is to use GeoIP VMOD: https://github.com/lampeh/libvmod-geoip

Simple example:

put country code to hash

sub vcl_hash {
        hash_data(req.url);

        if (req.http.host) {
                hash_data(req.http.host);
        }
        else {
                hash_data(server.ip);
        }

        # separate caches by countries
        hash_data(geoip.client_country_code());

        return (hash);
}

Now caches for different countries will be different.
Of course, you still need to take care about page generation in Drupal, it should provide different content for different regions too.


How to style map popup from GMap module?

infobubble.js is available as a patch: Add more theming options to popup bubble by using infobubble library plugin for Gmap module.

Have a look at it as it allows you to modify several parameters of the popups.

  shadowStyle - Options: 0 (no shadow), 1 (default shadow), 2 (sharp
  shadow)
  padding - Like the css property, the padding of the bubble.
  borderRadius - Like the css property, the radius of the bubble's
  corners.
  borderWidth - Like the css property, the width in pixels of
  the border.
  borderColor - Like the css property, the hex or rgb color
  of the border.
  backgroundColor - This is the background of the content
  of the bubble, but NOT the entire bubble itself.
  bubbleBackgroundClassName - A css class for the entire bubble.
  minWidth - Like the css property, the minimum width of the bubble.
  maxWidth - Like the css property, the maximum width of the bubble.
  minHeight - Like the css property, the maximum height of the bubble.
  arrowSize - The width of the pointer arrow. NOTE: if you choose an
  arrow style that only uses half of the arrow, this number will be
  twice as wide as your arrow at its widest point.
  arrowPosition - The
  percent from the left of the bubble where the arrow will appear.
  arrowStyle - Options: 0 (full triangle), 1 (half triangle leaning
  left), 2 (half triangle leaning right)
  closeImage - The url of the
  image to use as the close button for the bubble An example of most of
  these options can be seen on the infobubble examples page.


How to use the stomp module to send and receive a queue?

Drupal supports its own Queue interface out the box. See https://api.drupal.org/api/drupal/modules%21system%21system.queue.inc/group/queue/7  The stomp module when configured simply moves the queue infrastructure out of Drupal and into a 3rd party system.

See the readme on this integration settings http://cgit.drupalcode.org/stomp/tree/README.txt


Is there a module for site explanation messages?

The closest module I know is the Legal module, this is more for showing the terms of service or similar for users before registering, but it might be close to what you need.


Short version: You need to define a cache tag that you can invalidate when a record is created, updated or deleted.

See https://www.drupal.org/docs/8/api/render-api/cacheability-of-render-arrays for a lot of documentation on this.

I'd also recommend to look into using an entity type for this instead of a custom table. A bit of effort at first, but you get a ton of functionality with that, including default cache tags and for example views integration, so you can build searchable, sortable listings like that through views.


Don't use Contextual filters in this case, cause they are sent in url - use exposed filter.

Exposed filter will create form, which you can fill in and submit by js-code. Turn on AJAX fro view and filters will also work via AJAX.


How to add a result count in exposed filters?

There's no use trying to use hook_form_alter, as you need to wait until the view is rendered.  You can do this in hook_preprocess_views_view__VIEWNAME like this:

function examplemodule_preprocess_views_view__exampleview(&$variables) {
  $result = $variables['header']['result'];
  unset($variables['header']['result']);
  $variables['exposed']['result'] = $result;
}


How to redirect a cancel button to destination on each form?

In your code above, you're using wrong value for #submit. #submit accepts an array of submit callback function names, check e.g. here.

You can either add a link in form, which will take user to destination and style the link to look like a button. Check example below:

function _custom_form() {
  $form['actions']['cancel'] = array(
    '#type'   => 'markup',
    '#markup' => '
' . l(t("Cancel"), 'URL', array('attributes' => array('class' => array('form-cancel-button')))) . '
',
  );

  return $form;
}

OR you can create a normal submit button and add a custom submit handler which will take user to destination. Check example below:

function _custom_form() {
  $form['actions']['cancel'] = array(
    '#type'   => 'submit',
    '#value' => "Cancel",
    '#weight' => 55,
    '#submit' => array('_custom_form_cancel')
    '#limit_validation_errors' => array(),
  );

  return $form;
}

function _custom_form_cancel($form, &$form_state) {
  drupal_goto('URL');
}

Note: When you define a custom form element, you don't need to give #access property specifically, it is TRUE by default.


How to show block on pages with URLs containing a question mark ( 'searchquery' )?

You can use the Block Conditional Visibility by URI Query Parameters module to control block visibility via query string.

  Controls block visibility by URI Query Parameters. Drupal natively allows blocks to be placed on pages by using their paths, however, this module allows administrators to also display modules based on url query parameters.


Link items from Feeds module to original blog

I'm assuming you're using an RSS/Atom feed, and that you're using the node processor in your feed importer. In your feed importer settings, you can edit the node processor mappings. Add a mapping from the "Item URL (link)) to some text field in the content type you import to. Then you can use that field to create links back to the external url in views, and in the template files for the content type.

Once you have the url field, go through the following steps.

create a view of feed items. /admin/structure/views/add

a. select "show CONTENT of type Feed Item". You can create a block or a page. Either way:

b. select "display unformatted list of fields"

c. click "continue and edit"
add fields.

a. add Feed item URL. select "exclude from display".

b. add  content title. Make sure it appears after the feed item url in the fields list. Select "rewrite results", then "output this field as link". Click on "replacement patterns" to reveal the tokens you can use. Insert the token for "feed item URL" in the "link path" field, and select "external URL". Save the view.
if you've created a page, you'll need to give it a path. If you've created a block, you need to go to structure > blocks and assign the block to a region.

Hope that helps.


Form API submit handler does not get called

You can try the following :

 function email_action($form, &$form_state) {

    $form['#submit'][] = 'email_action_submit';

    }

    //submit function for the form

    function email_action_submit($form, &$form_state) {

    // write your submit code here
    }


Displaying parent nodes with child nodes - nested views, hard coding, or other approach?

Per the creator, the answer is in the comments with some additional documentation here: http://drupaleasy.com/blogs/ultimike/2009/02/displaying-hierarchical-content


What is the drush sql-sync arguments for modules, themes, sites, but "not core"?

There are also the --structure-tables and --skip-tables options. The --skip-tables option will completely remove the tables when dumping or syncing, while the --structure-tables option will sync table structure but not the data.

I don't think you want to drop the core modules tables in your development enviroment, so I suggest adding the tables to the --structure-tables option. You can add configure drushrc.php to have the tables listed separately, like this:

$options['structure-tables']['common'] = array(
  'cache', 'cache_*', 'history', 'search_*', 'sessions', 'watchdog');

And then you can use the --structure-tables-key option:

drush sql-sync --structure-tables-key="common" @project.prod @project.dev


Composerise Drupal command syntax and starting location

composer-root should not be your Home directory. It looks like you might have assumed that because there is a directory named git there, but that's not what the installation instructions at https://github.com/grasmash/composerize-drupal are referring to. Those instructions assume that your project files are being tracked as part of a Git repository. You can tell where the root of a Git repository is because it contains a directory called .git (note the dot in front, which the git directory in Home doesn't have).

If your project files are indeed part of a Git repository, the root would be in one of the upward directories from /opt/lampp/htdocs/d8/web.

  So is --drupal-root=./opt/lampp/htdocs/d8/web ??

Almost. The drupal root is where the core directory and index.php can be found. But that . in there makes this a relative directory path. You almost certainly mean to use an absolute path there, which would be --drupal-root=/opt/lampp/htdocs/d8/web.

  So is composer-root=./home ??

No. Most likely, you will want your composer-root to be one directory up from your project root (where index.php is). So I'd try --composer-root=/opt/lampp/htdocs/d8.


How to build multivalue form elements using Form API

Suppose 'field_page_collection1' is the field collection for the 'page' content type having two text fields 'field_page_collection1_text1', 'field_page_collection1_text2'.

To attach or create field-collection item for node having node id 1.

<?php
$node = node_load(1);
$field_collection_item = entity_create('field_collection_item', array('field_name' => 'field_page_collection1')); // Create new field collection item.
$field_collection_item->setHostEntity('node', $node); // Attach it to the node.
$field_collection_item->field_page_collection1_text1[LANGUAGE_NONE][0]['value'] = 'some value for text field 1'; // Fill value for field_page_collection1_text1.
$field_collection_item->field_page_collection1_text2[LANGUAGE_NONE][0]['value'] = 'some value for text field 2'; // Fill value for field_page_collection1_text2.
$field_collection_item->save(); // Save field-collection item.
?>


How do I set a path alias for each forum?

It is possible to add a path alias to a forum, without installing any third-party modules.
You could install the Pathauto module, but that is more for automatically assigning the path aliases when creating/editing an entity, or for bulk-assigning path aliases to existing entities. If you install the Pathauto module to create path aliases for the forums, notice that under Enabled entity types on /admin/config/search/path/settings, you don't see an entry like Forum. Use the default values for that form field (which include Content and Taxonomy term that you cannot deselect), and you will be able to set path aliases for the forums.

It is a quite confusing, since in /admin/config/search/path/patterns/add you need to select Forum for Pattern type.

Maybe it would be less confusing if Forum would be an option for Enabled entity types too.

In this case, anyway, the path aliases that the Pathauto module says to assign to forums are really assigned to the taxonomy terms associated with the forums. The effect of this is that the /forum page would not use any path alias for the forum links.

I created a sandbox site on simplytest.me, and I just enabled the Forum module. I created two forums (Module development and Theme development), and created a forum topic (Porting the "User activity" module to Drupal 8). I went to /admin/config/search/path, and created the following path aliases.

/forums/1/general-discussion pointing to /forum/1
/forums/2/module-development pointing to /forum/2
/forums/3/theme-development pointing to /forum/3

Doing so, the /forum page used the path aliases I set, in the links to the forums, but the forum topic pages used links like https://dsze.ply.st/taxonomy/term/2 under Forums.

So, or you set a path alias that is used from the /forum page (but not from the forum topic pages), or you set a path alias that is used from the forum topics page (but not from the /forum page), or you set two different sets of path aliases (a set used from the /forum page, and a set used in the forum topic pages).


Assuming you have a pathauto setting, such as, "the-base-from-the-auto-setting/[nid]", and all of these nodes use the automatic alias and not a custom alias, you can implement hook_init() in a custom module:

function mymodule_init () {
  $path = drupal_get_path_alias(request_uri());

  if (strpos($path, "/the-base-from-the-auto-setting/") !== false) {
    drupal_goto("/the-path-of-the-view/", NULL, NULL, 301);
    exit;
  }
}

Note that drupal_goto() calls exit on its own, but I keep the exit there as a reminder.

The above is untested, but modified from a code snippet that I frequently use that does a drupal_not_found().  See http://drupal.org/node/846930#comment-3451328 for more details.


Creating media_bundle entities programatically

use Drupal\media_entity\Entity\Media;

$image_data = file_get_contents("URL OF FILE");
$file_image = file_save_data($image_data, 'public://FILENAME', FILE_EXISTS_REPLACE);
$media_image = Media::create([
  'bundle' => 'image',(YOUR BUNDLE)
  'name' => "FILENAME",
  'field_image' => [
    'target_id' => $file_image->id(),
  ],
]);
$media_image->save();

Try this one, maybe this will help.


How to configure the toolbar in CKEditor?

It's possible you are using a version of CKEditor (the editor, not the drupal module) that doesn't have the font size and family plugin.

See the different versions at http://ckeditor.com/download (click the "Compare packages" link to see what is included in each package).

On that page you can see that only the full version has the "Font Size and Family (font)" package, so if you are using one of the other version then it won't have that package.

It is also possible to use the "Or let me customize CKEditor" option to create a custom version of CKEditor that contains just the plugins you require.
If using that make sure you include the "Font Size and Family (font)" package.

There is an issue here on Drupal.org regarding messages to the admin to notify them of missing plugins.


How to retrieve ConfigEntity instance from config factory?

\Drupal::config()

  Retrieves a configuration object.

  This is the main entry point to the configuration API.

The configuration API is a different system than the entity API.

$entity = \Drupal::entityTypeManager()
  ->getStorage('my_config_entity')
  ->load($id);

Configuration entity types should be used to store configurable content like content types or other site builder-esque things that you want to deploy from environment to environment that is not managed content (Something a content author would write).

If you're looking for a complex configuration object, then you should define that in config/mymodule.settings.yml and use the configuration API like in your question.


Display comment count of referencing nodes

Solved using the following workaround (patched #231 of #1349080 required):
add a second level relation discussion->comments and then use the aggregation with count distinct operator over the id field of the comments.


You may be able to use "Rewrite the output of this field" to wrap the image in a link using the "replacement pattern" token for the PDF file url as the href there.

Note you can "Exclude field from display" to add a field to the token list without displaying it.

You'll also need to drag the field, in the field order, above the one you want to use it in as a token for it to be available.

hth


Meta tags aren't saved with all content types

There is an issue with the module.

Try the following code in node.tpl.php.

render($content['metatags']);

Alternatively, try with the following code in page.tpl.php.

print render($page['content']['metatags']);


Download D7 module using Composer for D8?

If I were you, I would just use wget.

Copy the Zip file url, ex:

sudo wget https://ftp.drupal.org/files/projects/views-7.x-3.24.zip

and then

sudo unzip views-7.x-3.24.zip


Call $created variable in content type node template

The $created variable is just a number, but it's not random it is a unix timestamp of the node created date.

Since it is not a render array you do not print it using the render() function, you would just print it like this:

<?php print $created; ?>

However that is also probably not what you want because you probably want a human readable date/time, not a unix time stamp.

As you can see in the main variable preprocess function for the node template (template_preprocess_node()), there is also a variable $date, which is a formatted date based on the $created variable.
That will default to using your website's medium date format.

You can use it like this:

<?php print $date; ?>

If that is not the format you want you can also manually use the format_date() function to format it to your requirements like this:

<?php print format_date($created, 'short'); ?>

or like this for something more custom:

<?php print format_date($created, 'custom', 'd/m/Y'); ?>

See the php date() documentation for more information on custom date format options.


How to display the un promoted to front page link in teaser mode contextual links?

Contextual links can be added by adding a menu item (e.g. hook_menu() or hook_menu_alter()) and setting context to MENU_CONTEXT_INLINE & type to MENU_LOCAL_ACTION. For node actions, you can add a menu item to the node/% route. The nid argument can be passed through so you can execute your appropriate node frontpage toggle logic.

For example:

/**
 * implements hook_menu_alter().
 */
function MYMODULE_menu_alter(&$items) {
  $items['node/%/frontpage'] = array(
    'title' => 'Toggle Frontpage Status',
    'type' => MENU_LOCAL_ACTION,
    'context' => MENU_CONTEXT_INLINE,
    'page callback' => 'MYMODULE_toggle_frontpage',
    'page arguments' => array(1),
    'access arguments' => array('administer content'),
  );
}

function MYMODULE_toggle_frontpage($nid) {
  // @TODO: Add your $node->promote switching logic.

  // Jump back to the original page containing the context menu.
  drupal_goto(drupal_get_destination());
}


How allowing img tag in formats can be dangerous?

Project page of security review module says

  Text formats don't allow dangerous tags (protecting against XSS)

  Cross-Site Scripting (XSS) attacks are a type of injection, in which
  malicious scripts are injected into otherwise benign and trusted web
  sites. XSS attacks occur when an attacker uses a web application to
  send malicious code, generally in the form of a browser side script,
  to a different end user. Flaws that allow these attacks to succeed are
  quite widespread and occur anywhere a web application uses input from
  a user within the output it generates without validating or encoding
  it.

  An attacker can use XSS to send a malicious script to an unsuspecting
  user. The end user’s browser has no way to know that the script should
  not be trusted, and will execute the script. Because it thinks the
  script came from a trusted source, the malicious script can access any
  cookies, session tokens, or other sensitive information retained by
  the browser and used with that site. These scripts can even rewrite
  the content of the HTML page.

For example you can use img tag as below for XSS attack..

<img src='#' onerror=alert(1) />


For link, it's easy to provide in field--myfield.tpl.php:

$items[0]['#path']['options']['attributes'] = array('style'=>'border-style: none !important;');

But image doesn't have this, so you can miss upper code and rewrite formatter in template.php (add attributes there).

/**
 * Returns HTML for an image field formatter.
 *
 * @param $variables
 *   An associative array containing:
 *   - item: An array of image data.
 *   - image_style: An optional image style.
 *   - path: An array containing the link 'path' and link 'options'.
 *
 * @ingroup themeable
 */
function YOURTHEMENAME_image_formatter($variables) {
  $item = $variables['item'];
  $image = array(
    'path' => $item['uri'],
    'alt' => $item['alt'],
  );
  // Do not output an empty 'title' attribute.
  if (drupal_strlen($item['title']) > 0) {
    $image['title'] = $item['title'];
  }

  if ($variables['image_style']) {
    $image['style_name'] = $variables['image_style'];
    $output = theme('image_style', $image); // Here you should add attribute, check that it's your field.
  }
  else {
    $output = theme('image', $image);
  }

  if (!empty($variables['path']['path'])) {
    $path = $variables['path']['path'];
    $options = $variables['path']['options'];
    // When displaying an image inside a link, the html option must be TRUE.
    $options['html'] = TRUE;
    $output = l($output, $path, $options);  // Here you should add attribute, check that it's your field. Or just take upper code.
  }

  return $output;
}


How can alter the select options provided by Simple hierarchical select?

Finally, I was able to resolve it by using the module handler "shs_term_data_response". Like below

function YourModuleName_shs_term_data_response_alter(&$content, $context) {
  $termList = json_decode($content);
  $filteredList = array();
  /..your logic to modify $termList and push it to new array.../
  $content = json_encode($filteredList);
}

Hope it may help someone :)


ExtensionDiscovery::scanDirectory() takes too long

If you need the file_scan_ignore_directories setting changed, you should add the $settings['file_scan_ignore_directories'] assignment in your settings.php, not default.settings.php lest it's overwritten when you update Drupal core.
Regarding what path strings to add to $settings['file_scan_ignore_directories'], that's up to you. As the comment block states, that setting affects all calls to ExtensionDiscovery::scanDirectory() and FileSystem::scanDirectory() (if a nomask option isn't specified).
Add the most inclusive path that you know will never contain extensions or files to be scanned/discovered.


Can "Demonstrate block regions" use a specific template?

In order for a region to show up on the demonstration block, you need to define it in your theme's .info file and print the region in page.tpl.php (or the overrided version). The following could be the issue

Cache is not cleared (i.e. drush cc theme-registry if you are using drush)
Theme's .info file has not listed the new region
Page template is not overrided properly
The region is not printed properly in .tpl.php file

I would say, have a look into guide on how to override a template file prpperly here https://www.drupal.org/node/1089656 and https://www.drupal.org/node/223440#custom-suggestions.

If you would like a region to NOT show up on the front page, you can simply do not supply content to it and Drupal will not render it.

If you would like to add an extra region, then google for some tutorials on how to create custom regions.

Install Devel related modules.

devel_themer module, make it very easy to do themeing in Drupal, specially if you are new.

If you have devel_themer installed and enabled, then you can click on the page and see which template file is being used to render the page. You can click on regions, blocks and elements and it will give you details on how it is rendered and which template/function being used.

Hope this general answer help you.


What hook should I use to attach a script to a content type?

It depends on how you want to approach it. Clive's question is still relevant, Javascript redirects are neither great or optimal. However, if it must redirect based on a User Agent, Javascript might be the only option.

I would advise you to do the agent detection on the client side, as the server value may not always be accurate. Your code above won't work.

To load a script based on content type, you can do:

function mytheme_preprocess_node(&$variables) {
  if ($variables['node']->type == 'mytype') {
    $variables['#attached']['js'][] = array(args);

    // or

    drupal_add_js('path/to/script.js');
  }
}

Your script itself also needs to be in a closure:

/**
 * @file
 */
(function () {

  "use strict";

  // All the JavaScript for this file.

})();

If jQuery or the Drupal scope is needed:

/**
 * @file
 */
(function ($, Drupal) {

  "use strict";

  // All the JavaScript for this file.

})(jQuery, Drupal);

See the docs page for more:

https://www.drupal.org/docs/7/api/javascript-api/managing-javascript-in-drupal-7
https://www.drupal.org/docs/develop/standards/javascript/javascript-coding-standards


Drupal7 creating breadcrumb from url of custom page template

The custom breadcrumbs module can handle adding breadcrumbs to views.

The readme has information on how to use it.

The recommended module for breadcrumbs is path breadcrumbs.


How can I display a login and registration form, with an extra field on registration, and hybridauth in a modal?

Yes, this has a common solution with preexisting modules. Here's the summary with your 3 requirements:

Forcing capture of telephone on registration:

After enabling the Telephone module, you can add a phone field on a user entity (http://example.com/admin/config/people/accounts/fields). When you create the field, make sure the Display on user registration form & Required field checkboxes are ticked to enforce user submission of this data on registration & edit.

Hybridauth Social Login:

After enabling the module, and installing the libraries to the sites/all/libraries directory, configure each social network and set your other login options accordingly.

Modal Popup:

The Modal Forms module enables popup modals for the both the user/login & user/register paths. The popup presents the same login form as you see in Drupal so it will contain the HybridAuth login elements as well. The module lets you configure modal popups on a per-page basis so you can choose the pages where you want login/registration presented as modal form.


What are best practices for reusing blocks between sites?

Page Manager, Panels and Features.

The plugin architechture in Ctools, which is the project in which Page manager belongs, is the best way to re-use blocks, among other things.

All my block placements are done with Panels, and then exported to code with features.


Use different settings for a Views' block basing on the content type of the node being shown

You can use Entity Views Attachment to attach your view to those content types instead of using blocks. EVA will allow you to pass in the content type of the current article as a contextual filter.


Some things you can try:

The easiest way, in my opinion, is to look at the source of your page. Right click the page of your website and click "View source" (or something similar). Try searching for the reference to the javascript file in there.

This could be somewhat more difficult if you're using Javascript aggregation, which means that your file might be concatenated with other Javascript files into one big file. In that case: open the files you see in your source and search for something that's in your Javascript file.

You could also try to display an alert by appending alert('It works!') to your file.

Edit:

As said by Clive in the comments: you might need to clear your cache for the Javascript file to be included. You can clear the cache at /admin/config/development/performance.


How to retrieve the order id of an order in drupal commerce?

If you're looking for the order ID related to the current cart you can use commerce_cart_order_id():

$order = commerce_order_load(commerce_cart_order_id());

But you shouldn't use it directly in a template file. Use a preprocess hook instead, it's better all round.


Paginate results of entity reference widget type

Found a nice article related to Entityreference Multiselectors here.

You can choose one from variety of options mentioned in above article which suggests using of

Using of Multiple Selects.
Using of Chosen
An additional possibility is the Dynamic Multiselect Widget.
Another option is Entityreference Views Widget
There is jQuery UI Multiselect
And Improved Multiple Select

Hope one of the above works for you :-)


selecting all field_data_body for all content types

I needed to do something a bit similar a while ago, and used the drupal field definition tables to identify the field type (text/long et al) and work from there to the nodes. I suggest you do likewise.

You could consider using the mysql fulltext search facilities - it is much faster and much more capable than 'like'.

Of course, the drupal way would be to configure the search module properly...


Adding a radio button to a Drupal View page

Use HTML <form>, ex: w3schools.com/html/tryit.asp?filename=tryhtml_form_radio

To "inject" your code you could add a header text field to your view OR create a template file for your view.


How can I let a group of users edit anything in a specific section?

It's not clear to me what your rule for determining access control is. I'm going to guess it's menu paths.

I had a similar problem recently. I needed to ensure that users trying to access /somePathName/* were of a certain role. This is a bit of an odd scenario since any path in the system could be aliased under one of my UAC paths and it will automatically become access controlled whether it was a term, node, user, whatever.

I looked into existing solutions and found none. I wrote my own module that managed access control based on "arg(1)" and a user's roles.

Access control in Drupal is one of those pieces that you understand after a few hours of studying, do the work, then completely forget how you did it. Or maybe that's just me.

Documentation on Drupal.org is pretty good on this topic. Be sure to install the Devel module and enable the node access modules it provides. They are very useful.


Translated menu items with menu_build_tree in drupal 7

Normaly I use i18n_menu_translated_tree function. For example:

$main_menu_tree = i18n_menu_translated_tree(variable_get('menu_main_links_source', 'main-menu'));


How do I programmatically delete a node by internal url alias?

After some digging around through the available services and core classes, I have determined you need to get the nid through the path.alias_manager.  Additionally you need to wrap everything in a couple of conditions or you will throw errors if the path does not exist.  (eg. if you are trying to roll this change out to a fleet of sites that might or might not have this path already)

Below is my example code:

  // Check the path is valid before proceeding.
  $pathIsValid = \Drupal::pathValidator()->isValid('/blog');

  if ($pathIsValid) {
      $alias = \Drupal::service('path.alias_manager')->getPathByAlias('/blog');
      $params = Url::fromUri("internal:" . $alias)->getRouteParameters();
      // Get nid.
      $nid = $params[$entity_type];
      $node = Node::load($nid);

      // Check if node exists with the given nid.
      if ($node) {
      $node->delete();
    }


How do I add classes to form elements in the theme layer?

This is an ideal situation for a preprocess function.

I don't have Drupal 7 working to test at the moment, but something like this in your template.php should do the trick.

function mytheme_preprocess_textfield(&$vars) {
  static $counter = 0;
  $counter++;
  $vars['element']['#attributes']['class'][] = 'test' . $counter;
}


Table Drag problem with Jquery Update to jquery 1.4 and highers

The problem is that newer jQuery .after function returns the content to be added if you invoke it on an empty list. This breaks the tabledrag.js makeDraggable function.

The following patch that function fixed it for me:

   // Insert the handle after indentations (if any).
-  if ($('td:first .indentation:last', item).after(handle).size()) {
+  var td = $('td:first .indentation:last', item);
+  if (td.size() > 0) {
+    td.after(handle);
     // Update the total width of indentation in this entire table.


I would recommend that you use views as your source for the list of jpegs to output your XML file from. Using Views for example, I was able to make list of event images and make a custom XML file used to display the images in the Cub3r Flash plugin (I thought it was a bad idea but the client really wanted a Flash slideshow). I used the Views Bonus Pack export module, that gave me a style 'XML file'. I had only the image field, that was set to output the full image URL, the label I set it to was used as the custom tag. I then did an override of the XML template that came with the module and customized it to my needs (adding config parameters to cub3r).

Hopefully this will help you out. I also saw that the export module now has a fork that uses the batch API. Make sure you also checkout the Views data source module.


Track Simplenews newsletter open per user

As you mentioned, you need a unique values for GA tracking pixel. You need to utilize Simplenews's integration with the Token module so you can insert unique values into the URL for each newsletter copy that goes out.

For example, the inserting the token [simplenews-subscriber:user:uid] will let embed the unique user id into each tracking pixel copy.

The tokens will vary depending on the details you need to track, but Token integration should provide almost every detail you need.


How to reset Drupal's content cache / deleted content?

Unless you are using some module that I havent heard of (certainly possible) to give autocomplete style info as you are entering a node title, then I think the functionality you are describing is actually something being done by your browser.

You can alter your form to add automcomplete="off" to your title field (see https://stackoverflow.com/questions/2530/how-do-you-disable-browser-autocomplete-on-web-form-field-input-tag)


How can I build my own jquery ui theme and select it?

Use libraries-override in mytheme.info.yml.

These are examples from test_theme.info.yml:

libraries-override:
  # Replace an entire library.
  core/drupal.collapse: test_theme/collapse
  # Remove an entire library.
  core/drupal.progress: false
  # Replace particular library assets.
  classy/base:
    css:
      component:
        css/components/button.css: css/my-button.css
        css/components/collapse-processed.css: css/my-collapse-processed.css
        css/components/container-inline.css: /themes/my_theme/css/my-container-inline.css
        css/components/details.css: /themes/my_theme/css/my-details.css
  # Remove particular library assets.
  classy/dialog:
    css:
      component:
        css/components/dialog.css: false
  # It works for JS as well.
  core/jquery:
    js:
      assets/vendor/jquery/jquery.min.js: js/collapse.js
  # Use Drupal-relative paths.
  core/drupal.dropbutton:
    css:
      component:
        /core/themes/stable/css/core/dropbutton/dropbutton.css: /themes/my_theme/css/dropbutton.css
  # Use stream wrappers.
  core/drupal.vertical-tabs:
    css:
      component:
        /core/themes/stable/css/core/vertical-tabs.css: public://my_css/vertical-tabs.css
  # Use a protocol-relative URI.
  core/jquery.ui:
    css:
      component:
        assets/vendor/jquery.ui/themes/base/core.css: //my-server/my_theme/css/jquery_ui.css
  # Use an absolute URI.
  core/jquery.farbtastic:
    css:
      component:
        assets/vendor/farbtastic/farbtastic.css: http://example.com/my_theme/css/farbtastic.css

Reference: https://www.drupal.org/docs/8/theming-drupal-8/adding-stylesheets-css-and-javascript-js-to-a-drupal-8-theme See subsection Overriding and extending libraries


How can I group view results based on the week of the year using a date field?

You can do this without using a PHP field (or similar). Those modules are usually bad practice to put PHP into the database like that.

You can create a date format in Drupal for 'Week'.  Then you add the date field to the View and use this week format.  That will output the value of the date as a week #.  Then you group on that value.

A views filter can also help restrict the view to now + 4 weeks.  And some views theming can make each week header be whatever you need it to be.


Create a field programatically with let me to introduce two values

Download the examples module and look through the Field Example module.

It contains extensive code examples that show you in detail how to create a custom field, widget and formatter.


Programmatically enable Mollom protection for a form

I didn't find a better way, so I did inserts directly into the DB.

In mymodule.install:

function mymodule_update_70001() {
  # CAPTCHA on registration form
  db_insert('mollom_form')
    ->fields(array(
      'form_id' => 'user_register_form',
      'mode' => 1,
      'checks' => 'a:0:{}',
      'discard' => 1,
      'enabled_fields' => 'a:0:{}',
      'strictness' => 'normal',
      'module' => 'user',
    ))
    ->execute();

  # CAPTCHA on password reset form
  db_insert('mollom_form')
    ->fields(array(
      'form_id' => 'user_pass',
      'mode' => 1,
      'checks' => 'a:0:{}',
      'discard' => 1,
      'enabled_fields' => 'a:0:{}',
      'strictness' => 'normal',
      'module' => 'user',
    ))
    ->execute();

  # Text analysis of comments
  $response = db_insert('mollom_form')
    ->fields(array(
      'form_id' => 'comment_node_mynode_form',
      'mode' => 2,
      'checks' => 'a:2:{i:0;s:4:"spam";i:1;s:9:"profanity";}',
      'discard' => 0,
      'enabled_fields' => 'a:2:{i:0;s:7:"subject";i:1;s:27:"comment_body][und][0][value";}',
      'strictness' => 'normal',
      'module' => 'comment',
    ))
    ->execute();

  # Text analysis of submission
  $response = db_insert('mollom_form')
    ->fields(array(
      'form_id' => 'mynode_node_form',
      'mode' => 2,
      'checks' => 'a:2:{i:0;s:4:"spam";i:1;s:9:"profanity";}',
      'discard' => 0,
      'enabled_fields' => 'a:4:{i:0;s:5:"title";i:1;s:19:"body][und][0][value";i:2;s:32:"field_projectpage][und][0][value";i:3;s:33:"field_downloadpage][und][0][value";}',
      'strictness' => 'normal',
      'module' => 'node',
    ))
    ->execute();
}


How to add an edit and delete button to a custom html table?

$query = db_select('mytable', 'n')
    ->fields('n')
    ->execute();
  $rows = array();
  while($data = $query->fetchAssoc()){
  // Fill the table rows
    $data['operation'] = l(t('Delete'), 'admin/mid-modules/component/' . $data['cid'] . '/delete');
    $data['operation'] .= "|";
    $data['operation'] .= l(t('Edit'), 'admin/mid-modules/component/' . $data['cid'] . '/edit');
    $rows[] = array('data' => $data, 'style' => 'word-break:break-all;',);
  }

  // Prepare table header
  $header = array( t('S.No'),t('Component Name'));
  // Output of table with the paging
  $output = theme_table(
    array(
      "header" => $header,
      "rows" => $rows,
      "attributes" => array(),
      "sticky" => true, // Table header will be sticky
      "caption" => "",
      "colgroups" => array(),
      "empty" => t("Table has no row!") // The message to be displayed if table is empty
    )
  );
  return $output;
//following menus that delete or edit your selected content

    $items['admin/mid-modules/component/%ctools_js'] = array(
    'page callback' => 'popup_callback',
    'page arguments' => array(3),
    'access callback' => TRUE,
    'type' => MENU_CALLBACK,
    'file' => 'popup.inc'
  );
 $items['admin/mid-modules/component/%/delete'] = array(
    'title' => 'Delete Component item',
    'page callback' => 'delete_me',
    'page arguments' => array('delete_component_record_comfirm',3),
    'access arguments' => array('administer users'),
    'type' => MENU_CALLBACK,
    'file'=>'delete_record.inc',
  );

/**
 * Delete  Record Confirmation ------------------------------------
 */
function delete_component_record_comfirm($form, &$form_state, $cid){
   // print_r($cid);exit;
 $form['delete'] = array(
    '#type' => 'value',
    '#value' => $cid,
  );
  return confirm_form(
    $form,
    t('Are you sure you want to delete this?'),
    'admin/mid-modules/component/'. $data['cid'],
    t('This action cannot be undone.'),
    t('Delete'),
    t('Cancel')
  );
}
/**
 * Delete Survey Record Function
 */
function delete_component_record_comfirm_submit($form, &$form_state) {
  $record = $form_state['values']['delete'];
  if ($record ) {
    $num_deleted = db_delete('mid_components')
      ->condition('cid', $record )
      ->execute();
    drupal_set_message('The record has been deleted!');
  }
  $form_state['redirect'] = "admin/mid-modules/component";
}


FormState getValue on checkbox elements in hierarchical / tabular form structures broken?

Anyone still having this problem please allow collections of form elements using #tree set to TRUE. Its applied to the "parent" element, as the #tree property cascades to sub-elements. Use where you previously used in form calls. See D7 #tree and #parents on drupal.org.
Solution
Example for above case, change $form['#tree'] = TRUE; to $form['access']['#tree'] = TRUE; then the value will be obtained using $checked = $form_state->getValue(['access', 0, 'view']);.


Add theme settings field to theme-settings.php in d8 is not working for me

Try to remove this code:

  if (isset($form_id)) {
    return;

The hook interface of hook_form_system_theme_settings_alter is hook_form_system_theme_settings_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state).

You can remove the third parameter:

 $form_id = NULL


What is the difference between $container->get('current_user') and global $user?

The general idea is to not use service location but define the dependencies directly in the container. There are edge cases where you need to pass along the full container, but really, try to avoid them. For objects like plugins and controllers we use a static factory pattern, on which you get the container to get your dependencies. Note: There aren't any objects which depend on those.

On top of that you also should avoid having to change services. As much as possible! Instead you should build a wrapper service which has a method like the \Drupal\Core\Session\AccountProxy ... you can set the current user on there
using setAccount.

  public function __construct(AccountInterface $current_user) {
    $this->currentUser = $current_user;
  }

  public function doSomething() {
    $this->currentUser->setAccount(new UserSession(...));
  }


CSS not being loaded from CDN (CloudFiles)

The files had the wrong mime-type.

I wrote a php script using Rackspace's Cloud Files PHP api to upload all of my files to the Cloud Files container. All of the files had the default mime type/content type of "text/plain". I changed the content types of the css files to "text/css" and it all started working.


You can find totorial for adding specific CSS to specif page to the following links.

Drupal 8 Theming Fundamentals, Part 1, but it is describing how to add specific CSS to front page.
Drupal8 attaching libraries to specific pages, to add the specific CSS to specific node you need to follow tutorial on this page .

To give you example I am explaining with bartik theme for easy understanding.

I have created a css file cssfile.css and pasted at path css/cssfile.css Now this CSS file I want to use in one case to only front page and in otehr case to only specific node.

Step 1: Adding a library to the theme

Add the following code to bartik.libraries.yml.

css-filling:
  css:
    theme:
      css/cssfile.css: {}

The library name I used is css-filling, but you can use other names.

Step 2: Adding the CSS styles to a specific page

Step 2a: Adding CSS styles only to the front page

The following code in the bartik.theme adds the library to the front page.

function bartik_preprocess_page(&$variables) {
  if ($variables['is_front']) {
    $variables['#attached']['library'][] = 'bartik/css-filling';
  }
}

Step 2b: Adding CSS styles to a specific node

The following code adds the library only to a specific node.

function bartik_preprocess_node(&$variables) {
  $node = \Drupal::routeMatch()->getParameter('node');
  if ($node) {
    if ($node->id() == 3) {
      $variables['#attached']['library'][] = 'bartik/css-filling';
    }
  }
}

In the above code the important thing is path, bartik comes from the theme name and css-filling comes from step 1.


What is the suggested workflow for migrating (CMI) configuration from dev -> stage -> production?

After talking a bit with CMI maintainers, the discussion on what's the best approach isn't finished but the following is what makes the most sense at the moment.

Trying to keep it terse for now, will try to expand based on questions/when the referenced issue is resolved with an official answer.

So, first, the facts...

As already mentioned, there's the active and staging directory. Active is fully managed by Drupal, making changes directly in there (direct or indirect by switching to a different location) is not supported.
Staging is where Drupal looks for configuration to import and doe otherwise not care about it.
The import process is important, configuration changes can affect a site in a certain way and needs to be checked for validity. You can't change the field type of a text field to an entity reference, for example, that just doesn't work.
The config import always needs to run on all configuration, you can't import a single view or node type. It was tried, but trying to cope with dependencies, removes/renames and so on resulted in an very complicated system and it didn't work.
The only way to re-install default configuration, is to re-install that module. Which means that it would first try to remove all configuration (like fields). So that's not really an option. Manual, specific changes in update functions are possible but too tedious for this I think.
As the features module describes, it will be focused on providing re-usable functionality, not continuous deployments of configuration. This is what it was designed for in the first place.

Given that, the recommendation right now is to put the staging directory into version control. Each developer has then full control over what he puts there, either by copying the whole active directory over, or just a specific configuration file. The staging directory changes are then committed, pushed to production and the configuration import is run (in the UI or with drush).


If you are referring to the $content variable that is available in node.tpl.php, its value is set in template_preprocess_node() from the following code:

  // Helpful $content variable for templates.
  $variables += array('content' => array());
  foreach (element_children($variables['elements']) as $key) {
    $variables['content'][$key] = $variables['elements'][$key];
  }

$variables['content'] is then passed to field_attach_preprocess().

  // Make the field variables available with the appropriate language.
  field_attach_preprocess('node', $node, $variables['content'], $variables);

To alter the content of the $content variable, you can implement hook_preprocess_node() (in a theme, or a module), or hook_field_attach_preprocess_alter().

Remember that what in a template file is $content, in other places is $variables['content'].


How do I access a field value for an entity (e.g. node) object?

I guess you do not need to convert $entity into an array,
this would simply work.

$entity->get('field_name')->getValue();

FYI : Using kint() from the devel_kint module will let you know all the available methods that could be used to access the object elements, so comparatively var_dump() is less helpful.


Together with a bunch of other people we created the queue runner and it does support this use-case and we use it internally. You can add a collector task that includes all your small tasks and you add a second collector task so it is executed after the whole lot of small tasks. See the API file for the queue runner to figure out how you should do this exactly. It works with the default Drupal queue class so you can even extend it with external queue systems such as http://drupal.org/project/aws_sqs (amazon queue class) or others.

http://drupal.org/project/queue_runner Works for D6 and D7


The easiest way is almost always to visit the page you want to change, and hit the "Edit" button among the tabs.

However, sometimes this may not be practical for whatever reason. SQL-queries below:

D6

SELECT src FROM url_alias WHERE dst = 'home-care/vids';

D7

SELECT source FROM url_alias WHERE alias = 'home-care/vids';

You may in both version want to add AND language = if your site is multilingual.


As it turns out, webform 3 has the ability to create an email component which will serve as the recipient.
All I then did was to copy the desired email address into the email field using JQuery. I did so dynamically on each user page and it works just fine.


It can be done using Views:

set up the view in the format you want so that all Articles show
create a filter on the Node Reference Field in Content:Articles
expose this filter
make the operator: Is one of
Options: Select all - this should automatically update as new issues are created
Pager: Mini, Mini pager, 1 item - this will create a simple pager with only one item per page


The proper way to add a new variables in a class is to use hook_preprocess_page(&$vars) you can add the classes like the following:

$classes = array(
    'classes_main_page' => '',
    'classes_sidebar_first' => '',
    'classes_sidebar_second' => '',
  );

  // Classes when no sidebar
  if(empty($vars['page']['sidebar_first']) && empty($vars['page']['sidebar_second'])) {
    $classes['classes_main_page'] = 'small-12 medium-12 large-12';
  }
// Classes when left and right sidebars
  if(!empty($vars['page']['sidebar_first']) && !empty($vars['page']['sidebar_second'])) {
    $classes['classes_main_page'] = 'small-12 medium-6 large-6 columns';
    $classes['classes_sidebar_first'] = 'small-12 medium-3 large-3 columns';
    $classes['classes_sidebar_second'] = 'small-12 medium-3 large-3 columns';
  }

  // Classes when only left sidebar
  if(!empty($vars['page']['sidebar_first']) && empty($vars['page']['sidebar_second'])) {
    $classes['classes_main_page'] = 'small-12 medium-9 large-9 columns';
    $classes['classes_sidebar_first'] = 'small-12 medium-3 large-3 columns';
  }

  // Classes when only right sidebar
  if(empty($vars['page']['sidebar_first']) && !empty($vars['page']['sidebar_second'])) {
    $classes['classes_main_page'] = 'small-12 medium-9 large-9 columns';
    $classes['classes_sidebar_second'] = 'small-12 medium-3 large-3 columns';
  }
$vars = array_merge($vars, $classes);

and then in your page.tpl.php print something like this:

Don't forget to clear cache afterwards

<aside class="<?php print $classes_sidebar_second; ?>"> for sidebars
<aside class="<?php print $classes_sidebar_second; ?>"> for main container

Thanks


How to create custom rules action event conditions?

A "universal formula or module to create custom rules actions, events and conditions" (as is your question), is to write a custom module. To do so, you either create a new module, or you extend any of your existing custom modules. Refer to Drupal custom Rules how to write your own events conditions, actions and custom object (+custom tokens) for a great tutorial about how to do so. The main steps that are detailed in this tutorial are further described below (with the code included below quoted from that link).

Part 1: Defining the Event, Condition and Action

Define the Rules Event

/**
* Implementation of hook_rules_event_info().
* @ingroup rules
*/
function your_module_rules_event_info() {
  return array(
    'your_module_package_bought' => array(
      'label' => t('A package was bought'),
      'module' => 'your_module',
      'arguments' => array(
        'acting_user' => array('type' => 'user', 'label' => t('The user who bought the package.')),
        'package' => array('type' => 'package', 'label' => t('The purchased package.')),
      ),
    ),
  );
}

Define the Rules Condition

/**
 * implementation of hook_rules_condition_info()
 */
function your_module_rules_condition_info() {
  return array(
    'your_module_condition_package_type' => array(
      'label' => t('Type of the package'),
      'arguments' => array(
        'package_id' => array('type' => 'value', 'label' => t('The type of the purchased package.')),
        'package_type' => array('type' => 'string', 'label' => t('The type of the purchased package is')),
      ),
      'module' => 'your_module',
    ),
  );
}

Define the Rules Action

/**
 * Implementation of hook_rules_action_info().
 */
function packages_rules_action_info() {
  return array(
    'your_module_action_change_order_status' => array(
      'label' => t('Change the order status'),
      'arguments' => array(
        'order' => array('type' => 'value', 'label' => t('The order object.')),
      ),
      'module' => 'your_module',
    ),
  );
}

Part 2: Coding the custom Event, Condition and Action

Event:

Somewhere in your custom module, you need to include logic to trigger the event, with something similar to this example (note the your_module_package_bought in it):

  //here the code for buying a package will be located
  //when that code returns that a package was bought trigger the rule
  $order = order_load($oid);//$oid will be the id of the order made
  $package = package_load($pid);//pid will be the id of the bought package
  global $user;
  rules_invoke_event('your_module_package_bought', $user, $package, $order);

Condition:

To evaluate the Rules condition (to check if it is TRUE or FALSE), the function your_module_condition_package_type is executed using the arguments provided. Here is an example of how such function could look like:

function your_module_condition_package_type($pid, $type) {
  $package = package_load($pid);
  return ($package->type == $type) ? true : false;
}

Action:

Somewhere in your custom module, you need to include logic to perform the actual action, in this example it should be done within the function named your_module_action_change_order_status.


Serve compressed JS and CSS with S3 as filesystem

As Clive mentioned there is no config on s3 which could automatically compress the assets on s3.

The way we fixed it in our case was to add cloudflare CDN service(already in use) in front of s3 file system.

In order to route the s3 assets request via CF we added a proxy subdomain for our drupal origin. So if Drupal site was running on site-url.com we added a proxy subdomain as s3-<env>.site-url.com. We added a page rule in CF to override host to s3 bucket for any request to  s3-<env>.site-url.com/*.

Now, the challenge was to override s3 hostname configuration in Drupal to spit out resources on s3-<env>.site-url.com/* instead of s3 bucket url.
Big thanks to S3FS module maintainers for providing easy configuration to override that by adding following in settings.php

  $config['s3fs.settings']['use_cname'] = TRUE;
  $config['s3fs.settings']['domain'] = 's3-<env>.site-url.com';


It will be a pretty big list, you could get all packages known by composer which should contain pretty much everything

composer show drupal/* --all


Unable to delete feature content type after uninstalling feature

Solution

Using a hook_uninstall() in FEATURE_NAME.install file and changing the status of the content type, so the system thinks it is an unlocked, custom content type.

I posted this also on d.org.

<?php
/**
 * Implements hook_uninstall().
 */
function FEATURE_NAME_uninstall() {

  // List custom content types added by this feature
  $custom_ctypes = array(
    'blog',
  );

  // Go through each and unlock the content type
  foreach ($custom_ctypes as $ctype) {
    db_query("UPDATE {node_type} SET `custom` = 1, locked = 0 WHERE type = :ctype", array(':ctype' => $ctype));
  }

  // Clean Drupal cache; this is necessary for the "Delete" link to appear
  // next to the content type created by the feature.
  drupal_flush_all_caches();

}

This will make the "Delete" button appear for that content type, so you can delete it from the admin.

Hope this helps someone!


How to disable core JS aggregation and AdvAgg just for admin paths

So, the issue I describe in my question is this Drupal Core issue: Drupal.ajax does not guarantee that "add new JS file to page" commands have finished before calling said JS

So, my solution wasn't to disable the aggregation, but to apply the latest patch provided in the issue on Drupal.org


Cloned Sites and Original Site Are All Affecting Each Other

I just figured it out. I have a wildcard SSL setup for my server. By default when you clone a site in Aegir it does not set it up as SSL. However, I was still able to access the cloned site via HTTPS.

The issue was caused by accessing the site via HTTPS when SSL was not enabled in Aegir for that specific site.

As soon as I enabled SSL for the site in Aegir the problem went away.

I'm not exactly sure what was going on in the backend. It would be great if someone could chime in on that...


Migrate fields with content from drupal 6 from different DB

If by "writing by hand" you mean writing PHP code, then the answer is no. The migration module is a migration framework; it provides the tools (API, PHP classes, etc) to migrate data but it doesn't do it for you. Migrate D2D (built off the Migration framework) provides some support with "out of the box" importing (e.g. User Roles, Pics, Taxonomy, etc.), but it doesn't do it all for you.

The key thing to understand is complexity of the problem; content in Drupal can be configured in a myriad of different ways. As such, one module that can handle all the different permutations of sources (e.g. CSV, WordPress site, various DB's, & an old Drupal install), field configurations (e.g. ints, floats, text, custom objects, custom fields, module create fields), & destinations (e.g. custom node types, module-create node types, custom entities, etc.) is a mammoth task for an open-source project.

Instead, the Migration & Migrate D2D maintainers have made the problem more tractable. They've provided some common tools that are likely to be used in any Drupal migration. Filling in the last bit of details (e.g. should a phone field be mapped to an address field or as a text field) is up to you because only you can possible know that information and how it's used.


How can I allow a user to create a user, but not view all users?

Subuser module can help to achieve this goal. A user that is allowed to create a sub users can manage them as well.


One of our corporate installations had a forward proxy that prevented direct access to the internet, we ended up patching core with 'the proxy patch' (thus named this way because this issue has been open since 2004 - http://drupal.org/node/7881).

http://drupal.org/node/7881#comment-4134240 - has a patch for drupal 7
http://drupal.org/node/7881#comment-2446280 - has a patch for drupal 6

Once the patch is installed, then you will be able to alter drupal_http_request() to send all queries through the proxy.

This way all modules that require access to the internet will function as expected, e.g. update statue, aggregator, openID etc

UPDATE: The patch is already merged in Drupal 7 trunk ( https://drupal.org/comment/6425278#comment-6425278 ), and hopefully will be out with Drupal 7.16


Ajax InvokeCommand with custom Callback Primary tabs View(active tab)

In the JS side try with this:

(function($) {
  $.fn.uploadToS3 = function() {
    // Your code here.
  };
})(jQuery);

the PHP part looks ok to me.


How to configure access to courses for teachers and students?

You might want to give it a try to use the Group module, which allows for creating arbitrary collections of your content and users on your site, and grant access control permissions on those collections.

It is available as of D7, and has a D8 version also. It creates groups as entities, making them fully fieldable, extensible and exportable. Every group can have users, roles and permissions attached to it (refer to "What are the various roles supported by the Group module?" for more details about that).

Sample configuration

Below is an example of a possible configuration, which may help to get you started with possible configurations (using the Group module):

Group type ID ! Group type ! Group role ID ! Role
--------------+------------+---------------+------------
 1            ! Class      ! 3             ! Instructor
 1            ! Class      ! 4             ! Student
 1            ! Class      ! 5             ! Alumni
 2            ! Customers  ! 6             ! Lead
 2            ! Customers  ! 7             ! Prospect
 2            ! Customers  ! 8             ! Licensed Customer
 2            ! Customers  ! 9             ! Sales
 2            ! Customers  ! 10            ! Support
 2            ! Customers  ! 11            ! Accounting
 2            ! Customers  ! 12            ! R&D
 3            ! Project    ! 13            ! Project Manager
 3            ! Project    ! 14            ! Developer
 3            ! Project    ! 15            ! Customer

Group Types

The above example consists of 3 group types:

Class.
Customers.
Project.

Group Roles

For each of the 3 group types, there are specific Roles defined, some more details about some of them:

for the Class group, these are the 3 roles that are configured:

Instructor.
Student.
Alumni.

for the Project group, these are the 3 roles that are configured:

Project Manager.
Developer.
Customer.

These roles can be configured per Group type and will only be available on groups of that group type. As an example, for group type "Class", the defined roles are Instructor, Student and Alumni (which are not available for the other group types).

On top of the group specific roles, there are also Special Global Roles: These are the special (hardcoded) roles named Outsider (= a signed in user that did not join a group) and Member  (= a signed in user that did join a group). These cannot be defined by the Drupal administrator, and they are always available for any group. These roles can have different permissions sets for each group type. Special case: the role Anonymous is related to a user that is not signed.

Groups

Each of the configured group types can have any number of Groups.

Examples of groups:

for the Class group type, there could be these Groups:

Getting started with Drupal.
Drupal for site builders.
Become an expert in using the Rules module.

for the Customers group type, there could be these Groups:

Service Requests.
Order Processing.
Sales Orders.
Relationship Management.

Permissions

For each of the configured group types, you can then also configure for each Content Type which Role has what kind of access (= none, view, create, edit, delete). Be aware: even though this looks similar to Drupal's permission configuration, these permissions are not the same permissions (they are specific to the Group module).

Comparison with the Organic groups module

Have a look at my answer to "What are the features of the Group module versus Organic Group module?" for details about:

How both modules (Group versus Organic groups) compare to each other.
Integration with various modules that you might want to take advantage of also.

Resources

Community documentation for the Group module.
Video tutorial "How to use the Group module in Drupal 8 to manage editorial access control to different areas of a web site".

Integration with various modules

The Group module integrates with various other (popular) modules, including:

Rules, as illustrated in the answer to the question "How to bulk assign existing content to a group created with the Group module?".
Views, as illustrated in the answer to the question "How to show the content of a group on the group page when using the Group module?".

The beauty, IMO, of these integrations are that they are more or less out-of-the box (not dozens of extra modules needed to make those integrations work).

Addressing your specific questions

  Which access module helps me to organize the student to denied access to the module while course.status is deactive?

Probably the easiest implementation of this, is to use the Rules module to create an appropriate "Group Membership" entity, which is what it takes to grant a user access to a Group. And assuming you have something in place that allows you to create a view of all students (users) that at some point should receive access to some course, you could use the Views Rules to create such entity for each user in such views result, and thereby using some Rules Event(s) / Condition(s) related to the update of course.status from deactive to something like active.

  Which access module helps me to organize teachers to see information only from students who followed or is following his course?

This is by design of the Group module (just a matter of appropriate configuration of the Group module).

PS: this answer applies to either D7 or D8.


Accessing text of a field with type "Text"

start by downloading the devel module.

A suite of modules containing fun for module developers and themers
...
Devel
Helper functions for Drupal developers and inquisitive admins.
This module can print a summary of all database queries for each page
request at the bottom of each page. The summary includes how many
times each query was executed on a page (shouldn't run same query
multiple times), and how long each query took (short is good - use
cache for complex queries). Also a dprint_r($array) function is
provided, which pretty prints arrays. Useful during development.
Similarly, a ddebug_backtrace() is offerred. much more.

This includes a function dpm() which allows you to navigate through complex variables including $vars. dpm($vars) will create a user interface for navigating through it - then you can find the specific location for the field you want.
I included this as an answer instead of the presumed actual location of the field within $vars since this allows you future access to any variables you need. You can use this for example to go through a $form, $content, etc.


How to convert a block with views content into code?

You could also use something like this:

$view = views_get_view('view_name');
$view->set_display('block_display_name');
$view->set_arguments(array($arg1, $arg2)); //only if you need arguments
$view->execute();
foreach($view->result as $res) {
  // extra stuff here
}


How can Drupal be made to serve with root-relative paths?

You can use a template process (YOUR_THEME_process_html) hook to rewrite all resource urls (js and css) using a regular expression.

Here is an example which transforms all http:// or https:// to //:

function YOUR_THEME_process_html(&$vars)
{
    foreach (array('head', 'styles', 'scripts') as $replace) {
        if (!isset($vars[$replace])) {
            continue;
        }

        $vars[$replace] = preg_replace('/(src|href|@import )(url\(|=)(")http(s?):/', '$1$2$3', $vars[$replace]);
    }
}


Easy way to copy drush vget variables from one site to another site?

The problem here is that the output from a drush variable-get might be an array.  Drush can easily render arrays on output, but drush variable-set does not provide a feature that allows you to provide arrays as input.

The best you can do with array data is to use php-eval:

drush php-eval 'variable_set("var", array(...));'

How do you get the array value to insert in here, though?  Trying to do this directly from the drush variable-get output would be problematic; it would be very tedious to get all of the quoting and escaping right. I would not recommend this for your final solution.

Instead, you might consider using drush_invoke_process.  Something similar to this might work:

drush ev '$v = drush_invoke_process("@remote", "vget", array("var")); $data = $v["object"]; variable_set("var", $data);'

That would probably do the trick for you. However, rather than building up a custom solution to moving configuration from one site to another with Drush, I might recommend that you instead examine the ctools export bonus Drush extension. It can export and import variables nicely, and might ultimately be better suited to your purpose.


Where to view Google Analytics "Track clicks on outbound links" results?

The module tracks outbound links via GA event tracking. It will send a click action to GA under the Outbound links category. The metrics for this event category can be found in the Behavior > Events menu in the GA interface.


You have to create a view if you want this control.    Like this

This will give you a page with the exposed filters you asked for @ www.mysite.com/automobile.


Adding temporary field to form to print ID's

Devel - Helper functions for Drupal developers and inquisitive admins.

Add in hook_form_alte function dsm($form); and refresh your form page, you will get message with structured info.


This sounds like data transformation problem; the import didn't format the HTML entity title data on import. Instead of trying to code around the problem in your template, you should reformat your node titles.

Run a code snippet (e.g. drush scr myscript.php) that can fix the formatting on your nodes. Something like:

// @TODO: Retrieve your list of imported node nids in the $nids array
$nids = array(4, 5);
foreach ($nids as $nid) {
  $node = node_load($nid);
  $node->title = html_entity_decode($node->title);
  node_save($node);
}


Twig: Display media library reference user image at particular resolution with alt tag (on /user/1231 page)

but node is null since this is not on a node

In user template there is {{ user }} variable wich holds user entity. So just replace "node" with "user" in your snippets.


How to round the total price, display without decimal?

this solved my problem: https://www.drupal.org/project/commerce/issues/3076196
my module:
roundingmodule.info
name: Commerce rounding module.
type: module
description: Rounding.
core: 8.x
package: Custom

roundingmodule.services.yml
services:
  roundingmodule.rounding_order_processor:
    class: Drupal\roundingmodule\RoundingOrderProcessor
    tags:
      - { name: commerce_order.order_processor, priority: -10 }

roundingmodule.commerce_adjustment_types.yml
rounding:
  label: 'Rounding'
  singular_label: 'rounding adjustment'
  plural_label: 'rounding adjustments'
  has_ui: true
  weight: 20

src/RoundingOrderProcessor.php
    <?php

namespace Drupal\roundingmodule;

use Drupal\commerce_order\Adjustment;
use Drupal\commerce_order\Entity\OrderInterface;
use Drupal\commerce_order\OrderProcessorInterface;

/**
 * Processes the order's shipments.
 */
class RoundingOrderProcessor implements OrderProcessorInterface {

  /**
   * {@inheritdoc}
   */
  public function process(OrderInterface $order) {

      $rounder = \Drupal::service('commerce_price.rounder');
      $order_total = $order->getTotalPrice();
      $rounded_total = $rounder->round($order_total->divide(100))->multiply(100);
      $difference = $rounded_total->subtract($order_total);

      $order->addAdjustment(new Adjustment([
        'type' => 'rounding',
        'label' => 'Rounding',
        'amount' => $difference,
      ]));
  }

}


How do I set the default value for results?

Initially I tried some different approach:

extending SearchApiString
an event subscriber of KernelEvents::REQUEST altering the incoming url

because by default facets\search api rely on the query_params of the url and the "values" of the relative facets various objects of the modules.
Both of those those approaches kinda failed, because the first didn't update the query params of the request, while the second caused some bugs that I couldn't manage to solve.
The working approach was to extending the default url_processor QueryString - which both initialises the active facets filters and build the url after a search.
Injecting the logic when the class is created allowed to do a minor modification without breaking all the standard functionality.
<?php

namespace Drupal\my_module\Plugin\facets\url_processor;

use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\facets\Plugin\facets\url_processor\QueryString;
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
use Symfony\Component\HttpFoundation\Request;

/**
 * Query string URL processor.
 *
 * @FacetsUrlProcessor(
 *   id = "my_query_string",
 *   label = @Translation("My Query string"),
 *   description = @Translation("Add description")
 * )
 */
class MyQueryString extends QueryString {

  /**
   * A string of how to represent the facet in the url.
   *
   * @var string
   */
  protected $urlAlias;

  /**
   * The event dispatcher.
   *
   * @var \Symfony\Component\EventDispatcher\EventDispatcherInterface
   */
  protected $eventDispatcher;

  /**
   * {@inheritdoc}
   */
  public function __construct(array $configuration, $plugin_id, $plugin_definition, Request $request, EntityTypeManagerInterface $entity_type_manager, EventDispatcherInterface $eventDispatcher) {
    //this is where I'm adding a default value
    $this->alterRequest($request);
    parent::__construct($configuration, $plugin_id, $plugin_definition, $request, $entity_type_manager, $eventDispatcher);
  }

  /**
   * @param \Symfony\Component\HttpFoundation\Request $request
   */
  private function alterRequest(Request $request): void {
    $query = $request->query;
    $facet_new_parameters = [];

    if ($facet_parameters = $query->get('f')) {
      $content_type_filter_exists = FALSE;

      foreach ($facet_parameters as $parameter) {
        $sepator = ':';
        $explosion = explode($sepator, $parameter);
        $facet_type = array_shift($explosion);
        if ($facet_type === 'content_type') {
          $content_type_filter_exists = TRUE;
        }
      }

      if (!$content_type_filter_exists) {
        $facet_new_parameters = array_merge($facet_parameters, ['content_type:prodotto']);
      }
    }
    else {
      $facet_new_parameters = ['content_type:prodotto'];
    }

    if (!empty($facet_new_parameters)) {
      $query->set('f', $facet_new_parameters);
    }
  }
}


You can achieve that using the Remove Duplicates module.

Don't bother about the name of the module. you can use it as following way.

This module helps the administrator to easily find out the nodes according to one of the node fields.

So you can easily find out the same content pages and like those.


The commerce_product.field_produit_labels field needs to be updated

You can quick-fix it by adding module devel_entity_updates https://www.drupal.org/project/devel_entity_updates and run the command drush entup.
Don't forget to export configurations after that.
Also, you can fix it by manually creating an update hook - follow https://www.drupal.org/node/3034742#comment-13097250


You'll want to alter settings.tableDrag to remove that drag and drop functionality, but I think what you're actually running into is a css rule that sets a width for the table.


Why getMimeType() is returning wrong value for xlsx file

The value returned as MIME type of a file is the value returned from the file.mime_type.guesser service which, on a default Drupal installation, uses three classes to guess the MIME type:

The ExtensionMimeTypeGuesser class (a Drupal core class) guesses it from the file extension, but it doesn't have a mapping for the .xlsx files, for which it returns application/octet-stream (See ExtensionMimeTypeGuesser::guess() and ExtensionMimeTypeGuesser::$defaultMapping.)
The FileBinaryMimeTypeGuesser class (a Symfony class) returns the output of file -b --mime <filename> 2>/dev/null
The FileinfoMimeTypeGuesser class (a Symfony class) returns the output of finfo_file()

It is also possible that a module implements hook_file_mimetype_mapping_alter() to change the value returned from the first class, the file used from file or fileinfo_file() contains the wrong values, or another module implements another guesser class that is used before the other classes and returns the wrong MIME type.


Can entities as users exist without being tied to nodes

In D7 Users are an Entity type, they are their own Entity type. A Node is another entity type with various bundles such as Page, Article, etc.

Taxonomy is another example of an Entity.

An Entity does not necessarily mean a "Node" in drupal 7.

See this introduction to Drupal 7 Entities on drupal.org


Drupal function to convert node into Json object

To return on menu callback function in Ajax call you can use drupal_json_output(), you can use this function as an example.

On that exampe you can see that you only need to call drupal_json_output() function with the object as the parameter, there's no need to return anything from your callback function.

If you need to convert the Drupal node object into JSON object to be returned on a function, you could consider to use drupal_json_encode()


Query Drupal User Table for: date created < $today - '100000'

You can achieve this using EntityFieldQuery as shown below:

$query = new EntityFieldQuery();
$query->entityCondition('entity_type', 'user')
  ->propertyCondition('created', strtotime("-1 day"), '<')
  ->propertyCondition('uid', array(0,1), 'NOT IN');
$result = $query->execute();
if(!empty($result)){
    user_delete_multiple(array_keys($result['user']));
}


How to get term ID from translated term name?

A suggestion :

$my_translated_term_name = 'astuce';

$query = \Drupal::database()->select('taxonomy_term_field_data', 'td');
$query->addField('td', 'tid');
$query->condition('td.name', $my_translated_term_name);
// For better performance, define the vocabulary where to search.
// $query->condition('td.vid', $vid);
$term = $query->execute();

$tid = $term->fetchField();


Admin approval notification based on role choose by user on registration form?

I have created a module for this, which addresses my question. It can be found at Select registration roles. Some more details about it (from its project page):

  The Select Registration Roles module adds a role field on the user registration form. Admin can configure roles to be displayed on the
  registration form as, and can set roles which require admin approval.

Here is a screenprint of it also:


How do I use custom marker icons with Gmap?

Have a look at the IP Geolocation Views & Maps module. Partial quote from its project page:

Despite what the name may suggest, IP Geolocation Views & Maps (IPGV&M) is first and foremost a mapping engine.
The module makes it very easy to create Views-based mapping solutions using the map renderer of your choice (Google, OpenLayers or Leaflet) with any location storage module of your choice, e.g.:

Get Locations,
Geofield,
Geolocation Field
Location.

This allows you to bring together modules and feature sets that without IPGV&M you would not be able to combine.
Like beautiful animated marker clustering on Google or Bing or Mapbox ... any of various map providers.
But more importantly IPGV&M adds some features you won't find as conveniently packaged elsewhere.
These include marker differentiation based on field values or ranges (2nd screenshot) with or without font icons, various centering options, super-imposing the current visitor's location, allowing multiple content types to be displayed on the same map, full screen button and mini-map inset (bottom screenshot), polygon support (Geofield), marker tags and tool tips and cross-highlighting of associated content on the page when markers are hovered (and vice versa).
And the Set my location block allows your visitors to locate themselves on the map, either automagically --via the Wifi/GPS device on their mobile-- or by typing an address or landmark, like "Eiffel tower" (bottom screenshot, upper left corner, click to enlarge).
Follow this step-by-step tutorial to create a handy store locator with proximity search, from a list of addresses in a spreadsheet. You'll learn about the Feeds and Display Suite modules too!
Finally IPGV&M provides a set of visitor location retrieval technologies, both IP and HTML5-based, so that you can track where past visits came from and where current visitors are located, superimposing their moving positions as markers on your maps.

Head over to its (impressive) project page for even more information about it (it would be way too long to include a quote of it all here).


Add multiple friends at once with user relationships

Write your own integration!

Really, Views Bulk Operations is quite an easy module to write a plugin for and optionally you can submit it to the User Relationship project to have it maybe embedded in the main project. There is a complete tutorial here, but I will briefly explain each step of the process.

First off, you need to create a custom module. Create a folder with a fitting name for your module, like user_relationships_vbo or something. Add a user_relationships_vbo.info (writing .info files) and a .module file.
The module file should contain several specific functions to have it work with VBO.

The action

Implementation of hook_action_info(), this defines the action. On what entities it can act, what the action is called, how it can be configured and if it has an extra VBO configuration option.

The VBO configuration form

This is an optional form that adds settings the the Views VBO config form, allowing you to define additional settings. In your case this is not really important as you probably just want to relate users.

The bulk configuration form

This forms shows after your chose your action in VBO, and can be used to define settings for the current batch. You could for instance use this the choose to have the requester specify the relationship type. Again in the simplest form you would not need this.

The actual action

This is what will eventually relate the users. You can make this as long and as complicated as you like with all kind of notifications, etc. But the basics is to just add the relation.

So the code

Your .module file might look like this:

<?php
// The action definition
function user_relationships_vbo_action_info() {
  return array(
    'user_relationships_vbo_relate_users' => array(
      'type' => 'user',
      'label' => t('Relate users to the current user'),
      'configurable' => FALSE,
      'vbo_configurable' => TRUE,
      'triggers' => array(),
    ),
  );
}

//The per batch form
function user_relationships_vbo_relate_users_form($settings, &$form_state) {
  $form = array();
  $form['type'] = array(
    '#type' => 'select',
    '#title' => t('Choose your relation type'),
    // This assumes all users have access to all relationships. You might want to add a filter to check access somehow.
    '#options' => user_relationships_types_load(),
    '#required' => TRUE,
    '#default_value' => isset($settings['settings']['type']) ? $settings['settings']['type'] : '',
  );
  return $form;
}

// The form submission
function user_relationships_vbo_relate_users_submit($form, $form_state) {
  $return = array();
  $return['type'] = $form_state['values']['type'];
  return $return; //Note, return value here must be an array.
}

// The actual action
function user_relationships_vbo_relate_users(&$target_user, $context) {
  // Get the current user
  global $user;

  // See user_relationships_request_relationship()
  // http://api.drupalhelp.net/api/user_relationships/user_relationships.module/function/user_relationships_request_relationship/7

  user_relationships_request_relationship($user->uid, $target_user->uid, $context['type'], FALSE)

}
?>

Read the rest of the tutorial, but this should get you started.


Need Help passing field data from one content type to another

I don't have enough reputation to comment. I would approach this with an entity reference field, a block, and rules.

Your reservation content type should have an entity reference field for the 'customer' record.

A block would have the button to click. It goes on your customer record page. You might need a module like Rules Link  to trigger rules.

Set up rules so that when you click this button it:

creates a new entity (a node of type reservation)
populates the user reference field with the customer node you are looking at
saves the new node
opens the edit screen on the new node so more work can be done

It will take some playing around play around with rules to get it right.


Default File Display is Using Incorrect Image Style

After some search, I got your issue and from where you can set that. So I delete my previous answer and following is the updated one.

As in my setting, I have four Image settings,

Default
Teaser
Preview
Wysiwig

Now, by default it is taking some height and width.

Now those all four setting you can change at Admin/Structure/File types/Images/Manage file Display and you can find all four image file set on right hand top corner in following images. Now, you can see as I have selected Default and at bottom of the page it is showing None(original image).

Note: Now, image uploaded in the body field area before save/post of the body content may not show what you have selected, but if you post it it will show what you image style you had selected. As stated in following image.


How to create a default image per taxonomy term?

When creating a vocabulary you can add a image field this is the only way to add a default image for all future taxonomy terms (in that vocab)
so then when you create the term you would simply add your image to that term be it "default" or other.


How to build a user authentication workflow with AngularJS using RESTful module?

Do headless means no layout and block display at all ?
i believe u can leave CAS drupal module do the job ( and a connection menu )