What are the alternatives to Features module in Drupal 8 I am trying to export configurations from one Drupal site to other. This is not a one time operation, I will need to do this multiple times and Single Import, Simple Export is not an option as there will be changes to many files.

Is there any stable alternative to Features module?

There are multiple options available but please note that all of them are still in active development.

Config Inspector
As the name suggests it lets you inspect the configuration under a menu item in Administration > Reports

Config Devel

This module lets you both import and export the configurations code. You have settings page where you need to enter the absolute path of the files that will be imported or exported. If you want to get an idea of the filenames you can do a full site export from admin/config/development/configuration/full/export and checkout the file names. Please make a note that you need to give the full path of the files here.

If you have entered the file names correctly in Export Configuration, then whenever the respective settings are changed the changes will be written to the respective yaml file.

If you have entered the file names correctly in Import Configuration, then whenever the respective yaml files are changed the changes will be imported into the active storage.

This module can be helpful to track the configuration changes during the development stage and play around with them.

Config Tools

If you want to save the configurations of the site in code and be able to track it using git, you can use this module. It is very similar to the Config Devel module. I would prefer config devel module personally.

Config Update Module

  The main use case is: You update a module, and it has either changed
  default config that it provides, or added new config items. You want
  to be able to import the new items, view the differences between the
  site config and the changed config, and possibly "revert" (or it may
  be an update) to the newly-provided default config.

Config Reset Module

This module is similar to Config Update Module. Personally I would prefer Config Update Module as it is being used by Features Module.

Configuration Synchronizer Module

This module is similar to Config Update Module. Personally I would prefer Config Update Module as it is being used by Features Module.

Features Module

This module is actively being developed and I feel it has made some good good progress recently. As of now all the features are programmatically created. It has good drush integration. If you want to create a custom feature you must use drush features-add command.

Foot Note : If you are trying to export all the settings from one cloned site to other check out What are cloned sites in Drupal 8?

Bonus Links : If you have not yet understood CMI check out Alex Pott's articles:

http://www.chapterthree.com/blog/principles-of-configuration-management-part-one
http://www.chapterthree.com/blog/principles-of-configuration-management-part-two
http://www.chapterthree.com/blog/principles-of-configuration-management-part-three


Drush site install break when a custom commerce feature is enabled, why? The D7 site i'm working has a feature that includes two custom product types, amongst other things.  A custom feature gets auto-detected and added as a dependency because it contains a rule on one of the product types.  Another feature added to the site install profile contains the permissions to those types.

After i exported the features and tried to install the site again, it breaks because:

the product types are do not get created, i expect this log entry to show but does not:
WD features: Rebuilding feature_name / commerce_product_type
Which, i'm guessing, is when the types get created from the feature.  That log entry shows on a successful build (see below).
consequently, the permissions feature causes a fatal error when trying to insert the types permissions into the db, since they don't exist and not defined by a module (from commerce_entity_access_permissions).

The solution for the fix is to manually remove the auto-detected feature with the rules.

I assumed that there's something wrong with that feature but can't think of what.  Has anyone experienced something like that?

It seems to be a problem with Features and how Drush site-install processes.  Basically, features_include() is called after each feature is enabled during the site install.  Somehow (but most likely due to the ordering of the dependencies), the commerce_features module gets enabled after my custom feature.  As such, features_include(), which has already ran and cached its data, skips calling commerce_features_features_api(), which is crucial for my custom product types, included in yet another custom feature, to be created.

I opened an issue at http://drupal.org/node/1334438, see for more details and follow-ups.


My webhosting won't allow "Options" in .htaccess My webhosting provider of 4 years said they don't allow "Options" in .htaccess files. They were referring to lines 11 and 14 of the .htaccess file. Is it ok to comment these out?

These lines are

# Don't show directory listings for URLs which map to a directory.
Options -Indexes

# Follow symbolic links in this directory.
Options +FollowSymLinks

Does it pose a security risk?

Options -Indexes prevents users from seeing which files exist in a directory. You shouldn't use this feature to secure your site, it mainly exists for aesthetic reasons. It is technically never necessary.

Options +FollowSymLinks is not necessary in a vanilla Drupal installation, chances are you do not need this one either.

Have a look at the documentation of the Options directive for more details.


How to get contextual filter in hook_views_query_alter or hook_views_pre_execute? I want to alter contextual filter before executing the sql query of views. Is there any way to get current contextual filter in hook_views_query_alter or hook_views_pre_execute? Or which is the better hook to alter contextual filter for views?

The contextual filters are in $view->args.

$view->args is an array of arguments (contextual filters).

So you can do things like this:

/**
 * Implements hook_views_pre_execute().
 */
function MODULENAME_views_pre_execute(&$view) {
  // Set the first contextual filter value.
  $view->args[0] = 1;
}


How do I write a left join query? I want to get the value of "vid" knowing the node ID, and get the value of "name" for those rows where "vid" is equal to 2.

If it were a plain query, I would not know how to write it; I don't know how to write a left join query.

The "plain" SQL query in Drupal is the following:

$result = db_query('SELECT tid FROM {taxonomy_index} WHERE nid = :nid', array(':nid'=>$nid));

The equivalent raw SQL query is the following:

SELECT did, name FROM taxonomy_index as ti LEFT JOIN taxonomy_term_data AS ttd ON ti.tid = ttd.tid WHERE vid = 2 and nid = $nid

$terms = db_select('taxonomy_index', 'ti')
  ->fields('ti', array('tid', 'name'));
$terms->leftJoin('taxonomy_term_data', 'ttd', 'ti.tid = ttd.tid');
$terms->condition('vid', 2)
  ->condition('nid', $nid)
  ->execute();

while ($term = $terms->fetch()) {
  // $term contains the object for the taxonomy term.
}


post comments with approval on forum i use advanced forum. in permission page and comment module permission i  dont set post comments without approval for authenticated user but when authenticated user send post on forum it immediately appear in forum without admin approval.
but if this user add comment for a post it will add to approval list.
why?

edit: there is my mistake. when i dont set post comments without approval for authenticated user it works correctly (and user cant post comments) however authenticated user can create forum topic without approval.? how to handle this?

Have in mind that a post is a node, so it doesn't behave such as comments and so, it doesn't fall into the same logic.
If you want moderation for posts, you should do something else, maybe playing with rules (and or views) to establish a moderation panel/system.


How to change my homepage based on the time of day? I have searched high and low for this. How do I change my homepage based on the time of day? To be absolutely explicit, I want:

Between 8am and 7pm - Homepage 1 (node/4)
Between 7pm and 8am - Homepage 2 (node/5)

So I want to design two completely different homepages and then they change based on time of day.

I tried some code but it doesn't seem to do the job:

$current_front = variable_get('site_frontpage');

if($current_front== 'node/4'){
    variable_set('site_frontpage','node/5');
}else{
    variable_set('site_frontpage','node/4');
}

Note:  I am not a code whizz so wouldn't know where to start with hooks and I'm a million years away from creating my own modules.

Consider using the Rules module to set the appropriate node as your frontpage.

Based on the sample in the question, I'm assuming that node/4 is what the value is of site_frontpage. Here is the actual rule to be created that could work in your case:

Create a new rule
Event = Content is viewed
Condition: data comparison -> node:nid equals 4
Add an extra condition to check if current time is between 7pm and 8am.
Action: page redirect to node/5

For anybody not familiar (enough/yet) with Rules, checkout the 32 (!!!) great (+ free) video tutorials Learn the Rules framework. Possibly also the similar set of 8 video tutorials about the Flag module, often considered as a natural complement to the Rules module. Maybe also review the set of 30 video tutorials about the Views module ... Familiarity with only those 3 modules (Views, Rules and Flag) can get you pretty far in mostly any Drupal site (as a site builder).


How to hide language selector dropdown on node add page for a role? I would like to hide the language selector dropdown on node add pages of multilanguage enabled content types.

What would be the best way? A jquery selector perhaps?

Don't use jQuery for this. Better use hook_form_alter.

Check if user has target role.
Print out your $form and find language select in printed array.
Than hide language select.

There are 2 options for hiding:

1st:

$form['language']['#access'] = FALSE;

2nd:

$form['language']['#prefix'] = '
';
$form['language']['#suffix'] = '
';


How to create a hook for a module in a theme? I am trying to alter some data that is being passed from the Language Switcher module.

Here is a code snippet from the module.

if (isset($links->links)) {
  $build = array(
    '#theme' => 'links__language_block',
    '#links' => $links->links,
    '#attributes' => array(
      'class' => array(
        "language-switcher-{$links->method_id}",
      ),
    ),
    '#set_active_class' => TRUE,
  );
}

So '#theme' => 'links__language_block', as I could guess means that I have to create the function called

function mytheme_links__language_block(&$variables) {
    var_dump("HELLO");
    exit;
}

But it is not called. I have no idea what is the problem ?

The only hook is called - function mytheme_preprocess_page(&$variables)

Please suggest what can be wrong and why my hook function is not called.

I think this style of theme hook is deprecated in Drupal 8. From the API docs:

  Theme functions are deprecated in Drupal 8.0.x and will be removed before Drupal 9.0.x. Use Twig templates instead.

So since there doesn't exist a theme function theme_links(), the functions MYTHEME_links and MYTHEME_links__language_block would not be called.

You can still customize this output by adding a links--language-block.html.twig file to your theme.

You can also utilize preprocess functions (MYTHEME_preprocess_links()).


Show a block on the user registration form depending on destination parameter How can I show a block, or a a mini panel, on the user registration form depending on the destination parameter?

Right now, I'm showing, in a view, a link that leads the users to user/register?destination=courses. This works fine, but I want to show  certain infomation to the still anonymous users who are going to register an account.

As @runswithscissors pointed out this module does the trick Block Conditional Visibility by URI Query Parameters Thank you!

Step 1

Download and enable drush en block_query

Step 2

Go to blocks admin/structure/block and create a block or enable one of your choice. There are no specific configurations elsewhere. It's a very lightweight feature.

Step 3

At the page of your block, under the "Visibility settings" you will now see "Queries" to "show block on specific pages", add the query parameter ONLY.
E.g. if you have a destination parameter that leads to that particular page, only add the part behind the question mark ?, not the entire path.

Test it out

Let us know if it worked for you too.


Synchronize two drag-able tables I have two tables on a page that the row positions need synchronized when a row is drug. One table is the master table and is the only place that the actual dragging can take place.

Basically, what needs to happen is when the user drags a row in the master table, the changes in position need to be duplicated to the child table.
I've been poking around with the onDrop custom handler function, but I am about at my wits end.
I'm not willing to hack tabledrag.js, as my custom module will be deployed on a system that I don't manage.

I'm sure someone else has faced this same issue. Are there any suggestion for a solution?

Are you using the Draggable Views module? If so, you can set the child table to use the sort order of the dragged table, and possibly trigger an ajax refresh when the order of the master table is saved.


ImageStyles does not create thumbnail image while uploading large images I try to create a website using Drupal on a shared host, everything goes fine except ImageStyles.

When I try to upload large images (more than 1MB) thumbnails does not created , but works fine with smaller one.

I searched it and found these two:

Failing to create thumbnail, medium and large images

Image styles: Does not work with large images

but I can't use these solutions because I'm using a shared host.

Any suggestion will be appreciatived ;)

You can restrict the image upload size using field settings in the admin to less than 1 MB and show a help text that max upload size is 1 MB.

Other option already given by Molot.

Hope it will  help you.


Appointment Scheduling I am looking to create an apointment scheduling system on drupal 7.x, however all of the modules and instructions that I can find are for 6.x. The system is fairly simple, and only needs to be able to have users schedule appointments for certain blocks of time.

How would I go about doing this in 7.x? Are there any modules that I can use, or is there some way to "hack" this out?

We use the signup module for this - we actually used it for tax appointments this year. Yes, it's 7 version is in development but I don't see it being very much different from the 6.x version.

It enables you to attach "slots" to nodes and have people sign up for them. They can be timed or untimed. As the 7.x version is a straight port from the 6.x version, all the tutorials should be the same.


searching custom node type contents from a module If I create my own custom node type by writing my own module(s), is Drupal "smart" enough to index the contents of this new node type from my module?  If not, then would I need to use the Search API's so that contents are included in search results?

Core search module will index all nodes, no matter where they have been defined (manually through admin/custom module.).


How can the -value be passed as a param in a filtered url for a View? I have created a View with two exposed filters: name and status.
The name is a text field, the status is a key|name list: 10|one,20|two,30|three

Using the View as a page, the user can filter the view by entering a text into the name field. The user can filter the status from a dropdown. The dropdown shows 'one' by default because that is the most used filtering.

Everything ok so far.

Now I would like to construct a url as well for this filtering. No problem for the name: view_name?name=richard works perfectly.

For a specific status this also works well: view_name?status=10
(only the key is accepted as a value).

For some views I would like to show all records for one name, whatever the status is. The status defaults to 'one' (which must stay like that) therefore it is not enough to only pass a name. I have to pass something for the status as well.
I tried things like:
view_name?status=
view_name?status=10&status=20 (only last value is used)
view_name?status=0
view_name?status=-1
view_name?status=*
view_name?status=Any

How can I pass the Any-value through the url ?

I suddenly realized that the passed value probably has to match one of the values in the select-options. I just had to look at the source of user page. The value for the Any-option is All. So this works:

view_name?status=All


How do I inspect from a user's view how a given page element was created by Drupal? I would like to be able to access a Drupal site as a given user/user-type (maybe using Masquerade) and from their view of the site be able to inspect how/where the page's configs/scripts/modules/nodes/etc were loaded from.

Background: It's possible in the next week I'll need to take over 10+ existing Drupal sites and most likely the maintenance for the sites will be driven by request like "On this page, I'd like to change this." While it's likely that I'll just have to use what I know of Drupal and hunt down where/how the given page elements are being created/managed, it would be nice to have the option to inspect how/where a given page element is being set within Drupal given a URL and the user that accessed it; think Firebug for Drupal.

If possible. it would be nice if this worked for 6 and 7, since the sites I believe are in 6, but will likely be ported to 7.

Think Firebug for Drupal?

Try the Drupal for Firebug module and associated Chrome/Firefox extension :)


How to pass parameters to frontpage? I have created a frontpage with views. Also I have added the content field called Volume. The frontpage is arranged with 10 views and it shows the Volume by descending order, so the latest volume should be displayed in the front page. There is a page that shows the all released volumes, what I want to do that is when we clicking the volume number, then the frontpage will display all contents belongs to that volume number.

e.g. example.com will shows the default front page and example.com/volume/1 will have to show the volume number 1 and so on, but when we take the page example.com/volume/1 it displays the "Page not found " error

Have you tried Views Arguments? Parts of your URL (eg. volume/1) can be passed to the View as arguments to control the content displayed (eg. arg '1' tells View to display volume num 1).

Here's a solid tutorial video:
http://mustardseedmedia.com/podcast/episode39

And a more detailed explanation on Drupal.org:
"Arguments are parts of the URL of a view that can be used to reduce the result-set. A classic example of an argument would be in the case of taxonomy/term/TID or tracker/UID. In the former case, the view is restricted to posts tagged with the associated taxonomy ID; in the latter case, the view becomes restricted to posts by the specified user.

There is also a special case where arguments can be embedded into a View's URL. For example, the URL /user/$arg/track would be valid on any /user/WHATEVER/track URL, and the WHATEVER would be passed into the view as the first argument.

A given view can have multiple arguments. For example, you might have blogs as a view, and provide UID, Year, Month, and Day as arguments in that order. Thus the URL might look like blogs/1/2006/3/15 which would display all blog posts written by user id #1 on March 15th, 2006. Arguments can also be specified as , which will be interpreted as 'all values'; so in this case, blogs//2006/3/15 would show blog posts by ALL users on that date."

http://drupal.org/node/54455


Calling ajax function from jquery on change event Would appreciate help on a design strategy.

On a form I have an auto complete text field that I would like to populate with two separate values based on a radio button selection.

Currently the first radio button is loaded via an ajax call on load via hook_menu.

function hook_menu() {
$items = array();

$items['module/state_autocomplete'] = array(
        'page callback' => 'state_autocomplete',
        'access arguments' => array('create states'),
        'type' => MENU_CALLBACK,);

Can I attach an ajax call to an on change event that will reload the text field without reloading the page?

For example:

Can I attach an ajax call to an on change event that will reload the
  text field without reloading the page?

If that's your question, then the answer is yes, you can.

If you meant to ask how to do that, then please refer to Ajax Forms documentation for Drupal 8 or Drupal 7.

If you hit any problem when implementing it, then come back giving us the details of specific issue as provided information does not describe what the problem is.


Is there a way to limit / enforce permissions on image style downloads? I have a few image styles that I only want certain node types to be able to view because certain images on my site have an open license for use and so I have a style for a large image gallery view, while others do not and so they shouldn't use this style.

The images, and the image styles are stored in private locations and served through Drupal.

Is there a way I can set conditions on when an image style can be downloaded for an image; for example by node type, a field flag, or who a user is logged in as?

Is there another solution to this issue?

This is not really possible. The module the create this doesn't care or know where the image comes from, so you can't make any permission checks like that. It would be possible to display such images through custom theming Views and many other ways which makes a 100% failsafe permission check more or less impossible.

You can make sure nothing like this will happen based on how you setup your site, and you could add some extra security by overwriting the settings/rendering for image fields, but it won't be 100% fail safe.


Views: displaying related (referenced) content in a block I tried solving the following with "node_reference" and "entityreference" modules but failed.

I have the content types recipe and cook. A recipe has a mandatory field which points to a cook.

When Drupal renders a recipe I want to have a block on the sidebar (implemented via "views") which will be displaying info on the recipe's cook.

How can the block know which recipe is being rendered on screen in order to use the relationship and pull the cook's data as fields which I'll use for display within the block?

thanks

More info: The problem is that in the block I'm getting all referenced (from recipes) cooks and not just the one cook for the specific recipe. So for the following data:

recipe#1 -> cook#1
recipe#2 -> cook#1
recipe#3 -> cook#1
recipe#4 -> cook#2

When I visit any of the recipes the block displays data from:

cook#1
cook#1
cook#1
cook#2

You would need to add a relationship from the reference field in views (under advanced > relationships). This will extend the scope of fields available to the view include those of the referenced node (Cook).

However this will as you state show all cooks as it will come from all recipes. In order for the block to know how to filter out all irrelevant cooks (ones not referenced) you will need a contextual filter which knows what recipe you are currently on.

On this contextual filter you can specify the relationship to the one you have already created, then you will need to let the block view know which recipe you are on. You do this with the setting "provide default value" and "Content ID from URL". This will tell the view which content you are on and hopefully apply the filter. Sorry I do not have access to D7 right now for a better explanation


How to create a bean bundle programatically I don't want to use features. ;)

This is my code:

  beanform.info

name = Bean form
description = Configure beans blocks to print forms into it.
core = 7.x
files[] = "plugins/BeanForm.class.php"
package = "Bean"
dependencies[] = "bean"

  beanform.module

<?php
/**
 * @file
 * beanform module file to store the hooks.
 */

/**
 * Implements hook_bean_types_api_info()
 */
function beanform_bean_types_api_info() {
 return array('api' => 4);
}

/**
 * Implements hook_bean_types()
 */
function beanform_bean_types() {
  $plugins = array();
  $plugin_path = drupal_get_path('module', 'beanform') . '/plugins/bean';
  $plugins['bean_form'] = array(
    'name' => 'bean_form',
    'label' => t('Bean form'),
    'description' => t('Choose a form to print into a bean'),
    'handler' => array(
      'class' => 'BeanForm',
      'parent' => 'bean',
      // 'path' => $plugin_path,
      // 'file' => 'BeanForm.inc',
    ),
    'path' => $plugin_path,
    'file' => 'BeanForm.inc',
  );

  kpr ($plugins);

  return $plugins;
}

/**
 * Implements hook_theme()
 */
function beanform_theme(){
  $items = array();
  $items ['theme_bean_form'] = array(
    'arguments' => array(
      'form' => NULL,
    ),
    'template' => 'templates/bean-form',
    'file' => 'beanform.theme.inc',
  );

  return $items;
}

?>

But When I go to /admin/structure/block-types I don't see my bean.

I don't find the problem, and I'm checking bean_examples and bean_twitter_pull to see how it should be done.

Thanks

Oskar

With bean modules it's required that if you use "name" attribute  is the same name that the $plugins key.

In my case

'name' => 'beanform'

The beast options is not use it, it's no a required attribute.

Oskar

my actual code:

  $plugins['beanform'] = array(
'name' => 'beanform',
'label' => t('Bean form'),
'description' => t('Choose a form to print into a bean'),
'handler' => array(
  'class' => 'BeanForm',
  'parent' => 'bean',
  'path' => $plugin_path,
  'file' => 'Beanorm.inc',
),
//   'path' => $plugin_path,
//   'file' => 'BeanForm.inc',
   'editable' => TRUE,
  );


How to check if a basic page is published? I'm using Drupal 8.1.10. I have a basic page with the URL alias "/enter-competition". On a twig template (not associated with that page), I have the following HTML:

Enter Competition

I need this link to only be included if that basic page is in a published state, like so:

{% if page_is_published %}
Enter Competition
{% endif %}

How can I check if that basic page is published/unpublished?

If you look in the core theme file core/themes/stable/templates/content/node.html.twig under "Available variables:" you'll find

  node.isPublished() will return whether the node is published or not.

Can also be found here.

Which means you can do:

{% if node.isPublished() %}
  {# content for published nodes #}
{% endif %}

Edit by OP: (17/08/2017)

The above was a partial answer, but I also had the problem that the twig file I needed do this check in wasn't associated with the node I needed to check the published state of. So, using something like menu_get_object wouldn't work.

Since Drupal doesn't seem to have any easy function to get a node by ID/Alias, I created the following function to get a node by URL alias:

public static function getPublishedStateByPageAlias($pageAlias)
{
  $nodeIsPublished = false;

  // Get node path from alias
  $path = \Drupal::service('path.alias_manager')->getPathByAlias($pageAlias);

  // If there is a valid path
  if(preg_match('/node\/(\d+)/', $path, $matches)) {
    // Get the node from the path
    $node = \Drupal\node\Entity\Node::load($matches[1]);
    // Start an entity manager
    $node_storage = \Drupal::entityManager()->getStorage('node');
    // Get the relevant node by its ID using the entity manager
    $chosenNode = $node_storage->load($node->id());

    // Is it published?
    $nodeIsPublished = $chosenNode->isPublished();
  }

  return $nodeIsPublished;
}

I could then call this function in my site's custom module, pass the result to the relevant twig file as a boolean variable, and conduct the necessary check.


Views Row Style - Fields vs. Teaser? What is better for performance in views, using fields or a teaser view?  Assuming you would be adding all fields necessary for it to look just like the teaser.

The fields option is generally faster, because it performs only 1 database query (2 if there's a pager in use).  The teaser display requires a node_load(), which causes numerous hooks to fire and many more queries.


How to render data from external API With my current module I have a simple form where a user inputs some information, that information is then sent to an external API, and that API sends some data back.

How do I display the data that is returned from the external API?

Thanks

<?php
/**
 * Implements hook_menu();
 */
function find_rep_menu(){
    $items = array();
    $items['find-representatives/%'] = array(
        'title' => 'My Form',
        'page callback' => 'find_representative_value_callback',
        'page arguments' => array(2),
        'access callback' => TRUE,
    );
    return $items;
}

/**
 * My form
 */
function find_rep_form($form, &$form_state) {
    $form['address'] = array(
        '#type' => 'textfield',
        '#title' => t('Your Address'),
        '#size' => 60,
        '#maxlength' => 128,
        '#required' => TRUE,
    );
    $form['submit'] = array(
        '#type' => 'submit',
        '#value' => t('Find Rep'),
    );
    return $form;
}

/**
 * Submit handler for the find_rep_form.
 */
function find_rep_form_submit($form, &$form_state) {
    $address = $form_state['values']['address'];
    fetchGeocode($address);
    $fetchGeocode = fetchGeocode($address);
    fetchStateInfo($fetchGeocode['returnedLat'], $fetchGeocode['returnedLong']);
    $form_state['redirect'] = 'find-representatives/' . $form_state['values']['address'];
}

function find_representative_value_callback($address) {
    return t('Value: @value', array('@value' => $address));
    //Once I was able to get this working, I was going to push my returned data through here
}
    /*
     * The fetch code
     */
    function fetchGeocode($userAddress) {
        $userAddress = urlencode($userAddress);
        $fetchUrl = "https://api.mapbox.com/geocoding/v5/mapbox.places/" . $userAddress . ".json?country=us&proximity=38.8977%2C%2077.0365&types=address&autocomplete=true&access_token=APIKEY";
        $result = drupal_http_request($fetchUrl);
        if (in_array($result->code, array(200, 304))) {
            $geoResponse = json_decode($result->data);
            $long = $geoResponse->features[0]->geometry->coordinates[0];
            $lat = $geoResponse->features[0]->geometry->coordinates[1];
            return array('returnedLat' => $lat, 'returnedLong' => $long);
        } else {
            drupal_set_message("Geocode returned: " . $result->code); //For testing purposes
        }
    }

    function fetchStateInfo($userLat, $userLong) {
        $userLat = urlencode($userLat);
        $userLong = urlencode($userLong);
        $fetchUrl = 'http://openstates.org/api/v1//legislators/geo/?lat=' . $userLat . '&long=' . $userLong . '&apikey=APIKEY';
        $result = drupal_http_request($fetchUrl);
        if (in_array($result->code, array(200, 304))) {
            $stateInfo = json_decode($result->data, true);
            drupal_set_message($stateInfo[0]['full_name']);
        } else {
            drupal_set_message("State API Returned Error: " . $result->code);
        }
    }

I was taking some examples from example two on this comment here

If you don't need to save the data returned by the external source in your drupal database, then you can go through below mentioned points,

In hook_form_form_id_alter declare a custom submit function

$form['#submit'][] = "my_module_form_submit_handler";
in the custom submit function redirect after submission.(are you using cURL to send and receive data to and from external api.)

$value1 = 'value returned from external api';
$value2 = 'value returned from external api';
$form_state['redirect'] = 'myurl/' . $value1.'/'.$value2 ;

Create a menu item with hook_menu and pass the values as argument

$menu['myurl/%/%'] = array
(
  'title' => 'some title',
  'page callback' => 'my_page_callback',
  'page arguments' => array(1, 2), // 1 and 2 are the first and second indexes of the URL - the location of the wildcards
  'access callback' => TRUE,
);
in page callback function pass the variables

function my_page_callback($val1,$val2)
{
return theme('custom_data_page', array('val1' => $val1,'val2' => $val2));

}
implement hook_theme

function mymodule_theme($existing, $type, $theme, $path) {
    return array(
        'custom_data_page' => array(
            'variables' => array(
                'val1' => val1,
                'val2' => val2
            ),
            'template' => 'your_template_filename', // do not include .tpl.php
            'path' => 'path-to-your-template-file'
        )
    );
}

Create the template file in templates folder
Clear cache.
Let me know if you face any issues


Creating a contextual filter for a view based on month and day I've created a content type that represents a past events. I've added an extra date-field to this content type that indicates the date of the event.
I'm trying to create a calendar that groups events by day and month, but ignores the year in which the event happens.

e.g. when going to site.com/calendar/[month]/[day], I'd like to get a list of all events that happened on the given day of the given day, irrespective of the year in which they happened.

This seems impossible with the default tools, as they always expect a year to filter on. How can I customize these filters?

You will find the Date module useful for this. Date contains a number of sub-modules, including Date Views. Enable the Date Views module (and its required modules) and you will have what you need in Views.

Here's a link to the module:

http://drupal.org/project/date


How can I print render just location city in teaser view Drupal 7

I am attempting to print just the city value within the location array.

I have created a content type with location and created a custom node template node--content.tpl.php. Inside of my if ($teaser) statement I have the following code:

hide($content['field_event_location']);
print render($content)

Which effectively hides the full field_event_location and renders all other content listed in the display settings of drupal 7 admin. I am attempting to render the city field with the following line:

print render($content['field_event_location']['und'][0]['city'])

I used

print_r($content);echo

to print the array with the following results:

[field_event_location] => Array
    (
        [und] => Array
            (
                [0] => Array
                    (
                        [lid] => 167
                        [street] => 4501 Main Street
                        [additional] =>
                        [city] => Kansas City
                        [province] =>
                        [postal_code] => 64130
                        [country] => us
                        [source] => 3
                        [is_primary] => 0
                        [province_name] =>
                        [country_name] => United States
                        [email] =>
                        [phone] =>
                    )

            )

    )

I did some basic de-bugging I found from this post (How to print render Location's sub-fields?), and was able to print render($content['body']) as well as get the full location output from print render($content['field_event_location'])

The dirty way is : don't user "render".

Just print it:

print $content['field_event_location']['und'][0]['city'];


How do I add the login form in page.html.twig? I am using a subtheme from the Neato theme (in Drupal 8) and I am customizing page.html.twig.

Yesterday I performed a logout, and now I want to log in again, but the login form has disappeared.

How do I add the login form in page.html.twig? Do I need another html.twig file?

I think your best bet is to go directly to the path '/user' where the login form will be the main contents of the page.


max number of content types on drupal i have been handled a drupal site to work on, the problem is its very messy, they were building every single detail as a content type (using CCK), that produce around 150 content type and 560 database table ( now you can imagine the mess), and i want some document to convince my team leader that this is a bad approach to follow

if any one could help

560 tables isn't that much (D7 produces a lot more because of one field => 2 tables) but 150 content types is a lot, that's for sure. This will result in huge caches that Drupal needs to carry around all the time.

I assume that site uses content types to store any kind of data, including internal stuff that isn't displayed?

Using content types for anything that is displayed on the website usually makes sense, you also get a lot of integration for free (e.g. views). However, having a huge amount of content types, doesn't scale well as you found out so you might want to go through your content types and convert some of them to custom tables.

In Drupal 7, it is common to define entities for custom data structures, especially things that are not content (see drupal commerce, search api and so on for examples).

There, is, however, no official or technical limit of content types that you can have. I'd recommend using xhprof to profile the site, if you can e.g. show that the site is using a huge amount of memory because of that, that might be a good argument.


How do I deal with serialization unsetting object members? Let's say I have a plugin that uses an injected service to get some object. The object is expensive but can't be serialized, so I can only store it as long as my plugin instance lives.

To keep it away from DependencySerializationTrait, I declare it private.

class MyPlugin extends SomePluginBase implements ContainerFactoryPluginInterface {

  /**
   * @var \Drupal\module\ServiceInterface
   */
  protected $service;

  /**
   * @var \Drupal\module\SomeUnserializableThing
   */
  private $data;

  /**
   * Constructor
   *
   * @param \Drupal\module\ServiceInterface $service
   */
  public __construct(ServiceInterface $service) {
    $this->service = $service;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container) {
    return new static($container->get('my_module.service'));
  }

  /**
   * {@inheritdoc}
   */
  public getData() {
    if (!$this->data) {
      $this->data = $this->service->loadData();
    }
    return $this->data;
  }

}

Unfortunately, after serializing and unserializing the instance doesn't have any reference to the member - not even NULL. What happens in ::getData is that the !$this->data check causes an E_NOTICE error even though that variable is explicitly defined in the class.

Are we back to the dark age of isset() and empty() here, or do I need to implement __wakeup() for all my classes to explicitly initialize their private members to NULL? Both seem unpalatable...

__sleep() works by returning properties that need to be serialized. A private property is invisible, won't show up in $vars and therefore is also not serialized and just silently dropped.

Either don't use private (it only serialized services, I assume data is not a service), or override __sleep(), call the parent and then add data to the list of properties to be serialized.


Fatal error - Media module I keep getting the following error for some reason:

  Fatal error: Cannot redeclare media_views_invalidate_cache() (previously declared in /var/www/html/sitename/sites/all/modules/media/media.views.inc:140) in /var/www/html/sitename/profiles/dkan/modules/contrib/media/media.views.inc on line 140

Is there any reason I'm getting the error?

I'm using Drupal 7.54.

Looks like you have media installed twice. Once as part of your installation profile (or distribution) and once as a 'loose' module. Which I suppose occurred because there was a security update and you did not want to wait for the distribution to update.

Make a backup and remove /sites/all/modules/media. That should solve it.


How to use Hierarchial Select Module for select field's of webform module? Answer is to use Hierarchial select module for dynamic options list based on the previous select box value

How do I use Hierarchial select module in my webform module for select fields?

Seems like webform doesn't support Hierarchical Select module...

You can use Webform Conditional module to create dependent fields...

Project page says

  This modules enhances the existing Conditional Rules of the Webform
  Module. It adds the ability to make components dependent on select
  components(i.e. listboxes, radio buttons, and checkboxes) that appear
  on the same page.


Show warning for viewing only some nodes I am developing one website where I have one content type (News). Now, some of news content type nodes is adult and must to have age confirmation popup (just warning text, accept and decline button).

Any suggestion how to do that?

If you have registered users, you might do it with a role. This would have the benefit of not having to show this more than once.

Other than that, (this is just an idea, I haven't tried it), you could write a small module which implements hook_node_access() .

What you could do in this function is:

allow the user to view the node if there's an adult=true GET variable
disallow the user to view the node if there's an adult=false GET variable
redirect the user to your own YES/NO form when there's no adult variable in GET, appending your current path as a destination GET path, which is then used as the action target for the form, which itself uses the GET method and has an options box with the name of adult

I have no idea how easy it actually is to pull this off, but it seems quite reasonable.

Tell me whether you've done it and if it worked well, that'd be interesting.

EDIT: References you should read to accomplish this task, as you mentioned you are totally new to this.

Learn the basics about creating a new D7 module
Learn what hooks are
Learn how to create a new page with a path with the hook_menu() hook
In the callback function for hook_menu() provide the yes/no-form: Learn about the Drupal form API . Maybe get started with this tutorial on forms and complete it with the given API link.
Learn about hook_node_access() here and what to return. In this function, do what I mentioned in the list above and complete your functions.

I hope I could help you in any way, and trust me I know how hard it is to get started.


How to automatically capture images from URLs? My site is a bookmarking site where people share URLs.

First, if the page being submitted has Facebook open graph image information, Drupal should transfer that image to local files and display it (similar to sharing links on Facebook).

Otherwise, display a thumbnail preview of the page.

Thanks for help in advance.

Check out Opengraph filter module

  When you post a link on facebook, you get a little summary of that
  site under your comment or post (with or without thumbnail). This
  works with OpenGraph metatags. Basicly Facebook scrapes the content of
  the url and makes a nice little summary.


Add panelizer display when create a node programmatically I create a node programmatically on hook_enable of mu custom module. I have panelizer display for this content type and I want to set when create a node programmatically. Can you help me ?

Here is some example code for creating a node and setting the panelizer variant/display automatically.
Note: The EntityMetadataWrapper module is used for setting the title.

  $entity_type = 'node';
  $bundle = 'page';
  $variant = 'YOUR_VARIANT_NAME';
  $variant_name = $entity_type . ":" . $bundle . ":" . $variant;

  $values = array(
    'type' => $bundle,
    'uid' => 0,
    'status' => 1,
    'comment' => 0,
    'promote' => 0,
  );

  $entity = entity_create($entity_type, $values);

  ctools_include('export');

  $panelizer = ctools_export_load_object('panelizer_defaults', 'names', array($variant_name));
  $entity->panelizer['page_manager'] = $panelizer[$variant_name];

  $wrapper = entity_metadata_wrapper('node', $entity);
  $wrapper->title->set('Your Title');

  $wrapper->save();


How can I display the field in the tab that was active on save? I'm using Drupal 8 paragraphs. I have a banner_header paragraph that contains three fields,

field_active_callout_tab (boolean)

field_banner_header_single (entity reference revision: paragraph)

field_banner_header_multi (entity reference revision: paragraph)

two of which are displayed in tabs like so:

Here is how the banner_header paragraph shows up on the content type edit form:

When I save the content, I want the page to render with the paragraph from the tab that was active on save.

What I've done so far:

I added classes to the tabs which you can see in the image of the form display: .single-link and .multi-link.  I was told that I also needed to create a boolean field to manage the display behavior, which I did with field_active_callout_tab. The way that was suggested this to work is, the bool will change depending on which tab is selected, and then I can use the bool value to determine which field is to be displayed in the twig template. The default class for this boolean seems to be '.option'.

I created a custom js file to check the status of the tab:

(function($, Drupal) {

/* Add span to wysiwyg button classes for alignment
------------------------------------ */
Drupal.behaviors.calloutControl = {
      attach: function (context, settings) {
            $('.single-link').click(function () {
                  $('.option').prop('checked', true);
            });
            $('.multi-link').click(function () {
                  $('.option').prop('checked', false);
            });
      }
};

})(jQuery, Drupal);

And here is the banner_header template:

<div class="callout-options">
     {% if content.option == true %}
          {{ content.field_banner_header_single }}
     {% else %}
          {{ content.field_banner_header_multi }}
     {% endif %}
</div>

The bool does not change depending on the tab selection. It appears to not be impacted at all. The page will only render with the multi link paragraph, despite single link setting tab being open on save.

Is the bool necessary? If so, what am I missing?
If the bool is not necessary, what should I do next?

How can I get the paragraph field in the tab that was active on save, to render on the page?

I think it is being called multiple times. To avoid that try Change your JS as below

$(context).find('.single-link').click(function () {
  $(context).find('.option').prop('checked', true);
});
$(context).find('.multi-link').click(function () {
  $(context).find('.option').prop('checked', false);
});

OR

change the on click() event to hasClass() the will be classes added to the active tab


Workflow, Workflows, Workspace, and State Machine-- what is the difference? Drupal 8 core has an experimental module called Workflows.

There is also a contrib moduled called Workflow.

There's also the Workspace module, which is associated with the Deploy module.

Commerce 2 uses State Machine, another module that provides workflow management in Drupal 8.

What are the differences between these four modules?

Is one more future-proof than the others?  Normally, I would assume the module in core has the brightest future, but in this case Commerce picked a different module (perhaps because the core module wasn't ready?).  And in D7, Workflow has a large following.

There are also content moderation module which aims to define content states.
From my understanding, core Workflows is API and UI to utilize the moderation states and transition. I am not sure if core Workflows could work with states machine, but logically it should.

Core Workflows and contributed core Workflow must be similar in their general goal, but provides different widgets, and architecture.

It is very interesting question and I would be happy to hear some clarification.


Multiple billings for one user in one day for Monthly Recurring (Drupal commerce) Our Monthly Recurring Billing has been working successfully for more than 1 year. However, there are two customers are charged multiple times on February 28, 2018, once an hour.  Other 3 customers (monthly recurring) are charged correctly on the same day.

The cron "commerce_recurring_cron" runs every hour, and created a new order of recurring billing for the same user.

ORDER NUMBER    UPDATED NAME    USER    TOTAL   ORDER STATUS
8181    February 28, 2018 - 6:43pm  J* C*   j*  $4.99   Completed
8182    February 28, 2018 - 7:09pm  J* C*   j*  $4.99   Completed
8184    February 28, 2018 - 8:09pm  J* C*   j*  $4.99   Completed
8186    February 28, 2018 - 9:11pm  J* C*   j*  $4.99   Completed
8188    February 28, 2018 - 10:11pm J* C*   j*  $4.99   Completed
8190    February 28, 2018 - 11:00pm J* C*   j*  $4.99   Completed
8192    March 1, 2018 - 12:00am J* C*   j*  $4.99   Completed
8183    February 28, 2018 - 8:09pm  L* L*   l*  $4.99   Completed
8185    February 28, 2018 - 9:11pm  L* L*   l*  $4.99   Completed
8187    February 28, 2018 - 10:11pm L* L*   l*  $4.99   Completed
8189    February 28, 2018 - 11:00pm L* L*   l*  $4.99   Completed
8191    March 1, 2018 - 12:00am L* L*   l*  $4.99   Completed

All above payments of orders are charge successfully in Authorize.net.

System: Drupal 7.56; Authorize.net Gate Way.
Related modules: commerce 7.x-1.13, commerce_recurring 7.x-2.x-dev, commerce_order 7.x-1.11, commerce_payment 7.x-1.11, commerce_authnet 7.x-1.4, commerce_cardonfile 7.x-2.0-beta5+3-dev.

I have spent days on doing research,  and debugging the Drupal log and system log.  But I can't find any useful info.
I cannot repeat the problem on our DEV site.

I will deeply appreciate it if someone knows some clues about it by chance.

Thank you very much!

There is a fixed issue with Commerce Authorize.Net, discussed on https://www.drupal.org/project/commerce_authnet/issues/2161989.

If your setup already incorporates that fix, then most probably it is hitting the issue Duplicate queue items should not be created. Apply the patch in #6 and you should be fine.


How to change the format that shows the autocompletion of reference entities? I am trying to change the format that it shows by default in the text fields that have an associated reference entity.

I found an article where a format modification is made, I think it may be a good starting point, but this module changes the format of all the fields of the whole site, what I am trying to do is that I can define the format by type of content, that is, for Articles, it would have one format and another type of content, depending on what is most convenient.

For example, in the module mentioned, it changes the behavior of the autocomplete globally, is there a way to do it by type of content?

<?php
namespace Drupal\alter_entity_autocomplete\Routing;

use Drupal\Core\Routing\RouteSubscriberBase;

use Symfony\Component\Routing\RouteCollection;

class AutocompleteRouteSubscriber extends RouteSubscriberBase {
  public function alterRoutes(RouteCollection $collection) {
    if ($route = $collection->get('system.entity_autocomplete')) {
      $route->setDefault('_controller', '\Drupal\alter_entity_autocomplete\Controller\EntityAutocompleteController::handleAutocomplete');
    }
  }
}

Is there any way to do it?

The github project of the module

You can filter for the entity type & bundle in the getMatches() method.

It is also possible to add specific handlers to your forms: https://www.qed42.com/blog/autocomplete-drupal-8


Dashboard - empty blocks are shown I had a some blocks on the dashboard page.
Then I created a new role with fewer permissions and wanted to show only a couple of them on the dashboard.
I edited all blocks and restricted the access by role.

Now all the blocks with restricted content are still visible in the dashboard but they all have the "(empty)" text on it.

How can I get rid of these blocks completely ?

There is a bug in dashboard.module.

Quick and silly solution: disable, uninstall, enable and reconfigure again the Dashboard module. Remember: You will lose all dashboard settings you made :)


Creating a view by comparing two fields of two different content types using the same taxonomy I'm trying to create a view to desplay contents based on shared taxonomy terms.

More concretely, I have two content types:

Offers (with field "Category")
Needs (with field "Category")

This contents share the same vocabulary "Category". Indeed, the "Category" fields of the content types "Offers" and "Needs" are refered to the same vacabulary (taxonomy) with terms:

electronic
chemistry
mathematics
science

Each user can define their offers and needs through 2 differents forms.

To put it simply, let's take the case of 3 users who created their offers and needs using this forms. Here is a table of a concrete example:

==> Case 1: current user (logged in user) = user 1

Imagine that I am user 1 (current user). The view page will have to desplay to me a list of the contents "Needs" of other users (user 2, user 3) and that have the peculiarity of having a "Category" field equivalent to the "Category" field of my contents "Offers".

In other words:

1) My content "Offers" are "Offer 1" and "Offer 2" with fields category ("electronic","science")

2) The contents "Needs" of other users are "Need 2", "Need 3","Need 4","Need 5" and "Need 6"

3) Comparing fields category between my contents "Offers" and contents "Needs" of other users:

Field Category of "Need 2" = chemistry. The value of this field is different from the values ("electronic","science"), that are the values category of my offers ==> The view will not display the content "Need 2"
Field Category of "Need 3" = electronic. The value of this field is equivalent to the value category of my Offer 1 ==> The view will display the content "Need 3"
Field Category of "Need 4" = mathematics. The value of this field is different from the values ("electronic","science"), that are the values category of my offers ==> The view will not display the content "Need 4"
Field Category of "Need 5" = science. The value of this field is equivalent to the value category of my Offer 2 ==> The view will display the content "Need 5"
Field Category of "Need 6" = electronic. The value of this field is equivalent to the value category of my Offer 1 ==> The view will display the content "Need 6"

4) It means that the view page should display this list of Needs:

Need 3 (electronic)
Need 5 (science)
Need 6 (electronic)

In other words, Offer 1 and Offer 2 (that are my Offers) match with Need 3, Need 5 and Need 6 (that are needs of the other users covered by my Offers). And this because they have the same categories "electronic" and "science"

==> Case 2: current user = user 2

Using the same logic, if the current user is user 2, the view page is going to desplay this list of Needs:

Need 5

==> Case 3: current user = user 3

And for the user 3, this list of Needs:

Need 1
Need 2
Need 4

Question : How can I create this view with view UI ? Any other suggestion is welcome.

This types of matching (list Taxonomy siblings) is usually done through Has Taxonomy term ID Contextual filter, but your case is a bit more indirect.

You're not showing related content on other node pages. You want to list some content on User pages, but the matching is not done between the listed content and the user (because you don't have Taxonomy on users), it is one step more removed, you're matching content through the user "bridge" to other content.

You need to go "the entity reference" way to achieve all the necessary matching and contextual filtering.

First we list the user Offer nodes because they give context, they tell us which categories to look for. Once we have that we pull into Views Needs nodes that share the same category field values as those offers, and we additionally filter out that user Needs, in case they have any, because they're only interested in seeing other people's matching Needs.

Create Page Display Views listing Offers! (filter Content type)
Change Path to user/%user/related-needs
Add Menu Tab (it will show on user profiles)
Add Relationship Taxonomy term referenced from field_category from the Content Category, you can require it since they will all have it filled in
Add a new Relationship Content using field_category from the Taxonomy term Category.

This Relationship automatically uses the first Relationship. This is where the matching is done from all Offers nodes category back to all the nodes on the system using that same category.

You have the Title field showing Offer nodes at this point. You can keep it this way just to test, but that field isn't our target since we want to see the list of Needs related to the Offers. Or if you don't need it: modify it according to the following step:
Add another Title Field and make it use the second Relationship (it will be the only one available). This will show the nodes that share the same category taxonomy as the Offer node in that same views row.

From now on, for every field you add, if you're not using a Relationship it will show Offer node data, and if you use the second Relationship it will show the data from nodes that share the same category as the Offer node from that row. This includes the Needs node we are after.
Add Contextual filter Authored by from the Content Category and configure it:
Do not use a relationship
When the filter value is NOT available
Provide default value
User ID from route context
When the filter value IS available or a default is provided
Override title
Needs matching user {{ arguments.uid }} Offerings (check your argument token under Replacement patterns)
Specify validation criteria
User ID

This Contextual filters out Offer nodes authored by the user whose profile is being viewed.
Add another Contextual filter Authored by from the Content Category and configure it:
Relationship field_category (the second one)
When the filter value is NOT available
Provide default value
Raw value from URL
2
When the filter value IS available or a default is provided
Specify validation criteria
User ID
More
Exclude

This Contextual filter excludes Needs nodes authored by the currently viewed user since it doesn't make sense to show these. This step isn't necessary if your users will never have Needs nodes that share the same category with their Offer nodes.
Since you'll probably have duplicates in your results you can sort it out by turning Aggregation on. If you have Needs fields other than Title you may need to change their Aggregation settings from Entity ID to Target_id.

Make sure you have all Sort Criteria removed since it interferes with Aggregation.

Visit the user profile page and find the tab, and check that the results are as you'd expect. It seems like a complicated procedure but it makes sense once you understand what is happening in each step.


Conditional state integer number Using Drupal 8 and the new webform module "8.x-5.0-beta19".

Like it a lot! Many options now to control the webforms.

Problem:
I have one input field 'NUMBER'.
When the web visitor enters a number greater than 0... the other input field should appear.
So on the second input field, I do a conditional statement.

Make visible when Value is not ---> 0

Seems to be this options only accepts integers greater than 0, but not 0.
See image... When saving the 0 disappear and 2 he accepts and does save it....

Is this a bug... does somebody has a solution?

Thanks for reading.

This is issue has been fixed. @see https://www.drupal.org/node/2916409


Multisite config directories of subsides I set up a local Drupal 8 multisite, using Acquia dev desktop. It's working fine. I added all Drupal 8 core files to my local repository and pushed them to a central remote repository.

in sites/default/settings.php I added
$config_directories['staging'] = 'sites/default/config/staging';to
make the configuration directory versionable.
All sites (main site, subside1 and subside2) has different databases

But what about the sites/subside1/ and sites/subside2/ config files? Do I have to add also a different path for those files? Do those have to be versioned or not?

I want to clone my repo to make instances of this multisite for staging and live environments.

It's a little bit up to you how you manage your config. In my multisites I have a ../config directory outside the web root. Each site instance then has it's own folder in there. And inside each one I split the config per environment.

shared/ holds the config that is similar on all environments. local/ holds all the extra config for local development. And live/ holds the extra config for the live site. This can be achieved using the Config Split module.

project/
├── config/
│   ├── bar/
│   │   ├── live/
│   │   ├── local/
│   │   └── shared/
│   └── foo/
│       ├── live/
│       ├── local/
│       └── shared/
└── web/
    └── sites/
        ├── bar/
        └── foo/

The settings.php config for the foo/ instance then looks like this:

$config_directories['sync'] = '../config/foo/shared';

And the Git-ignored settings.local.php on my local machine looks like this:

$config['config_split.config_split.local']['status'] = TRUE;
$config['config_split.config_split.live']['status'] = FALSE;

Whereas on the live server it looks like this:

$config['config_split.config_split.local']['status'] = FALSE;
$config['config_split.config_split.live']['status'] = TRUE;


How do I translate view's page path alias that has a dynamic path? I have a view that has a dynamic path and I want to create a path alias for each language installed on my site. Following the answer on How do I translate view's page path alias? I'm able to create a path alias when no dynamic path is involved in the view, but when a contextual filter with dynamic path is in the view I can't find how to create the path alias.

The view is a simple view like this:

So, how do I translate view's page path alias that has a dynamic path like /jobs/% ?

Views pages generate routes including route parameters for contextual filters. So you could add for each language a duplicate page, set a language specific path and inherit all other properties from the master display.

But as the routing system is not language specific this has some shortcomings. You get multiple language prefix/route path combination, which is not good for SEO and makes it difficult to build outgoing links.

Language specific path handling is outside of the routing system. The standard tool for this is path aliasing, so you would need to set for each dynamic value and language combination an alias in the lookup table. Don't know if you can generate them with Pathauto, but I wouldn't recommend it anyway in this case, because the path has a clear pattern you can easily transform in a custom path processor to match the internal view's page display route.


How do I correctly cache a themed menu output? In mytheme_preprocess_menu(), I am altering the main menu:

function mytheme_preprocess_menu(&$variables, $hook) {
  $node = \Drupal::routeMatch()->getParameter('node');
  if ('menu__main' == $hook) {
    if ($node) {
      _mytheme_menu_replace_with_project_items($node, $variables['items']);
    }
  }
}

In _mytheme_menu_replace_with_project_items(), I check whether the current node is a project node, and show that node's submenu instead.

When I visit the node the menu gets displayed, but when I add another node with another project reference, the menu of the former node gets displayed.

How can I correctly cache that?

I tried with the following code, but it didn't work.

$variables['#cache']['tags'][] = 'node:' . $node->id();
$variables['#cache']['contexts'][] = 'route.name';
$variables['#cache']['contexts'][] = 'theme';

Okay, so this combination worked...

$variables['#cache']['tags'] = ['node:' . $node->id()];
$variables['#cache']['contexts'] = ['route', 'theme'];
$variables['#cache']['keys'] = ['entity_view', 'node', $node->id()];

I dont see a huge difference to my first attempt but whatever!


Show datetime value in views with entity api I made a custom entity with a date field stored as datetime in mysql.

I see the proper output in my content, and all other field values in my views except the datetme value. Only the label is shown. So I believed that I have to write a getter callback because of this:

  getter callback: (optional) A callback used to retrieve the value of the property. Defaults to entity_property_verbatim_get(). It is important that your data is represented, as documented for your data type, e.g. a date has to be a timestamp. Thus if necessary, the getter callback has to do the necessary conversion. In case of an empty or not set value, the callback has to return NULL.

Question is how to use it? Apparantly I have to get a timestamp from a datetime field!???

Another one mentioned that views doesn't relate to property_info():

  Getter and Setter callbacks are used only by entity metadata wrappers, not Views.

So my code looks like this atm:

$info['pricedefault']['properties']['preis_zeitraum_von'] = array(
'label' => t('Start period'),
'description' => t('Preis Zeitraum von'),
'type' => 'date',
'schema field' => 'preis_zeitraum_von',
);

So it makes no sense to add a getter callback??? Or do I have to make my own views entity controller class?

ATM I'm very confused. Can anybody explain how to proceed?

THX in advance

maen

You won't need to define a custom getter callback for known data types with a schema field since it can use entity_property_verbatim_get as it's getter callback, which is used by default if no 'getter callback' property is set.

$properties = &$info['foo']['properties'];
$properties['created'] = array(
  'label' => t('Date created'),
  'description' => t('The date the foo entity was created.'),
  'type' => 'date',
  'schema field' => 'created',
);

For maximum control, I would suggest you try describing your entity to views. Assuming you have an entity type called foo, stored in the table foo with a created field, you can:

/**
 * Implements hook_views_data()
 */
function foo_views_data() {
  $data = array();

  $data['foo']['table']['group']  = t('Foo entity');

  $data['foo']['table']['base'] = array(
    'field' => 'foo_id',
    'title' => t('Foo entity'),
    'help' => t('The foo entity.'),
  );
  $data['foo']['table']['entity type'] = 'foo';

  // Expose a timestamp (e.g. created date).
  $data['foo']['created'] = array(
    'title' => t('Created'),
    'help' => t('The date the foo was created.'),
    'field' => array(
      'handler' => 'views_handler_field_date',
      'click sortable' => TRUE,
    ),
    'sort' => array(
      'handler' => 'views_handler_sort_date',
    ),
    'filter' => array(
      'handler' => 'views_handler_filter_date',
    ),
  );
}

Then, you can also do things like:

// An argument handler accepting year and month
$data['created']['created_year_month'] = array(
  'title' => t('Created year + month'),
  'help' => t('In the form of YYYYMM.'),
  'argument' => array(
    'field' => 'created',
    'handler' => 'views_handler_argument_node_created_year_month',
  ),
);

For more info on integrating with views, you can install Advanced help module, and check out the included Views documentation.


Override permissions per user I have the following problem and I am currently looking for the best approach to solve it:

I have a site with various entities. These entities all have their own permissions to view, edit, delete and so on.
Now I don't want to restrict the access to an entity per entity type but per entity element, with every user probably having access to different entity elements.

This means that I will need a very granular way to change permissions.

Thats why I would suggest to add a few basic roles to which you can assign your users.
On top of these roles you are able to overwrite the permissions per user per entity element. This would probably happen in a seperate tab in the profile of a user.

If you have any idea on how to do so or you have another approach on my problem I would welcome your response.

Thanks in advance.

I think you can use Access Control Lists. It does not have a UI on its own but your can use probably content access to give you the ACL functionality.

NOTE: After installing and configuring the ACL is not part of the user profile but part of the node (as you have suggested in your question)


Entity creation-form: Prepopulate all existing entity-references of a field collection I have a content-type seasonal_prices with field-collection containing an entity reference field (referencing content-type room) and a number field; the field-collection is multi-value with unlimited cardinality.

When adding new content of type seasonal_prices, I want the form to be pre-populated with an instance of the field-collection for every existing content of type room.

An example: If there are 5 nodes of type room, the create-form of seasonal_prices should show me 5 instances of the field-collection, where each reference-field is pre-populated with its reference to room, so all I have to do is fill out the number-field.

UPDATE:
Here is the code i finally used in a custom module, hope this is helpful:

<?php

function seasonal_prices_form_field_ui_field_edit_form_alter(&$form, &$form_state, $form_id) {
  // Increase the max cardinality to 20
  $range = drupal_map_assoc(range(1, count(get_roomtype_ids())));
  $new_options =  array(FIELD_CARDINALITY_UNLIMITED => t('Unlimited')) + $range;
  $form['field']['cardinality']['#options'] = $new_options;
}

function seasonal_prices_form_alter(&$form, $form_state, $form_id) {
  // update cardinality in field settings
  $field_name = 'field_prices_and_roomtype';
  $field = field_info_field($field_name);
  $field['cardinality'] = count(get_roomtype_ids());
  // field_update_field() throws an exception on failure
  try {
    field_update_field($field);
  }
  catch (Exception $e) {
    drupal_set_message(t('Could not update cardinality of field.'), 'error');
  }
  // generate fieldcollection instances
  if($form_id == 'seasonal_prices_node_form') {
    $items_count = count(get_roomtype_ids());
    $form_theme = $form[$field_name][LANGUAGE_NONE]['#theme'];
    // remove delete and add more buttons
    $form[$field_name][LANGUAGE_NONE][0]['remove_button']['#access'] = FALSE;
    $form[$field_name][LANGUAGE_NONE]['add_more']['#access'] = FALSE;
    $items = &$form_state['field'][$field_name][LANGUAGE_NONE];
    // generate required number of fields collection
    if ($items_count > 1 and $items['items_count'] != $items_count) {
      $items['items_count'] = $items_count;
      $items['field']['cardinality'] = $items_count;
      $form[$field_name][LANGUAGE_NONE] = field_multiple_value_form($items['field'], $items['instance'], LANGUAGE_NONE, array(), $form, $form_state);
      // reset theme function, as field_multiple_value_form hijacks it
      $form[$field_name][LANGUAGE_NONE]['#theme'] = $form_theme;
    }
    // fill generated instances with default values and disable access
    for ($delta = 0; $delta < ($items_count); $delta++) {
      $form['field_prices_and_roomtype'][LANGUAGE_NONE][$delta]['field_ref_roomtype'][LANGUAGE_NONE]['#default_value'] = get_roomtype_ids()[$delta];
      $form['field_prices_and_roomtype'][LANGUAGE_NONE][$delta]['field_ref_roomtype']['#access'] = FALSE;
      // designate Fieldcollection Items correctly
      $form['field_prices_and_roomtype'][LANGUAGE_NONE][$delta]['#prefix'] = '
' . get_node_title(get_roomtype_ids()[$delta]) . '';
      $form['field_prices_and_roomtype'][LANGUAGE_NONE][$delta]['#suffix'] = '
';
    }

  }
}

// Helper function to get the node title without loading the whole node object.
function get_node_title($nid) {
return db_query('SELECT title FROM {node} WHERE nid = :nid', array(':nid' => $nid))->fetchField();
}

// Helper function
function get_roomtype_ids() {
    $query = new EntityFieldQuery();
    $query
    ->entityCondition('entity_type', 'node')
    ->entityCondition('bundle', 'roomtype')
    ->propertyCondition('status', 1)
    ->propertyOrderBy('created', 'ASC');
    $result = $query->execute();
    return array_keys($result['node']);
}

You will need to create a custom module that alters the node creation form before it rendered using hook_form_FORM_ID_alter().

You want to edit the form_state which stores the information on how a form is filled out.

It should look something like this:

<?php

/**
 * Module to prepopulate season price list with rooms
 */

/**
 * Implements hook_form_FORM_ID_alter(&$form, &$form_state)
 */

function mymodule_form_seasonal_prices_node_form_alter(&$form, &$form_state){

    // Load all of the room node ids into an array
    $node_type = "room";
    $result = db_query("SELECT nid FROM node WHERE type = '%s' ", $node_type);
    $nids = array();
  while ($obj = db_fetch_object($result)) {
    $nids[] = $obj->nid;
  }

  // Set the form state to include each room
  foreach($nids as $nid){
    $form_state->field_collection_you_want_to_edit[] = $nid
  }
}

You will need to do a bit of sleuthing to figure out what to put in the last line as it is specific to your build, and I don't know whether you need to set it to the $nid or node_load($nid) or something else.  But this should give you a framework to go on with.

If you haven't come across the Devel module yet, install it, and use dpm($form_State); to look at the structure of the variable so that you know what to change.

Finally, make sure you change the name of the function from 'mymodule' to whatever name you have given your module, make sure the machine names for your content types and form ids are correct (I just guessed them), and clear the cache so that Drupal picks up the hook.


Is it possible to use a Display Suite Code Field in Views? I've created a code field in Display Suite to to manage the display of a file (the file entity has a few fields per file).

Is it possible to use this same Display Suite code field in Views when creating a list of nodes for display?  I know I can do the same thing in a php field, but I'd rather not have to manage different code in different places to get to the same end result.

Instead of using Views fields, just use the Content -> Display Suite view modes in the view, that way you can just render the DS view mode with the custom field of the returned nodes in views.


SQL And Drupal skips admin set up I filled out the Database name, Database username, password, and port number within the Drupal set up. I selected continue, then the page loads for a long time. Next, I was leaded to another page saying, Drupal already installed. Next, I clicked on View your existing site, displaying the log in for the admin. Drupal literally skipped the admin set up, resulting in not allowing me to log in as admin. Anyone is familiar with this error? Is this even an error, or the norm for Drupal (since I seen other users experiencing this errors, but no answers)?

Drupal explain the the error is the following

  The website encountered an unexpected error. Please try again later.
  Drupal\Core\Config\UnmetDependenciesException: Configuration objects
  (automated_cron.settings, block.block.bartik_account_menu,
  block.block.bartik_branding, block.block.bartik_breadcrumbs,
  block.block.bartik_content..

If anyone that knows this, feel free to provide some input.

You are asking a lot of questions at the same time, but I assume your main question is How to recover from this failed installation?

You are seeing an UnmetDependenciesException, which means Drupal requires stuff (has a dependency) that has not been loaded... So probably several system modules did not install properly.

That would also explain the behavior you are experiencing, your Drupal installation is broken...

Best would be to start over from scratch, remove all the files and the database tables and try again. Also verify if you have met all of the web server requirements (Drupal 7 & 8).


Solr search api indexing referenced fields by their id not value So i created a basic Solr core and index. In the index i added several diff. content types and added a lot of fields from those CT, including a aggregated field (union of several diff. fields: plain text, entity ref. fields, etc) Now i built a view based on that index (displaying rendered entities), and in the filter added a Fulltext search which will search on the Aggregated field.

For the most part it all works as designed, except that the fields which are entity reference fields (taxonomies) are indexed by their reference id (tid) and not the human readable value. E.g.: if a term (Math) from the vocabulary Subjects is indexed, the value which will be stored by solr is 5 (which is the term id), so when you use the fulltext search field and search Math there will be no results, but if you search 5, the content type where Math is selected will be displayed, not the best UI if you agreee.

Is there any way to search by the human readable values, without me altering the query and then finding the corresponding tid of the value entered in the search and then passing it back to the query, because that kinda defeats the purpose of having a backend search engine.

Thanks,
Will

Just to provide an answer, maybe it'll be useful to someone.
You can't At least not without a lot of hacking/patching the solr api module.


Override image dimensions set by image style I am trying to override the image dimensions set out by image style and can't seem to do that unless I select no image style for the field. I need that image style on another pages but I would like to override it only on the front page. The images the front page are from nodes loaded from simple view configuration. I tried theme_image_style to override the dimensions but it stops images from rendering on other pages. I tried theme_preprocess_node and even though the image['width'] and [height] were changed it still loaded the image style dimension. Would really appreciate some help thank you.

You could alter the width and height properties of your image(s) using CSS, it depends on the (base) theme you use in which file these CSS rules should be entered. However, the image produced by the image style is still used (so, this might not be quite mobile friendly).

Another option is to use the Image Style Selector (ISS) module, which provides an extra field on your node edit page that you can use to select an extra image style (to apply on the image on for instance your front page). When displaying the node on the front page you can hide the original image field and display the ISS field (the result is that your image will be shown using the style selected in the ISS field).


Multiple nodes within a node Does anyone know if there's a module out that would provide the functionality for displaying multiple nodes within a node i.e. similar to how a blog looks with its articles, simply a page that displays a number of teasers that link directly to other nodes.

The big thing would be the CMS part and the ability to add existing nodes within a node. By this I mean like the way you would with a field, except in this case it would be a list of existing nodes.

So far my attempt at such as set-up has been to use the field collections module to put a few fields together like title, image, long text, etc, then use this field collection as part of a basic page. This does exactly what I'm after except all we are doing here is giving the content manager the ability to supply a path to an existing node so there is not relationship here at all.

A content manager could delete the node and forget to delete the teaser on another page that was linking to it.

Please could I stress that 'Node embed' is not an option or anything similar because its just not practical for clients to use such methods. It needs to be very simple that almost requires them not to think.

Any suggestions please?

Sounds like you need to use entity reference module and have it render the teaser view mode.

This field can have unlimited values so you can keep "adding more". This will allow you to specify nodes to embed in another node.

Alternately you can use field collection if you do not require these embedded nodes to be a node on their own.

Furthermore you could even add a view which shows teasers as a block to bottom of the node, however the filters / contextual filters will be more dynamic in nature rather than manually selecting specific nodes. You could argue that node queue would allow you to do this but I would say thats a lengthy way of resolving you question.


How to get constant string array field into db_query? First post here :)

Here's a valid MySQL query: SELECT "'a','b'" AS FieldStrArray;

(To enter as a string in PHP, remember the backslashes before double quotes.)

At least in Drupal 7's db_query(), this produces a fatal PDO exception, complaining that 'a','b' is not a known field.

My question: how do I work around this apparent limitation of db_query()/PDO?

(Yes, I need a constant string array as one of the field results. This is a minimal replication of the problem... :) )

Any suggestions MOST welcome... including a) whether this is also a problem in PHP itself, b) how to report this as a bug to the Appropriate Authorities, c) Any creative ideas for a workaround assuming it is a real bug.

Thanks!

Not sure if this is a bug or not (I've seen weird things with single and double quote in PDO queries before), but either way you can work around it by using single quotes to wrap the expression:

$sql = "SELECT '\'a\',\'b\'' AS FieldStrArray";
$val = db_query($sql)->fetchField();
// $val == "'a','b'"


print.module error - Warning: file_put_contents I am using the print.module and dompdf to convert the PDF files. I am getting the following warning on my pages. How would I go about fixing this?

  Warning:
  file_put_contents(/home/mysite/public_html/sites/all/modules/print/lib/dompdf/lib/fonts/php_Times-Bold.afm): failed to open stream: Permission denied in Cpdf->openFont() (line 2354 of /home/mysite/public_html/sites/all/modules/print/lib/dompdf/lib/class.pdf.php).

  Notice: Constant DOMPDF_TEMP_DIR already defined in require_once() (line 73 of /home/mysite/public_html/sites/all/modules/print/lib/dompdf/dompdf_config.inc.php).

  Notice: Constant DOMPDF_ENABLE_PHP already defined in require_once() (line 185 of /home/mysite/public_html/sites/all/modules/print/lib/dompdf/dompdf_config.inc.php).

  Notice: Constant DOMPDF_ENABLE_REMOTE already defined in require_once() (line 196 of /home/mysite/public_html/sites/all/modules/print/lib/dompdf/dompdf_config.inc.php).

Take a look at the INSTALL.txt file.  You need to give the webserver write access to the dompdf/lib/fonts directory.

In my case, I chowned it to apache:apache.  Make it mirror how you have your sites/default/files directory set up.


Is using Drupal for a frontend and a non-Drupal API for a backend possible? For my design, I want to have Drupal handle all security and presentation.  My backend is an api that returns JSON.  All I could find showed Drupal as "headless," where Drupal was the back end.

I am trying to avoid building too much into Drupal and being dependent on it.

Is using Drupal for the frontend and having separate API for the back end possible?  It sounds like I have it backwards, but I do not to build everything in Drupal.  I want to do all the Database and Business logic outside of Drupal.

Edit:  This is for an Intranet where I hit many databases.

Drupal 7/8 can make use of Remote Entities which could be provided in a JSON format. But, what your describing seems needlessly complex. If you have a JSON based backend I would do something more simple like create the frontend using Javascript to talk to your backend, or maybe using a more generic php framework.

Attempting to use Drupal as a frontend and ignoring its data creation CRUD, Content Types and storage mechanisms -- sounds like big headache.


Moving the Sites/Default/Files Directory We have a client with simple request to move the Public File folder up simply so that links will be shorter like example.com/files/ instead of example.com/sites/default/files/.

I assumed this would just entail running

mv ./sites/default/files/ ./files/

in the root directory where my index.php resides and then changing the line in settings.php. Yet, this does not work, and I can't figure out why. In the file_managed table the uri column looks like public://example.png. Does that variable 'public' not resolve to the default public path?

Here's what my settings.php line reads:

# Change Public File directory
$settings['file_public_path'] = 'files';

The folder is right next to my index.php file and the entire folder, including contents is set to 775, or rwxrwxr-x.

drwxrwxr-x. 47 apache webgrp  28672 Nov 15 10:14 files
-rwxrwxr-x.  1 apache webgrp    648 Oct 25 08:17 index.php

Weirder, in the browser inspector, it appears that Drupal is looking for files at /files/example.png and there is definately a matching file at /files/. What am I missing? The only docs I can find are for Drupal 7, and all modules I've seen are only for 7 as well.

Look in Admin > Config > Media > File System:

/admin/config/media/file-system

  Public file system path
  sites/default/files
  A local file system path where public files will be stored. This directory must exist and be writable by Drupal. This directory must be relative to the Drupal installation directory and be accessible over the web. This must be changed in settings.php

So there you have it. If you want to change the file system path for the public:// stream wrapper, you will need to edit settings.php.

EDIT: I'm not sure what else is at play here. If you still can't get this working to your client's specifications, you may be able to spoof it with a symbolic link in the file system:

ln -s files sites/default/files

The files would still be hosted in the wrong location, so this is actually no solution. Hopefully somebody else can point you in the right direction. Good luck!


Text format and field profile I am working in Drupal 7.

I have a text-area in profile. I need the text area has a specific text format without editor but allows tags HTML.

The text format only is for the role "registered users", not for other roles and only in the text-area in the profile. This restriction is only for the field in profile.

If I have a role named "role test" that can edit articles and edit the profile, I need that the "role test" has not html tags in the text-area field in profile but the "role test" has editor in the content articles.

Thanks.

Make sure "registered users" have permission to use that input format and "role test" does not have permission to use that input format. "role test" could have permissions for the editor format without having permissions for the input format for the profile field.


Adding a block to a page build with a call to theme (Drupal 7) I have a page on Drupal site that needs to render a webGL canvas.  This page is visited by hitting an end point defined in hook_menu.  Here is the code I use to render the webGL page.

function inflatable_icons_canvas_page() {
    $base_path = drupal_get_path('module', 'inflatable_icons') . '/Online_Inflatable_Icons/IconEditor/public/';
    drupal_add_js(array('inflatable_icons' => array('basePath' => $base_path)), 'setting');
    drupal_add_css($base_path . 'js/dojo-release-1.7.2/dijit/themes/claro/claro.css');
    drupal_add_css($base_path . 'css/shared.css');
    drupal_add_js($base_path . 'js/includes.js');
    return theme('webgl_canvas');
}
function theme_webgl_canvas() {
    $html = file_get_contents(drupal_get_path('module', 'inflatable_icons') . '/Online_Inflatable_Icons/IconEditor/public/editor.html');
    $page = new SimpleXMLElement($html);
    $table = $page->body->table;
    $div = new SimpleXMLElement("

");
    sxml_append( $div, $table );
    return $div->asXML();
}

I also need to be able to add some blocks to this page (either programmatically created or created through interface builder), how would I add these blocks to my page which is created through loading the html file editor.html and calling theme.

inflatable_icons_canvas_page() is the callback function for your hook_menu page,  therefore in your hook_menu you will define a route as:

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

Then you can use the route 'abc/def' to determine the visibility of your blocks either in the admin blocks UI or in your module code. In later case it will be something like:

$blocks['example_empty'] = array(
    'info' => t('Example: empty block'),
    'status' => TRUE,
    'region' => 'sidebar_first', // Not usually provided.
    'visibility' => BLOCK_VISIBILITY_LISTED, // Not usually provided.
    'pages' => 'abc/def', // Not usually provided here.
  );

Then configure the block as usual from blocks admin UI. If you go to configure the block you will find the configuration of visibility settings to "show block in specific pages" option "only the listed pages" and your hook_menu route in text area. You could change it now if desired, as you will with a block created through UI.


Altering existing route for translation overview page ie: entity.node.content_translation_overview I have followed this documentation page :  https://www.drupal.org/docs/drupal-apis/routing-system/altering-existing-routes-and-adding-new-routes-based-on-dynamic-ones in attempt to alter access of translation overview page ie: www.example.com/node/1/translations
<?php

namespace Drupal\link_enhancements\Routing;

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

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

  /**
   * {@inheritdoc}
   */
  public function alterRoutes(RouteCollection $collection) {

    $route_name = "entity.node.content_translation_overview";
    var_dump($collection->get($route_name)); exit;
    if ($route = $collection->get($route_name)) {
      $requirements = $route->getRequirements();
      unset($requirements['_permission']);
      // if both role then only we will allow ...code will go here.....
      $route->setRequirement('_access', 'FALSE');
    }

  }

}

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

But below route output is null and similar code works for other routes but requirement to alter translation overview route which returns null.
$route_name = "entity.node.content_translation_overview";
    var_dump($collection->get($route_name)); exit;

core/modules/content_translation/src/Routing/ContentTranslationRouteSubscriber.php
route is added in core module by below code and I have searched and tried but not sure how can we alter such routes, please suggest.
if ($entity_type->hasLinkTemplate('drupal:content-translation-overview')) {
        $route = new Route(
          $entity_type->getLinkTemplate('drupal:content-translation-overview'),
          [
            '_controller' => '\Drupal\content_translation\Controller\ContentTranslationController::overview',
            'entity_type_id' => $entity_type_id,
          ],
          [
            '_entity_access' => $entity_type_id . '.view',
            '_access_content_translation_overview' => $entity_type_id,
          ],
          [
            'parameters' => [
              $entity_type_id => [
                'type' => 'entity:' . $entity_type_id,
                'load_latest_revision' => $load_latest_revision,
              ],
            ],
            '_admin_route' => $is_admin,
          ]
        );
        $route_name = "entity.$entity_type_id.content_translation_overview";
        $collection->add($route_name, $route);
      }

It was not working because in content_transaltion module priority was set to -210 so make need to change priority of custom module to -220 and it started working.
public static function getSubscribedEvents() {
    $events = parent::getSubscribedEvents();
    $events[RoutingEvents::ALTER] = ['onAlterRoutes', -220];
    return $events;
  }


Render an entity in a string and return it through an AJAX callback in a custom form I use the code snippet from:
render a drupal 8 entity in a string

$node = \Drupal::entityManager()->getStorage('node')->load($nodeid);
$view_builder = \Drupal::entityManager()->getViewBuilder('node');
$renderarray = $view_builder->view($node, 'full');
$html = \Drupal::service('renderer')->renderRoot($renderarray);

It works in a normal controller class without problems. But I did not get it to work in an Ajax Callback in a Custom Form.

The $html = \Drupal::service('renderer')->renderPlain($build);  returns nothing.

Where ist the problem? Here is the reduced code of my test form:

<?php

namespace Drupal\mymodule\Form;

use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;

class SearchApiPageBlockForm extends FormBase {

  public function getFormId() {
    return 'search_api_page_block_form';
  }

  public function buildForm(array $form, FormStateInterface $form_state, $args = array()) {

    $form['form']['actions'] = array('#type' => 'actions',);
    $form['form']['actions']['submit'] = array(
      '#type' => 'submit',
      '#value' => $this->t('TESTBUTTON!'),
      '#ajax' => array(
        'callback' => '::myAjaxCallback',
      ),
    );

    return $form;
  }

  public function submitForm(array &$form, FormStateInterface $form_state) {
  }

  public function myAjaxCallback(array &$form, FormStateInterface $form_state) {

    $view_builder = \Drupal::entityTypeManager()->getViewBuilder('comment');
    $storage = \Drupal::entityTypeManager()->getStorage('comment');
    $node = $storage->load(103); //cid 103 already exists
    $build = $view_builder->view($node);

    dpm('before rendering'); // -> dpm output is: 'before rendering'

    $html = \Drupal::service('renderer')->renderPlain($build);

    dpm($html);// -> dpm has no output
    dpm('after rendering');// -> dpm has no output

    }

}

My goal is, to return the html of an entity via the

$response->addCommand(new HtmlCommand('#testtmp_message', $output));

UPDATE: Content of build:
dpm(build)

The code in my question is OK. The problem was caused by a conflict by calling the form from hook_preprocess_field(). I changed the hook, and I am calling the form from template_preprocess_block() and the AJAX callback of the entity gets fine.

4k4 put me on the right track. Thank you.


Views filter by contextual filter I have an interesting question regarding Views, Taxonomy and Contextual Filters AND Views->Filters

I have a content type Basic Page with additional field -> industry category (term reference, taxonomy).

There are multiple Basic Pages on the website but only 5 with industry category field filled in.

I have second content type Industry Page (Page Title, Body with additional field -> *industry categor*y (term reference, taxonomy), pointing towards the same vocabulary.

I have a view should display nodes of type industry page depending on the page you are in (The “basic page” with the additional field-> industry category.)

I need to do something with contextual filter to display all nodes of type “industry page” where the basic page->field industry category = “industry page”->industry category.

Can you help me with it, since I am a bit stuck.

Regards

Oleg

I think you are looking for creating a block of similar node by term with one more filter "another content type". There is a module to do this exactly but it doesn't have the content type filter in it. I will still recommend you to have a look at it - Similarterms.

You can achieving the same with view. Please look into the answer given at these links, it has been explained in details --

https://stackoverflow.com/questions/10454507/creating-list-of-similar-nodes-in-drupal-7-views-3

Recommend nodes based on current node field value in view block


Date range2 Field Validator not firing I am attempting to create a validator on a birthday (date) field I added to the user. The validator is setup as such but it never fires when I test it by registering a new user on the front-end.

Anyone have any ideas why this validator isn't firing?

A possible solution that might help to simplify the challenge in your question, is the fairly new Math Field module (for D7). Some more details about this module (from its project page):

  The Math Field module defines a new field type to dynamically calculate values on entity forms. This is an alternative to Computed Field
  that does not require the use of PHP Filter.

  Math expression fields are dynamically updated via ajax on the entity form as soon as all necessary fields are populated. If JavaScript is disabled, the field will be evaluated when the form is submitted. The result is stored in the database when the form is submitted.

By creating some auxiliary field(s) (calculated via the Math field), you may be able to complete your puzzle via some additional logic implemented via the Rules module, to actually verify "18 Years or Older" (which I believe is the actual validation you want to implement).

For more details (step-by-step instructions), refer to either of these links:

the (amazing!) Community documentation about the Math Field module.
the interesting article about Introducing the Math Field module, which also includes some screenprints to see it at work (such as the the add/edit form example).