In order to cluster your map pins/node results, you'll need to write your own javascript function to call the Google Maps Clustering Library/initialize the map (since as of Feb 23, 2018, the GMap module has yet to be fully ported/available for D8).

Based on Google's Marker Clustering Documentation/Example, I'd recommend creating a custom module that includes:

The Google Maps Marker Clusterer js library.
Setting up a json endpoint/route for the location nodes/entities
Custom module javascript that loads the nodes from the endpoint above and parses them (their latitude & longitude data) for the locations array in the init_map function.

Worth noting:
The Google Maps clustering library is grid-based, dividing the map into squares of a certain size.

If you want regions bounded by state/provincial borders, this library won't satisfy the zoomed out map with multiple regions; you'll need something more custom. In such a case, you can:

add a taxonomy for the regions (with a custom set of geocoordinates for the center or political capital of each region)
load a custom high level map with the regions defined/outlined with svg polygon paths and displaying custom cluster pins
on each specific regional map utilize the grid-based clustering library


Drupal 7 Teaser Image Block - no titles or other data

Instead of showing the content with a view mode of Teaser, rather show fields, and only the image field.

If you want to continue using content with a view mode, install and use Display Suite


How can I add a custom CSS class to checkboxes labels?

According to issue #2774255 and line 38 in the FormElementLabelTest.php you should be able to use #label_attributes for this.

'#label_attributes' => ['class' => ['meow']],

Update: Seems you can also try to do this by implementing template_preprocess_form_element. There's an example on line 493 in the form.inc. In your theme implement template_preprocess_form_element and hopefully you find some unique identifiers in there to have this class added only for elements in certain forms or elements of certain types. And then it's

$variables['label']['#attributes'] => ['class' => ['meow']]

Last but not least there's the new Formdazzle! module you could try to use to override the label element templates directly.

  Drupal form theming with less pain

  Theming Drupal forms can be difficult and time-consuming. This module
  provides a set of utilities that make form theming easier.

  Currently, this module provides theme suggestions for forms that are
  much more useful than those provided by Drupal core.

  Theme suggestions for all form elements (including buttons)
  Theme suggestions for all form element labels
  All theme suggestions include the form ID and the form element name; e.g. [element-type]--[form-id]--[form-element-name].html.twig


Multiple submit buttons: Which one was pressed?

Data about clicked button is stored in $form_state['triggering_element']. You can get the node ID by looking at $form_state['triggering_element']['#parents']. In your case the node ID would be the second item in the parents array. Please note that the name attribute of the field definition needs to be defined and unique. Otherwise the triggering element will point to the last submit button on the form. I would alter your code as follows:

$form['f'] = array();
foreach ($rows as $row) {
  $form['f'][$row['nid']] = array();
  $form['f'][$row['nid']]['nid'] = array(
    '#markup' => $row['nid'],
  );
  $form['f'][$row['nid']]['submit'] = array(
    '#type' => 'submit',
    '#value' => t('sumbit'),
    '#name' => 'submit-' . $row['nid'],
    '#submit' =>  array('f_submit'),
  );
}

Good way to view $form_state is to install the Devel module (for krumo()) and then putting krumo($form_state);drupal_exit(); to top of the submit handler. This will print out a nice structured tree of data.


What are the 'todos' when your database is hacked?

In Drupal 7, while all passwords are hashed (SHA-2 with 64-bit words) and salted, if your user's passwords have low entropy, brute-force password attacks are feasible.

Image source: xkcd, explanation.

Also note that the cartoon above assumes that an attacker tries to brute-force passwords over the web. As pointed out by @Damon in a comment:

  Readily available brute-force crackers check 200-500 million hashes per second on a single commodity PC, not 1000. That means a 44-bit password doesn't even last half a day, and a password as 99% of users will realistically have will last 1-2 seconds at most.

This means that if you experience a breech, you should force your users to reset their passwords, there's is the Force Password Change module that will invalidate all passwords and force users to set a new one.

There is also the Password Policy module that let you set a policy to force users to pick a password that is hard to crack by brute force (but it tends to enforce the type of policies the xkcd cartoon above lampoons, so I am not a big fan of it).

In addition to these modules, there is a recipe on Drupal.org to create a drush command to change passwords on accounts that are not actively used that may be used to invalidate passwords for stale accounts.

You may also condsider making your site less vulnerable to password cracking by adding Two-Factor-Authentication.

To guard against PHP injection, you may want to install the Paranoia module.

  The Paranoia module attempts to identify all the places that a user can evaluate PHP via Drupal's web interface and then block those. It reduces the potential impact of an attacker gaining elevated permission on a Drupal site.

To monitor your site and detect unauthorized changes, you may want to install the MD5 Check module.

  The MD5 Check generates a md5 checksum of all module files. If module is changed a critical security error is generated in watchdog log.

There may be other sensitive data in your database beside passwords (e.g. credit card numbers, medical records). If you're really worried about your database being stolen, you need to encrypt sensitive data stored in the database.  The Encryption module helps you defend sensitive data by means of symmetric encryption.

The the Payment Card Industry PCIComplianceGuide.org AFQ provides guidelines for what you should do if your site stores sensitive data.  It also links to guidelines for dealing with data breeches.

Depending upon your location, yoy may have to report a  data breach to affected parties. In the EU/EEA, this is mandated by the Privacy Directive. In the US there are now over 38 states that have privacy law that mandates notification. See www.privacyrights.org for more details.

Acknowledgements: Thanks to @Damon for pointing out that even 44 bits of entropy may not be good enough these days. Thanks to author of Cracking Drupal and Security Team member @greggles for bringing the Drush command to invalidate old passwords and the Parnoia module to my attention. Thanks to @Ben for making me aware of the PCI guidelines.


You should use the SMTP Authentication Support module: http://drupal.org/project/smtp  for sending email messages. You can go there: https://stackoverflow.com/questions/8939238/gmail-smtp-configuration-for-drupal-7 to see how they can use the SMTP Authentication Support module with Google Account.


In a Drupal 7 block, how to enable calling a Javascript function using behaviors

$ isn't defined in the global scope...you either need to use a closure:

(function($) {
  // Use $ safely here.
})(jQuery);

or use jQuery every time

jQuery("#trial").click(...

If you check the console you should see an error in there to the effect "$ is undefined".


How to make an entity reference field an editable field in views

All I need to do was to change the format of the view from "Table" to "editable table" :/


It looks like from the output image above you are trying to create a widget that would show a select number of twitter users from either your own followers or from a specific list, etc. I would suggest that this is not a Drupal issue or at least you shouldn't try and treat it as one. You could do this by creating a content type and outputting it as a view using a view template, etc. but thats a lot of database overhead for data that will likely be changing frequently.

The better way to do this is to use a jQuery / javascript plugin that will pull the data as a json file from your source (either a followers feed or your list feed from twitter) and output it directly. You can use any number of existing plugins and widgets available online for this, ex. this one:

http://twittercounter.com/pages/buttons

or roll your own, but further details would be out of scope for this site.

Finally, I'd recommend that you take a look at the site you got that image from first and see if you can figure out what widget it is using, I'd bet that they are using an open widget / plugin that you can then just copy for your own site.


hook_node_update() is called after the node has been updated.

You want hook_node_presave() instead. If the nid is not empty, it is an update.


Forcing file migration after deleting field

My current solution is to use a query, and manually cleanup the {migrate_map_files} table

$fids = db_query('
  SELECT mmf.sourceid1 FROM {migrate_map_files} mmf
  LEFT JOIN {file_managed} f ON f.fid = mmf.destid1
  WHERE f.fid IS NULL
')->fetchCol();

db_delete('migrate_map_files')
  ->condition('sourceid1', $fids, 'IN')
  ->execute();

reset the watermark in {migrate_status} and then re-run my files migrations.


Why does drupal_http_request return a 400?

It's probably that you are missing the Content-Type header, as detailed here. For Drupal 7, this should look like this:

<?php
$response = drupal_http_request(
 'http://www.example.com',
 array('headers' => array('Content-Type' => 'application/x-www-form-urlencoded'),
 'method' => 'POST',
 'data' => 'param1=value1&param2=value2'));
?>


How do I programatically change default values in a contact form?

You can override your contact forms(both the default and the custom ones) by adding a field widget hook.
Why a field widget hook and not the usual form alter hook like D7? Because overriding the default value of the field can be done only in the respective field widget and not at the form level.

Here's the sample code:

function <mymodule>_field_widget_form_alter(&$element,  \Drupal\Core\Form\FormStateInterface $form_state, $context) {
   $field_definition = $context['items']->getFieldDefinition();
   $entity = $context['items']->getEntity();
   if(($entity->getEntityTypeId() == 'contact_message') && ($entity->bundle() == '<your-custom-form-machine-name>')) {
     if($field_definition->getName() == '<your-field-machine-name>') {
       $element['value']['#default_value'] = 'Hi there!';
     }
   }
}

NOTE This has been tested with Drupal 8.1.1.


Cannot create release for my contributed module

There is just a small change that you need to make. The projects on drupal.org are expected to have the releases in lowercase. This is done to support the project infrastructure which is in place like update status and the testing bot.

You should be able to create a new release with a tag like 8.x-1.0-rc1

More info here : https://www.drupal.org/node/1015226


Why is my Twig Override not displaying any content, when the original Twig was barely different and worked just fine?

After a lot of frustration, and realizing that I could (in fact) manage to get Superfish to do what I had originally wanted, I just composer remove'd the module and that's where it'll stay. Thanks for the help everybody!


Be sure to create a JSON Data Document display for your View with a unique page path, then you can use that path in your DrupalGap Views Render Array. More documentation and examples are available here: http://docs.drupalgap.org/7/Views/Displaying_a_View/Views_Render_Array


Videos Stored in D7-s private file system do not play on Android devices

To make it work on android device you need to pass .webm format along with .mp4 of the same video. Please check sample shown below:

<video id="my_vid_id" class="video-js vjs-default-skin" controls preload="auto" width="640" height="264" poster="poster.png" data-setup='{}'>
   <source src="movie.mp4" type='video/mp4' />
   <source src="movie.webm" type='video/webm' />
</video>


Commerce Module allowing user to customize product

Yes, you can do something like this example:

https://drupalcommerce.org/videos/tutorials/customizable-products-pizza-store

Have to tweak a bit for the sharing part, probably would go with a custom module and hook_entity_view_alter() using the variables from the url to adjust for the specific changes.


Is there a way to output the machine name of a taxonomy term?

I see, the output I'm looking for somewhat like the key value of a
  list field. For example Taxonomy term it becomes taxonomy-term

As discussed the correct way is

{{ themes.entity.label|lower|replace({' ':'-'}) }}

It's suitable for other entity types as well


How to solve the error " Could not determine command name from tag @command" with Drush?

The comment on the traderbot method is incorrect:

   * @command
   * @aliases tb,traderbot

There is no value after @command. I believe you want:

   * @command traderbot
   * @aliases tb

See: Porting Commands to Drush 9

Clear the cache after the change and try again.


How get a programmatically menu fields into template?

This is how i get my custom image field from menu into twig

function hook_preprocess_menu(&$variables, $hook) {

    if($variables['theme_hook_original'] == 'menu__main'){

            $items = $variables['items'];
            foreach ($items as $key => $item) {

                if(count($item['below'])>0)
                {
                    foreach($item['below'] as $id=>$array)
                    {
                        $entity = \Drupal::entityTypeManager()->getStorage('menu_link_content')->loadByProperties(array('uuid'=>$array['original_link']->getDerivativeId()));

                        foreach($entity as $idMenu)
                        {

                            if($idMenu->get('image')->entity != null) {

                                $image = file_create_url($idMenu->get('image')->entity->getFileUri());

                                $items[$key]['below'][$id]['imageUrl'] = $image;

                            }
                        }

                    }

                }

            }

        $variables['items']=$items;

    }

}

I just work on my item menu and add 'imageUrl' into my array.
I first load my entity by properties with the UUID for access to my menu item fields.

This method is only for my sub menu ( inside my mega menu, i want just add an image by item in submenu )

  that why i check count(item['below']>0)

For now i can't find better way.


Login to external server from Drupal site

This depends what you mean by external server? There's a tonne of contribution modules at the moment that support a variety of external logins.

You can implement Open Auth 2 to allow a single sign on:

https://www.drupal.org/project/oauth2_authentication

Or you can use Facebooks Oauth authentication:

https://www.drupal.org/project/fboauth


Maybe you could use the Data module.

  Data module helps you model, manage and query related sets of tables. It offers an administration interface and a low level API for manipulating tables and accessing their contents. Data module provides Views integration for displaying table data and Drupal search integration for searching table content.


Views exposed filters set per content type in same view

Create a filter that filters on content type for Album
Create a filter that filters on content type for Songs
Create a filter that filters on title (set it to exposed and set the operator to "Starts with"
Under Filter Criteria instead of add, click on the arrow and choose "And/Or, Rearrange"
Click "Create new filter group"
Now drag the filter created in step 2 and 3 to the new group (Songs and Title)
Make sure the operator between the filter groups is OR and the operators between the filters in a group are set to AND

Your filters should look like


How do I do custom shapes (Complex Multipoint Geometry) using Geofield and Leaflet?

I think this is already possible when using Geofield with OpenLayers. Although I'm not using complex geometries in my current case, all settings indicate that the module is capable of it. E.g. if you choose in the setting of your Geofield for the storage option for 'single collection' it indicates that the widget will allow complex geometries.


Forbidden 403 http request using deployment module

The answer to my own question:

Add this to your .htaccess file (I have put it at the top):

#
# Apache/PHP/Drupal settings:
# Paste the code under this sentence
<Limit PUT>
    allow from all
</Limit>


How to call functions from another module in hook_language_negotiation_info()?

Not sure if this is the correct reason for this behaviour or not but it seems like the language negotiation process runs before the modules and the themes are bootstrapped in Drupal which would explain why the function is not available by default.

Changed the module_load_include to actually include the file directly by calling drupal_get_filename and requiring the file and it worked.

function _my_module_language_callback() {
  $geoip_file = drupal_get_filename('module', 'geoip');
  if( file_exists( $geoip_file ) ) {
    require_once DRUPAL_ROOT . DIRECTORY_SEPARATOR . $geoip_file;
  }

  $languages = _my_module_language_mapping();
  if( function_exists( 'geoip_country_code' ) ) {
    $country_code = geoip_country_code();
  }
  $default_langcode = language_default( 'language' );

  if( !isset( $country_code ) ) {
    watchdog( 'geoip_language', 'Country Code could not be identified by IP.' );
    return $default_langcode;
  }

  if( !isset( $languages[$country_code] ) ) {
    watchdog( 'geoip_language', 'The country code is not in the language mapping.' );
    return $default_langcode;
  }

  return $languages[$country_code];
}


Appropriate theme function for alter specific field for a view

Fences should be the answer of your problem:
https://drupal.org/project/fences

Or you could create a template for this view-field:
https://drupal.org/node/352970


How to expose a select field to a Rules Condition?

Well, I found my answer:

I need to create a 'Entity has field' condition and equate it to the machine name of the field in question.

Then the field becomes exposed in 'Data Comparison' to be evaluated.


Hope this will help you,

As answered theme_menu_link OR theme_menu_tree wil help you to do this. If you go through the above links you can get an idea to change the html of required menu item.

On page load:

for example im using theme_menu_link in template.php refer this code. Node count will be update on every page load, if any changes.
I have updated l() for you requirement. For example I have used a simple function , modify the function as per your requirement.

$output = l($element['#title'] . ''.get_node_count($parms).'', $element['#href'], array('html'=>TRUE));

function get_node_count($parms){
    //you code goes here for get node count
    return $node_cnt;
    }

If you don't want on page load, it can also be done using ajax callback, but not preferable to make ajax callback again and again.

If you want to do refer ajax callback, then the only change has to be done in the l(). Add the unique menu id, which is used to show the node count for the corresponding menu id.

$output = l($element['#title'] . '', $element['#href'], array('html'=>TRUE));

On sucessfull ajax callback you have to update the node count for each menu.
using
...
success: function(data) {
// Change node count
$('#menu_title__node_count').html(data);
}
You will get the class for each node count, you can style as required. And also you can add a common class for common style, based on your requirement.


How to dpm() the Drupal.settings.basePath var

Drupal.settings.basePath is a javascript variable, not PHP...you can't access it on the server side like that.

I imagine the output you're getting in the message area is 'DrupalsettingsbasePath', which is how PHP would interpret Drupal.settings.basePath, along with a few PHP Notices complaining about the use of an undefined constant.

Assuming you're using a browser that supports console.log, to debug the base path just add the following in a javascript file that's included in your page:

console.log(Drupal.settings.basePath);

The variable will then be printed to your browser's console area.


How to remove search on Site and leave only search on Content?

So you are trying to make sure that the core Search only searches for content? if so you can tweak the core Search module at /admin/config/search/settings.


Where did date-time "add [custom] format" go in Drupal 7?

Configuration -> Regional & Language -> Date and time -> Formats -> Add format.

You end up at /admin/config/regional/date-time/formats/add.


Load a variation (or Line Item) based a previous choice

Please use COMMERCE OPTION module with COMMERCE PRODUCT ATTRIBUTES to explore the possibility of achieving this. Go through by documentation for using it properly & I hope you will have fun in achieving what you want...


When clean URL are enabled, the page at admin/config/search/clean-urls is like the following one:

When clean URLs are not enabled, you should see a description such as the following one, and a button to test the clean URLs ("Run the clean URL test"):

  Use URLs like example.com/user instead of example.com/?q=user. If you are directed to a Page not found (404) error after testing for clean URLs, see the online handbook.

Once you click on the submission button ("Run the clean URL test"), Drupal would check if the clean URL are possible to enable, and show you the checkbox to enable them, which should be not selected.
If that doesn't happen, the online handbook reported in the description has a link to How do I unset the clean URLs? where three methods are listed:

Run the following Drush commands:

    drush vset clean_url 0 --yes

Run the following MySQL commands:

    UPDATE variable SET value = 's:1:"0";' WHERE name = 'clean_url';
    TRUNCATE cache;

If previous update statement didn't solve it, some drupal version may need a different key :

    UPDATE variable SET value = 'i:0;' WHERE name = 'clean_url';
    TRUNCATE cache;

Alternatively, you can modify the appropriate settings.php file to include the following line at the bottom (or similar code in the site settings array you'll see there).

$conf['clean_url'] = 0;


8 - How to Get Values From $variables hook_preprocess_commerce_order_receipt?

How do I get the order_id from this $variables object?

All entities have an id method, inherited (or perhaps overridden) from Entity::id. From your debug output $variables['order_entity'] appears to be one such entity, so:

$order_id = $variables['order_entity']->id();

  How/where did you find this information telling you how to get this value out?

Short answer, in the source and the docs (following/finding isn't always straightforward though). For example if you've read the Introduction to Entity API in Drupal 8, you'll intuitively know that a Drupal\commerce_order\Entity\Order is an entity type, both by the folder structure and its annotation, and you can start thinking about how to address an object of that type in more generic terms.

That leads to searches like "Drupal 8 get entity id" or "Drupal 8 get entity field value programatically", and Google will dutifully tell you everything you need to know.

If you can spare a bit of time to follow the class hierarchy up the chain, and get at least a broad idea of what each class does and how it works, that will probably take some pain out of future encounters with the entity API too.


I found a way to do it by using user_presave, i created a field_profile_email field using this answer : https://drupal.stackexchange.com/a/205308/65949


Custom fields added via form api not working as expected

AFAIK, hook_form_alter() does not require you to perform a drupal_render() in it. And I suspect that is why you are not getting a proper rendered for item.

Also, each custom field needs to processed (by you) on form submit.
Thus, you need to add $form['#submit'][] = 'my_submit_function_submit';, where my_submit_function_submit() handles the database inserts.


Views query alter but Views calc is not rendering right result

I have the same problem (pagers not working for custom queries), and while I am getting close to the solution I do not have it yet. Something that helped me to understand what is happening is a piece of code from OG that generates a table with pagers.

og_ui.admin.inc line 221

query:

  $query = db_select('users', 'u');
  $query->innerJoin('og_membership', 'ogm', 'u.uid = ogm.etid');
  $query
    ->condition('ogm.gid', $group->gid, '=')
    ->condition('ogm.entity_type', 'user', '=');

and the important part where the query gets cloned jost for the counter:

  $count_query = clone $query;
  $count_query->addExpression('COUNT(u.uid)');

  $query = $query->extend('PagerDefault')->extend('TableSort');
  $query
    ->fields('u', array('uid', 'name'))
    ->fields('ogm', array('state', 'created'))
    ->limit(25)
    ->orderByHeader($header)
    ->setCountQuery($count_query);
  $result = $query->execute();

My current solution is
do not use pagers when you edit view queries,
if you have to use a pager than create a whole template using the example from OG module (og_ui_menu() in og_ui.module + og_ui.admin.inc).

Hope it helps, but I would still be happy to know how to fix counter in views.


SelectQuery::fields and Drupal's naming conventions - how to make it all match?

What the naming conventions actually say is that "Methods and class properties should use lowerCamel naming." (my emphasis).

The properties added to the object returned by a query are not class properties. This is confirmed by the PHP documentation which defines "properties" (or "class member variables") as "defined by using one of the keywords public, protected, or private, followed by a normal variable declaration". There is no such declaration that applies here.

The object you are looking at is of type StdClass. There isn't much about the concept behind StdClass in the PHP documentation (unless I missed it), but the concept of a class-less object with dynamic fields is sometimes known as "anonymous object". You can create one in PHP by doing:

$obj = (object)(array('field' => 'value'));
echo $obj->field; // Outputs 'value'

In the case of the object returned by the query, it doesn't even have methods - it could just be an array (which it would be if you fetched your data using DatabaseStatementInterface::fetchAssoc). So we can think of anonymous objects as containers, rather than instantiations of classes to which the coding style should apply.

Since this object is a container of fields from the database, I think it makes sense for the database convention to apply. It is an object wrapper around a database row.

As a Drupal programmer, if I get a result that is essentially a database row, I will actually expect it to be in underscore notation. While it may feel wrong, it is what people are used to expect. Every time I use [node_load][4], the result I get is an object in underscore notation. Even when you use the entity meta data wrappers, which essentially are there to provide an object interface around Drupal entities, you still use the underscore notation. Changing this approach would potentially confuse other Drupal programmers.

I understand that if you are writing, say, an API which returns your own data, you may want to abstract the fact the result is a database row and present it as an object like any other (as suggested by your param vs. result example). One option, though one that has some overheads, would be to create a class to hold such result, and casting the database result object to it. This would at least make it clear that what you are returning is a proper object, not just a container around a database row. You could do something like this:

Class MyApiResult {
  function __construct($row) {
    $vars = get_object_vars($row);
    foreach ($vars as $name => $value) {
      $cc_name = to_camel_case($field);
      $this->{$cc_name} = $value;
    }
  }
}

Then your API would return:

return new MyApiResult($row);

However this has some overheads, it depends whether those will be acceptable in your particular case.


Domain Access module: Adding nodes programmatically to subdomains

Since I didnt find a way to do this with api I solved this by editing the table where domain access keeps the info about which node belongs to which domain.


I think the implementation has some issues. The first contextual filter that you have added is date, right and when you are passing an argument, it's not a date. Is that a username? If so then you need to use proper contextual filer. You have a filter as "Add Property View" and also the same in Contextual Filer.


How to make Views rows clickable with jQuery

Please change your JS code to below given one and try again. It should be working.

Drupal.behaviors.clickableRowsOnViews = {
  attach: function() {

    jQuery('.clickable-row .views-row').each(function() {
      if (jQuery(this).find('a').length) {
        jQuery(this).click(function() {
          window.location = jQuery(this).find('a').attr('href');
          return false;
        });
      }
    });
  }
}


Drupal modules to display external RSS feed

Feeds (previously FeedsAPI) is the one you want. Here is a quote about it (from the module's project page):

Import or aggregate data as nodes, users, taxonomy terms or simple database records.

One-off imports and periodic aggregation of content
Import or aggregate RSS/Atom feeds
Import or aggregate CSV files
Import or aggregate OPML files
PubSubHubbub support
Create nodes, users, taxonomy terms or simple database records from import
Extensible to import any other kind of content
Granular mapping of input elements to Drupal content elements
Exportable configurations
Batched import for large files


Sometimes the best way to merge/split features is to edit the module code directly. It's pretty straightforward where everything is laid out in a module created by Features. And it's a great way to start learning module development (if you're new to it). Just start at the *.info file - that's where Features describes all the various things it manages in the module. Then you can pretty easily find those things in the *.module file and other *.inc files. Just clone the whole module, rename it and all the files, search and replace all occurrences of the name in the code, then remove the stuff you don't want in each.


How to map fields from content type to user Profile

If you want the content of the fields in application to be saved in the user entity, I can think of a couple of approaches:

Use Rules module to copy the values to the user entity when the application content is saved.
Write a custom module and use hook_node_update() to add the values to the user entity.


How to render a view as a entity field on form edit?

Use EVA  module. It will provide the view as field. So in display settings you can assign views the region you would like. Quite simple and useful module


There is a Field Storage API you can use for external storage in fields.


how to get the absolute path for files based on fid

Drupal 7

This is a two part process, using file_load() and file_create_url()

First, you need to turn the $fid into a Drupal URI:

$file = file_load($fid);
$uri = $file->uri;

Now, you can turn this into a URL

$url = file_create_url($uri);

file_create_url() always creates an absolute URL, either using the global $base_path that you have defined, or using the one that Drupal guessed during bootstrap.


Prevent hook_form_alter to works only on frontend not in admin?

you could use the global variable $user to achieve it.

<?php

function MODULE_form_alter(&$form, &$form_state, $form_id) {
  global $user;

  if($user->uid == 1) {
    return;
  }
  else {
    //alter fields logic goes here
  }
}


MongoDB can be used to store most or all your entities into fast, document-oriented storage. This type of storage scales way better then the standard SQL based storage we have in Drupal core (which is based on a "one table per field" schema).

In the current state of Drupal 7, you would have:

The base table of the entity stored on SQL (ie. the users table, the node table, etc.)
All fields stored in SQL
The properties of the entities from their base tables duplicated in MongoDB

This allows fast querying on the entities on MongoDB, and the ability to add complex indexes that no Opensource SQL database support (including indexes across tables). At the same time, you don't lose interoperability because the base table of the entity is still stored in SQL and can thus be joined by modules that are still SQL-only (like Flag).

This type of fast querying is available thanks to the EntityFieldQuery mechanism, a way to build queries on entities, their properties and their fields in an abstract manner. The default implementation in core translate those queries to SQL, but the MongoDB module has a full-featured implementation that can satisfy those queries from MongoDB directly.

Thanks to the EntityFieldQuery backend for Views, you can easily leverage this power, by using the tools you are used to. The only downside is that relationships are not supported (but in practice you rarely need them anyway - and this can be worked-around by pushing additional data into the entity object and add exposing them as additional properties of the entity).

In a nutshell, as soon as query performance is a problem on your project, which happens as soon as you have a significant dataset (let's say starting at a few tenth of thousands of entities on a given entity type), MongoDB is a net gain for very very few drawbacks. Highly recommended.


warning: number_format() expects parameter 1 to be double, string given in

The number_format() function requires a float type variable for its first parameter.

Try casting the parameter like this:

$html .= '
'.$fontValue->fontValue.''.str_replace('.ttf','.png',$fontValue->fontValue).''.number_format((float)($fontValue->price),2,'.','').'
';


I'm not exactly sure why you are having this trouble... Though in a quick attempt to test (in Drupal 7), it does seem a little screwy.

However, since you don't seem worried about other timezones and no need to convert timezones, it would seem easiest to set the "Time zone handling" on the field to "no time zone conversion"
Then the views should pick up whatever date and time is there to begin with.


Dynamically generated radio buttons share name

You can try using #tree:

$form['#tree'] = TRUE;

Or you can add it to only your questions element:

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


I am thinking you are wanting to learn more about blocks.  You could, for example, have a block that output an iframe/html/whatever widget.  In the blocks hooks, you can use all sorts of information to decide when to display it it, eg what page/url, what type of node, etc.  So, for example with twitter, you could grab information/fields from the node it is being displayed next to and customize it appropriately.


Find out the user's IP address given their UID?

If you have statistics module enabled, the "accesslog" table contains the IPs for all your visitors.

SELECT hostname FROM accesslog WHERE uid = %UID_FOR_YOUR_USER% LIMIT 1

If you do not have statistics enabled, I advise you to leave it off, even for this result, because enabling it, causes a severe performance-penalty.

In that case, you can use sessions table:

SELECT hostname FROM sessions WHERE uid = %UID_FOR_YOUR_USER% LIMIT 1

The benefit of the first over the latter, is that the first will always show you the latest hostname, whereas the latter might not always be up to date.


Setting a URL alias breaks the relative image paths on those pages. Is there a way to fix this?

src="sites/default/files/mobile-nav.png"> should be src="/sites/default/files/mobile-nav.png">

Please note the additional "/" before "sites." Without the forward slash the image will always be called from wherever you're at on the site so if you were at say site.com/news/ it would look for the images in site.com/news/sites/default.... if you don't have the forward slash before sites.


Yes, you can, here is an article about my own experience with it, working with Bootstrap http://makina-corpus.com/blog/metier/2015/develop-with-twig-in-drupal-7

So http://www.drupal.org/project/tfd7 is the way to go if you want to write template files with Twig syntax, it must be moved to theme/engines.
Note that development is now happening at https://github.com/TFD7/TFD7 and documentation is at http://tfd7.rocks.

Don't be confused with the project https://drupal.org/project/twig, unfortunately, it is only an input filter because modules cannot provide theme engines in Drupal 7 (due to license reasons it seems).


How to limit showing of a block just in home page?

You can do this by following below way :

After creating Views Block.
Goto Admin -> Structure -> Blocks (Search your block)
Configure -> Your block
Goto Pages section. Click on "Only the listed pages" & write <front> & Save block.


How to mirror product date attribute availability on the availability calendar?

Unfortunately, there is not a particular bit of code that can be shared to fix your situation. But take heart! You're using libraries that are designed to be changed before display. That means with a little bit of custom php and javascript you can do this.

First you need to determine how to change your widget

Using Javascript: https://stackoverflow.com/questions/9742289/jquery-ui-date-picker-disabling-specific-dates

Using Drupal to send variables to Javascript: how to send variable from .php file to .js file?

Next you need to determine where your availability dates are stored

This is probably the most abstract issue. It sounds like you're storing the availability from within the node. I recommend you use the devel module and try to $node = node_load(123); dpm($node); to see what the availability field array looks like. We will do this in the next step. (Lynda series on the devel module)

Finally, you need to connect both your knowledge of how to tweak the calendar and where the availability is stored with your line item form.

Fortunately, this is quite straightforward. Unfortunately, it's not complete and will need a fair amount of trial and error to get to a working solution. Welcome to learning the hard way :)

<?php

/**
 * Implements hook_form_alter()
 */
function MODULE_form_alter(&$form, &$form_state, $form_id) {
  // Avoid bundle cart forms and other forms
  if (strpos($form_id, 'commerce_cart_add_to_cart_form_') === 0) {
    $current_node = menu_get_object();
    // view the current node structure for your availability
    dpm($current_node);
    // view the current product's form array
    // you may not actually need to change the form here, but
    // I anticipate you needing to attach a javascript snippet to the
    // form so that it gets run each time the ajax loads a new
    // product
    dpm($form);

    // add your js to the php form
    $js_settings = "js array for your availability?";
    $form['#attached']['js'][] = array(
      'data' => array('module' => $js_settings),
      'type' => 'setting',
    );
  }
}

?>


Is that mac address is a required field?
It may be possible mac address passing to this function not getting change, you may need to debug mac address before the function call.


field_media_image/alt belongs in the immagini migration, not in the node migration.

In migration that creates the media item (destination plugin entity:media) you can map the media item's fields:

  # Image field see media_entity.bundle.image.yml.
  field_media_image/target_id: fid
  field_media_image/alt: field_file_image_alt_text/0/value
  field_media_image/title: field_file_image_title_text/0/value

  # Description field.
  field_description: field_image_description
  # Caption field.
  field_caption: field_caption

destination:
  plugin: entity:media

See https://www.previousnext.com.au/blog/migrating-drupal-7-file-entities-drupal-8-media-entities


Is there a module for creating images and labelling and placing them in a document?

No such module exists.  The default Article content type in Drupal 7 already has an image field, but not  the fields you request for holding metadata.

However, with Fields in core in Drupal 7, it is trivial to add the required fields to any content type.  If you're not familiar with Fields, you may want to look at this tutorial.

After adding the field for the image itself, and the metadata you want, you may want edit the template for the content type to make sure all the fields are rendered nicely.


How to create a view with contextual filters and then make menus to filter it?

I managed to figure this out. With help from this tutorial http://www.metaltoad.com/blog/using-drupal-contextual-filters-views and the reason why the links in the menus dind't work for me were because I was using the same url as the taxonomy term had so I only got a term list. So I just changed the view url to something else than the taxonomy and it worked.

It now works if I write the view adress/any termreference without having to create a separate view for all of them.


How to silently prevent Webform spam (specific names, email addresses)?

All the available SPAM protection modules for Drupal 8 are listed on the Webform Add-ons documentation page.

Text inputs now support patterns, you could explore creating a negative lookahead pattern like ^(?!.spam).$,


Drush is updated but not usable in Drupal 8 in Windows

You need drush 8 for drupal 8. You have drush 7 installed.


Using Entity Field Queries with "does not contain"?

The comments on the official documentation page for propertycondition() give an example using sql like on propertycondition().

From that example try the following change to your code:

   -> propertyCondition('title', '%panda%', 'NOT LIKE')

EDIT: I haven't actually tried this, just going offa docs and comments.


How to db_select DISTINCT on a particular field in Drupal 7?

Assuming you're trying to get to roughly this query:

SELECT DISTINCT e.nid AS nid, e.time AS time, n.type AS type, n.status AS status, n.title AS title
FROM
{my_table} e
INNER JOIN {node} n ON n.nid = e.nid
GROUP BY e.time
ORDER BY e.time ASC

You would use:

$query = db_select('my_table', 'e')
  ->distinct()
  ->fields('e', array('nid', 'time', 'foo', 'bar'))
  ->fields('n', array('type', 'status', 'title'))
  ->groupBy('e.time')
  ->orderBy('e.time');

$query->join('node', 'n', 'n.nid = e.nid');


You can use this twig to theme the status message:

status-messages.html.twig

{#
/**
 * @file
 * Default theme implementation for status messages.
 *
 * Displays status, error, and warning messages, grouped by type.
 *
 * An invisible heading identifies the messages for assistive technology.
 * Sighted users see a colored box. See http://www.w3.org/TR/WCAG-TECHS/H69.html
 * for info.
 *
 * Add an ARIA label to the contentinfo area so that assistive technology
 * user agents will better describe this landmark.
 *
 * Available variables:
 * - message_list: List of messages to be displayed, grouped by type.
 * - status_headings: List of all status types.
 * - display: (optional) May have a value of 'status' or 'error' when only
 *   displaying messages of that specific type.
 * - attributes: HTML attributes for the element, including:
 *   - class: HTML classes.
 *
 * @ingroup themeable
 */
#}
{% for type, messages in message_list %}

    {% if type == 'error' %}

    {% endif %}
      {% if status_headings[type] %}

{{ status_headings[type] }}

      {% endif %}
      {% if messages|length > 1 %}

          {% for message in messages %}

{{ message }}

          {% endfor %}

      {% else %}
        {{ messages|first }}
      {% endif %}
    {% if type == 'error' %}

    {% endif %}

{% endfor %}

I'm not sure, if you can get the form id in this template. But you can try to narrow down the kind of error message and make the modifications to this twig conditional.


Views: How to list "files" view for their own files?

First open the workbench file tab, then from the contextual menu on the right select edit view.

Add the relationship 'The user that uploaded the file.' if it does not already exist.
Above Relationship, you will see Contextual Filters (these are dynamic contextual parameters you pass to views). Add a contextual filter 'The User ID' and set the relationship to 'User who Uploaded'.

In the same window just below that there is a section 'When the filter value is not in the URL'. You select 'Provide default value'. This opens a select list, from which you choose 'Use ID from logged in user'


Getting .info file not found in my custom module, even though it does contain an .info file

Mystery solved.

I traced back to the update_manager_install_form_submit() function in update.manager.inc.

When the file is uploaded, it is placed in the temp directory.  Drupal then creates a temp directory to extract the file into, using a unique directory name.  After the extraction, Drupal can't determine the module name any more, so it depends on the directory name in the archive. They commented on this in the code:

// Unfortunately, we can only use the directory name to determine the project
// name. Some archivers list the first file as the directory (i.e., MODULE/)
// and others list an actual file (i.e., MODULE/README.TXT).

I did not have my files tar'd in a directory.  So, I created a directory named after my module, moved the files into the directory, tar'd it up, and all is well.

Before

modulename.install
modulename.module

After

modulename/modulename.install
modulename/modulename.module


Unable to edit node translation other than current language

Anyone having this issue should read https://www.drupal.org/node/1399506.

The problem arises from the feature Language Path Checking within the Global Redirect module. Use the dev version to correct the problem.


Your error was quite simple; you forgot to put <?php at the top of your alias file.


How should I share sessions transparently across domains?

There are some related answers and solutions at "Enterprise" authentication, single sign-on and user provisioning for multiple sites.

While you have a more specific question, the goal is similar to what many SSO solutions in Drupal try to achieve.


Use node (if this is a node template) to get the field value, see Conditional statement doesn't work in node.html.twig. Another reason in this case is that Yes/No would be translatable in a multilingual site, while the field value from nodeis the untranslatable left key of a select list.

If it is not a node template look at the variables listed at the top of the template, for example paragraph.html.twig:

/**
 * @file
 * Default theme implementation to display a paragraph.
 *
 * Available variables:
 * - paragraph: Full paragraph entity.

 * - content: All paragraph items. Use {{ content }} to print them all,
 *   or print a subset such as {{ content.field_example }}. Use
 *   {{ content|without('field_example') }} to temporarily suppress the printing
 *   of a given child element.

Here the variable for the entity is paragraph and for the render array content.

So use {{ content.field_example }} to print fields and {{ paragraph.field_example.value }} to get field values from the database.


Query and load entity by Entity Type Manager

You can do this in one step by using loadByProperties():

$term = current(\Drupal::entityTypeManager()->getStorage('taxonomy_term')
  ->loadByProperties(['field_code' => $code, 'vid' => 'computer'])
);

This method is a shortcut for basic entity queries like you have here and also includes the step for loading the entities.


RewriteRule fails if called after line 112 of .htaccess

Just put it above line 112. The reason it doesn't work below that is line 117:

RewriteRule ^ index.php [L]

that [L] means that if the conditions above it match and that rule is applied no further rules will be checked. If you put it above that line clean or non-clean style url will work fine but probably don't want to include an L on the end of your rule so use:

RewriteRule ^home/code/([^/]+) home/software/node?code=$1 [R=301,NC]

on line 111 (well whatever actual content rule you need).


How to print author's email address in in node template

Use

<?php
  print $user->mail;
?>

If $user is not available use

<?php
  $user = user_load($node->uid);
  print $user->mail;
?>


Show View Pane in Node Template based on Taxonomy Term

Ok, I finally figured it out!

To show a view in a panel where the view and panel are related by a taxonomy term (in my case Team Term (field_team_term), do the following:

Use the view content panes module to create a view content pane (How can I show a view in panel with argument in Drupal 7).
In the view content pane use contextual filter "Has Taxonomy Term ID". When Filter Value is not available: Hide View. When Filter Value is available - specify validation criteria - choose taxonomy vocabulary - Filter Value Type: Term Name converted to Term ID. (Some writers suggested checking the "Allow Multiple Values" box at the bottom of the window under More; I found that unnecessary.)
In the Pane Settings - Argument Input, select "From Context".
Under Required Context, select Name under Taxonomy Term.

That completes the views setup.

In the panel settings,

Set up a relationship"Taxonomy term from Node (on Node: Team Term [field_team_term])" in the case of my taxonomy term field.
In content, add the view pane, and select the taxonomy term relationship as the argument.

As near as I can tell, that is only combination of panel context and view arguments that will get the job done. I hope this helps someone.


I would use views module with a plugin that fits your export format expectations such as views datasource or views_data_export for CSV, XML, etc


Can I deploy my Content on drupal using scripts?

If you would like to automate your deploys of content, just like you automate your code deploys, you'll probably want to look into the migrate module.  This model is best for sites where the content is managed by a content-generation team; it is less applicable for sites that have a lot of user-generated content.  This is a viable model that some people use, though, and is a very compelling workflow if your use-case supports it. One good extant site that uses this technique and has a public GitHub repository is Gizra's Negawatt.


How do I direct users to my custom search?

I would use hook_form_alter() to alter the default search form to call your own submit function.

So, in your custom module do something like this:

// Alter regular search box
function YOURMODULENAME_form_alter(&$form, &$form_state, $form_id) {
  if($form["#id"] == 'search-block-form') {
    // Add any additional fields or things you need here

    ...

    // Modify the submit handler that is called
    $form['#submit'] = array('YOUR_CUSTOM_search_submit');
  }
}

This actually modifies precisely that block search form, so including the search block just like you've described in the template file should work once you've implemented the form alter.


Most likely because on() didn't exist before jQuery 1.7, and Drupal ships with...well, not 1.7.

The standard solution is to install jQuery Update and select 1.7 as the version for the site.

For future reference, check for JS errors in the browser console - there will be something very similar to this in there:

  Object [object Object] has no method 'on'


Why does swiftmailer doesn't use my HTML template?

My mistake!
I put my email template swiftmailer--sel--emailforurgentservice.html.twig in "mayo" theme which is the theme the users of the site will see.
Mailsystem was set to use "current" theme.
When I made my tests, I did it as 'user 1' and the theme when the email was triggered was "Seven" (Administration theme).
I changed the settings of Maisystem:

And it works as expected!


Views can be a little heavy, and if you don't need the module it's lighter just to drop it.

If you just want to grab some info for a template, you could also do it with Entity Field Queries.


CKEditor links wrap the contents of a container individually instead of a container

The CKEDitor by default restricts the HTML you can use to what it considers safe by means of something called the advanced content filter (ACF). It is this feature of CKeditor that rejects your HTML-construct.

To change or otherwise prevent this behavior, you must describe the construct you want to allow by using the syntax described in the allowed content rules and assigned the JavaScript variable config.extraAllowedContent.

PS: If you Google this, you'll often see the following JavaScript suggested to "fix" to CKEDitor removing "unsafe" HTML:

config.allowedContent = true;

What the above line does it to turn ACF of completely.  It will allow any valid HTML to be inserted.  It is OK to do this for testing and debugging, but it is not recommended that you do this on a production site.


How to log custom entries in 'Recent log entries'?

watchdog() is what you are looking for. See the description of its parameters, in particular these:

  $type: The category to which this message belongs. Can be any string, but the general practice is to use the name of the module calling watchdog(). The $type parameter is limited to 16 characters; anything longer is truncated.

  $severity: The severity of the message; one of the following values as defined in RFC 3164:

  WATCHDOG_EMERGENCY: Emergency, system is unusable.
  WATCHDOG_ALERT: Alert, action must be taken immediately.
  WATCHDOG_CRITICAL: Critical conditions.
  WATCHDOG_ERROR: Error conditions.
  WATCHDOG_WARNING: Warning conditions.
  WATCHDOG_NOTICE: (default) Normal but significant conditions.
  WATCHDOG_INFO: Informational messages.
  WATCHDOG_DEBUG: Debug-level messages.

  $link: A link to associate with the message.


PHP cli script for flushing drupal cache

Install Drush. It's your friend. Then you can issue

drush cc all

To clear caches.

You can also rebuild registries if needed to if you have that module installed.


Unable to Install/Uninstall a custom module

You should pay close attention to the Module developer's guide on Drupal.org.

To appear in the lists, the module should be placed in its own sub-directory like modules/modulename, and it must have a properly configured modulename.info file in addition to a file named modulename.module.

If you have properly segregated the functions into the proper files, there should be no problem. Drupal will detect them automatically and will maintain an entry in the system table for the module. You should be able to activate or deactivate the module normally.

The installation routines (which are used to create or to remove the tables should be handled by functions in a modulename.install file. Drupal will look for the modulename.install file to see what tasks are required for installation or removal of the module.

My first advice would be to make sure that the module is correctly structured, and let Drupal handle the deactivation and uninstall, but you can do it manually if all else fails.

Deactivate the module and drop the tables using queries directly on the database. Start by looking for the definition in the system table.

UPDATE system SET status=0 WHERE type='module' AND name = 'modulename';

Then manually DROP any tables your module created and remove any variables it created.


Unable to display images after Drupal Update

My guess is you didn't correctly copy sites/all and sites/default/ over during the update or the permissions on the files in those directories aren't correct so Drupal can only "see" core modules and themes.  The data in the database is still working, but any field, content type, or url that requires a module from sites/all probably doesn't work either.


How to join two Drupal CCK content types in view without a node reference field, fast?

Since you don't have a reference between the two, Views has no way of knowing how the node's relate to eachother. Views has no direct support for joining on arbitrary columns.

So to solve this, you need to declare the relationship to Views your self. You do this by implementing hook_views_data, or in this case, since Views has likely already created most of the array, hook_views_data_alter. The documentation for the first function has an example with code for a relationship.


How do I get a LEFT OUTER JOIN in Views that displays all rows with no match in the LEFT JOIN-ed table?

In your RID contextual filter, if you expand the "More" fieldset at bottom of the options modal, you should see an "Exclude" option which will flip the filter operator to negate.


variable_del wildcard when uninstalling a module

You can try db_delete but handle with caution.

Example :

db_delete('variable')
->condition('name', '_campaign_text_%','LIKE')
->execute();
cache_clear_all('variables', 'cache_bootstrap');


Beans use the entity system, so you have a couple options here:

As AyeshK stated, hook_entity_insert and hook_entity_update are the obvious options.

If you need to do something before creating OR updating you can use hook_entity_presave.

Finally, Drupal doesn't have any native hooks that runs after an entity is created/updated, but the Hook Post Action module offers a nice set of additional functions to solve this problem.  If you don't want yet another module dependency, read the module's codebase and figure out how it implements the post-save functionality, then add similar custom code in your own module.


How add related nodes to content profile?

You can load nodes by various parameters. Just give the parameters which you want to load.
See here Here is for Drupal 6 also.

If you had a code in D6 to load a node using an array of conditions to match against in the database query like this:

<?php
$param = array(
    'type' => 'your_node_type',
    'title' => 'your node title',
    'status' => 1,
);
$node = node_load($param);
?>


It is impossible to tell whether you've missed something without having complete access to your schema.  The fact that you get an entityreference error after clearing all caches is not a good sign.

A safer approach to renaming a content type machine name is to recreate the bundle with the correct machine name, and then use Node convert to convert it from the old machine name to the new one.

  Node Convert ... gives the ability of converting the node from its current node type to another node type. Also it gives the ability of transfering all the custom CCK field values of the current node type to the destination CCK fields, or discard them. As of 5.x-1.4 you can bulk convert many nodes of the same type, to another one that can be accessed in Administer → Content → Convert Nodes.

It allows both single node a and multiple node conversion. Here is a link to the documentation.

I've used the module for a similar use case as yours, with success.


node:url token not returning clean (alias) URL

Option 1 (a): Try another token

Check what result you get by using either of these tokens:

[site:current-page:url].
[node:node-path].
[node:node-url].

Option 1 (b): Pass the URL as an extra parameter

Inspired by the answer to the question "Send node path alias to user", you might be more lucky to get access to the correct value of your URL (or either of the tokens I suggested above) if you just pass that value to your Rules Component as an extra parameter (so on top of the "node" parm you already have). And of course use the value of that parameter in your Rules Component instead.

The reason why I think you may be more lucky, is that you already have that "node_is_of_type"-condition. So because of that, and similar to the answer in the above mentioned question, it should be available in your first rule in which you schedule the Rules Component.

Option 2: Perform Rules debugging

If Option 1 doesn't help, then I'd recommend you to do some further debugging of your actual rule, as detailed below (and in the order specified).

Basic debugging

Rules is great, but sometimes also tough to debug if things don't work as you'd expect. There are some typical facilities to do such debugging, but my Keep-It-Super-Simple technique I often use is my BINGO-trick. A sample of such rule can be found in my answer to "Which Rules condition can be used to email a user when an admin updates their profile?". Stupid, but simple and efficient (I think).

Debugging using Rules settings

Something else that might help to find the answer to your question, is to have a look at Rules debugging ... Within the Rules settings, experiment a bit with the debugging facilities that come with the rules module. At least have a look at the "Rules Evaluation Log" (to check that the Rules logic being executed, actually matches what you expect that logic to be).

Debugging using the Devel module

Depending on what the result of that type of debugging is, you may also want to (temporary) enable the Devel module, so that you can (temporary) add a Rules Action like "Display a value".

Video tutorial about Rules debugging

Refer to the (great!) video "Debugging rules configuration" for way more details about the last 2 variations.


What are best practices for supporting and upgrading a list of contributed and custom Drupal module?

Using an Install Profile can really help with these situations.  Have the consultant create a profile and manage the modules they are responsible for in profiles/[PROFILE NAME]/modules.  You will be responsible for everything that is in sites/all.

You can use https://www.drupal.org/project/profiler_builder to easily generate an install profile from an existing site.  https://www.drupal.org/project/profile_switcher can be used to convert a site started with a standard install to use a profile.

https://www.drupal.org/project/profile_status_check is also useful to visually see which modules are being loaded from profiles/[PROFILE NAME]/modules vs. sites all as well as break out custom modules (regardless of location) vs. contrib.

Install profiles are as easy as developing a custom module.  Most people are only familiar with the Install Profiles that are included in Popular Drupal Distributions like OpenAtrium and Acquia Commons. Distributions are more difficult to manage.  They require drush make and/or .make files to manage contrib modules as well as 3rd party libraries.

While going to a full blown Distribution makes sense in some use cases, just using an Install Profile could be an elegant solution to defining who is responsible for different modules in your use case.


How to get the field settings values in filed constraint validator

If they are field storage settings, then you could pass them along as arguments to the constraint.

If not, then add the constraint on the field type, not on the property. You can do that directly in the annotation, see \Drupal\file\Plugin\Field\FieldType\FileItem as an exampe. Then you get the whole field item in your validator and you can access the values and the definition/settings.


How can I export and import users and their content (preferably as code)?

You could use backup and migrate to just export the "users" table and if you have additional fields all those "fields" tables.


How to remove a specific item from the search index?

Looking at the code executed from node_delete_multiple() (which is then the function used by node_delete()), I see that the function called is search_reindex().

    // Remove this node from the search index if needed.
    // This code is implemented in node module rather than in search module,
    // because node module is implementing search module's API, not the other
    // way around.
    if (module_exists('search')) {
      search_reindex($nid, 'node');
    }

The code executed from that function to delete rows from the search tables is the following one.

db_delete('search_dataset')
  ->condition('sid', $sid)
  ->condition('type', $module)
  ->execute();

db_delete('search_index')
  ->condition('sid', $sid)
  ->condition('type', $module)
  ->execute();

// Don't remove links if re-indexing.
if (!$reindex) {
  db_delete('search_node_links')
    ->condition('sid', $sid)
    ->condition('type', $module)
    ->execute();
}

I suggest using search_reindex(), but to reply to your question, it doesn't seem that updating the "search_total" table is necessary, at this point; Drupal doesn't do it when a node is deleted. That table is updated from search_update_totals(), which is called from search_cron(). See the comment given for the following code, executed from search_update_totals().

  // Find words that were deleted from search_index, but are still in
  // search_total. We use a LEFT JOIN between the two tables and keep only the
  // rows which fail to join.
  $result = db_query("SELECT t.word AS realword, i.word FROM {search_total} t LEFT JOIN {search_index} i ON t.word = i.word WHERE i.word IS NULL", array(), array('target' => 'slave'));
  $or = db_or();
  foreach ($result as $word) {
    $or->condition('word', $word->realword);
  }
  if (count($or) > 0) {
    db_delete('search_total')
      ->condition($or)
      ->execute();
  }

In Drupal 6, the equivalent of search_reindex() is search_wipe(), which is called from node_delete(). The function contains the following code to delete the tables' content.

db_query("DELETE FROM {search_dataset} WHERE sid = %d AND type = '%s'", $sid, $type);
db_query("DELETE FROM {search_index} WHERE sid = %d AND type = '%s'", $sid, $type);
// Don't remove links if re-indexing.
if (!$reindex) {
  db_query("DELETE FROM {search_node_links} WHERE sid = %d AND type = '%s'", $sid, $type);
}

Also in this case, I suggest using search_wipe().


This module can be used to add help text to node title
https://www.drupal.org/project/node_title_help_text


phpwkhtmltopdf engine pdf printing configuration issues

/opt/drupal/vendor/mikehaertl/phpwkhtmltopdf/src/Pdf.php: cannot open
?php: No such file

You need to install the missing library using composer
composer require mikehaertl/phpwkhtmltopdf

In addition, you might also need h4cc/wkhtmltopdf, see Entity Print documentation


How to setup a Facebook page block for each user?

I'm presuming you want to do something like a Facebook Likebox embedded iframe (e.g. https://www.facebook.com/plugins/likebox.php?my_user_facebook_page_details...) with the user supplying his own URL in his user account profile.

If that's the case set up your block view to render your user's URL field with a custom template. Under the Views UI in Advanced > Other > Theme, the Information link will give you a list of template names (e.g. views-view-field--field-my_user_field.tpl.php) that you can put in your theme's template directory and some boilerplate code (found via the link next to the template names). You can alter the template such that the $output is wrapped in a iframe src attribute.

Flushing the cache should rebuild everything so that your block's URL field now renders as an iframe on the user page (if you've configured your contextual filter correctly). It probably should be noted that rendering a user-supplied iframe URL is dangerous so you probably should be filtering out non-Facebook URLs.


Views 2 Drupal 6 Filter Result if none of the fields have a value

Module Views Or allows me to add OR clauses to my filters and get the job done. Here is an excerpt about it from the module's project page:

  ... allows Views to combine filters or arguments with OR and fields with COALESCE.


For any source or path of any thing in drupal site use src like this. It will work everywhere.$src = base_path() .'sites/files/logo.png';


In Drupal Commerce, to prevent a product displaying on the front end you either.

Unpublish the product display node (the node referencing that product)
Remove the product from the product_reference field on the relevant product display node.


This is no secure issues with this.

Drupal 6 return node_add('story')
Drupal 7 return drupal_render(node_add('story'))

  Returns a node submission form.

for more information checkout the node_add() function


Using drupal_add_css to dynamically add inline CSS based on term reference

If using render you should attach the css to that render array.

$term = taxonomy_term_load($node->field_example_category['und'][0]['tid']);
$category_color = field_view_field('taxonomy_term',$term,'field_example_category_color');
$name = $term->name;
$category_color['#attached']['css'][] = array(
  'data' => ".bg-unit-color {background-color: $name;}",
  'type' => 'inline',
);


How can I run client side validation before a Drupal AJAX submit call?

I would attempt to hijack the submit form by changing the event type and triggering the submission yourself.

For example:

$form['actions']['submit']['#ajax'] = array(
    'callback' => 'fantasia_user_login_ajax_callback',
'wrapper' => 'user-login-form',
    'event' => 'submitmyform',
 );

Then just add your own click or form handler. Once you happy with the validation simply trigger the event "submitmyform". For example:

Drupal.behaviors.loginAjax = {
  attach: function (context ,settings) {
    // Cache the form object
    var $form = $("form#user-login-form", context);
    var $submitButton = $('input[type="submit"]', $form);

    // Use once so we dont attach submit multiple times
    // Use off to remove any existing submit handler
    $form
      .once('loginAjax')
      .off('submit')
      .on('submit', function(e){
      e.preventDefault();
      var $form = $(this);

      // Run validation on $form object.

      // If success, trigger event on button
      if(valid) {
        $submitButton.trigger('submitmyform');
      }
    });
  }
}

I have not tested this code but in essence this is how I recommend you approach it rather than messing around with the ajax object itself.


How can I detect whether the install process is running?

You're probably looking for drupal_installation_attempted():

  Returns TRUE if a Drupal installation is currently being attempted.


Is it possible to link images to different URLs?

You can do this using the Rewrite feature of Views.
These instructions assume that the view is set to show Fields (instead of Content or something else).  If you are not using fields, you can switch to fields under FORMAT in the Views UI.

Click the image field in your view and select the checkbox Exclude from display.
Add a new field to the view of type Custom text.
On the custom text configuration screen, check the Replacement patterns. This will include some twig tokens that you can use, including the image file. You can then use this token to add HTML to the Text field to get the link you want.  For example, {{ image }}.

Note that when using Views twig replacement tokens in a custom text field, order matters!  If your custom text field is above another field, it won't be able to get the tokens from the field(s) below.  In that case, you will need to click the flippy triangle to the right of Fields in the Views UI and choose rearrange, and then move the field that uses tokens below the field(s) that supply the tokens.
Another option is to open up the settings for your image field in Views and, under Rewrite results, click Output this field as a custom link and set the link options there.


Drupal 7 + Services : Error 500 on user registration (Integrity constraint violation: 1048 Column 'uid' cannot be null)

I think that on the other side of your code you are trying to save the user. So, to create a new user using user_save() function you have to left the first parameter blank so a new user is created. Also, add the parameter true to your json_decode($response, true) to obtain an array rather than an object.

$account = user_save('', $fields);


What is the equivalent of a call to drupal_http_request()?

Finally i find a code in https://api.drupal.org/api/drupal/core%21includes%21install.core.inc/8 (1375)

and its working for me :)

 try {
    $response = \Drupal::httpClient()->get($uri, array('headers' => array('Accept' => 'text/plain')));
    $data = (string) $response->getBody();
    if (empty($data)) {
      return FALSE;
    }
  }
  catch (RequestException $e) {
    return FALSE;
  }

Hope this will help for some one


In the code above $parent is an array so $parent->tid is illegal. I am not sure what you are trying to find in the $parent but you should also note that the parent array has numeric indicies. So you probably have to do it this wat $parent[45] or $parent[$city->tid] depending on your requirement


Are you going to use the same webform for all your node events?

Then maybe you should consider creating a url pointing to your webform with parameters. In your webform you can catch the parameters with %get[parameter].

Although I should warn you that when I tried something similar I had this problem: Ampersand does not get urlencoded and breaks my GET parameters


How to get the administrator role id to assign new permissions?

unless you install Drupal in your custom installation profile and modify the administrator role there, the rid or administrator will be always 3.
Or you could just do a db_query() on role table to return the rid of administrator as:

$result = db_query("SELECT rid FROM {role} where name like :id",array(':id' => 'administrator'));
$admin_rid = $result->fetchField(0);


Try using the Views Natural Sort module, it is an add on to views and provides a better sorting option than the build in views sort.

Provides a views filter that sorts node titles by a more natural manner by ignoring articles like "The" and "A."


That folder is needed by LetsEncrypt and is nothing to do with Drupal. For some details elsewhere on the SO network see https://serverfault.com/questions/796745/letsencrypt-do-i-need-to-keep-well-known-accessible-for-certificate-renewal


In Drupal 8, pathauto patterns are configuration entities. You have  at least two choices to provide them with your custom module:

(1) Provide your pattern as YAML configurations in your module's config/install folder. They will be considered and installed to your Drupal, when your module will be installed. Easiest to create using the UI and doing a configuration export afterwards. Just remove the generated UUID of the pattern.

(2) On run-time or in your install/update hooks, you can use Drupal\pathauto\Entity\PathautoPattern::create() or the \Drupal::entityTypeManager() to create them dynamically:

$data = [
  'id' => 'my_pattern_machine_name',
  'type' => 'canonical_entities:node',
  'pattern' => 'my-path/[node:title]',
  'weight' => 0,
];
$pattern = \Drupal::entityTypeManager()->getStorage('pathauto_pattern')->create($data);

You can then use the returned pattern entity in $pattern to add selection conditions (e.g. bundles, language, ...) as required. Don't forget to save the entity afterwards, and - of course - check, if the pathauto module has been installed before or make it a dependency of your custom module.


Add bootstrap.inc to file to programatically save nodes

Drupal 7 uses the DRUPAL_ROOT constant that is set to the Drupal root directory path. If you look at the code of the index.php file, you will notice the following code.

/**
 * Root directory of Drupal installation.
 */
define('DRUPAL_ROOT', getcwd());

require_once DRUPAL_ROOT . '/includes/bootstrap.inc';
drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);
menu_execute_active_handler();

The constant is also used from Drupal functions, such as module_load_include().

  if (function_exists('drupal_get_path')) {
    $file = DRUPAL_ROOT . '/' . drupal_get_path('module', $module) . "/$name.$type";
    if (is_file($file)) {
      require_once $file;
      return $file;
    }
  }

If you have to write, for any reason, a function similar to module_load_include() you should use DRUPAL_ROOT to get the Drupal root directory.

Supposing that in your case Drupal is not in the current directory, you can use the following code.

define('DRUPAL_ROOT', 'the directory containing Drupal');

require_once DRUPAL_ROOT . '/includes/bootstrap.inc';
drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);


Reverting/updating "FILE_DISPLAY" in Features

There is a bug with media and the media modules.

There is some patches already that you could try

https://www.drupal.org/node/2104193


To know if there are translations available for particular node, You need to call the below function to get the available translation nodes.

$translations = translation_node_get_translations($node->tnid);

Ref : Function translation_node_get_translations

So what you can do is, You can call this function when you are returning node from service API along with translated nodes.

Hope this will help.

Thanks


How to resolve composer autoloader not found error?

So, this is something that is a little bit wonky in the user interface for composer manager. The file path to where the autoloader should be gets generated automatically in reference to the drupal root of where you configure composer. If your live and development environments have different doc roots, as is likely with a shared host (e.g. /var/www/html/mysite vs /yourhost/public_html/blahblah, your path will be different and drupal won't know where to look. To solve this problem you have to modify the composer manager file directory variable to reflect where the file actually is. You can't change this through composer manager's settings tab, because it will generate a site error that prevents navigating to the tab and editing it there. You can most easily edit this variable with the devel module's variable editor function.


Don't do it in the Twig file. This is not where that logic belongs. It should be in an Event.

See this similar question: EventSubscriber called on specific node type or path

All that is left is checking the node type and sending a RedirectResponse.

Gabe Sullice has a Gist that sounds very close to what you are trying to accomplish: https://gist.github.com/gabesullice/96bdae1518d11bb4565e72c33ffcae4c

So your code would fill in something like:

  /**
   * Determines whether we should send a RedirectResponse for this node.
   */
  protected function redirectApplies(NodeInterface $node) : bool {
    $redirect_types = ['type_1', 'type_2', 'type_3'];
    return in_array($node->getType(), $redirect_types);
  }

But if you go to different urls for different types, you will need to adjust it a little more.


Why do start and end dates in views appear the same but are not in content?

It sounds to me like you have a single date field in your content that you have set with an end date but in your view you have set this with two different fields. Instead you should edit the view and click the first date field and check the formatter settings to be one that includes start and end dates.


How do I resize image directly while uploading the image?

Try Max Image Size module

On the module page it says:

  This module will resize uploaded images to be below the set
  dimensions. It is not an image style or other presentation layer
  module. If you want to maintain the original image you should use
  Image Resize Filter or an image style. The use case for this module is
  sites where users may upload very large images, but you do not
  want/need to keep the original.


If you want to use the method language() in Twig

{{ node.language.name }}

you have to add it to the whitelist of the Twig sandbox policy in settings.php:

$settings['twig_sandbox_whitelisted_methods'] = [
  'id',
  'label',
  'bundle',
  'get',
  '__toString',
  'toString',
  'language',
];


Custom module blocks: where to put html code?

You could improve that with 2 different options:
1) Creating a theme function
2) Creating a template file (tpl)

The tpl may be a cleaner option, but they are both similar. In both cases, you should pass preprocessed variables instead of putting the logic inside the theme function/tpl file.

Also, note that the literal strings should go through the t() function.


amazons3-7-x-2.0, Multiple upload to S3, #upload_location wrong URI

ok, after spending a few hours debugging the code, I have finally identified  the problem and come out with a solution :

Amazons3 implements a amazons3_field_widget_form_alter that fixes the $element['#upload_location'] :

  function amazons3_field_widget_form_alter(&$element, &$form_state, $context) {

  $field = $context['field'];
    $instance = $context['instance'];
    $delta = $context['delta'];

  if (in_array($field['type'], amazons3_file_like_field())) {
      $element[$delta]['#upload_location'] = amazons3_field_widget_uri($field, $instance);
    }
  }

The problem is that this function is only called once, on $delta=0. Thus, it only fixes the first delta instance of the field, correcting the first upload. But the second upload fails because the bucketname is not in the remote URI.

In order to fix this, I propose the wrote following function in my module :

  function mymodule_field_widget_form_alter(&$element, &$form_state, $context){
      // On essaie de corriger les settings upload_location
      if (!function_exists('amazons3_file_like_field')) {
          return;
      }
      $field = $context['field'];
      $instance = $context['instance'];
      $delta = $context['delta'];

if (in_array($field['type'], amazons3_file_like_field())) {
    foreach (array_keys($element) as $count => $key) {
        if (is_numeric($key) && isset($element[$key]['#upload_location']) && !(strpos($element[$key]['#upload_location'],'s3://')===FALSE)) {
            $element[$key]['#upload_location'] = amazons3_field_widget_uri($field, $instance);
        }
    }
}
return;

  }

It works well, allowing multiple uploads in S3 with the new release of the library.
Next step would be to post a patch to the amazons3 module. Which I will do now.


I had a similar problem where I wanted to link to filtered versions of an ajaxified view, but the aforementioned line of code in ajax_views.js prevented the view from displaying all results when all filters where cleared. In my use case, I wanted all views filter identifiers removed, but in yours, as I understood it, you need the clicked filter value removed, so you could modify the code accordingly.

The first step is identifying all valid filter identifiers. We want to do that, so we don't parse out all of the query string's parameters, since some of them might serve another functionality. If you don't care about creating a dependency to the better_exposed_filters module you can find the views identifiers from Drupal.settings.better_exposed_filters.views.[view_name].[view_display].filters.
Otherwise, you could expose them in your own Drupal setting through a views hook:

function hook_views_pre_render(&$view) {
  if ($view->display_handler->has_exposed) {
    $valid_identifiers = array();

    foreach ($view->filter as $name => $filter) {
      if (!$filter->options['exposed']) {
        continue;
      }

      $valid_identifiers[] = $filter->options['expose']['identifier'];
    }

    drupal_add_js(array('validViewsIdentifiers' => $valid_identifiers), 'setting');
  }
}

So, now we have the identifiers and in our custom js file we can change the related properties of the views instance(s). The code for my use case is the following, but you can change accordingly:

Drupal.behaviors.fixAjaxQueryString = {
  attach: function(context, settings) {
    if (!Drupal.views || !Drupal.views.instances) {
      return;
    }

    for (var i in Drupal.views.instances) {
      var instance = Drupal.views.instances[i],
          url = instance.element_settings.url;

      // Check for any valid views filter identifiers and remove them
      var validViewsIdentifiers = Drupal.settings.validViewsIdentifiers || '';
      if (validViewsIdentifiers) {
        url = decodeURIComponent(url);

        for (var j = 0; j < validViewsIdentifiers.length; j++) {
          var regExpr = '\\&?' + validViewsIdentifiers[j] + '(\\[\\])?=[^&]*';
          var regExprObj = new RegExp(regExpr, 'g');

          url = url.replace(regExprObj, "");
        }
      }

      // Only the .options.url part is needed for the desired functionality
      // The rest is modified for consistency
      instance.element_settings.url = url;

      if (instance.exposedFormAjax) {
        instance.exposedFormAjax.options.url = url;
        instance.exposedFormAjax.element_settings = instance.element_settings;
        instance.exposedFormAjax.url = url;
      }

      if (instance.pagerAjax) {
        instance.pagerAjax.options.url = url;
        instance.pagerAjax.element_settings = instance.element_settings;
        instance.pagerAjax.url = url;
      }

      if (instance.refreshViewAjax) {
        instance.refreshViewAjax.options.url = url;
        instance.refreshViewAjax.element_settings = instance.element_settings;
        instance.refreshViewAjax.url = url;
      }
    }
  }
};


Views Slideshow only shows one static image and doesn't cycle in IE8

It turns out that this was caused by something in the template.  The developer had called the JQuery library from the page.tpl file when it was already being called by core, so it caused the error in IE.  See this page on drupal.org for more information.


According to Ryan, it's based on the weight of the terms you reference.

As far as the default product that is selected, it should be the first product referenced in the field. If you're wanting to set that dynamically, you can look at Commerce Product URLs which provides that functionality.


According to the documentation:

  Changes to the form must only be made in the form builder function (ajax_example_autocheckboxes() in the example here), or validation will fail. The callback function must not alter the form or any other state.

You have been changing the form_state and the form in the callback.

Based on how I understood the documentation, you should be just returning the whole form in your ajax callback and then do the change in your form in the form builder function. You can just check the form_state value of the drop down to know which form to render. I imagine it'll be something like this:

function add_term_form_callback($form, $form_state) {
  return $form;
}

 function add_term_form($form, &$form_state) {

 // If vocabulary has value
      // do stuff
      // $form = drupal_get_form('taxonomy_form_term');
 // else :
  $options = array();
  $options[0] = t('- Select -');
  $vocabularies = taxonomy_get_vocabularies();
  foreach ($vocabularies as $vocabulary) {
    $options[$vocabulary->vid] = $vocabulary->name;
  }

 $form['vocabulary'] = array(
   '#type' => 'select',
   '#title' => t('Select vocabulary'),
   '#options' => $options,
   '#default_value' => $selected,
   '#ajax' => array(
     'callback' => 'add_term_form_callback',
     'wrapper' => 'container',
     'event' => 'change',
   ),
 );

  $form['#prefix'] = '
';
  $form['#suffix'] = '
';
  );
  // endif;

  return $form;
}

EDIT: I just noticed that you weren't wrapping the form but a container in the form. you would have to wrap the form if you want the whole form to be reloaded.


It appears that the functionality does not yet exist for Drupal 8

https://www.drupal.org/node/2296437


Looking at the source code on your live site, I see that the code for the fb:like section becomes:

<fb:like href="http://indiansnakes.org/frontpage" send="true" layout="box_count" width="450" show_faces="true"></fb:like>

...so I assume [url] is a token. Assuming that's true, I'd recommend using a more specific URL token.


How can I re-write feeds xpathparser data?

You can use the REGEX find/replace plugin in Feeds Tamper to do it.

Find: ([^,]+),\s*([^,]+)

Replace: $2 $1

Note: The above regex is more-or-less a guess and assumes that there are no commas in the FIRST_NAME or LAST_NAME.


How do you add Views to a View Mode?
If you want to add a view to a content type's view mode there is a few ways to do this and depending on your exact requirement one might be better than the others
views field formatter
Use https://www.drupal.org/project/views_field_formatter will allow you to choose a formatter for a field and it will pass automatically the value of the field to the view
viewfield
https://www.drupal.org/project/viewfield will allow you to add a field and to choose what views can be chosen and allows you to also include an argument on the node edit form
EVA: Entity Views Attachment
https://www.drupal.org/project/eva will allow you to create a specific EVA views display and configure it to appear for specific bundles (content types).  After saving the view it will appear as a field in the display mode of that content types so it can be positioned appropriatelly
All the above module can take advantage of arguments and contextual filters so you can do very complex things with them


How to dynamically populate select options?

As said before you could make use of Form APIs #states to display one element only after a certain input to another form element has been made. In your case you'd maybe go with two additional select lists, both initially hidden. Check form_examples_states_form() for more information.

$form['main'] = array(
  '#type' => 'select',
  // ...
);
$form['sub_a'] = array(
  '#type' => 'select',
  // ...
  '#states' => array(
    'visible' => array(
      ':input[name="main"]' => array('value' => 'foo'),
    ),
  ),
);
$form['sub_b'] = array(
  '#type' => 'select',
  // ...
  '#states' => array(
    'visible' => array(
      ':input[name="main"]' => array('value' => 'bar'),
    ),
  ),
);


Drupal 7 - Create a custom template that can be assigned to different pages

See here Drupal 7 Theme Hook Suggestions

For nodes You can use

    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

Also Drupal 6 Template Suggestions

To use same tpl for multiple pages you need to use theme_preprocess_node
Like

function theme_preprocess_node(&$vars, $hook) {
  $node = $vars['node'];
  if(in_array($node->nid), $myuids)
   $vars['template_file'] = 'your_template_file';
}


Rules - send email when users role changes to x

Arpitr got me on to the correct solution for this. Here is the code that you can import:

{ "rules_update_user_role" : {
"LABEL" : "Update User Role",
"PLUGIN" : "reaction rule",
"OWNER" : "rules",
"REQUIRES" : [ "rules" ],
"ON" : { "user_update" : [] },
"IF" : [
  { "user_has_role" : { "account" : [ "account" ], "roles" : { "value" : { "7" : "7" } } } },
  { "AND" : [
      { "NOT user_has_role" : {
          "account" : [ "account-unchanged" ],
          "roles" : { "value" : { "7" : "7" } }
        }
      }
    ]
  }
],
"DO" : [ { "drupal_message" : { "message" : "Changed User!" } } ]

}
}

I like the way arpitr used a drupal message for testing if the rule had worked - i didn't realise you could do this.

It looks like the mistake I might have been making was to use the condition of type 'data comparison' and then try to drill into it to get to the user role rather than just using the 'user has role' condition. I think when i had tried previously to use the 'user has role' condition it failed because I made the used 'account:roles' rather than just account.

Hope this helps someone else.


There are a couple of ways of doing this. You can create an entity. This requires the writing of a custom module to do so. Entities can be challenging if you have never done them before.

Another way and slightly simpler (still requires a custom module). Is to use the Views API. The first thing you would implement is hook_views_data(). This is a really good example of hook_views_data borrowed from Drupal Commerce.

Lastly, there are some modules out there that might help. One of them is Schema Views.


No such file or directory in Drupal\Component\DependencyInjection\PhpArrayContainer->createService()

I needed to use drush 9.6 and updated that by composer require drush/drush:"^9.6". Thanks drugan!


Field Collection vs. Entity View Modes with Field Group

Jim -

I love Field Collections because it allows me to create "structures" of fields that I can tie to multiple content types. You can still use Field Collections with Field Groups (in order to create field sets and the like). Would definitely recommend for projects with lots of content types / data that needs organization.


Drupal\Component\Plugin\Exception\PluginNotFoundException after upgrading drupal

That means you have a field with an unknown field type. Are you sure that you're not missing any modules that you used to have installed? And the the missing entity type sounds like you used to use https://www.drupal.org/project/block_visibility_groups but now it's gone?

My guess is that you accidently removed all/some contrib modules before updating, which you shouldn't do. Minor updates are like any other normal core update, except they come with some more changes.


Is there a property that is set by the field API once fields have been attached to an entity?

No, there is no property on the entity, but you can use field_info_instances() to check on which bundles the field is in use.


Take a look at hook_views_query_alter(). You can grab exposed filter values by inspecting $_REQUEST and grabbing the appropriate value from that array. I usually implement hook_views_query_alter and just wrap the query in a dpm() call (from the Devel module) so I can browse the array.

If using AJAX in your views, you'll need to refresh the page after you filter your view before Devel can print the array in your messages.


Views with relationship of taxonomy terms

In your view FIELDS click on your Catagory field, since your category allows for multiple values, you should see the following option Multiple Field Settings, click on it to expand it:

All you gotta do is uncheck this.


what variable can i use to identify a specific pages

You may have trouble adding CSS with drupal_add_css in hook_preprocess_page because the $styles variable has already been built.

Better to add CSS in hook_preprocess_html or hook_page_build

Note, you should be able to target specific pages in CSS by using body classes.

e.g:

body.page-node-type-article #content{
  background-color:pink;
}

But yes, to check the path, you can use

$arg = arg($index); // system path component
$path = current_path(); // full base system path ($_GET['q']);
$alias = $_SERVER['REQUEST_URI']; // full alias only


Contextual link in Product Display type to allow me to edit the referenced Product?

This is a year old question, but worth answering I think.

You can use this hook (hook_menu_contextual_links_alter). The sample does exactly what you want. (I mean altering node's contextual links)

Here's an actual code I did. And it works for multiple products too.

    // Add a link to all contextual links for nodes of type product_display.
    if ($root_path == 'node/%' && $router_item['page_arguments'][0]->type == 'product_display') {

      // Loop through all products
      foreach ($router_item['page_arguments'][0]->field_product[LANGUAGE_NONE] as $element) {
        $product = commerce_product_load($element['product_id']);

        // Add your contextual link
        $links['edit_prod_'.$element['product_id']] = array(
          'title' => t('Edit @sku', array('@sku' => $product->sku)),
          'href' => 'admin/commerce/products/'.$element['product_id'].'/edit',
          'localized_options' => array(
            'query' => array(
            'destination' => current_path(),
          ),
        ),
      );
    }
  }

This will add contextual links like 'Edit HMWPB' or 'Edit POHPB'


importing blogs from another database with different content type fields

Try using the feeds module and export to a CSV file then import the data under the new respective fields. You may need to add extra fields to the new content type to prevent data loss


By default drupal don't let you do this , you should achieve it with this two solution

use nodeblock

  This module allows you to specify content type(s) as being a block.
  This allows the content managers of the site to edit the block text
  and title without having to access the block administration page.
  Users only need edit access to that node in order to edit it.

  We advice you to use this module together with Node Level Blocks or
  Block Reference module.

  It is very handy to create a simple block content type and enable this
  content type for blocks and use these in place of the normal 'add
  block' functionality.

Achieve it by views block,I mean create a view, get result of it with what you want ,then save it as block ( I mean create block view), then put the block in the region you want.


What is the progress bar periodic update function return data?

The core example is in FileWidgetAjaxController::progress. You need to return a JSON-encoded associative array with message and percentage keys. For example:

$progress['message'] = t('Uploading... (@current of @total)', ['@current' => format_size($status['bytes_uploaded']), '@total' => format_size($status['bytes_total'])]);
$progress['percentage'] = round(100 * $status['bytes_uploaded'] / $status['bytes_total']);
...
return new JsonResponse($progress);


php and html tag problem when customizing menu items

You could check if where the call to the l() function is created (in the function mentioned: bootstrap_menu_link), the third parameter contains the following element in the array:

'html' => TRUE

This tells drupal to output the title of the link as html and not run it trough check_plain().

Also, I would create a custom theme based on the bootstrap theme and add my customization there.


Correct way to change the active Drupal theme programmatically?

Drupal 6 solution:

You want to make sure you change the global $custom_theme variable fairly early in page execution.

global $custom_theme;
$custom_theme = 'garland';


You can use feeds module which import data, uses, taxonomy term into Drupal website using CSV file.

In module page:

  Import or aggregate data as nodes, users, taxonomy terms or simple
  database records.

  One-off imports and periodic aggregation of content
  Import or aggregate RSS/Atom feeds
  Import or aggregate CSV files
  Import or aggregate OPML files
  Create nodes, users, taxonomy terms or simple database records from import
  Extensible to import any other kind of content
  Granular mapping of input elements to Drupal content elements
  Exportable configurations Batched import for large files