Build an EntityFieldQuery that selects referenced entities

You can use target_id instead of value to retrieve entities based on the ID of referenced entities:

$query = new EntityFieldQuery();
$query->entityCondition('entity_type', <type-of-the-entity>);
$query->fieldCondition('<name-of-the-field-referring-the-other-entity>', 'target_id', <id-of-the-referenced-entity>, '=');
$results = $query->execute();


Is there a way to temporarily disable multilanguage selector links when a page doesn't have a translation?

You could implement hook_preprocess_block in your theme.
Hope this helps you.

/**
 * Implements hook_preprocess_HOOK() for block.html.twig.
 */
function bartik_preprocess_block(&$variables) {

  if ($variables['plugin_id'] == 'language_block:language_interface') {
    // Gets current node object from the current path.
    $node = \Drupal::routeMatch()->getParameter('node');

    // Gets all the translation languages, returns an array.
    $languages = $node->getTranslationLanguages();
    // Gets the number of languages.
    $number_of_languages = count($languages);

    if ($number_of_languages == 1) {
      // Basically, clears out the content render array.
     $variables['content'] = array();
    }
  }
}


Version control on Entity form type submissions

Trying to hack data out of an Entity form seems to make things unnecessarily more complicated, so I decided to redesign the whole form as a content type create form, while using entity reference fields to link the various instances.


Main Menu Display Description as span Tag

Looks like your friend is: $element['#original_link']['depth'];

You would adjust your conditional to be something like:

 // Not sure if top level depth is 0 or 1 for this so experiment with that a bit.
 if ($element['#original_link']['menu_name'] == "main-menu" &&
     isset($element['#localized_options']['attributes']['title']) &&
     $element['#original_link']['depth'] == 0
 ){
    $element['#title'] .= '' . $element['#localized_options']['attributes']['title'] . '';
 }

Check out this comment from the drupal documentation.


Detect translatable strings in custom module code

You can install the Translation template extractor module.

  The Translation template extractor provides a web based and a command line Gettext translation template extractor interface for Drupal as well as a reusable API to look for translatable strings and translatability errors. This tool is used under the hood at http://localize.drupal.org/ as well to serve as a parsing machine for Drupal.org project releases.

If you want a user interface that allows you to translate in any language the strings provided by your custom module, then you can install the Localization server.

  It provides a generic translation database backend with a community localization user interface, which allows people to collaborate on translating projects to different languages. It currently contains tools to translate Drupal projects as well as general Gettext based sources.

The difference is that the first module allows you to create the translation template files necessary to translate the strings provided by any module running on your server, including any custom module. Those files need to be edited to create the actual translation files that provide the translated strings.
The second module, which depends from the first one, allows to create the translation files using a user interface. While the first module requires you to manually edit the translation template files to obtain the translation files, with the second module you can do it using Drupal.


Disable client- or proxy-side caching on anonymous pages (Cache-Control header), without disabling server-side caching?

I solved this using context and context_http_headers (7.x-1.x) to add custom Cache-Control: headers on the user page.


I found the culprit. After turning most of the modules I found out it's WORKBENCH.. Probably it has efficiency problems. Now instead of 15-20 seconds it takes 1 sec to node_save.


Trying to list all articles where category field is empty

It seems to me your mistake is you are requesting the column field_tags from the table node, which is not a column from node, so doesn't exist.
Unless you have a very specific database structure, your "field_tags" should be contained in the table field_data_field_tags, so you may have to make an INNER JOIN between these tables in your query (maybe using field_data_field_tags.entity_id = n.id), and then check if the n.id exists in field_data_field_tags.entity_id, or (maybe better) use a LEFT JOIN between field_data_field_tags and node, so only the node with a n.id existing in field_data_field_tags will be returned.


Display fields from a view in node template

Drupal 6

  $view = views_get_view('view-name');
  print views_build_view('embed', $view);

Drupal 7

<?php echo views_embed_view('view-name', $display_id = 'display-name') ?>


I know that this question has already been answered, but thought I'd point out the Views Data Export module for anyone looking for a contributed solution rather than a bespoke one. This module allows you to define Views that generate CSV files for export. We're using this with Drupal 7 for a client so that they can export all users and their associated custom fields. It's working well.


launching parser script once in 24 hours

If you don't want your script to execute on each page load, you have to set up a cron job, either via hook_cron() or a separate job.

To make a variable available in a template file, you have to use a preprocess function of some sort.

With these two elements, you should be able to make your script work and be integrated with Drupal.


How to customize the output of node content in Drupal 6?

These are the available them files where you can get $content

  node--[type|nodeid].tpl.php

  base template: node.tpl.php

Theme hook suggestions are made based on these factors, listed from the most specific template to the least. Drupal will use the most specific template it finds:

  node--nodeid.tpl.php

  node--type.tpl.php

node.tpl.php

See node.tpl.php in the Drupal API documentation for more information.

Drupal 7 Template (Theme Hook) Suggestions


How can I query a database created using the previous core version from the new core version?

You can add external databases in your settings.php file:

$databases['external']['default']= array(
  'database'=>'',
  'username'=>'',
  'password'=>'',
  'prefix'=>'',
  'host'=>'',
  'port'=>'3306',
  'namespace'=>'Drupal\\Core\\Database\\Driver\\mysql',
  'driver'=>'mysql',
);

Then, in a custom module you can query for nodes, terms etc.

// Switch to external database
\Drupal\Core\Database\Database::setActiveConnection('external');

// Get a connection going
$db = \Drupal\Core\Database\Database::getConnection();

$vid = 5; // The vocabulary I want to query
$query = $db->select('taxonomy_term_data', 't');
$query
  ->join('taxonomy_term_hierarchy', 'h', 'h.tid = t.tid');
$query
  ->addTag('translatable')
  ->addTag('taxonomy_term_access')
  ->fields('t')
  ->fields('h', array(
    'parent',
  ))
  ->condition('t.vid', $vid)
  ->orderBy('t.weight')
  ->orderBy('t.name');
$results = $query->execute()->fetchAll();

Switch back to your current db

\Drupal\Core\Database\Database::setActiveConnection();

Save the results to a d8 vocabulary

foreach($results as $result) {
  Term::create([
    'tid' => $result->tid,
    'name' => $result->name,
    'vid' => 'my_d8_vocabulary_name'
   ])->enforceIsNew()->save();
}


the module aint workin.

hacked it to fix.

$block = module_invoke($block_info->module, 'block_'. $op, $block_info->orig_delta, $edit);


How to add a database index to a base field

Currently the only way to do that is to create your own storage_schema entity handler.

See Node as an example, the annotation:

*     "storage_schema" = "Drupal\node\NodeStorageSchema",

There you can alter both the schema for a while table, or you can do it for a specific field. NodeStorageSchema does both:

  /**
   * {@inheritdoc}
   */
  protected function getEntitySchema(ContentEntityTypeInterface $entity_type, $reset = FALSE) {
    $schema = parent::getEntitySchema($entity_type, $reset);

    $schema['node_field_data']['indexes'] += array(
      'node__frontpage' => array('promote', 'status', 'sticky', 'created'),
      'node__status_type' => array('status', 'type', 'nid'),
      'node__title_type' => array('title', array('type', 4)),
    );

    return $schema;
  }

And below in getSharedTableFieldSchema():

if ($table_name == 'node_revision') {
  switch ($field_name) {
    case 'langcode':
      $this->addSharedTableFieldIndex($storage_definition, $schema, TRUE);
      break;

    case 'revision_uid':
      $this->addSharedTableFieldForeignKey($storage_definition, $schema, 'users', 'uid');
      break;
  }
}


There's no assistance available, really, this is out of your hands and can only be fixed by the server admins.

Your three options are:

Convince your hosting provider to upgrade the version of PHP you have available in the shell. If they tell you they don't know how to do that, go to option 3.
Downgrade drush to something that works with old versions of php
Change your hosting provider to one who's got their act together. Your current provider hasn't, clearly.


arg(1) would be your friend here. In your view header definition (PHP format) put something like:

print l(t('Add album'), 'node/add/album/' . arg(1));


How should I add multiple markers using geofield module?

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).

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). That project page also includes various screenshots.
Note: Uploading custom markers should be possible also, similar to what you can see in the screenprint in the feature request about Custom markers.
PS: I'm assuming this question is about D7 ...


Ajax on Add another item of field collection

Sounds like you need to use Drupal.behaviors and not just document.ready for your javascript.

  Drupal uses a "behaviors" system to provide a single mechanism for
  attaching JavaScript functionality to elements on a page. The benefit
  of having a single place for the behaviors is that they can be applied
  consistently when the page is first loaded and then when new content
  is added during AHAH/AJAX requests.

More info on Drupal.behaviors here


Use this Mass Contact module it will match your requirement.

  The Mass Contact module allows anyone with permission to send a single
  message to multiple users of a site, using its roles functionality.

or

The Advanced User Module allows users who have "administer users" permission to send mail to selected groups of users, and that includes selection by role.


How to let user add multiple sub-content fields in the main content?

If apartment is one content type, and unit is another content type, you can use entityreference module to reference units in apartments. You will create in apartment content type - entityreference field with unlimited values, type of referenced entity would be unit content type - user will be able then to add as many units to his apartment as he wants.

You can even create a view of entity reference display, and use it for selection of available options in your entityreference field.

http://www.lullabot.com/blog/article/entityreference-multiselectors - also something about multiselector widgets for entityreference field.


How to grant user User Points after publishing content, while content's default is unpublished?

I solved my problem by doing this:

Create flag and give flag name as Publish node and grant points to user
Add new rule with event A node has been flagged, under "Publish node and grant points to user"
For actions publish this node and grant points to user use this data selector: flagged-node:author

Special thanks to oneng on Stackoverflow!


Drupal 8 doesn't cache Ajax forms anymore, so you can't get properties of the form object set in the initial form build. see Bypass form caching by default for forms using #ajax.

Forms are only cached as rendered form. Put the entity id in a hidden form element to load the entity before saving. Add the entity cache tag to the form if you use default values from the entity.

Or consider to switch from a general Form API form to an entity form.


Translated node overwrites other languages

Try to do editing of node using path prefix of language in which the node you edit is. So, this would look like:

[site-domain]/[language-path-prefix]/[path-to-node-edit]

You need to enable 'URL' detection method in '/admin/config/regional/language/configure'

Let me know if this is working for you.


Views in D8 uses for contextual filters routes and you can't put a route parameter first in a route pattern, see Content type slug in route, how?. What you can do is aliasing. I don't know if there is a module for this, but you can build a custom path processor to change inbound and outbound the position of the route parameters in the path so that the View route does work.


Addresses Module - Province (State) Used to Be a Drop-Down

A quick look suggests that you put in a patch to the module that didn't get re-rolled into the module after your update as when I installed the module on a testbed it didn't work until I did :)

Anyways, if you look at https://drupal.org/node/244471 and scroll on down to comment #63 you'll see the patch.

If you want to just edit up the code directly, you want to change

  // Invoke addressfieldapi to allow modules to add their own addresses fields.
  // Then update these fields with the global settings for each field instance.
  $extra = module_invoke_all('addressesfieldapi', 'form', $fields, $values);
  foreach (element_children($extra) as $ename) {
    if (isset($settings[$ename . '_label'])) {
      $extra[$ename]['#title'] = t($settings[$ename . '_label']);
    }
    if (isset($settings[$ename . '_desc'])) {
      $extra[$ename]['#description'] = t($settings[$ename . '_desc']);
    }
    if ('textfield' == $extra[$ename]['#type'] && isset($settings[$ename . '_size'])) {
      $extra[$ename]['#size'] = $settings[$ename . '_size'];
      // $extra[$ename]['#attributes'] = array('class' => 'text');  // REMOVE OR COMMENT THIS LINE OUT

      // ADD THE FOLLOWING:

      if (isset($extra[$ename]['#attributes']['class'])) {
        $extra[$ename]['#attributes']['class'] .= ' text';
      }
      else {
        $extra[$ename]['#attributes'] = array('class' => 'text');
      }

      // THIS IS THE END OF THE NEW CODE

    }
  }

around line 253 in addresses.module.  That made it work for me anyway.

Oh, if you are interested, the reason it didn't work is AJAX couldn't find the class of the province field, as further on up the chain it was being added, but then overwritten here.


Cannot move block Main Page Content to different region

Something similar happened to me.  The problem was that the main content block was configured to show on "all pages except those listed" and the one listed was front.  When I removed front, I was able to move the block, or rather my changes showed up on the front page too.


Why hook_preprocess_html() isn't working?

Try the general preprocess hook, like:

/**
 * Implements hook_preprocess().
 */
function my_module_preprocess(&$variables, $hook) {
  if ($hook == 'html') {}
}


How to get different size image on views

I used IMCE under Drupal 6.x. However, the resize only occurs at the time you upload and image with their editor which is cumbersome, to say the least. It depends on who has to upload the images, I guess.

Otherwise, CSS, as others mentioned, is probably your best bet. Now a day, browsers properly (cleanly) resize images so they still look good. (10 years ago, however, it was horrible!)

If you want to use IMCE and need to resize existing images, you could look into using convert on your server to resize existing files. However, you'll have to write an intelligent script that properly renames everything properly...


Show whole taxonomy tree starting from current term

Take a look at Taxonomy Menu Block Module

  Taxonomy Menu Block allows you to make blocks containing unordered
  lists that represent the structure of your vocabularies, creating a
  menu out of your taxonomies (without using Drupal's menu system).


Show contact form in block only, not page?

You can use the module Webform for contact forms. It comes with the option to make it available as a block. Here's a quick screenshot of the option:

You can also add other function like email notification, AJAX, template for confirmation page, etc. It's a highly customizable module, very recommended.


Use Composer to manage sub-theme Bootstrap LESS dependencies when using LESS starterkit

composer require twbs/bootstrap ^3.3.6 --prefer-dist -vvv

Drupal Bootstrap requires 3.x.x the caret will stop us tripping into v4.

We don't want to include any git files so we do --prefer-dist.

This downloads the latest bootstrap source to vendor/twbs.

I can expose this dir to my subtheme by editing:

/themes/custom/MYSUBTHEME/less/bootstrap.less

Now when I run composer update I will get the latest bootstrap less in my subtheme.


Similar to this question:

I have an user field called "custField" and it's value (example : 123456). I need to check all users that have "123456" as value:

$users = \Drupal::entityTypeManager()->getStorage('user')
  ->loadByProperties(['field_custField' => '123456']);

Then, I need to check if this user:

$user = reset($users);

has the role "director":

$user_has_role = $user && $user->hasRole('director');


How can I change the precision of a field used in a field collection or content type?

Larry,
On the Drupal side, those are the only changes you need to make, the field_config_instance table doesn't track the data specifications. Just don't forget to clear the cache_field table, and the MySQL tables themselves too.


How to migrate a value into a field attached to a taxonomy_term (from CSV using YML)

Looks like the field name is misspelled?

  field_leagcy_id: City_Code


Ajax call returning JSON forces IE8 and 7 to download file instead of reading it

I finally located the error: it was because of the file codification, some of them were in UTF-8 and other ones in UTF-8 without BOM so IE7 detected an strange character at the beginning of the json being unable to parse it, coding all files (js files, php and module files) in UTF-8 without BOM solved the problem


window.location.hash returns the part of the URL after the #, including the #.
Passing to $() a string like, for example, "#tab1" selects any element that uses "tab1" as ID. (Differently, ".tab" selects any elements that uses "tab" as CSS class.)

$(window.location.hash, this) select all the elements that has window.location.hash as CSS selector, using this as context; this is the element on which an handler is triggered.
$().closest() returns then the first ancestor element that matches the selector passed ad argument.


How do I use a submit callback on a Drupal admin settings form?

The default submit handler of $form_id . '_submit' only fires if no other submit handlers have been set.

Because system_settings_form() sets a submit handler, the default handler doesn't fire, so you have to specify it if you want to use it.

You can do so like this:

/**
 * A custom form.
 */
function custom_form() {
  $form = array();

  $form['custom_form_field'] = array(
    '#type' => 'textfield',
    '#title' => t('Custom form field'),
    '#default_value' => variable_get('custom_form_field', ''),
  );

  // Set a submit handler manually because the default submit handler
  // gets overridden by the system_settings_form() submit handler.
  $form['#submit'][] = 'custom_form_submit';

  return system_settings_form($form);
}

/**
 * Submit handler for the custom form.
 */
function custom_form_submit($form, &$form_state) {
  // Submit code here.
}

Adding your submit handler like this means yours will run before the system_settings_form() submit handler.

If you want yours to run after, instead of:

// Set a submit handler manually because the default submit handler
// gets overridden by the system_settings_form() submit handler.
$form['#submit'][] = 'custom_form_submit';

return system_settings_form($form);

Do:

$form = system_settings_form($form);
$form['#submit'][] = 'custom_form_submit';
return $form;

Make sure not to do this though:

$form = system_settings_form($form);
$form['#submit'] = array('custom_form_submit');
return $form;

because that would overwrite the system_sttings_form() submit handler, which would defeat the purpose of using the system_settings_form() function in the first place.


Figured it out: for the _links href I was using a relative URL instead of absolute.


How to use metatags_quick to add no-cache meta tags in D7?

I want to say that, in some cases, you can add by template way your meta tags to your specific page.

you can locate html.php.tpl in modules > system file. copy and paste it inside your template directory. then add your meta tags using some php code to show these tags only in that specific page:

  <?php
  if(isset($_GET['q'])){
      $path = $_GET['q'];
      if(preg_match('/test/', $path)){
      ?>
        <meta http-equiv="Cache-Control" content="no-cache, no-store, must-revalidate">
        <meta http-equiv="Pragma" content="no-cache">
        <meta http-equiv="Expires" content="0">
      <?
      }
  };
  ?>

(you can add this snippet before, for example, the <title> tag line)

remember that if you need your meta in more pages, you can replace the pattern of preg_match() php function (in this example is /test/) for several pages (for example /(test|another_test_page|another)/ )

Update: if you do not see changes, is very important clear cache to see changes.

Update2 drupal_get_path_alias() could be an useful function to get the current alias: Given an internal Drupal path, return the alias.


Stop User From Publishing an Event if the Start Date is Before a Certain Month Using Rules

I'm not sure that Rules is required to do that.

I would rather use Field Validation module. It is able to configure complex validation rules for any field.

In its submodule called "Field validation extras" there's a validation rule that will help you, it's called "Date range2". You can set a specific minimum date according to your needs, and a far enough maximum date.


Google map in jQuery UI tabs / Drupal behaviors.js

Further to the comments, here is a jsfiddle of what I was talking about. This is a quick example, but should be easily adapted to your own code. I altered the dimensions on the maps to show the change

CSS:

#toolbar
{
    width:100%;
    height:20px;
    background:#000;
}

#toolbar li
{
    display:inline-block;
    min-width:100px;
    background:#fff;
    color:#000;
    border:1px solid #ffff00;
    cursor:pointer;
}

#maps
{
    position:relative;
    width:800px;
    height:600px;
    overflow:hidden;
}

#maps #tabs-1,
#maps #tabs-2,
#maps #tabs-3
{
    position:absolute;
    top:0;
    left:0;
    width:800px;
    height:600px;
}

#maps #tabs-2,
#maps #tabs-3
{
    opacity:0;
}

HTML:

Map 1

Map 2

Map 3

JS:

jQuery('#toolbar_tabs1').click(function(){
    jQuery('#tabs-1').animate({'opacity':1}, 200);
    jQuery('#tabs-2').animate({'opacity':0}, 200);
    jQuery('#tabs-3').animate({'opacity':0}, 200);
});

jQuery('#toolbar_tabs2').click(function(){
    jQuery('#tabs-1').animate({'opacity':0}, 200);
    jQuery('#tabs-2').animate({'opacity':1}, 200);
    jQuery('#tabs-3').animate({'opacity':0}, 200);
});

jQuery('#toolbar_tabs3').click(function(){
    jQuery('#tabs-1').animate({'opacity':0}, 200);
    jQuery('#tabs-2').animate({'opacity':0}, 200);
    jQuery('#tabs-3').animate({'opacity':1}, 200);
});


Form #states only work after change, but not on initial load

My given code works correctly. However, there is a bug in Paragraphs that instantly re-shows hidden fields from form API, see:

https://www.drupal.org/project/paragraphs/issues/2868155#comment-12493576
https://www.drupal.org/project/paragraphs/issues/2946856

Applying the patch from issue #2946856 fixed it for me.


How can I serve individual static text files with the same name from the webroot for each multisite instance?

It maybe is possible with Nginx but Nginx config is off-topic. Please have a look at the RobotsTxt module instead. The RobotsTxt module simply provides you a /robots.txt route that behaves just like a normal robots.txt file with the difference that you can configure the content of it from the back-end per site. You only need to pay attention that you deleted the physical robots.txt file to let the RobotsTxt module do its work.

  Use this module when you are running multiple Drupal sites from a
  single code base (multisite) and you need a different robots.txt file
  for each one. This module generates the robots.txt file dynamically
  and gives you the chance to edit it, on a per-site basis, from the web
  UI.

  Note: You must delete or rename the robots.txt file in the root of your Drupal installation for this module to display its own robots.txt
  file(s).

This solves your robots.txt problem. The ads.txt needs to be solved the same way. You need to create a custom module that does just the same as the RobotsTxt module for the /ads.txt route. With an admin settings form to store its content.


it sounds like you aren't trying to add a field, but rather, are trying to DISPLAY a field (link, more specifically) on the user account page.

What you need to do is simply edit the user profile template of your theme to show the link you need in the footer/header or wherever else you need.

Something like the below should work:

Go into our drupal root folder and from /modules/user/ copy the user-profile.tpl.php file and paste it into your theme's /templates folder
It should just have code that looks like this to begin with:

<div class="profile"<?php print $attributes; ?>>
   <?php print render($user_profile); ?>

Add your link at the bottom, making the template file something like

<div class="profile"<?php print $attributes; ?>>
    <?php print render($user_profile); ?>
    <?php if (in_array('my_role', $user->roles)): ?>

My link

    <?php endif; ?>

Make sure you clear your caches, visit a user account page, and make sure it's all working.
Adjust the HTML above as you see fit...


Create content types containing other content-types

Ok, you should be familiar with

entity
view mode
entityreference

after install entityreference create a reference to books in your catelogs content-type, then go to catelogs > manage display and for books reference select Rendered entity formatter and in its options set something like teaser

after this go to books > manage display and configure teaser as you need.

also you can add more view modes by Display Suite or via simple module:

function mymodule_entity_info_alter(&$entity_info) {
  $entity_info['node']['view modes']['render_in_catelogs'] = array(
      'label' => t('render in catelogs'),
      'custom settings' => FALSE,
  );
}


Filter by end date if it exists, if not then filter by start date

Either you make end date field mandatory or use hook_views_query_alter to get  ongoing  or future events.

If you go with field mandatory option, you simply need to add two view filters with OR condition.

Start date >= Today OR
End date >=Today


Outputting main menu in full in page.tpl.php

Calling menu_navigation_links() with only the menu name by default provides only the top level links.  To delve deeper you need to provide the second $level argument, eg:

$main_menu =menu_navigation_links('main-menu', 1);

will provide the top and next level links, and:

$main_menu =menu_navigation_links('main-menu', 2);

will provide one level deeper.


How to fix "GeoType" plugin does not exist

Alfter some reading and searching, i finaly found a solution. Just go here and apply patch #10. It's just one change that need to be done in the GeoConstraint.php file in src/Plugin/Validation/Constraint/GeoConstraint.php. In line 14,7 change "@Plugin(" to "@Constraint("


Is it possible to pass configuration values as arguments to services?

In your services file add the following service:

# The bar configuration for the foo module
config.foo.bar.immutable:
  class: \Drupal\Core\Config\ImmutableConfig
  factory: config.factory:get
  arguments: ['bar']
config.foo.bar.mutable:
  class: \Drupal\Core\Config\Config
  factory: config.factory:getEditable
  arguments: ['bar']

In your service create method add either config.foo.bar.immutable or config.foo.bar.mutable service as an argument.


If your looking for a module then there is Role Field that creates a new field type that allows you to choose from the list of roles.


Webform: send uploaded files as attachments

All sorted in the end with host entries on the server,I have updated
host entries for sending email and added domain name as host entry
then webform very fast to submited .it's works for me


Drupal Queue example : form_state->get('XXX') always empty

Lets try with

$form_State->getValue('insert_counter');

or

$form_State->get('insert_counter')->getValue();


Export Content Type to a Form Like Structure?

I would recommend looking into Webform Template. All you have to do is make the Webform the one time, then you can copy the configurations for new forms.


Rules - Send mail to all addresses in email field of specific content type

You can use Views Rules module. For achieve this goal first you have to create a view to get all mail values of content type (school) and than its result provide to rules using this module. For more information go through the documentation of Views Rules module.


Block Node Access After A Certain Amount of Views

You can control it using hook_node_access($node, $operation, $account) for Drupal 7. For Drupal 6 one can use hook_nodeapi() for similar result.

When $operation is view, first update usage index for that $account (you need a database table with nid and uid as keys, and number of uses field) and then test if he still can see it, or no. Return appropriate NODE_ACCESS_* constant. Done.

Of course you will need to write your own module, but I guess it'll take less time to wrap simple function in a module than to hack 3 or 4 modules to work together in a way they was never designed to.


how to prevent user from clicking button twice on server side in jqx

Preventing users from submitting forms twice becomes very easy with that module hide_submit.

Take a look at the issues as many features patched but not yet in the master branch of that module.

It may guides to achieve the same thing for (non submit buttons).


Display formresults in same block as form

Solved it. Solution:

in function reiskosten_form_submit($form, &$form_state) {

$result = drupal_json_decode($data->data);
$form_state['results'] = $result;

in function reiskosten_form($form, &$form_state) {

$form['destination'] = array(
  '#markup' => '<div>' . $form_state['results']['destination_addresses'][0] . '</div>',
);

Wrap t in an if to see if the values are there and the magic happens. Pfff


Is it possible to POST values to another page from the FORM SUBMIT function

It sounds like you are doing a multi step form (given the URL in your form is "confirm"). You don't want to be looking at $_POST values, you'll want to utilize FormAPI all the way through.

See for examples:

http://www.sitepoint.com/building-multi-page-wizard-like-form-drupal/

http://jamesdavidson.io/blog/how-create-multi-step-form-drupal-7

http://www.webomelette.com/ctools-object-cache-multi-step-form


Custom module 'managed_file' variable info keeps disappearing

Scott's code is right (and is nearly identical to what I had) but the final step I was missing is in the form's submit handler, where I needed to grab the file that was uploaded and mark it as permanent, and add a file usage to tell Drupal the file was in use. By default Drupal treats uploaded files as temporary and they are deleted from the database and filesystem after 6 hours (when cron runs).

Here's the submit handler code.

function MODULE_admin_settings_submit($form, &$form_state) {
  global $user;
  if (isset($form_state['values']['custom_managed_jpg']) && $form_state['values']['custom_managed_jpg']!="") {
    // Load the file via file.fid.
    $file = file_load($form_state['values']['custom_managed_jpg']);
    // Change status to permanent.
    $file->status = FILE_STATUS_PERMANENT;
    file_save($file);
    // Record that the module (in this example, "custom module") is using the file.
    file_usage_add($file, 'custom_module', 'custom_managed_jpg', $user->uid);
  }
}


Trade-offs between Job Queue vs. Drupal Queue

Drupal Queue is a backport of Drupal 7's queue API for Drupal 6. It provides basically the same features as Job Queue. However a big advantage with Drupal Queue is that it uses the same API as Drupal 7 Core. This means if your module uses Drupal Queue in D6, your upgrade path to 7 will be effortless.


How can I allow/facilitate users to upload images and create a slideshow?

Sure you "could" use the 'Book' module with the child pages as you described. However that is not really going to help your users a lot. Except maybe from easily navigating from the images posted by 1 user to another user (if that is what you also want to consider)? And it does not really help I think for reducing the number of nodes to be created.

What I think is more important to consider are these items:

Add an image field to the content type you are considering using, in which you allow "multiple images". That way a single user may add all their images to "their" node. And with "permissions" it's straight forward to ensure that they can only edit their "own" node (e.g. to add more images later on). And at the same time avoid they (accidently?) add "their" images to a node of another user.
Use the Field Slideshow module to actually create a slideshow from these images.
To further simplify (for your users) the upload process of images, you may also want to consider using the IMCE module, which is an image/file uploader and browser that supports personal directories and quota.

With only these 3 items you should get pretty close to what you're looking for I think, no?


Theme based altering of default image-style for the same node-type and view-mode

Well after reforming my question 3 times and rethinking what the actually question should be like to find a solution, I came to the conclusion that the Domain_views module is completely broken (ALL Domain views fields always output the default Domain ID/name/path no matter what), and that the theme layer node--view-mode.tpl.php altering approach is not generic enough to have this functionality in other use-cases.

So I found a nice trick, which maybe also helps others to change field styles in a given steady node-type and same view mode under certain conditions, but it needs Views module:

Use the Views_conditional module and use your fantasy to get the needed result. :-) That easy!

In my case I was able to turn off the Domain_views module completely (finally!) and have used the absolute path setting from the content:path views field to change the image-style under the condition, that the path includes a given pattern of one of my domains. I have 2 image fields (excluded in Views) and a conditional field showing one of them if needed, e violá! :-) My image style changes in the 2 different domains by the same given node-type and node-view-mode! Awesome

Views as a full node view mode designer... I never stop learning. ;-)


Maintaining order history when creating orders as admin

I was able to solve this issue:

RECAP

Problem: Keeping order history in situations where the admin creates orders on behalf of Customers.

Solution:
a) User profiles must exist for the customer profiles. If the admin is creating customer profiles, a Rule can be created to a create User Profile whenever a Customer Profile is saved. To do this, I created a field for Customer Profiles called "Username", and use that data to populate the name of the new User.

b) A script will need to be written to automatically associate ownership of the Customer Profile by the appropriate User Profile. I was unable to create a functioning Rule which doesn't use my own php code to handle this.

c) One more rule to change the data value of the Order before it is saved. Specifically, you want to change [commerce-order:owner] to the right value (which can also be supplied by my Customer Profile's "Username" field). You will need to ensure that your rule has a Condition of "entity has field -> username" or the appropriate token won't be available.

I hope this can be helpful to someone!


Drupal 7 theme similar to Wordpress Twenty Fourteen theme?

You're going to find Drupal is pretty limited on well made pre-built themes. If you're looking for a good grid system, NineSixty and Boostrap provide a good base to build upon. As far as menu settings and post output, this is typically custom to each site. The post output, for instance, would rely on a custom content type and View to display this information.


How to organize a lot of related blocks for facet search programatically?

I ended up doing this with Panels.  I took the facet blocks and grouped them using mini panels, and then I used Panels Style Collapsible to allow them to be expanded or contracted as necessary.


Remove query strings from static resources in template.php

The only reason you'd want do this is to remove any cache busting query parameter. These are query parameters that are appended to a URL (e.g. www.example.com/js/some_file.js?b= 1433781670 & www.example.com/css/some_file.css?b= 1433781671 ) to prevent browser caching.

As the tutorial probably explained, you'd only want to do this for static resources (i.e. any web resource like a CSS/JS/Image file that will never change) so that the browser will cache the static resource.

As for the template question you can place the MYTHEME_processs_html() function anywhere in template.php (if you don't have one, create it). On top of that, the only thing you'd need is to replace MYTHEME with the short name of your theme and flush your theme cache.

If you're new to Drupal I'd recommend avoiding this for now; unless you're sure there's only static CSS stylesheets that can safely have its cache-busting query string removed, you can end up with a scenario where modules/themes aren't displaying correctly because the cache busting query parameter was needed.


How to add Profile2 form to ctools multistep wizard

I found the answer in a similar thread, works perfectly with ctools.

How to display a profile form using profile2 module


If the table doesn't exist (for some reason), you can create it manually by executing an sql query.

Here is the query to create the semaphore table:

CREATE TABLE `semaphore` (
  `name` varchar(255) NOT NULL DEFAULT '' COMMENT 'Primary Key: Unique name.',
  `value` varchar(255) NOT NULL DEFAULT '' COMMENT 'A value for the semaphore.',
  `expire` double NOT NULL COMMENT 'A Unix timestamp with microseconds indicating when the semaphore should expire.',
  PRIMARY KEY (`name`),
  KEY `value` (`value`),
  KEY `expire` (`expire`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='Table for holding semaphores, locks, flags, etc. that...';


Changing blocks based on visitor's country

Your code seems to be right. You've mis-spelled the module name in the module_invoke function at #3 and misplaced the semicolon ;

Try this:

<?php

$detectedcountry = module_invoke('ip2country','get_country',$_SERVER['REMOTE_ADDR']);
$us_canada = array(
  'US','CA'
);

//return true in block visibility when the country appears to be in detected country
if(in_array($detectedcountry,$us_canada)){
  return true;
}

?>


Change style of custom view mode condionally

This is pretty similar to How to provide template for particular view mode? where as you can add custom php code to add further variables used in that viewmode or add simple if/ else/ in_array to the used template (this is not limited to a custom template - you can always override the default node.tpl.php in your theme.

UPDATE: add only a css class depending on the term reference field.

// can also be THEME_
function MYMODULE_preprocess_node(&$vars) {
  if ($vars['view_mode'] == 'myviewmode') {
    if(isset($vars['node']) && isset($vars['node']->field_my_term_reference)) {
      // class to add a general has-term-reference-class
      $vars['classes'][] = 'has-term-reference';
      // add a specific term-reference-class
      foreach($vars['node']->field_my_term_reference as $tid) {
        // class based on term id
        $vars['classes'][] = 'term-id-' . $tid;
        // class based on term name
        $term = taxonomy_term_load($tid);
        $vars['classes'][] = 'term-name-' . $term->name;
      }
    }
  }
}


Unserialize() Error after moving the installation directory

After making a back-up of current db,

Try this in phpMyAdmin or mysql console.

TRUNCATE `cache`;
TRUNCATE `cache_block`;
TRUNCATE `cache_bootstrap`;
TRUNCATE `cache_field`;
TRUNCATE `cache_filter`;
TRUNCATE `cache_form`;
TRUNCATE `cache_image`;
TRUNCATE `cache_libraries`;
TRUNCATE `cache_menu`;
TRUNCATE `cache_page`;
TRUNCATE `cache_path`;
TRUNCATE `cache_rules`;
TRUNCATE `cache_token`;
TRUNCATE `cache_views`;
TRUNCATE `cache_views_data`;


Why are my if/else statements in page.html.twig ignored?

I would check, if the page render-array contains the element sidebar_first. You can do this with

{{ dump( page|keys) }}

in your page.html.twig (or use devels kint function for that). The |keys filter will prevent you from memory overflow if your page is big.

If this is the case, then your template is ok and you don't have to look at twig, but to search, what else is in the render array and where it could be originated.


User may edit their webform submissions, but only while in draft

You don't need a custom route, you can hook into the entity access check for the existing entity routes:

mymodule.module:

use Drupal\Core\Session\AccountInterface;
use Drupal\Core\Access\AccessResult;
use Drupal\webform\WebformSubmissionInterface;

/**
 * Implements hook_ENTITY_TYPE_access().
 */
function mymodule_webform_submission_access(WebformSubmissionInterface $webform_submission, $op, AccountInterface $account) {
  if ($op == 'edit' && !$webform_submission->isDraft() && in_array('role', $account->getRoles())) {
    return AccessResult::forbidden()->cachePerPermissions();
  }
  return AccessResult::neutral()->cachePerPermissions();
}


Remove orphaned module data after uninstall

Use following database query to remove the module:

Drupal 8

DELETE FROM key_value WHERE collection='system.schema' AND name='module_name'

Drupal 7

DELETE from system where name = 'old_module1' AND type = 'module'

See: How to fix "The following module is missing from the file system..." warning messages.


What other PHP memory_limit restrictions could there be besides php.ini?

Try including "RLimitMem 128000000" in your .htacess file.


The only template file used from the Taxonomy module is the taxonomy-term.tpl.php file. If a theme implement that template file, it receive the following variables. (The list is partial; for the complete list see the documentation.)

$term_url: Direct URL of the current term
$term_name: Name of the current term
$term: Full term object

page--taxonomy.tpl.php is a page template that Drupal uses for pages with a URL matching taxonomy/*. It is a page template, for which the variables are different. In particular, it doesn't get any $term* variable.

References

taxonomy_theme()
theme_get_suggestions()


Add unique class to each link outputted by views

Go to Theme information link in your view, create a new

 views-view-fields.tpl.php

http://api.drupal.org/api/views/theme!views-view-fields.tpl.php/7

there you could assign a dynamic value from your query result to $field->class or add another custom wrapper to each field or use
http://api.drupal.org/api/views/theme!views-view-field.tpl.php/7

for this field only


How to get node.tpl.php to display different content for different nodes?

I don't See any node id in your code. If all you want is to have PHP generated output for an URL, define the path with hook_ menu() and just return the generated HTML from the call back method.


How to create hook for altering every node form?

/**
 * Implements hook_form_BASE_FORM_ID_alter().
 */
function MYMODULE_form_node_form_alter(&$form, &$form_state) {
  // Do stuff.
}

It could be that it didn't work because you have to clear the cache after adding the hook.


Somewhere you specified image_image, a widget, formatter or field type. There is no such thing, find it and correct it.

You get better help if you share your code.


Remote Entity Create with Node Reference

If you are using the entity api to create and save your entity its fairly easy:

// Create the node and wrap it in entity metadata wrapper
$node_create = entity_create('node', array('type' => 'my_content_type'):
$node_wrapper = entity_metadata_wrapper('node', $node_create);

$node_wrapper->title->value("My Title"); // Set the title
$node_wrapper->save(); // Node is now saved
$node_nid = $node_wrapper->getIdentifier(); // We now have the nid

// Doing the same thing here except adding the reference
$node_create2 = entity_create('node', array('type' => 'my_other_content_type'):
$node_wrapper2 = entity_metadata_wrapper('node', $node_create2);

$node_wrapper2->title->value("My referenced title");
$node_wrapper2->field_node_reference->value($node_nid);

$node_wrapper2->save();


Lightbox 2 - Embeded Media Field / Media : Youtube can't play videos on LightBox2

You can install Embedded Media Field  module and Video Embed Field module.

Then add a cck field of type "Video Embed" and widget "Video" for a content type.

In that field you can enter the youtube video url. Then display that node in lightbox and it will work fine to play in the lightbox.


How to display a block on only the listed pages using wildcard and excluding subpages?

Method 1. PHP filter

I think your question is partially answered here:

How to add page restrictions for blocks in drupal?

Only you might use this code:

<?php
$arg = explode('/', drupal_get_path_alias());
if ($arg[0] == 'about-us' && $arg[1] && $arg[2] == NULL) {
  return TRUE;
}
else {
  return FALSE;
}
?>

Method 2: Context module

Alternatively, you can try the Context module, which offers more robust visibility options. For instance, in addition to including paths you can prefix a path with a tilde "~" to exclude it.

I think this should do it:

about-us/*
~about-us/*/*

Edit: Added second method.

Edit: Using $_GET['q'] in method 1 instead of arg() (Thx, @leymannx!)


Filter title and use token like:
[Title]


Different placement/alignment for image (field) in teaser and Full content view

Just pick the field with right parent

on node teaser view - you will find class as "node-teaser"

and on full node view - you will find class as "node-full"

so its just matter of picking field with parent while applying the css.
OR also you can have a separate template for your node-teaser view, check this link


Change default Scald legend or caption output

It seems that you can alter the settings of players as much as you like, but it won't change the caption text because the pattern is hardcoded in the function theme_sdl_editor_legend() of the Scald module.

So we need to overwrite the output by something of our choice.

The previously mentioned theme function can be overwritten in your themes functions.php. Probably you use a Drupal Core or contributed theme as administrative theme, those template.php files you should not change. Thus the preferred method is below (a custom module).

Below you find a simple example of how to get rid of the "by" part in a custom module.
Effectively we just completely overwrite the output of theme_sdl_editor_legend() using an implementation of the hook_scald_dnd_library_item_alter() hook. You can change $item['meta']['legend'] to any string you like using data from $atom.

/**
 * Alter a scald library item.
 *
 * Implements hook_scald_dnd_library_item_alter()
 *
 * @param $atom
 *   The atom object.
 * @param $item
 *   The scald library item.
 */
function MODULE_scald_dnd_library_item_alter($atom, &$item) {
  $item['meta']['legend'] = "
   <div class='meta'>
    <!--copyright={$atom->sid}-->{$atom->rendered->title}<!--END copyright={$atom->sid}-->
  </div>
 ";
}


how to validate file size in drupal file upload

You're currently setting the limit to 1024*1280*800 bytes, which is the equivalent of about 1Gb.

Remember, 1kb = 1024b, 1mb = 1024kb, so for a 1mb limit:

'file_validate_size' => array(1024 * 1024),


Rather than storing the form ID, you could just store the webform ID and check that in a form alter. Webform provides its own form alter hook that only fires for webforms and lets you put the hook in a dedicated include file.

See honeypot_webform_submission_form_alter() in third_party_settings/webform.honeypot.inc for an example of getting the webform from the hook:

/**
 * Implements hook_webform_submission_form_alter().
 */
function honeypot_webform_submission_form_alter(&$form, FormStateInterface $form_state, $form_id) {
  // <snip>

  /** @var \Drupal\webform\WebformSubmissionInterface $webform_submission */
  $webform_submission = $form_state->getFormObject()->getEntity();
  $webform = $webform_submission->getWebform();

From there you can use $webform->id() to get the webform ID.


Create New User After Subscribing with Simplenews

I changed tact. The above probably has security issues, but I only needed a simple temporary solution for a new project launch. I dropped the use of a frontend 'Subscriber' option and instead reverted back to a standard registration page and commented out the $vars tabs option in the theme template.php page.


Low level way is to use hook_query_alter - with it, you can add UNION with anything.
More direct Views way is hook_views_post_execute:

This hook is called right after the execute process. The query has been executed, but the pre_render() phase has not yet happened for handlers.
Adding output to the view can be accomplished by placing text on $view->attachment_before and $view->attachment_after. Altering the content can be achieved by editing the items of $view->result.


How to create multiple nodes using Rules once?

You could use the Flag module and define a none global flag used to flag nodes of type "Run" (name the flag whatever you want).

Then extend your existing Rule like so:

Add an extra Rules Action to flag that node of type "Run" (to indicate that the rule was executed a first time for that user).
Add an extra Rules Condition to check that the node was NOT yet flagged by the user viewing the node.

Using this approach, you have a mechanisme in place that allows you to keep track of the users for which your rule was yes or no executed exactly 1 time.


Identifying the level of menu items in the item array?

I'm not sure to understand your problem, but as you define everything by code, it should be straightforward.

You can create any menu entry you want, on any existing or newly created entry.

As for the hierarchy, you just have to define your paths like any URL path. As per the doc :
If you have

function mymodule_menu() {
    $items['abc'] = array(
      'page callback' => 'mymodule_abc_view',
    );
    return $items;
}

You can then define a child entry like this :

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

This will give an entry at the root level 'abc' and a child entry 'abc/def'.

HTH.


PHP Fatal error: Uncaught Error: Call to undefined function cache_get()

In my case (moving production website to fresh server) memcached was enabled in settings.php, PHP daemon was installed and running on server, but no PHP extension was installed


How to show the contents of view page from template?

In view Advanced Section  Theming information click Rescan template Files for your theme.


modules -> migrate UI -> configure.

Press on the gear and you will enter the migration process.


A nice way to deal with that is to temporarily get out of profile2 rendering way. What I explain here works also for the input form.

1 - Enable the field_collection module.

2 - Create your fields collections.

3 - Then you can arrange the field collection display, including for the form.

4 - You replace your fields in profile 2 with the field collections.

5 - Enable the overlay module (not mandatory), at the bottom of each field collection you can now see add and edit buttons.

Now your fields collections are rendered as you wanted, including for profile2 form.

This is a "good to go" workaround as can be seen on the screenshot.

OR

profile2-display-suite-forms


Why can't I find any pages after migrating a site?

So, the usual way to do this is like this.

dump all caches and back up the database
clean drupal install on your new server
move the db to your new server
configure proper db user on new server
copy the sites folder to the new server
make sure settings.php is correct for new server config
run update.php

It's not clear from your description exactly what's happened, but I would try it again. From what you describe, it doesn't sound like you followed all the steps for a normal site migration, so you need to make sure all the stuff drupal needs is there. I've also had some issues with folder permissions when moving stuff to Godaddy, so you can look at that too.


Views math expression or Computed field to find date difference in views

You can achieve this use a template file, since you can use PHP inside templates in Drupal 7

In your view

Now, add both of your date fields and do this to each of them

In your web directory, go to /sites/all/themes/[yourtheme]/templates folder

Create a file named views-view-fields--[view-name]--[machine-name].tpl.php

EX: views-view-fields--hello-world--block-1.tpl.php

Inside the template file put:

<?php

$date1 = new DateTime('$fields["field_invoice_issue_date"]->content');
$date2 = new DateTime('$fields["field_payment_receipt_date"]->content');
$interval = $date1->diff($date2);
echo "difference " . $interval->y . " years, " . $interval->m." months, ".$interval->d." days ";

// shows the total amount of days (not divided into years, months and days like above)
echo "difference " . $interval->days . " days ";

?>

Remember to flush/clear the cache to see changes.


The module Migrate is the most versatile Drupal tool for database migration.

However, book module migration is still not trivial.  Books are nodes, so they can inherit most of their migration from a common class.  But to preserve book node hierarchy that is stored within menu links, you need to use special code  to migrate the hierarchy.  Here is a sketch of the required workflow:

Migrate nodes as normal.
Get hierarchy from the source database book table, and weights from the menu_links table.
Place a public function complete() in your Migration class to call _book_update_outline() to migrate the hierarchy.

A more detailed receipe, with a special code example, is at Drupal.org: Book node migration.


Example:

/**
 * Implements hook_views_api()
 * @file modulename.module
 */
function modulename_views_api() {
  return array('api' => 2);
}

/**
 * Implements hook_views_data()
 * @file modulename.views.inc
 */
function modulename_views_data() {
  $data['custom_table']['table']['join']['node'] = array(
    'left_field' => 'nid',
    'field' => 'nid',
  );

  $data['custom_table']['price'] = array(
    'title'  => 'Title',
    'help'   => 'Help',
    'group'  => t('Node'),
    'field'  => array('handler' => 'views_handler_field'),
    'sort'   => array('handler' => 'views_handler_sort'),
    'filter' => array('handler' => 'views_handler_filter_string'),
  );

  return $data;
}

Read more info in oficial manual Describing tables to Views


Change function hook_block to function my_module_block, and add return $block; to the end of the 'list' and  'view' cases.


Views depends of ctools and this is the cause of autosubmit.

On do: https://www.drupal.org/node/1735254

This is the feature what I need.

  If you want to exclude a field from the ctool-auto-submit-full-form
  auto submission, add the class ctools-auto-submit-exclude to the form
  element. With FAPI, add:

'#attributes' => array('class' => array('ctools-auto-submit-exclude')),


If you are using Contextual Filter in the view then you can override the title by putting %1 for first argument, %2 for second argument etc..

Otherwise add a contextual filter for something like "Content:Author"(depend upon your need) in your created view & override the title in there by placing %1


How to add extra menu source and access it in a theme

To be able to put it in a theme variable I think you're looking at something like the following.  Please note I haven't tested this, but i should put you in the right direction.

In your template.php or a module:

function MYTHEME_preprocess_page($vars){
  $global_menu = menu_navigation_links('menu-global-menu');
  $vars['global_menu'] = theme('links__menu_global_menu', array('links' => $global_menu));
}

Then clear your theme registry/caches.


How can I alter the breadcrumbs on a search page?

For ease of use you might want to look at Path breadcumbs:

  This module is a solution for all problems with the breadcrumbs on
  your site!

  Path breadcrumbs module helps you to create breadcrumbs for any page
  with any selection rules and load any entity from the URL!

There is also Custom Breadcrumbs which was pretty awesome, but be careful if you choose this route as there is serious discussion about deprecating it in favour of Path breadcrumbs.

Hansel Breadcrumbs is useful, but I have found it INCREDIBLY complicated to get set up and working properly. I would suggest to use it only if you're going to be setting up a lot of complicated rules. If it's just for one or two pages, it's probably overkill and might end up making you hate Drupal (and no-one wants that!) ;-)


Create Text Field Programmatically to Media Type

In Drupal 7 fields were shared across all content types; in Drupal 8 they're shared across a single entity type.

As such you've just missed the entity_type when creating the storage:

$field = FieldStorageConfig::create(array(
  'entity_type' => 'file',
  'field_name' => $field_name,
  'type' => 'text',
  'settings' => array('max_length' => 64),
));

As an aside, hook_update_N is for updates only, those functions won't be executed upon install. The point of them is to allow older versions of the module to get up to date with the current version that they're upgrading to. The initial state of the latest version of the module should reflect the state the older version of the module would be in after the update.

You can use hook_install or config files in config/install/*.yml to perform initial setup of your module upon install.


Views: Limit amount of a node type by percentage

This might be a job for _views_pre_render().  In it, you can go through your views results and modify them to your module's content.  The issue here is creating a view result big enough to make your percentages work. For example, let's say you want to have that view of 4 nodes, but only 1 of which is of a certain type.  Since you are sorting by date, if the first 4 are all of that type, you grab one but need to keep looking for 3 of the other type.

In a dull ax approach, you could, though, create a view that returned 100, or however many is reasonable on your site based upon what you actually see re mix of nodes, of both types sorted by date and then do something like:

function YOURMODULE_views_pre_render(&$view) {

  if ($view->name=='NAMEOFTHEVIEW') {

    //  drupal_set_message('
' . print_r($view->result[0], true) . '
'); // just the first row
    //  drupal_set_message('
' . print_r($view->result, true) . '
');    // all of them

    $max=1;    // hardcoded for example purposes
    $total=4;  // hardcoded for example purposes

    $new_result=array();

    foreach ($view->result as $result) {

      if ($max && $result->FIELDTHATHASTHENODETYPEINIT==NODETYPEWEARELOOKINGFOR) {
        $new_result[]=$result;
        $max--; $total--;
      } elseif (--$total) {
        $new_result[]=$result;
      }

    }

    $view->result=$new_result;

  }

  // any other views_pre_render()ing here

}

which if my logic gene is in gear today will cycle through your view results and pick out at most $max nodes of one type and then fill up $new_results up to $total with the rest of the view results and then replace the results of the view with that.

The issue, again, is that if all the results are of one node type, or there aren't enough of the other node type to fill up $new_result, you will have less than $total results returned.

(One or both of the drupal_set_message()s will/might be helpful for figuring out FIELDTHATHASTHENODETYPEINIT.  If there isn't one in your view already, you can put one in and then not display/hide it if necessary.)


How to migrate products display nodes with multiple product references?

I'm in a similar boat, but doing an import for a content type. If data is prepared with multi-value fields as in your second table, I can import the data using Feeds and the plugin 'Feeds Tamper'. So I'm also looking at repeatable and efficient ways to arrange data with multi-fields in CSV format. Saw a post about using Drupal 7 'Feeds Tamper PHP' to do create the multi-valued fields here, https://www.reddit.com/r/drupal/comments/2tumv9/drupal_7x_feeds_tamper_column_values_to_single/co2hesj. <-- Untested, just a reference. HTH.


menu_tree_page_data() is not loading sub-menu items

If you want the whole array of the menu use this function,

menu_tree_all_data('MENU_NAME');

If you find any difficulty, please let me know!


Well, there are a number of screencasts available on the module project page as well as the official module documentation. Assuming you've already tried these and still need help, there are two possibly less obvious places you can go for 'tutorials':

Look through the source code of the module. Many of the more popular contrib modules have excellent documentation in the source on how to use the specific functions, methods, etc.
Scan the issue queue for relations. Other users may have some of the same questions you have (especially issues filed under 'support request') that may be of use to you.

Finally, most modules won't have really useful tutorials on how to use them and rely on the user community to help each other define what is needed. One of the best things you can do to help is to ask questions as you explore the relations module, either here or on Drupal.org, as others may have the same questions. As you get more confident, you can help by adding some of your experience back as a tutorial for other beginners.


Adding HTML class attributes to Entity Reference field links in View

So I finally figured out the problem.

I wasn't supposed to touch the $variables['items'][…]['attributes'] object, I was supposed to create a $variables['items'][…]['content']['#attributes'] array instead and put the class name(s) there.

Having done so, that now works.


How should I get data from the node table?

I don't think you need an execute on a regular query like that. But the way to get any node data would be loading the node with the entityTypeManager service, and getting the field values with $node->get('field_advertiser_id')->getValue(). Its rare to have to get a value that way from the database.
The same goes for the insert or update - you definitely should be using the API for this and not direct database writes.
On top of that you don't need to do anything with the database at all in this example, because the node being deleted is already passed to this hook. Just look at its field values. https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Entity%21entity.api.php/function/hook_entity_delete/9.1.x
But in a case like this, hook_entity_delete may be too late to get values depending on what you need to do. Instead, you probably want to use hook_entity_predelete: https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Entity%21entity.api.php/function/hook_entity_predelete/9.1.x
Example:
function mymodule_entity_predelete(Drupal\Core\Entity\EntityInterface $entity) {
  if ($entity instanceof NodeInterface && $entity->getType() == 'your_content_type') {
    $advertiser_id = $entity->get('field_advertiser_id')->first()->getValue();

    // do something with id, like load that node
    if (isset($advertiser_id)) {
      $entityTypeManager = \Drupal::entityTypeManager();
      $advertiser = $entityTypeManager->getStorage('node')->load($advertiser_id);

      if ($advertiser instanceof NodeInterface && $entity->getType() == 'advertiser_content_type') {
        // Delete this other node.
        $advertiser->delete();
      }
    }
  }
}

You have to be careful with these hooks though, because it can trigger an infinite loop since these hooks are fired every time the actions are performed. Meaning, if you wanted to delete the advertiser node here for example, this hook would get called on that action too. So you need to be specific with your conditions check each value and logic. People get caught in presave hooks all the time.


Migrate only taxonomy terms from a specific vocabulary

source:
  plugin: d7_taxonomy_term
  bundle: tags


Drupal site does not show well when SSL is enabled

You get this message from MSIE because the page has a mixture of secure and insecure content.

The culprit is usually inline/embedded content (images, iframes, javascript, css, etc.) that originate from a non-secure URL. Chrome just refuses to load it, causing the error you see To fix it, you need to locate those elements of the page, and replace them with secure versions.

To locate for these elements of the markup (unless they are obvious now that you know what to look for), use FireBug (requires that you use FireFox instead of MSIE/Chrome) or just press CTRL+uin MSIE to analyze the markup.  In the markup, search for inline/embedded content hyperlinked with URLs starting with http: (instead of https:).

If all your links are internal (i.e. pointing to stuff below the webroot of the same server), you can eliminate the problem by dropping the scheme element of the URL (as suggested in a comment below by @JohnathanElmore).

In other words: if your server is example.com and you currently have the following URL reference as part of your theme:

src="http://example.com/sites/all/modules/spamspan/spamspan.js?somequerystring"

you should replace it with the following:

src="//example.com/sites/all/modules/spamspan/spamspan.js?somequerystring"

or even:

src="/sites/all/modules/spamspan/spamspan.js?somequerystring"

I can't tell you exactly how to go about making these replacements without knowing what you can and cannot do on your site. (If it was my site, I would simply edit the theme templates and clear alll caches. But I've no way of knowing whether this option is available to you.)


The Drupal Themable Forms module adds some helpful theme suggestions for form elements that are missing from core.

The added theme suggestions for form elements are:

  form-element--[form-id]--[element-type].html.twig
  form-element--form-id--[form-id].html.twig
  form-element--type--[element-type].html.twig
  form-element.html.twig


How to display a block if a Boolean on/off checkbox is checked?

Generally, if you're wanting to enable or disable a block based on some parameters (and assuming this block is defined within a module of your writing), you'd use hook_block_list_alter(), test for your condition, and then either display or hide your block.

You can see how this works by look at the block module's implementation of it's own hook, block_block_list_alter().

For instance, if you wanted to hide something based on the current node:

MYMODULE_block_list_alter(&$blocks) {
    $node = menu_get_object();
    $my_hiding_condition = isset($node->somefield[LANGUAGE_NONE][0]['value'])
      && $node->somefield[LANGUAGE_NONE][0]['value'] == TRUE;
    if (isset($blocks['my_block_id']) && $my_hiding_condition == TRUE) {
        // Hide the block.
        unset($blocks['my_block_id']);
    }
}


How to use views to filter specific workflow state in current month

You may want to check if using the Views Date Format SQL module could be a solution for you. Here are some quotes about it (from its project page):

  ... allows to format date fields using SQL.

  The core functionality is to remove the date formatting from render() and put it in query(). I.e. format date values using SQL's DATE_FORMAT rather than PHP's format_date.
  This is achieved by assigning a new default handler to node 'created' and 'changed' date fields. This handler extends and overrides views's build in views_handler_field_date.

  The UI is completely unobtrusive, only a single checkbox "Use SQL to format dates" is added to the handler configuration popup.

Your question is not about creating charts in Drupal, but you may want to refer to this comment also for an example of how we typically use it within the Charts module.


Add a "Save" action in local task to a node

Local tasks are the wrong tool for the job. Local tasks are for providing context-sensitive action links (e.g. Edit, Delete, View) around an item (e.g. node/user). Trying to make a local task become a form submission button would involve all kinds of hacks that probably would be more trouble than its worth.

If the goal is to alter the save button's position for UI concerns, look at using hook_form_alter to alter the appearance/positioning of the node form's Save button. For example, look at a module like Floating Action Buttons that uses a form alter to place the action buttons in a fixed location.


For menus that are printed by invoking theme('links__YOUR_MENU'), you can use the following code and place it in your theme's template.php file:

function YOUR_THEME_links__system_main_menu(&$variables) {
  // Copy here the code from theme_links() function and adjust it to your liking.
}

See the source for theme_links() here.

For menus in blocks, you can do that using theme_menu_tree__YOUR_MENU() override in your theme's template.php file. Here's example code that will work for the main menu:

function YOUR_THEME_menu_tree__main_menu(&$variables) {
  $your_custom_html  = '

your custom HTML

';
  return '
' . $your_custom_html . $variables['tree'] . '
';
}

This will add the content before menu links.


URL contains a number after node/nid: why?

Drupal's path-matching is greedy. The path node/%nid will match anything with that string at the start, that has a separator after it. e.g

node/%nid/1
node/%nid/giraffe
node/%nid/barack-obama
node/%nid/this/is/just/too/much

The 'extra' path segments are passed on as extra parameters to the item's page callback, whether it wants/uses them or not.

The page that you see at node/%nid/1 isn't different at all from the standard node/%nid page.

You'd do well to keep those URLs out of the page source at all costs, or make sure you have an appropriate canonical URL set, as Google will consider them duplicate content otherwise.


How can I get public files path in javascript files?

It depends where you are storing all your files, to use the base url of your site you need to do this:

$base_url."/sites/default/files/xxx.jpg"

If your files are inside some theme:

$base_url."/".drupal_get_path('theme', 'name_theme')."/images/xxx.png

If you are using files with public://, use this:

$uri = $your_file_name; // Example "public://xxx"
$path= file_create_url($uri);

I hope it works in your case


Despite your statement in your question, Hierarchical Select is the standard way to approach this sort of need.

There's likely no other stock solution for this, since no one bothered to duplicate HS.


Hook to replace custom tags in block showing related articles

This is not easy to solve in preprocess, it is better to do this earlier when the view() of the node is executed, for example:

function mymodule_NODE_view_alter(&$build) {
    if ( isset($build['body']['0']['#text']) ) {
      $build['body']['0']['#text'] = replace_tags_in_content($build['body']['0']['#text']);
    }
}

This works, no matter if the node is used as page or in views (as content).

You might run into caching issues, when you make changes, that are not coming from the database and drupal does not know, which cache tags have to be invalidated. This would be a version of this code to address this:

function mymodule_NODE_view_alter(&$build) {
    $nocache = false;
    if ( isset($build['body']['0']['#text']) ) {
      $build['body']['0']['#text'] = replace_tags_in_content($build['body']['0']['#text'], $nocache);
    }
    if ( $nocache ) {
      $build['#cache']['max-age'] = 0;
    }
}

You have to set $nocache in the function replace_tags_in_content($string, &$nocache) to true, if you change dynamic data from outside.


Review the css and theme also like we do for code using code review module

If by the 'Code Review module' you mean the Coder module, it already supports reviewing the code in themes.

  Beginning with the 5.x-2.x version, this module adds a new UI, core
  support, theme support, and a cache for faster display of unchanged
  files. It also supports rule #severity levels of "minor", "normal",
  and "critical."


File field breaks AJAX form in Drupal 7 form API

I experienced the exact same: Drupal 7, custom AJAX form, multiple pages, all working fine. After adding a managed file field it broke the AJAX functionality. Or that was what it looked like...

The past couple of days I spent quite some time digging around misc/drupal.js, misc/ajax.js and modules/file/file.js to turn the managed file field into a single customizable "Select & upload file" button with client side file size validation and auto submit functionality.

After reading your question and remark about that the problem even occurred when manually inserting a plain non Form API file field it dawned to me that I read the following in misc/ajax.js > Drupal.ajax.prototype.beforeSend:

  For forms with file inputs, the jQuery Form plugin uses the browser's normal form submission mechanism, but captures the response in a hidden IFRAME.

I tested this on the dev site and it appeared that AJAX only "broke" after visiting a form page which contained a plain file field. Though the requests felt less snappy and in Chrome and Firefox loading throbbers appear in the browser tabs and the status bar showed a new page was being requested, it seemed to not harm my forms.

But the jQuery Form plugin for Drupal 7.28 has version number 2.52, see misc/jquery.form.js. The jQuery update module 7.x-2.4 ships with path/to/jquery_update/replace/misc/jquery.form.min.js with version number 2.69, though the latest version is 3.51, see http://malsup.com/jquery/form/#download. This latest version appears to use another technique for file uploads which feels like AJAX (or maybe ís using AJAX), see http://malsup.com/jquery/form/#file-upload. I tried this version on the dev site and so far with success!

Download the latest version to your module or theme and use ie. hook_js_alter() to replace the old script for the new one. I implemented this hook for the site's theme:

/**
 * Implements hook_js_alter().
 */
function YOURTHEME_js_alter(&$js) {
  // Define path to old jQuery Form plugin, alter to your needs.
  $old_path = drupal_get_path('module', 'jquery_update') . '/replace/misc/jquery.form.min.js';

  // The script does not get loaded on every page, so check the $js array.
  if (isset($js[$old_path])) {
    // Define path to newer jQuery Form plugin, alter to your needs.
    $new_path = drupal_get_path('theme', 'YOURTHEME') . '/js/jquery.form.min.js';

    // Copy data from old javascript to new and remove old javascript.
    $js[$new_path] = $js[$old_path];
    unset($js[$old_path]);

    // Set new path as data property and alter version number.
    $js[$new_path]['data'] = $new_path;
    $js[$new_path]['version'] = '3.51.0';
  }
}

Or see how jquery_update_library_alter() did it and apply this method to your module.


How do I share configuration between custom admin form and node type edit form?

So the bottom line appears to be that Third Party Settings is a great way to handle content type settings without really caring which content type you're dealing with, but there doesn't seem to be a way to get this working with a custom admin settings form for the reason described in the question.

If I didn't want to have a separate configuration form that handled the content type settings for all content types on one form, I would definitely have used Third Party Settings. However, since I had this extra requirement, I wound up fixing whatever broke along the journey from D8 beta to stable release.

Now the node type gets included with each of the desired settings using the following code:

function mymodule_form_node_type_form_builder($entity_type, NodeTypeInterface $type, &$form, FormStateInterface $form_state) {
  $node_type = $type->get('type');
  $config = \Drupal::getContainer()->get('config.factory')->getEditable('mymodule.settings');
  $config->set('my_setting_'.$node_type, $form_state->getValue('my_setting'));
  $config->save();
}


You need 2 text-formats.  Allow "Image" in tinyMCE profile of one text-format and not allow it for the other.

To set fixed text-format to each text-area field, you can use Better Formats module.  Download from http://drupal.org/project/better_formats and install it.

In "Managed Field" page of your text-area field, check "Filtered text (user selects text format)" and "Limit text format".  You will see all your defined text-formats with leading check-boxes.

Click the check-box of a text-format and save.  In your "Add Content" page, you will see your text-area is assigned with respective tinyMCE editor.


Cannot run composer update after going from 8.3 to 8.5

As of 8.5 core now explicitly requires several PHP extensions in composer.json, including gd:

...
"require": {
  "ext-date": "*",
  "ext-dom": "*",
  "ext-filter": "*",
  "ext-gd": "*",
  ...

The requirements match the required extension list in system_requirements, which would theoretically have to have been met for the original installation, and they were the same all the way back to 8.0.x, so it seems likely you did have gd installed when Drupal was installed.

Without gd installed you should also see an error message in the status report telling you it's missing; if you don't see that error, perhaps you have a different php.ini for FPM and CLI, and gd is only enabled for FPM, so it works in web but not the command line.

The relevant issue on drupal.org is here for reference.


How to add security questions in Drupal 8?

Well at this time you have 2 modules but only for Drupal 7:

Security Questions

  Security Questions provides administrator configurable challenge
  questions for use during the log in and password reset processes.
  Think of it like most bank website logins.

Password reset

  The password_reset module allows for passwords to be reset without
  involving e-mail addresses through the use of security questions.

There is not a 8.x branch at this time, so your best option is study the code and migrate one of them.


Make a block from a "part" of a drop down menu

I would advise using menu block (https://drupal.org/project/menu_block), which allows blocks to be created from menus. The most important part would probably be starting level and max depth, which allows you to specify the options you'd like to use.

If you'd like an example usage similar to what you're attempting to achieve, just let me know and I'll take some screenshots.


How to add data from one Drupal site to other?

You need to migrate the content of site 1 keeping the config of site 2. My recommendation is to use migrate module coz I prefer it. But you'll have to write code to use migrate module.

There are other modules that may help you like node export, deploy. You can also write custom script but I have had most success with migrate module. You might need to justify the use of migrate in comparison to the content to be migrated, because you'll need to write migration classes but for lets say 300 nodes I'd still use migrate.

I wrote an answer sometime ago which talked about migration of content, users, categories etc. See if it helps you to choose as well - Updating content after major upgrade from 5 to 6 (changes to production site need to be reflected in dev environment)


How to trim a field that's been excluded from display?

I've double checked your problem and it seems to works like a charm.

In your view go to Field -> Title -> [edit] -> Rewrite results -> Trim this field to a maximum length -> set maximum length to 50

Add Global: Custom text field and place [title] in text field.

Result should looks like this:


Hide tab for user page for specific roles

You can use arg() function. The function returns a component of the current Drupal path. i.e. if you're on edit user page, the values returned by arg() function will be arg(0) as 'user', arg(1) as user ID, arg(2) as 'edit'.

function bartik_preprocess_page(&$variables, $hook) {
  $arg = arg();
  if (('user' == $arg) && (!empty($arg[1]) && is_numeric($arg[1])) && in_array('editor', $variables['user']->roles)) {
    // Your code goes here..
  }
}


You may want to take a look at hook_menu()

Here you can define paths and route variables to where they are needed.

For example:

function hook_menu() {
  $items['admin/structure/optimizations/manage/%'] = array(
      'title' => t('Your Page Title'),
      'page callback' => '_your_callback', // The callback that is building the page
      'page callback' => array(1), // This is the value from the % array key
      'access arguments' => array('administer users'), // A permission to require
      'type' => MENU_NORMAL_ITEM,
  );
}

function _your_callback($val) {

  //Access the % from the URL defined in hook menu using $val.

  ...

}


See all nodes where user profile entity reference matches the same entity reference on the node

The easiest way is creating a view for the School content type and add the fields you want to display on your list. Then add:

A reference to the entity that is common between the School content type and the ZipCode content type. If there is no connection between the two, you will also need to add a reference to the Region content type and then to the ZipContent type.
Add an argument or contextual filter for the user ID of the currently logged-in user and limit the number of nodes displayed.

Note: I have sometimes achieved the same result by creating a view (for users) referencing the content types and adding the desired fields.

This is a video about view arguments: http://mustardseedmedia.com/podcast/episode39.


How do I create a content type that has another content type embedded inside of it?

Use References dialog. "This module extends reference fields like the user and node reference fields by adding links to add, edit and search for references through a dialog"


What is the best caching solution for website with a lot of content?

Part of the solution could be to compress those cache tables where the typical values to cache are quite big and allow for a high compress ratio. I think render caches fit that description very well.

See e.g. issue [#1281408] and a comment on another issue mentioned in comment #23.


Show page content on another page using views

Not sure if I'm understanding you correctly, but you can create two view modes for the node that contains all the images that users upload, one for 'presentation' and one for 'upload' using Display Suite (see tutorial on view modes). If you don't want the upload version to show the images, simply hide the Image field in the 'upload' view mode.

Additionally, you can use a module like Juicebox to create a nice-looking and easy to navigate Javascript gallery in the 'presentation' view mode - just select "Juicebox Gallery" as the formatter for the Image field (instead of the default Image formatter) in your 'presentation' view mode.


Create a view from both user and node content

You would normally add a relationship to the view to achieve this. I'm guessing you've got a field on either the user entities the organization entities that references the other?

If you add that field as a relationship in the view that will expose that entity's fields for you to add into your view


Uncaught TypeError: Cannot read property 'fn' of undefined

Check out the drupal.org document on using new versions of jQuery for a few solutions. One good solution is the JQuery Multi module that lets you target multiple versions of jQuery via its hook_jqmulti_libraries() hook (its README explains how).


I am not familiar with the flickr integration, but in the included colorbox.js file, it appears that colorbox is looking for images with the .colorbox class.

Have you tried adding the .colorbox class to the img elements in that view? It's possible that the class may have beren removed by a drupal filter.

The relevant Javascript:

 $('a, area, input', context)
      .filter('.colorbox') // target class
      .once('init-colorbox')
      .colorbox(settings.colorbox);
  }


build an admin view of all available rules (rules module), a better rules UI

I am not aware of any hooks but rules_filter looks promising.


How can I make a view showing all users who have not created any nodes or made comments?

Before some days I was also work on some thing like this. In my registration page there is a field named looking-for. I was created a view to show all the members as per there looking-for field. It mean that if user selected male in looking for then only male is shown. I have added below code in the view. You can change condition as per your condition & add relationship & filter criteria.

global $user;
  $profiles = profile2_load_by_user($user);
    foreach ($profiles as $profile) {
        if ($items = field_get_items('profile2', $profile, 'field_sex')) {
        break;
      }
    }
    $i_am=$items[0]['value'];
 if($i_am=='sdmale' || $i_am=='sbmale'){

  $looking='smfemale+sbfemale';

}

if($i_am=='smfemale' || $i_am=='sbfemale'){

  $looking='sdmale+sbmale';

}

   return $looking;


Based on your question I honestly think you are doing something wrong, but if you really do have a legit use case I think you can just do this:

$view = views_get_view('machine-name-of-view');
views_export_status($view, TRUE);
views_save_view($view);


How do you run custom functions after Migrate class finishes an import?

For what you're asking (running a function prior to or after a single Migration) see the documentation for Less Commonly Implemented Migration Methods. They include:

function preImport()
function postImport()
function preRollback()
function postRollback()

Note this caveat from the documentation:

  NOTE: If you are running your migrations through the web UI, which
  chunks the work into batches, if a given migration takes long enough
  to be broken into separate batches, these functions will be called for
  each batch. They are called each time the migration is invoked, not
  just the first (or last, in the complete case).

If you don't like that behavior, then in your preImport() or postImport() simply use a static variable to see if your custom logic has already run once. Lullabot Posted a good blog entry on using drupal_static back in 2011 on this subject.

With regards to per-record migration completion (like moving 1 song from legacy data store to drupal -- 1 "row" of a migration) take a look at the documentation for Commonly Implemented Migration Methods. They include:

function prepareRow($row)
function prepare($entity, stdClass $row)
function complete($entity, stdClass $row)
function createStub()


Have a look at these VBO issues:

views_bulk_operations_action_load_list not working.
Load a list of entity from a VBO View doesn't work (AJAX error).

Since you're using the 7.x-3.3 release of VBO, I recommend you retry your scenario with at least the 7.x-3.4 release. However, as per this comment you might only get it to work using the latest DEV version of VBO.


You can use node--(machine name of contenttype).html.twig to achieve this thing.

{{ content.field_machinenameofimage }}

{{ content.field_machinenameofotherfields }}

Replace the {{ content }} by the above code. And change the above code how you want to achieve.


Domain Access - restrict content for only authenticated users (and keep domain specific settings)

Actually I found the issue was with the content_access module. It was overriding the settings for the domain access.

Once this was turned of domain was able to operate as designed with just the 'publish to ...' settings.


Javascript calander to pick contents on a particular date

You can get this sort of functionality with the very powerful FullCalendar module. It provides extensions to Views enabling you to build complex calendars displaying content, users, and basically anything else a View can display.


Editting/Modifying markup of registration form

You can use hook_form_alter to alter the registration form. This allows you to add markup, change labels, add divs, ...

Also to add markup, you could have a look at markup field

ANd last but not least, check out this page: https://www.drupal.org/node/350634. It contains a lot of info on how to override the user login/registration page

function mymodule_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id === 'user_register_form') {
    // perform other changes here
  }
}


Look for booking / reservation modules. There are some that would be a good starting point for you.

Rooms, Simple Reservation, Easy Booking and Open Hotel are just a few worth trying.


How to hide taxonomy terms from node display and still have them indexed by Drupal search?

I would recommend the Search API. You end up with much more control over the search results, and you have the extra flexibility of using it with views.

You can configure it to also include taxonomy term descriptions in the index which would be an excellent place to store your synonyms/alternate search terms. You could even create a new vocabulary that is never displayed on the node (just set it to hidden in the display tab for the content type), and is limited to only search terms.


We have done this using the Flag module:

  Flag is a flexible flagging system that is completely customizable by
  the administrator. Using this module, the site administrator can
  provide any number of flags for nodes, comments, users, and any other
  type of entity. Some possibilities include bookmarks, marking
  important, friends, or flag as offensive. With extensive views
  integration, you can create custom lists of popular content or keep
  tabs on important content.

Make a flag and add it to your content type.  You may be able to use one of the default flags.

Configure the flag to appear on just teasers.

In your view, configure it for node output, and choose teasers and show links.  I think you can add the flag as a "field" in field-based output, but I don't remember.

Then, your view should show your list of nodes and each will have a flag link with it.  Users can flag their nodes.

You can then make views over the nodes that your users have flagged, either all together or per user.  The Flag module integrates very nicely with Views.


View of users flagged by a user, users flagging a user, and nodes from users flagged by a user

Better late than never, To get your followers of fans you can:

create a view of type users.
create a relationship Flags: User's flaggings.
now this is were most people go wrong you should remove "Include only users who have flagged content."
chose your flag.
Add Contextual filter "Flags: Content ID".
make sure to use the relationship.
WHEN THE FILTER VALUE IS NOT AVAILABLE provide default value of "user Id from logged in user".


Get author id in field template - or make an edit button on a node's teaser

Assuming in your use case an Author is a user on your site, I believe you will be able to access to Author's ID using

{{ element['#object'].getOwner.uid.value }}

No need to create a custom field to hold the author's value.


Loading a large node body sequentially for better performance

It sounds like you've hit an architecture (DBMS) constraint. I'm not aware of a way to break up a node body into segments easily (I mean i'm sure you could use a list of text fields in drupal -- but ewww).

I'm also not sure of a clean way to make the paragraphs index-able for asynchronous javascript fetching, i believe you run into issues like:
https://stackoverflow.com/questions/19477494/per-paragraph-commenting-system

What I would recommend is installing an in-memory cache like Varnish, or Memcache and storing a copy of the full page for anonymous users ... or learning Authcache for more complex scenarios.


How to implement an option for users to limit access to nodes/comments to users with the same role while posting it?

The short answer is: Yes, you can do this with the Group module.

Here are some instructions on how to do so:

Install the Group module and its dependencies.
Enable the Group Node module as well (a sub-module of Group).
Navigate to admin/group, or click the new Group link in the admin toolbar.
Create a Group Type "Year".
Configure the permissions for that group type to allow members to create and/or view nodes (outsiders will not have access unless checked).

There are numerous things you could add to the mix, such as a "Year admin" group role. But giving a sitewide admin the "Bypass group access" permission will do just fine as well.

You can also delete the group_admin role under Group > Group Roles should you not need it.

If you find any bugs or need support you can also use the Group module's issue queue.

Disclosure: I'm the module maintainer.


What function/method can I use to redirect users to a different page?

This is the code that should be used in Drupal 8. See change Record for more info.

use Symfony\Component\HttpFoundation\RedirectResponse;

function my_goto($path) {
  $response = new RedirectResponse($path);
  $response->send();
  return;
}


I had to do this recently also. Revert your jquery_update to 1.3.2 (or whatever it provides by default) and follow the instructions at http://drupal.org/node/1058168.

They key is to notice that you load the newer version of jQuery before the <?php print $scripts; ?> in your page.tpl.php.

The final thing you need to do, which is not mentioned there, is to load your jquery plugin in between the new jQuery and the jQuery.noConflict(). This will make it so you don't have to modify the plugin (That pages tells you how to modify the plugin if you can't do this final step).


How to send an email to a node author after selecting a specific value in a selected list field?

You can use hook_node_presave() and in this function check if the select value is "new litter" and generate email.

function YOUR_MODULE_NAME_node_presave($node){
    if($node->type == 'YOUR_CONTENT_TYPE'){
        //get your field value
        $field = field_get_items('node', $node, 'YOUR_FIELD_MACHINE_NAME')[0]['value'];
        //check if value equals "new litter" key
        if($field == 'NEW_LITTER_KEY'){
            generate_email();
        }
    }
}

change uppercase strings with your module and machine names


How to display a field twice in a view mode?

If you want to display a field twice in hook_ENTITY_TYPE_view(), you can get the field object from the first field and clone the field with a different field formatter and custom display settings.

For example to add the body a second time with the field formatter text_summary_or_trimmed and a custom trim length of 80:

function mymodule_node_view(&$build, $entity, $display, $view_mode) {
  if (isset($build['body']['#items'])) {
    $build['body_teaser'] = $build['body']['#items']->view([
      'type' => 'text_summary_or_trimmed',
      'settings' => [
        'trim_length' => 80,
      ],
    ]);
  }
}

You can clone the current settings this way:

$build['body']['#items']->getSettings();


How to create URL alias for node edit page

Use a src/Routing/RouteSubscriber.php file in your module.

namespace Drupal\example\Routing;

use Drupal\Core\Routing\RouteSubscriberBase;
use Symfony\Component\Routing\RouteCollection;

/**
 * Listens to the dynamic route events.
 */
class RouteSubscriber extends RouteSubscriberBase {

  /**
   * {@inheritdoc}
   */
  protected function alterRoutes(RouteCollection $collection) {
    if ($route = $collection->get('entity.node.edit_form')) {
      $route->setPath('/project/{node}/edit');
    }
  }

}

Use a example.services.yml file in your module (if the module is named example).

services:
  example.route_subscriber:
    class: Drupal\example\Routing\RouteSubscriber
    tags:
      - { name: event_subscriber }

https://www.drupal.org/docs/8/api/routing-system/altering-existing-routes-and-adding-new-routes-based-on-dynamic-ones


You should try below solution as well. I have added JS & CSS for the specific node.

function YOURTHEME_preprocess_page(&$variables){
  if (array_key_exists('node', $variables)) {
    $node = $variables['node'];
    if ($node->nid == 8) {
      drupal_add_css(path_to_theme() . '/css/cdata.css', array('group' => CSS_THEME, 'media' => 'screen', 'every_page' => TRUE, 'browsers' => array('IE' => 'gte IE 9', '!IE' => FALSE), 'preprocess' => FALSE));
      drupal_add_js(path_to_theme() .'/js/custom_records.js', 'file');
    }
  }
}


Writing a view handler would be the perfect way to do this. The handler itself will be almost as simple as your example code.

However getting everything right to get the handler called from views isn't easy. A good example to learn from is the maillog module. It integrates its log table with views and adds a custom handler.