ajax modified form drop down doesn't save I have used form_alter to add a ajax callback to an element to my form. When the user chooses an option, it creates dropdown options for the other field. However, while this works fine for changing the form, it doesn't actually save the value in the field when you click save. I checked the database and its not saved, value is 0. Not exactly sure what is happening.

Here is my code:

/**
 *  Implements hook_form_alter().
 */
function chapter_sponsor_levels_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id === 'sponsor_node_form') {
    //we need to add an ajax call to the OG Group field on the Sponsor node page, so that it populates the sponsor level dropdown
    $form['og_group_ref']['und'][0]['default']['#ajax'] = array(
      'callback' => 'chapter_sponsor_levels_update_levels',
      'wrapper' => 'edit-field-sponsor-level',
      'method' => 'replace',
    );
    if(!empty($form['og_group_ref']['und'][0]['default']['#default_value']) && empty($form_state['values'])) { //if we are viewing the form not from an ajax request
      dpm($form);
      dpm($form_state);
      $gid = $form['og_group_ref']['und'][0]['default']['#default_value'];
      chapter_sponsors_levels_set_levels($gid, $form);
      dpm($form_state);
    }
    elseif (!empty($form_state['values']['og_group_ref']['und'])) { //if we have chosen a group
      //$gid = 8; //new york
      $gid = $form_state['values']['og_group_ref']['und'][0]['target_id'];
      chapter_sponsors_levels_set_levels($gid, $form);
    }
    $form['#submit'][] = 'chapter_sponsor_levels_save_level';
  }
}

function chapter_sponsors_levels_set_levels($gid, &$form) {
  $query = 'Select * from {og_vocab_relation} where gid = :gid';
  $results = db_query($query, array(':gid' => $gid));
  foreach ($results as $result) {
    $vid = $result->vid;
  }
  $chapter_vocab = taxonomy_vocabulary_load($vid); //get the vocabulary associated with the group
  if(!empty($chapter_vocab)) {
    $terms = entity_load('taxonomy_term', FALSE, array('vid' => $chapter_vocab->vid));
    $form['field_sponsor_level']['und']['#options'] = array('_none' => '- None -');
    foreach($terms as $term) {
      $term_names[$term->weight] = $term->name;
    }
    ksort($term_names); //sort the terms by their weight and set them as the dropdown values
    foreach($term_names as $name) {
      $form['field_sponsor_level']['und']['#options'][] = $name;
    }
    $form['field_sponsor_level']['und']['#title'] = $chapter_vocab->name;
  }
}

EDIT: Forgot to add this in to the post

function chapter_sponsor_levels_save_level(&$form, &$form_state) {
  dpm($form_state);
}
/*
 * AJAX callback when click on OG Group field on Sponsor page
 */
function chapter_sponsor_levels_update_levels($form, $form_state) {
  return $form['field_sponsor_level']; //update the sponsor_level field with the new dropdown values
}

EDIT:
I may be getting closer, but not yet there. I realized that if its not saving the value, its proabably because it doesn't match a list of allowed values. While I didn't see such a constraint in the database, I found a 'allowed values' list in the $form_state array. I modified my code above:

foreach($term_names as $name) {
      $form['field_sponsor_level']['und']['#options'][$name] = $name;
      $form_state['field']['field_sponsor_level']['und']['field']['settings']['allowed_values'][$name] = $name;
    }

However, now when I try to save the form when choosing a value, it says that it is an illegal value. I found that it was throwing the error from line 397 in the list module - for some reason, its not passing the 'allowed values' test.

Ok, I finally got it right, here's the code of the function which does the work:

function chapter_sponsors_levels_set_levels($gid, &$form, &$form_state) {
  $query = 'Select * from {og_vocab_relation} where gid = :gid';
  $results = db_query($query, array(':gid' => $gid));
  foreach ($results as $result) {
    $vid = $result->vid;
  }
  $chapter_vocab = taxonomy_vocabulary_load($vid); //get the vocabulary associated with the group
  if(!empty($chapter_vocab)) {
    $terms = entity_load('taxonomy_term', FALSE, array('vid' => $chapter_vocab->vid));
    $form['field_sponsor_level']['und']['#options'] = array('_none' => '- None -');
    foreach($terms as $term) {
      $term_names[$term->weight] = $term->name;
    }
    ksort($term_names); //sort the terms by their weight and set them as the dropdown values
    foreach($term_names as $name) {
      $form['field_sponsor_level']['und']['#options'][] = $name;
      $form_state['field']['field_sponsor_level']['und']['field']['settings']['allowed_values'][$name] = $name;
    }
    $form['field_sponsor_level']['und']['#default_value'] = $form_state['build_info']['args'][0]->field_sponsor_level['und'][0]['value'];
    $form['field_sponsor_level']['und']['#title'] = $chapter_vocab->name;
  }
}


How to get a parameter value from the current URL in views-view-fields.html.twig? I need the argument value in the theme templates and using the views-views-fields--view_name--block_1.jhtml.twig.

I'm current getting the current URL like that:

{% set url = url('current')%}

Which outputs:

https://example.com/questions/12225

But I need only the 12225 value from the current url. How can I get the last parameter from the current URL in Twig?

You could use Twig's split filter, though I don't recommend scripting too much inside templates.

Instead I recommend to pass the value over to Twig from a preprocess function from inside your theme or a custom module via template_preprocess_views_view_fields.

/**
 * Implements template_preprocess_views_view_fields().
 */
function MYTHEME/MYMODULE_preprocess_views_view_fields(&$variables) {

  // Retrieve an array which contains the path pieces.
  $current_path = \Drupal::service('path.current')->getPath();

  if ($current_path[0] == 'questions') {
    $variables['question_id'] = $current_path[1];
  }
}

And then inside your template print it for example like so:

{% if question_id %}

Question ID: {{ question_id }}

{% endif %}


How to create landing pages and Main Menu based on taxonomy I'm trying to build a website for a non-profit which has multiple locations (~6) besides the headquarters.

The frontpage needs to be generic for the whole organization and will contain content from all locations.

However, each location needs have its own page ( not only the content part but also the main menu and the header etc.) and all the content(nodes etc.) associated with this location should use the same page template associated with this location. So I've created a taxonomy term for each location and tried to use template suggestions based on the term but it didn't work.

So far I was successful creating a panel page with its own path (such as website.org/headquarters) for each location and show content only for that location by filtering via the taxonomy term but no luck for having custom main menu or custom node pages for the location.

Is there something trivial that I'm missing or is there no easy solution for this?

Thanks,

This seems like the perfect use case for Organic Groups

  Enable users to create and manage their own 'groups'. Each group can
  have subscribers, and maintains a group home page where subscribers
  communicate amongst themselves.

  They do so by posting the usual node types: blog, story, page, etc. A
  block is shown on the group home page which facilitates these posts.
  The block also provides summary information about the group.

There is also a kick-ass set of tutorial videos from BuildAModule here that should help you set it up.


Multiple points openlayers geojson display only the last of it I made a module retrieving data with geodata. The import feature allows to create a file in geojson. So, i'd like to display the points and the data without using Views, only openlayers module.
I saw the layer example provided with the module : Example GeoJSON, "Picture This", displaying a marker with the given raw geojson data provided.
In the Layer section, I tried to use the URL field instead of the raw data field to provide a link to my datafile, but when i use it on a map, only the last point is displayed.

I saw that in the example :

  {
    "type": "Feature",
    "properties": {
      "name": "Picture This",
      "description": "Outside of the North Carolina Museum of Art."
    },
    "geometry": {
      "type": "Point",
      "coordinates": [
        -78.702798,
        35.809411
      ]
    },
    "crs": {
      "type": "name",
      "properties": {
          "name": "urn:ogc:def:crs:OGC:1.3:CRS84"
      }
    }
  }

but the "regular"geojson is a collection of such features :

{ "type": "FeatureCollection", "features": [
      {
        "type": "Feature",
        "properties": {"name": "point1", "description": "desc of 1"},
        "geometry": {"type": "Point", "coordinates": [-78, 35]
        }
      },
      {
        "type": "Feature",
        "properties": {"name": "point2", "description": "desc of 2"},
        "geometry": {"type": "Point", "coordinates": [-79, 34]
        }
      }
]}

So, since i have more than 1 point i used the second version, and i only get the last point showing when i use this overlay on a map.

Is there something special to do to display several point or shapes (from a layer) using that technique : i'd like to avoid using Views or any other plugins for this.

I've read https://www.drupal.org/node/1481374 and other generic openlayer Drupal 7 tutorials, but i haven't found any help for this kind of problem.
Thanks in advance

Finally, i found out that the problems (only the last point and that point wasn't at the right place) had nothing to do with my geojson file : i created a new layer and by default it had projection EPSG:3857, but i needed a projection with GPS coordinates => EPSG:4326 see this . With that change, every point is now displayed. I guess with the wrong projection, all the points where somehow stacked, and then only the last one was displayable.

In Openlayer > Layers

Use Projection EPSG:4326 (instead of EPSG:3857)

In Openlayer > Map
Use

Map Projection EPSG:3857 (Default)
Display Projection EPSG:4326(Default)


hook_entity_view_alter - redirect First up I'm very new to the Drupal way of things but have jumped on board with Drupal 8 and quite excited about the possibilities.

What I'm trying to do is redirect the default node view route (i.e. /node/12345/), for a specific content type, to a route I've setup in my module i.e. /module_name/view/12345/

Currently I've done this via a hook which I'm 99.9% is the wrong way to do it but it does work. However I'm getting warnings in my log file as other Drupal commands (including drush) occasionally trigger the hook.

Here is my code so far:

function gst_return_entity_view_alter(array &$build, Drupal\Core\Entity\EntityInterface $entity, \Drupal\Core\Entity\Display\EntityViewDisplayInterface $display) {
    if($entity->bundle() == 'gst_return') {
        header('Location: /gst_return/view/' . $entity->id());
        exit;
    }
}

Two questions really:

Is there a better way to be doing this? I'm sure there is.
If the above is acceptable then what can I add to it so that the header redirect (which probably should be a Drupal core redirect?) so that it is only triggered in the context of someone viewing the site.

Thanks for any assistance.

Instead of using header redirect try using RedirectResponse class which comes together with the Symfony HttpFoundation.

use Symfony\Component\HttpFoundation\RedirectResponse;

 function my_menu_callback_foo() {
    //....
    return new RedirectResponse(\Drupal::url('user.page'));
 }

Refer link for more details.


Dynamic URL aliasing? Let's say we have a section /latest-projects with a menu block listing nodes sorted descending by their post date. Thus, the first item will often change and be the freshest one. Is it possible to make the /latest-projects alias always link to (= open) the top-most node?

Indeed it is.

Steps you will need to do:

Create a custom module
Implement hook_menu()
Define the route 'latest-projects', and make the menu callback a function
In the custom menu callback function do SQL or whatever to find the latest project (maybe use EnityFieldQuery in Drupal 7)
Use drupal_goto() to then redirect the user to the latest project node

Note in the above solution, a redirect is used to send the user to the project node, but if needed you can also simply render the node on the page as another idea.


How to add JavaScript or CSS library to Composer project? For some cases, there is the need to add a JavaScript or CSS package to a project. One of those cases was the DropzoneJS package for the drupal/entity_browser. All recommendations I could read online read like

  Download manually
  Install manually

or like

  Use Drush

This is not really satisfying as there should be a way without user interaction or working around interaction in setup scripts.

The library can be installed into a custom path by utilizing extra : installer-paths to for e.g.:

web/sites/libraries/{$name}

Additional to that, we define the required package repository with the needed type of drupal-library. Example composer.json for a project:

{
    "name"              : "example-composer/example-project",
    "description"       : "Project template for Drupal 8 projects with composer",
    "type"              : "project",
    "minimum-stability" : "dev",
    "prefer-stable"     : true,
    "scripts"           : {
        "post-install-cmd" : "sh ./scripts/composer/post-install.sh"
    },
    "require"           : {
        "composer/installers"       : "^1.0.20",
        "drupal/entity_browser"     : "8.1.0-alpha1",
        "cweagans/composer-patches" : "~1.0",
        "drupal/core"               : "8.0.*",
        "drush/drush"               : "~8.0",
        "drupal/console"            : "~0.9",
        "drupal/devel"              : "dev-8.x-1.x",
        "drupal/entity_browser"     : "8.1.0-alpha1",
        "drupal/inline_entity_form" : "8.1.0-alpha2",
        "drupal/dropzonejs"         : "8.1.*@dev",
        "enyo/dropzone"             : "dev-master"
    },
    "repositories"      : [
        {
            "type" : "composer",
            "url"  : "https://packagist.drupal-composer.org"
        },
        {
            "type"    : "package",
            "package" : {
                "name"    : "enyo/dropzone",
                "version" : "dev-master",
                "type"    : "drupal-library",
                "dist"    : {
                    "url"  : "https://github.com/enyo/dropzone.git",
                    "type" : "drupal-library"
                },
                "source"  : {
                    "url"       : "https://github.com/enyo/dropzone.git",
                    "type"      : "git",
                    "reference" : "origin/master"
                }
            }
        }
    ],
    "extra"             : {
        "installer-paths" : {
            "web/core"                    : [
                "type:drupal-core"
            ],
            ...
            "web/sites/libraries/{$name}" : [
                "type:drupal-library"
            ]
        }
    }
}

The dist part can be left off and is only needed for --prefer-dist cases when installing via php composer.phar update --prefer-dist (opposite: --prefer-source). To install a version and not the latest from the master branch, you need to set the version directly at the package to require then from there. Example:

"require" : {
    "enyo/dropzone" : "v4.2.*@dev"
},
"repositories" : [
    {
        "type"    : "package",
        "package" : {
            "name"    : "enyo/dropzone",
            "version" : "v4.2.0",
            "type"    : "drupal-library",
            "source"  : {
                "url"       : "https://github.com/enyo/dropzone.git",
                "type"      : "git",
                "reference" : "origin/master"
            }
        }
    }
]


Get content based on taxonomy I can't figure out what I am doing wrong, as my block isn't showing up with the content from the taxonomy.
I am trying to create a block that shows the content based on the taxonomy; I made a path on the taxonomy, and the main content shows up, but when I try to add a block using Views, it never shows.

This is the settings page for the taxonomy.

This is the view I am using with the argument.

Edit: I fixed the issue; all I had to do was create a new content and it worked. I guess my only question now is how to keep the block on the front page after adding the filter.

the way I did was i used global:null as the contexual filter and then selected provide default value and then went to type: taxonomy term ID from URL and added it in and then added content: has taxonomy term ID and gave it the same settings as the global:null and saved the view, now the reason why i didnt see it is because you have to add new content, for some reason it doesnt pick up the current content with taxonomies


Setting event date in views i have events page on my Drupal and it is showing events until the relative date (is greater than) "now" which means the event disappears from the table on the starting date of the event.

Can you please help me with setting that date to the last day of the event - so that the event stays on the table until the last day. I have multiple events, so i really dont know how to do this. I checked other relative formats, but i am no developer, so i am puzzled.
Thank you in advance.

If your node contains Date field than you can set start and end date (you can turn on/off end date field in field settings). Both are available in Views so instead of building your Views filter on start date, build it on end date.


How can this buying logic be achieved using drupal commerce and/or ubercart? I think the following scheme describes best what I am trying to achieve:

I am trying to make a ticket booking "shop" if you will.

There are different events
For each event you can buy tickets, like the graphic above shows
There are different ticket types, like normal, vip and special vip (for instance)
Each ticket type can vary in its price depending on the date
The visitor should be able book several tickets for that event at once
Optional: beneath the table is a summary of the selected tickets/ total price
The visitor can checkout and pay, gets a summary (different story)

My attempts so far

On an existing drupal project I installed the commerce module.

I installed commerce booking since it pretty much claims to do what I am looking for. Unfortunately there has been a bug in this module for several months making it unusable, there is no fix there yet (https://www.drupal.org/node/2134449 for instance). What a bummer.

So I installed drupal commerce kickstarter and tried around a little bit in here.

I came up with a product type/ variation "Event", two taxonomy vocabs "Ticket Type" and "Date" and added taxonomy reference fields to the event/ product type.
The cool thing is I can now add a new event "Jam session at Alex's" and add many product variations in it.
For instance I can add a variation which's price is 1 €, pick a term for a date like "Date 01" and pick a term for the type of ticket like "Ticket Normal". With these fields I can add x numbers of product variations to actually depict the variety of tickets as shown in the graphic. So far so good.

However, I cant manage to create an output like shown in the graphic, how would you do that with views? How could you implement an ajax quantity indicator (it actually should work like the add to cart form, but with AJAX) and adding a payment process right after? Help would be greatly appreciated.

I havent tried to use ubercart yet, would it be far more easy to do it with uc, maybe?

This isn't going to be easy to do with either Drupal Commerce or Ubercart. What you're proposing is a very specific, custom bulk Add to Cart form. You're going to have to code it yourself in a site-specific module. The closest you can get would be Commerce Cart Extras, but you'd still have to reformat it to look like your proposed grid and also to have a live updating order total in the footer.


Views search for term reference in field collection I have content type where tagged persons names are automatically saved as a taxonomy term. These created terms have a field, which is a field collection of a date and another taxonomy term which keeps information about the unit. What I'm trying to achieve is, to search for nodes via the unit taxonomy term which will bring up nodes where persons from this unit are tagged. I have no clue how to get it work. I guess somewhere under relationships or contextual filters should be the options but so far I wasn't able to figure it out.

Node

title
Person (taxonomy term)

date / unit (taxonomy term in a field collection field of taxonomy term above)

image

I've solved it by adding a relation with the field which holds the taxonomy term data for persons. A second relation needed to be added, this time related to the field collection name. This way I'm now able to expose the field which holds the job data as a search option.


Delete system menu links I'd like to know the best way to delete system menu links.  I can't delete them through the UI because they have somehow become stray links (there is no "delete" link next to them).

I've looked at menu_link_delete, which calls _menu_delete_item, but that won't hit if $item['module'] == 'system' unless I force it which is discouraged.

So... if I can't do it through the Drupal API, do I need to do a DB query?  If so, which tables should be involved in the delete?  Can I get away with just removing records from the menu_links table?  It looks like the has_children value may also need to be altered?

Are there other options besides a DB query which I'm not seeing?

I've also seen this answer, but he just moved the stray links to another menu, which I don't want to do.

Rather than deleting the menu items myself through the DB (see here for possible explanation on how), I decided to try to find the underlying issue, and this is what I found:

In my case I have two modules which have the ability to add links to the menu(that I know of...):

Views (/admin/structure/views -> Edit a View -> Page Settings ->
Menu)
Pages (/admin/structure/pages -> Edit a Custom Page -> Click on Menu)

The above modules were adding menu items to the menu which cannot be deleted from the menu system unless you go to the modules and remove them first.

In order to remove the menu links I had to do the following:

In the module that creates the menu item (Views, Pages, etc.) set the Menu option to "No Menu".
In the menu config (/admin/structure/menu/manage/), go to the menu item and click on "reset" to remove it from the menu.
Disable the Custom Page or View (the individual view or page, not the entire module)
Re-enable the Custom Page or View
The menu item should no longer be present in the menu_links table.

My issue was related to what seems to be a core problem (see:  https://www.drupal.org/node/1058672 OR https://www.drupal.org/node/1029022) which is that if a menu item is created and then removed, it can leave behind a stale record in the menu_links DB table.  Disabling the affected Custom Page or View is what actually removed it from the DB for me.


How to remove user role using hook_user_update I am having trouble trying to remove a role after user account submit.

I have used the following code:

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

}
  if(($form_id === 'user_profile_form')and (isset($form['account']['pass'])) and (in_array('Hybridauth', array_values($user->roles))) ) {
      $form['#submit'][] = 'my_module_hook_user_update';

}
function my_module_hook_user_update($edit, $account, $category) {
  $role_position = array_search('Hybridauth', $account->roles);
  // Use !== or === here since $role_position may be zero or FALSE
  if ($role_position !== FALSE) {
    unset($account->roles[$role_position]);
  }
}

Resulting in the following errors:

Warning: Missing argument 3 for vdb_hook_user_update(), called in \includes\form.inc on line 1471 and defined in vdb_hook_user_update() (line 46
Notice: Trying to get property of non-object in vdb_hook_user_update() (line 47
Warning: array_search() expects parameter 2 to be array, null given in vdb_hook_user_update() (line 47
Warning: Attempt to modify property of non-object in vdb_hook_user_update() line 50

I have tried using hook_user_presave however using this hook hybridauth module gets stuck.

The errors in your code are two:

vdb_hook_user_update() is not the correct name for an implementation of hook_user_update()
vdb_hook_user_update() is being used as form submission handler

As consequence of the second point is that you are declaring the function with the wrong arguments, since a form submission handler gets two arguments: $form and &$form_state.

As Clive pointed out, you should use hook_user_presave(), which is invoked before the user account is saved in the database. Remove the code adding the form submission handler, and implement hook_user_presave() using code similar to the following one.

function vd_user_presave(&$edit, $account, $category) {
  if (!empty($account->uid) && ($key = array_search('Hybridauth', $account->roles)) !== FALSE) {
    unset($account->roles[$key]);
  }
}


How to properly add anchor to form element I try:

         $form['field_profile_club']['anchor'] = array(
           '#value' => '',
         );

But my field (field_profile_club) disappear.

Could somebody help?

Take a look at the form apis prefix and suffix attributes these will allow you to wrap html around your form element.


Fields attached to Workflows do not get saved Using Drupal 7.41 and workflow 7.x-2.8, when you attach fields to a Workflow, the fields do not get saved with the workflow field.

It's easy to replicate: Create a workflow, add a field to that workflow in admin/config/workflow/workflow/manage/workflowname/fields (ex: field_confirm), attach a workflow field to a node type (ex: article, I'm using workflowfield here), create an article and set a workflow state & comment. Upon saving the article, the workflow state and comment get saved (see workflow tab) but no field_confirm data gets saved or displayed. The data is not in the database either - the table field_data_field_confirm / field_revision_field_confirm remains empty.

Is that feature not ready yet? Or am I missing something? I tried with workflownode and it didn't seem to work either.

Please find a full configuration steps tutorial  for workflow https://www.drupal.org/node/1027546.

I also used this for my site.


Send system message to user i would like to send system message to user such as site announcement, notification and etc.

i know the private message module, but it could not differentiate the message is send by the real system/admin or a normal user.

How should i do that??

Try the notifications framework:

  This is a complete Subscriptions/Notifications Framework aiming at extendability and scalability. It allows any number of plug-ins defining new event types or subscription types or a different user interface.

Its a full featured module with a number of companion modules for sending messages via different channels depending on different events but what you're probably looking for is the 'Web messaging' submodule:

  Sending Method: Show messages on user's page


what security measures should be taken when creating/updating/retrieving entities with data from users' form submissions? We have webforms for authenticated users (anyone can create an account without admin approval) to fill out.  With their submission data I'm using the civicrm_api to create contacts and relationships.

For example:

// in hook_webform_submission_insert I do this:
$newcontact= civicrm_api3('Contact', 'create', array(
  'sequential' => 1,
  'contact_type' => 'Organization',
  'contact_sub_type' => 'Sub_Type',
  'organization_name' => $submission->data[20][0],
));

Is there any filtering I should be doing or are Drupal's security measures sufficient?

There are various hooks I could use.  Currently I'm using a combination of hook_form_alter with submit callbacks and hook_webform_submission_insert.  Would one of these or some other hook have significantly greater security measures?

Designers need to worry about two things, making sure that user-supplied data can go into the database successfully, and also that data pulled from the database can be written to the page successfully.

When adding data to the database, Drupal will use prepared statements to ensure the SQL injection does not occur. What this means is, Drupal will tell the database, "Expect to see an INSERT command that looks like {statement}." and then sends all the data. If the resulting statements does not match, there will be an error.

Drupal Fields are defined such that the system knows how the data in that field should be displayed. The database schema guarantees that only a certain data format is available. For example, if the field is a number, we know we won't get a string because the database is designed to only record numbers. Drupal can just worry about formatting it properly. Same if it's text, it will make sure that it is not displaying a URL by passing the text through check_plain() after retrieving the data from the database.

In your case, you are going to be inserting this user-supplied data into the database. The Drupal Field API should be ensuring that the data is of the correct type for the database, and that it is not too long, or improperly formatted before inserting the record. It will insert it using the prepared statement to prevent SQL injection. So, you should be fine.

Make sure you read the CiviCRM secure coding guide:
https://docs.civicrm.org/dev/en/latest/security/


Webform Validation Allow Lowercase Only I have an email field in a webform that will trigger a rule that checks against that field against a user's email.  The issue is, rules is case sensitive so if the webform field had capitals, and the user's email does not, they don't match like they should.

In webform validation, there are two options that should work for me to force the email to only contain lowercase values.

Regular expression, case-sensitive
Validates user-entered text against a case-sensitive regular expression. Works with: email, hidden, number, textarea, textfield.
Regular expression, case-insensitive
Validates user-entered text against a case-insensitive regular expression. Works with: email, hidden, number, textarea, textfield.

Which one of these should I use, and what is the regular expression so that it only disallows capital letters?

Thanks!

Figured it out - Regular Expression, case-sensitive:

Regex Code: [A-Z]

Negate Rule is checked.


Views and contextual filter as user id from url I want to create some views that shows the content created by the user, content flagged by the user and so on. I also need that when user a views user b then user a can see the content created by user b and so on. So i though i under Contextual filter i passed a default values as User Id from url. However when i visit the page i just see the view heading and no content.Please Help

Regards

Create a new Views view with Format, Fields, and Filter criteria configured as needed.

Then do the following:

Under Advanced, add a new Contextual filter for Content:
Author uid.
Choose Provide default value and select User ID
from URL.
Under Page settings, set Path to user/%/myview.

Now when you navigate to user/1/myview you should see content from user 1.

For Flags you need to add a relationship for the flag and filter by it. I believe this answer would help with that.


How do I recreate the system.site configuration element? For some reason system.site, system.performance and system.date config values have been deleted from our site.

I have the original configuration files, but when attempting to import those using drush cim, Drush complains about the site UUID mismatch.

The import failed due to the following reasons:
Site UUID in source storage does not match the target storage.

I assume this is because UUID is missing entirely. If I run drush cget system.site, I get the following error:

[error]  Config system.site does not exist

Attempting to set the UUID with drush config-set "system.site" uuid "my site id" also fails with:

[error]  Config system.site does not exist

So now I'm in a bit of conundrum.

Any suggestions on how to restore the system.site configuration?

I solved it with Drush.

To get around the UUID mismatch I uncommented the UUID field in system.site.yml and ran drush cim. After that I specifically set the UUID by running drush cset "system.site" uuid "my site id".


Modify default drupal 8 search results I am using Drupal 8 default search and I don't want to use search api module. Default search is working fine. But I Want to modify it. I want to categorize search result and get count of that category. Also I want to add class of that category so that On click of that category, I can hide other results.

There was hook hook_preprocess_search_results()  in 7 but in 8 I think they have removed.

So is there any alternate hook available? Is there any other way around without using search api and facet api?

Perhaps a view with exposed filters may be a quicker solution for this kind of thing.


How to display shops near by user I am creating a website in which I want to show the similar shops near by user location.

Like if a user selects Bangalore -> M.G. Road then the similar shops near by M.G. Road should be displayed.

However, I don't want to use Google Maps, because it will take too long to open.

Any suggestions about how I can do this in Drupal7?

Using Google Store Locator module you can solve your query.

  This project uses Google's Store Locator Utility Library and Google
  Maps to create a 'Store Locator' page that your site visitors can use
  to find and get directions to one of your physical stores. It was born
  out of a need for a simple to install and easy to use locator feature
  for Drupal 7. This module is different from other 'locator' type
  modules (e.g. OpenLayers Locator) in that it doesn't require you to
  have any knowledge of it's dependant modules, and it allows developers
  to focus on implementing personal customizations quickly because the
  installation process is so light.


redirect in hook_init makes body text disappear What is wrong with this code. It makes my body text disappear in all of my nodes.

function MYMODULE_init() {
  if (arg(0) == 'node' && is_numeric(arg(1)) && !arg(2)) {
    $node = node_load(arg(1));
    if ($node->type = 'event') {
      if ($items = field_get_items('node', $node, 'field_event_date')) {
        $date = date_create($items[0]['value']);
        drupal_goto('news/events/day/' . date_format($date, 'Y-m-d'));
      }
    }
  }

I'm using the Calendar module. I don't want to display the full event node, I want to redirect to the Calendar's day display. The redirect works fine. Just when I go to view other nodes there is not body text. I also have Workbench moderation installed. On all of my non-workbench managed nodes I also get a workbench draft tab and errors related to workbench. It is not workbench related as I uninstalled workbench and body text is still not visible.

It seems to be related to node_load, as all is well when I remove that area of code.

Okay, got the answer. hook_init() needs to document what functions are ok/not ok to call

Documention of hook_init() should mention that it's not allowed to call ... node_load() within this hook.
The correct way to redirect is as follow:

MODULE_menu_alter(&$items) {
  $items['node/%node']['page callback'] = 'MODULE_node_page_view';
}

MODULE_node_page_view($node) {
  if ($node->type == MODULE_NODE_TYPE) {
    $referenced_node = MODULE_get_related_node($node);
    drupal_goto('node/'. $referenced_node->nid);
  }
  else {
    return node_page_view($node);
  }
}


How to create the slideshow as the background slideshow using drupal 7? We are currently developing a single page responsive site in drupal 7.In our home page we tried implementing slideshow through view slideshow module (drupal 7). The slideshow is working perfectly fine. I want to know how to create a background slideshow using views slideshow?

You can try using the Vegas Background jQuery Plugin module.

  Vegas is a jQuery plugin to add beautiful fullscreen backgrounds and slideshows to your webpages.

Try out the module demo.


How to alter the $item value in taxonomy_field_is_empty without altering core taxonomy module? How to alter the $items value found in hook_field_widget_form(&$form, &$form_state, $field, $instance, $langcode, $items, $delta, $element) and pass it to hook_field_is_empty($item,$field)?

In a custom module,

function hook_field_widget_form(&$form, &$form_state, $field, $instance, $langcode, $items, $delta, $element){
$item = $items[$delta];
}

In taxonomy.module,

/**
 * Implements hook_field_is_empty().
 */
function taxonomy_field_is_empty($item, $field) {
  print_r($item);print_r($field);die('edd');
  if (!is_array($item) || empty($item['tid']) && (string) $item['tid'] !== '0') {
    return TRUE;
  }
  return FALSE;
}

The  $item array structure in hook_field_is_empty($item,$field) is $item[0]['tid']
whereas taxonomy_field_is_empty($item,$field) expects to have structure as $item['tid'] .

Since its $item[0]['tid'], it gives undefined 'tid' which leads to returned value to be TRUE and hence field is said to be empty ,which is not the case usually.
I tried adding a custom hook in my module for hook_field_is_empty but it did not execute the hook at all ,even I tried adding -1 weight so it executes before taxonomy_field_is_empty (taxonomy module has weight 0) but still it did not help
So I need to alter $items value in hook_field_widget_form in a way that taxonomy_field_is_empty($item,$field) gets $item value such that $item['tid'] is defined(which was not case due to $item['0']['tid'] )

Is there any way I can alter $item value in hook_field_is_empty ?

Altering taxonomy_field_is_empty's behavior is, by definition, altering core, so the answer is no. Hacking core shouldn't be done (unless there's a clear what & why you're doing the hacking).

With that said, you should follow back on your original problem:

  I tried adding a custom hook in my module for hook_field_is_empty but it did not execute the hook at all ,even I tried adding -1 weight so it executes before taxonomy_field_is_empty (taxonomy module has weight 0) but still it did not help

The problem is, for some reason, your module's hook_field_is_empty implementation isn't firing so you'll need to troubleshoot that problem.

Look at other module implementations of the hook to see what those are doing that your module isn't and throw debug statements into module_invoke_all to see if your module's hook is even recognized by core.


Change format of product attribute I have products with a few options.

Option 1: Same price.
Option 2: -50 cent ($9.50).
Option 3: -$1 ($9).

Can I change the display so that it looks like this?

Option 1:
Option 2: ($0.50 off)
Option 2: ($1.00 off)

In uc_attribute.module file comment out from line number 1360 (starts at if ($adjustment != 0) {) to 1363 and add the bellow code

if ($adjustment != 0) {
    //$display_price = $adjustment > 0 ? '+' : '-';

    //this variable is used to flag your custom discount on minus values
    $set_discount = false;

    if($adjustment > 0){
        $display_price = '+';
    }else{
        $display_price = '(';
        $set_discount = true;
    }
    if($set_discount){
        $display_price .= uc_currency_format(abs($adjustment)). ' off)';
    }else{
        $display_price .= uc_currency_format(abs($adjustment));
    }
}


Show field collection fields with profile field I have used Recruiter module to manage job and resume and its working almost well but when i m displaying resumes it has field collection like Personal information which contain some field like name, address etc. and some normal fields. Now i want to show all of them in table.I tried field collection views but its showing all field collection data in single column called personal information with other fields.

Please let me know how i can do this....really struggling in drupal.

If I'm reading it correctly, you should be able to create a relationship based on your Field Collection field.

Under Advanced (this might be collapsed in the Views UI - it normally is by default) click relationship, and then click on the Field Collection field containing your user information.

Now you'll find when you go to add a field into your Views display, that there are more fields available to you.  These are the fields stored in the Field Collection entity that you can now style in a table, an accordion, a list...whatever you fancy!


TypeError: $.ui and $element.dialog is undefined I have been handed a site to work on. It's on 8.5.1. The site was working. However, I cannot make changes on certain configs. For example, the dialog boxes for the views do not open anymore. I keep getting the following js error under the console.

I do not want to revert the database back to a working condition since the client would lose their data.

Update: The dialog box does work very very random.

Thank you everyone for helping.
I informed of the senior development of your suggestions. He was able to find the issue. Font Awesome module was installed incorrectly, he also updated to the latest core. We've uninstall Font Awesome and migrated to using Font Awesome CDN.


Using theme_get_setting getting empty value I am using theme settings in my Drupal 7 theme to provide a theme option as follows.

$form['mythemename_settings']['loaderImage'] = array(
  '#type' => 'fieldset',
  '#title' => t('Loader Icon'),
  '#collapsible' => TRUE,
  '#collapsed' => FALSE,
);

$form['mythemename_settings']['loaderImage']['loader_img'] = array(
  '#type' => 'file',
  '#title' => t('Upload Loader Icon Image'),
  '#default_value' => theme_get_setting('loader_img','mythemename'),
  '#description' => t("Upload your desired loader icon."),
);

I then use theme_get_setting('loader_img') to call the value of the setting, but it returns an empty value. I have also added settings[loader_img] = "loading.gif" in my theme.info file, but I am still getting only the empty value.

My intention is to add a Image browse button which can be accessed in the admin end  and can be changed time to time. I have uploaded the image but I couldn't find my image inside my projects. Do I need to set a path for the image to get uploaded?

Where are the values of the settings page get stored in the database? I checked my whole database but I couldn't find the value I saved.

Change the type of image input to managed_file. Check updated code below:
$form['mythemename_settings']['loaderImage'] = array(
  '#type' => 'fieldset',
  '#title' => t('Loader Icon'),
  '#collapsible' => TRUE,
  '#collapsed' => FALSE,
);

$form['mythemename_settings']['loaderImage']['loader_img'] = array(
  '#type' => 'managed_file',
  '#title' => t('Upload Loader Icon Image'),
  '#default_value' => theme_get_setting('loader_img','mythemename'),
  '#description' => t("Upload your desired loader icon."),
  '#upload_location' => 'public://images/',
);

Values of theme settings are stored in variable table. Check theme_<THEME_NAME>_settings under name column & value is stored as serialized array in value column.
Update 1
To get file object use following sample:
$file = theme_get_setting('loader_img','tmhgs');
$file = file_load($file);


create tabs inside nody body I want to create tabs inside the node body and so I found the yui_tabview module but it only works in Drupal 6. Anyone know a module that works for Druapl 7?

Drupal has jQuery UI tabs built right in so you'd be better off leveraging that if possible. This is a standard theme function I chuck into most projects to help with this sort of thing:

function theme_tabs($vars) {
  if (empty($vars['items'])) {
    return '';
  }

  $js_added = &drupal_static(__FUNCTION__, FALSE);
  static $delta = 0;

  if (!$js_added) {
    drupal_add_library('system', 'ui.tabs');
    drupal_add_js("jQuery(document).ready(function(){ jQuery('.tabs-container').tabs(); });", 'inline');
    $js_added = TRUE;
  }

  $tabs = $content = '';
  foreach ($vars['items'] as $key => $item) {
    if (isset($item['#access']) && !$item['#access']) {
      continue;
    }

    $tabs .= '
' . $item['title'] . '
';
    $content .= '
' . render($item['content']) . '
';
  }

  $delta++;

  return '
' ."
$tabs
$content
";
}

You would call it like this:

$tabs = array(
  'tab1' => array(
    'title' => 'Title for tab 1',
    'content' => 'Content for tab 1' // Note this can be a string or standard Drupal render array
  ),
  'tab2' => array(
    'title' => 'Title for tab 2',
    'content' => 'Content for tab 2'
  ),
  // etc.
);

$args = array('items' => $tabs);
print theme_tabs($args);

Of course if you're doing this 'properly' you would register the theme function in a module like so:

function MYMODULE_theme() {
  return array(
    'tabs' => array(
      'variables' => array('items' => array())
    )
  );
}

and call it like this instead:

print theme('tabs', array('items' => $tabs));

Hope that points you in the right direction.


Remove superfluous divs from views fields output? I've set the Wrapper HTML Element option to none, and removed any wrapper divs in the templates presented in Theme Information, but my image fields are still getting wrapped in plain divs.

There are several ways to strip HTML. You can under rewrite results Strip HTML tags or under style settings Customize the HTML. If you have tokens enabled you can exclude a bunch of fields then add a Global text markup field. Most of the wrapping markup will be removed and you can use the your own markup or not by typing HTML into the Global text field placing the placeholder tokens where in the HTML the field should be rendered. Another way to clean up Views markup is to create override theme templates by clicking on theme templates for the theme override template title and copying the default code changing anything you don't want in them before you save.


How do I change total number of rows in a view programmatically? I had to remove manually some rows from a View programmatically for a lot of good reasons, too long to explain. I did it removing item in the pre-render hook from the array

view -> result

It works fine, but the total number of items contained in the view is not changed. How can i change it programmatically? I tried changing

view -> total_rows

but it seems not to be enough. I saw a lot of total_items elements in the object view, and i think changing them would work, but there are 60 items like that, each contained in objects contained in arrays that are contained in objects and so on and i am not really sure how to change every element with that name, parsing the structure of the object view and changing every total_item with the number X instead of the number Y.

You're probably looking for the view::set_items_per_page() method, e.g.

/**
 * Implements hook_views_pre_build
 **/
function MYMODULE_views_pre_build(&$view) {
  if ($view->name == 'foo') {
    $view->set_items_per_page(10);
  }
}

That method updates both the instance var and the limit on the internal query that Views will eventually run.

Note that you need to make this change before the query is executed (i.e. in a pre build, not pre render, hook), or you'll get inconsistencies with pagers etc.


Integrating Authorize.net into Drupal I have a friend with a single page website that sells a single product. All he wants is an order form embedded on the one page that uses authorize.net. I can't find a single way to embed the form onto the website like I can embed a mailchimp form, for example. Do I need to set up an Advanced Integration Method to accomplish this? If I need to would it be easiest to do it though Drupal? And, what is the easiest way to do it through Drupal?

hook_menu

items['authorize-form'] = array(

  'title' => t('Pay via Authorize'),

  'page callback' => 'generate_authorize_form',

  'access arguments' => array('access content'),

  'type' => MENU_CALLBACK

);

Callback function to generate authorize form using Authorize.net SDK

function generate_authorize_form(){
    require_once 'anet_php_sdk/AuthorizeNet.php'; // The SDK
    $url = "http://YOUR_DOMAIN.com/index.php";
    $api_login_id = 'xxxxxxxxx';
    $transaction_key = 'xxxxxxxxxxxxxxxx';
    $md5_setting = 'xxxxxxxxx'; // Your MD5 Setting
    $amount = "5.99";

    ob_start();
    AuthorizeNetDPM::directPostDemo($url, $api_login_id, $transaction_key, $amount, $md5_setting);

    $output = ob_get_content();
    ob_end_clean();
    return $output;
}


7- Disable a block or edit it without access to the admin interface I activated php code in a block in the header, and I put "echo $user;" instead of "echo $user->name;".

Now I get an error on page load and can't edit the block to correct the mistake.

If I could change the active admin theme back to bartik, that would also solve the problem.

Any ideas welcome. Thanks

Edit: ok I think I solved by deleting my custom theme folder. Good that the block was only enabled for the custom theme.

If you have devel installed, you can edit the default theme by editing theme_default variable.
http://yoursite.com/devel/variable/edit/theme_default

Or deactivate the block in your database

update blocks set status = 0 where delta = 'block';


Categorised Multiple File uploads within a page in Drupal 7 I have a situation where I have to upload multiple files within categories. This can be explained by the following picture.
As you can see I need to upload multiple files, but also need to categorize them. Each category has different files and even though below picture shows the same name of the files, they are not shared. How can I do it in Drupal 7. Any idea?
Thanks

Assuming you want all of these attached to one node and the categories need to be dynamic, I'd use field collections where each category is a field collection item which has a title field and a multi value file field.


Display Suite module is not displaying field labels I am using the Display Suite module (version 7.x-1.9) and Drupal 7.37.

I selected above or inline in the Label column for all the fields, but I don't see the labels on my page for any fields.

I also don't see the display suite tab when I try to edit the page. If I want to change the layout, I have to go to admin > module > ds > configure to change the layout.

Can anyone help me workout what's happening?

The page you see is from the "Default" Manage Display. Make sure you use this instead of others. The Display Suite layout is based on per content type, not per node. To change the Default display, you should go to "Structure > Content types > Your content type > Manage display" or "Strurture > Display Suite > Manage display(your content type)".

=== Update: June 25, 2015 at 8:37am - screenshot for @Kaimei Wang ===


Conditional e-mails based on radio buttons Drupal Webform I've built a form at http://dev.vies.dk/tilmelding. In the backend, it is easy to send e-mails to people filling out the form.

However, I need to send additional e-mails to other people based on some of the answers in the webform, namely the subjects they choose and the sex they have.

Subject         Female       Male
Soccer          mail@mail.dk mail@mail.dk
Handball        my@mail.dk   your@mail.dk
Kayak           mail@mail.dk mail@mail.dk
Dance           be@mail.dk   eb@mail.dk
Biking          sv@mail.dk   ls@mail.dk

Is there a hook, where this can be programmed, so I can achieve what I want?

Yes, you want to use hook_mail_alter() in a custom module. This will intercept the outgoing email from Drupal and allow you to add programming logic to the process. For example you could:

Load the webform in question and view its results.
alter the to value of the $message to meet your needs.

  'to': The address or addresses the message will be sent to. The
  formatting of this string will be validated with the PHP e-mail
  validation filter.


Entity Reference returns blank I have a content type where users upload a file. An administrator then uses a select list which is an Entity Reference that assigns the node to another user with a specific role. They do there work on the file and upload their work. The issue is, when the second user saves the node the entity reference gets blanked. Using version 7.51
How can I insure that the field stays populated through the whole process?
Thanks

Try using the Field Permissions module and only allow admin to edit and view value for the entity reference field.


Adding ajax to a date field Anything I could find related to this question was for Drupal 7.

I am building a form that needs to perform a certain ajax function when a date is selected. I have built my form to work similarly to the "Form API Examples - Ajax Form Example" part of the Examples module.

To test, I set it up so that, like in the example, when this Select element is changed it triggers the function "dateCallback":

$form['dropdown'] = [
    '#title' => $this->t('Test'),
    '#type' => 'select',
    '#options' => ['option1' => '1', 'option2' => '2'],
    '#ajax' => [
        'callback' => '::dateCallback',
        'wrapper' => 'log-wrapper',
    ],
];

This executes perfectly.

However, when I try to set up a Date element to do the same function, nothing happens. No Ajax spinner, just nothing happens at all.

$form['date'] = array(
    '#type' => 'date',
    '#title' => t('Date'),
    '#ajax' => [
        'callback' => '::dateCallback',
        'wrapper' => 'log-wrapper',
    ],
);

It does not work even if I include 'event' => 'onchange' in the #ajax array.

Is it possible to make ajax functions trigger on a changed date field?

After some more searching I found a patch for this issue here: https://www.drupal.org/node/2781103

Seems to be working for me in Drupal 8.2.6. I did have to restart apache before it started to work, maybe a cache clear was all I needed for it though.

Not sure if I should accept this answer since it may become quickly outdated.


Use Image Styles with remote images? I have a set of images on a separate host, images are available by a URL. I would like to render one of these using Drupal's image styles, but I note that theme_image_style says it won't work with remote images.

Is this possible some other way?

I would like it to use Drupal's caching (so it doesn't fetch the original image every time).

There's a module for that.

Imagecache external


Drupal Home page permission I forbid content access to all user that are not connected. The problem is that Drupal prevent also the access of the main page (And I want that an anonymous user will be able to see it..). How can I separate the main page access to the other content of the site ?

Thank you

This question was asked on the Drupal forums here.

If your frontpage is a node you can control access using the Content Access module.

If your frontpage is being generated by a custom module then you can do it by modifying the hook_menu implementation in your module. You can change the access_callback to the value TRUE so that everyone can access that page. See this related question

  "access callback": A function returning TRUE if the user has access
  rights to this menu item, and FALSE if not. It can also be a boolean
  constant instead of a function, and you can also use numeric values
  (will be cast to boolean). Defaults to user_access() unless a value is
  inherited from the parent menu item; only MENU_DEFAULT_LOCAL_TASK
  items can inherit access callbacks. To use the user_access() default
  callback, you must specify the permission to check as 'access
  arguments' (see below).

See the full documentation here.


Drupal Commerce Entity Query Line Item Prices I'm working on a Drupal module that needs to access the line items in a Drupal Commerce Shopping Cart. On most carts, there is a "line items" table of some sort that is linked to the cart via an unique cart id.

However, Drupal Commerce uses "Entities" which effectively obfuscate the relationship between the shopping cart id, the line items, the products and their prices. If you've played around with it at all, then you understand my pain when seeing the "revision" tables and how the data could exist in one of a dozen tables and requiring complex joins that would break if (when) the client upgrades their Commerce module.

I know there is a way to query entities, but I haven't found adequate explanations for using those queries with Drupal Commerce to allow me to pull line items and pricing from a cart. I keep running into Ubercart documentation which is close, but doesn't use entities.

Does anyone know where there is documentation on doing Entity queries (particularly with Drupal Commerce)? Better yet, do you have a query in your pocket that can pull cart contents, and line item pricing?

You can use Entity API that provide  a unified way to deal with entities and their properties, please read README.TXT there. Handbook is poor.


How do I set the title tag for the maintenance page? I need to change the default title tag for the maintenance page, which currently is "Site under maintenance | [sitename]".

I tried to set $variables['head_title'] in hook_preprocess_maintenance_page() but it doesn't work.

Also I think it can be set in hook_preprocess_html(), but I don't know how to check the served page is the maintenance page.

How can I achieve this?

TEMPLATE_preprocess_maintenance_page changes only variables for maintenance-page.html.twig. But <title> is outputted in html.html.twig, so you have to choose another preprocessor template_preprocess_html. So you can use this code(don't forget to clean cache after it):

function mytheme_preprocess_html(&$variables) {
  $maintenance_mode = \Drupal::state()->get('system.maintenance_mode');
  if (!empty($maintenance_mode)) {
    $variables['head_title'] = (string)t('My Custom Maintenance Title');
  }
}


One click upload setting not able to save I want upload file enable to upload image from my system for that i have installed ONE CLICK UPLOAD plugin for drupal and using Ck editor. now i have to change preference setting for upload button but when i changed toolbar buttons its not saving my changes and i am not able to add that upload button to my editor. please guide if anybody has any solution. my setting path for drupal ch editor is:: module > ck editor > edit/config > Editor appearance

why don't you use drupal image field for this. You can use add multiple image with drupal core cck image or you can install contrib module multiple image widget. You can be use to display on page or using views can be display.


Redirect with ? in URL - Drupal 7 I have Domain Access instaled, but not very sure if that is the problem: I have several domains under the same installation. It all works perfectly, but when I try to enter www.example.com/?q=user, it only works for some of the domains, for others it redirects to the home, and this causes other problems.

I have revised .htaccess (even installed a fresh copy), I have seen in the database, and cannot trace the problem, which is completely consistent. When using the same config in localhost (home PC), the problem is not found, so there is some incompatibility that came accros the project.

Any suggestion? I have Clean URLs switched on, but because it depends on any domain config, I cannot be sure because don't know where it stores the data, apparently it does work perfectly (don't understand ? in a content node, for example).

I have discovered the problem. It is a malfunction of module or submodule Domain Locale. If you have a domain whose list of languages does not contain your default language (main site), then it doesn't work. All the project to the trash, months of development ruined.


Add textfield to system branding block form to specify link URL I would like to alter the branding block to add a textfield in the block form to specify the URL it should redirect to. The URL is currently fixed to <front> in the Twig template.

What I've done so far is to add the text field with hook_form_alter. I'm saving the value using $form['entity_builders'] and $block->setThirdPartySetting. This works.

I want to retrieve this value in hook_preprocess_block__system_branding_block(&$variables) but $variables does not contain the block entity. How can I get the block in this preprocess function so that I can load my added value with $block->getThirdPartySetting?

A different approach: You can override the system branding block template via the block--system-branding-block.html.twig file (instead of using a preprocess hook).

On a Bootstrap theme, block--system-branding-block.html.twig looks like this:

{% block content %}
  {% if site_logo %}
    <a class="logo navbar-btn pull-left" href="{{ path('<front>') }}" title="{{ 'Home'|t }}" rel="home">

  {% endif %}
  {% if site_name %}
    <a class="name navbar-brand" href="{{ path('<front>') }}" title="{{ 'Home'|t }}" rel="home">{{ site_name }}
  {% endif %}
  {% if site_slogan %}

{{ site_slogan }}

  {% endif %}
{% endblock %}

You can alter the href of those links to point anywhere you'd like, for example:

<src="{{ site_logo }}" alt="{{ 'Home'|t }}" />


name of last person who modified node - Display suite with Display suite in Drupal 7 I can get the last modified date , but how can I display which user did the last modificatioin?

The easiest way to see who did the last revision is to, well, enable revisions for that content type and require them. This won't help you with past edits, but going forward, every edit will create a new revision, which will have a user associated with it, so you can see who made the last edits.


Rewrite Views field result using code How do I rewrite views field result programmatically? I want to change the link basing on another field value.

I have a field called room typ,e which is a reference to taxonomy terms (Bedroom / Meeting Room). The second field is the node ID, which I want to use to give the link of the page (there are two different page: Enquiry and Booking). If the selected term is Bedroom, I want to link the Booking page; if the selected term is Meeting room, the link should be Enquiry. I want to change the link text for Meeting room: It should be Enquire Now and Book Now.

You could add news fields to your vocabulary for the link text ('Enquire now') and for the href ('Enquiry')

You'll add these new fields to your view, and then you will be able to format your link like nandhana said.
And the reference will do the rest ...

But be sure that the 'nid' is the lower field among all others, so that you can access to all others fields


how to use images uploaded to public:// with a form I've got the possibility to upload images, this is the piece of code that says where the files go: '#upload_location' => 'public://',

this is the piece of code which generates the rows in my table view:

$rows[] = array(
        'data' => array(
            l($node->id, 'node/'. $node->id),
            $node->url,
            $node->title,
            $icon = "icon'>",
            $node->created,
            $delete = "id/delete'> " . t('Delete') . " | id/edit'> " . t('Edit') . ""
        )
  );

notice '$icon'. $node->icon returns for example usa.gif. But of course the path is invalid.

The question is: how can I use my images? I cant figure it out

There's probably some drupal way to do this, advice is highly appreciated!

If $node->icon is the path relative to public://, then you can use the following code.

if ($wrapper = file_stream_wrapper_get_instance_by_uri("public://{$node->icon}")) {
  $url = $wrapper->getExternalUrl();
}

The code works also for stream wrappers that are not local, for which the file is not local to the server running the code.


How do I update the unit price of an order item on Add to Cart in Commerce 2.x? I added an event subscriber for add to cart event. There I defined a function to react on add to cart event. Everything works fine as my eventsubscriber is being called. I want to update the unit price of product which is being added to cart. Below is the code I used but it is not working. Price of the product is not updating to the price I am setting.

public function updateProductPrice(CartEntityAddEvent $event) {
    $unit_price = new Price('15.00', 'EUR');
    $event->getOrderItem()->setUnitPrice($unit_price,TRUE);
  }

I have tried with both overide TRUE and FALSE but nothing works.

I managed to update the price by updating the order item of order rather than the order item in event.

$items = $event->getOrder()->getItems();
foreach ($items as $key => $item) {
    $currencyCode = $item->getUnitPrice()->getCurrencyCode();
    $unit_price = new Price('20.00', $currencyCode);
    $item->setUnitPrice($unit_price,TRUE);
    $item->save();
}


What is the purpose of the user_data table? I'm using Drupal 8 and I wonder what the purpose is of the user_data table? How can I can store custom data in that table? In my site, the content of that table is the following.

This table is the backend for the User Data service. The User Data service is used to store data specific to users in the system.

You can set data like this:

\Drupal::service('user.data')->set($module, $uid, $key, $value);

Where:

$module = the machine key of your module

$uid = the UID of the user for whom data should be retrieved

$key = a key to identify which data you are storing

$value = the value to be stored

This data can be retrieved with the get() method:

$value = \Drupal::service('user.data')->get($module, $uid, $key);

$value will be equal to the $value you used when setting the data.


What is an allternatve approach to many fields in an entity? I have an entity bundle 'A' that has about 30 fields in it.
This is probably affecting the page load performance of any view requiring to load these entities.

As an alternative, I was thinking about putting a number of the entity fields in a separate entity bundle 'B' which is connects the entities to bundle 'A' with an entity referenc field.

Would that improve performance or is there a better solution.

Like Clive said, testing would be the definitive answer. But if you look at the mysql queries that will have to be executed behind the scenes, I'm pretty sure you'd find that your bundle A with 30 fields will be simpler and faster than the bundle B option. You can use the Views Show Query module to output your view queries in both scenarios and compare them. In bundle B option, I'm pretty sure the mysql query will have to not only look up all of A's and B's fields but also look up the relationship between A and B bundles, an expensive additional JOIN.


Display webform results I want to display webform submitted data in a view. How to recover submissions of my webform in a list?

I think that I can use hook_views_query_alter to change my view's query.

If that's right, how can I implement it?

Any idea please? Thank you!

Yuu can use https://www.drupal.org/project/webform_mysql_views to display submission.

For More info you can visit : https://knackforge.com/blog/sivaji/displaying-webform-submission-data-drupal-views


How do I get information about the payment method from the order object programmatically? I'm trying to do some different processing after an order is placed depending on which payment method a customer uses.

In my EventSubscriber, I have the following code:

 public static function getSubscribedEvents() {
    $events = [
      'commerce_order.place.post_transition' => 'onPlaceTransition'
    ];
    return $events;
  }

  public function onPlaceTransition(WorkflowTransitionEvent $event) {
    $order = $event->getEntity();

Now I want to get the name or id of the payment method that was used from the order, but when I used kint($order) I couldn't find a way to access the payment method.

How do I access the payment method given an $order object?

The Commerce Payment module adds the payment_method base field when it is enabled, see commerce_payment_entity_base_field_info https://github.com/drupalcommerce/commerce/blob/8.x-2.x/modules/payment/commerce_payment.module#L28

You can access the payment method (and gateway) through

$order->get('payment_method')->first()->entity
$order->get('payment_gateway')->first()->entity

Example of when we get the payment method label for the order receipt email.

if (!$order->get('payment_method')->isEmpty()) {
  $variables['payment_method'] = [
    '#markup' => $order->get('payment_method')->first()->entity->label(),
  ];
}

From https://github.com/drupalcommerce/commerce/blob/77b25bf4889a940eed6652475c3952c36144efc0/modules/payment/commerce_payment.module#L122


Can I use fewer modules for implementing my newsletter? I came across a Drupal 7 site that combines following modules to send a newsletter for contact-form users (till now 6000 people subscribed): "Simplenews", "Mail system", "Mime mail", "simplenews rules", "variable email", "HTML mail" & "Rules".

I think this whole combination of 7 (or even more) modules is a wired solution.

Shouldn't only the modules "Newsletter' and "Webform" be enough?
If I move to a more minimalist solution, how could I save all the 6000 or so leads?

I think that with 6000+ emails to send you need to use an external mailer like MailChip or MailUp. Remember that these services have the correct infrastructure to support massive send email and dashboard report.

We have written a module for 1 of our clients that permits to create NewsLetters in Drupal and send it via MailUP for example.

However 7 modules to send an email are not a big number because in Drupal each module exec a single work:

Simplenews is the module that manages the newsletter (user subscribe,
unsubscribe, check, etc etc).
Mimemail, htmlmail and Mail system permits to create correct HTML
email and send it in correct way. And in this case you can reuse all
for the internal mail (wellcome, lost password, etc.).
Rules manage "the" rules of sending email (in this case).

In other systems you have a big module that manages all but not so good like single modules for single works. And in many cases the big module is not compatible with other modules. In Drupal I have found only very few cases where a module is not compatible with other modules.


Programmatically set the value of a date/Time field I am trying to copy the value of a Date/Time Webform element to a Date/Time field set on the article node.

Below is the source code of the Date/Time Webform element:

expiry_date:
  '#type': datetime
  '#title': 'Expiry Date'
  '#title_display': before
  '#required': true
  '#required_error': 'You must add an expiry date'
  '#date_date_format': ''
  '#date_year_range': '2019:2100'
  '#date_time_format': ''

Below is my custom handler:

// Get an array of the values from the submission.
    $values = $webform_submission->getData();

    // Get 'Expiry Date' Value.
    $ExpiryDate = $values['expiry_date'];
    date_default_timezone_set('UTC');   // Sett the time to 'UTC' time zone.

    // Format the "Expiry Date" to return "Y-m-d\TH:i:s".
    //$FormattedExpiry = date('Y-m-d\TH:i:s', $ExpiryDate);

// Create a new "Article" node.
    $article = \Drupal\node\Entity\Node::create([
        'type' => 'article',
    // Set the node field values.
        'title' => $Title,
        'langcode' => 'en',
        'uid' => $CurrentUid,
        'status' => '1',
        'created' => $current_time,
        'field_expiry_date' => $ExpiryDate, // $FormattedExpiry,
        ]);

// Save the created node.
    $article->save()

But I am facing the below error:

Drupal\Core\Database\DatabaseExceptionWrapper: SQLSTATE[22001]: String data, right truncated: 1406 Data too long for column 'field_expiry_date_value' at row 1: INSERT INTO {node__field_expiry_date} (entity_id, revision_id, bundle, delta, langcode, field_expiry_date_value) VALUES (
:db_insert_placeholder_0, :db_insert_placeholder_1, :db_insert_placeholder_2, :db_insert_placeholder_3, :db_insert_placeholder_4, :db_insert_placeholder_5);
Array (
[:db_insert_placeholder_0] => 84
[:db_insert_placeholder_1] => 88
[:db_insert_placeholder_2] => article
[:db_insert_placeholder_3] => 0
[:db_insert_placeholder_4] => en
[:db_insert_placeholder_5] => 2021-05-25 11:26:02 +03:00
)
in Drupal\Core\Entity\Sql\SqlContentEntityStorage->saveToDedicatedTables() (line 1414 of /home/username/public_html/example.com/web/core/lib/Drupal/Core/Entity/Sql/SqlContentEntityStorage.php).

The expiry_date from webform return something like 2021-05-25 11:26:02 +03:00 so you should to format it before you passe it to create like the following:

// Get 'Expiry Date' Value.
$ExpiryDate = $values['expiry_date'];
// Format the "Expiry Date" to return "Y-m-d\TH:i:s".
// Here use strtotime to format date correctly
$FormattedExpiry = date('Y-m-d\TH:i:s', strtotime($ExpiryDate));

Then passe $FormattedExpiry instead of $ExpiryDate:

$article = \Drupal\node\Entity\Node::create([
    'type' => 'article',
   // Set the node field values.
    'title' => $Title,
    'langcode' => 'en',
    'uid' => $CurrentUid,
    'status' => '1',
    'created' => $current_time,
    'field_expiry_date' => $FormattedExpiry,
    ]);

Update: your date already has +3h, if you want to not add 3 hours to your time there is two options i guess:

Change you webform field settings to work with UTC to get the value of $values['expiry_date'] something like 2021-05-25 11:26:02 without +03:00
Remove the +03:00 before date conversion from $values['expiry_date'] by change the line $ExpiryDate = $values['expiry_date']; with something like:

$ExpiryDate = explode('+', $values['expiry_date'])[0];


/index.php/ appearing in generated clean URIs I have a Drupal 8 site with clean URLs. Recently, URLs are similar to example.com/index.php/page-url-alias. The page still loads correctly, but I don't want the index.php part to be indexed.

If I empty the cache, the URLs are shown correctly.

How can I force Drupal not to add index.php in the URLs it generates?

In D7 Global Redirect was used for clean urls. In D8 this was moved to the module Redirect.

The global redirect options in Redirect are set by default to avoid unclean urls:


Splash page for drupal 7 website i need to put a splash page with flash intro.

I have already a front page with the name page--front.tpl.php and how can i put a new splash -page before this home page.

The new splash page will be a simple html page with a flash intro to navigate to the website's home page.

Any suggestion.

....

I would recommend to take advantage of jQuery over Flash. As Mohammed suggested, you could try the TinyBox module.

But, the other option is the Splashify module:

  Display a splash page anywhere on your site by redirecting the user,
  showing a lightbox, or displaying a popup. This module is designed to
  be search engine friendly, mobile device friendly and offers multiple
  configuration options.


Adding a button above rendered output from a contrib module What I'm trying to do is add a button above some content that's being outputted by a contrib module (Search Api Saved Searches) .

Can I do this with hook_page_alter, if so how can I add this new render to the $page[content][system_main] .  If not what hook would be best to solve my problem.

Many thanks.

If you are already using Display Suite or would like to use it, there is an area to create custom fields and display them within your node. You can use tokens and html.

Here is a good video.


How do I implement a sub-module? I can't find anywhere documentation on how to create a sub-module inside a module in Drupal 8. I have created a custom module for translations I am trying to enable as sub-module.

In the main module, can I simply create a sub_modules folder and place my sub-module, including the submodule.info.yml file and the translations folder? I'm guessing I have to add something into my mainmodule.info.yml file but I have not found anything to help me.

Drupal doesn't have the concept of sub-modules. It just happens that it looks for modules in the directories where it expects to find modules, recursively. For example, if you install the CAPTCHA module, Drupal will find also the Image CAPTCHA module, and allow you to install it.

Drupal will not install it automatically, nor will it handle it differently from any other module. This means, for example, that the module still needs to declare its dependency from the CAPTCHA module, if it requires it, which is what the Image CAPTCHA module does in its image_captcha.info.yml file.

name: Image CAPTCHA
type: module
description: Provides an image based CAPTCHA.
package: Spam control
core: 8.x
dependencies:
  - captcha
configure: admin/config/people/captcha/image_captcha

Usually, developers put any "sub-module" in the modules directory, but this is not required from Drupal, nor is it followed by every developer.


Where does Drupal save the trim length for the body field? When I navigate to Manage display for any node type that has a standard body field and click on the Teaser tab the default format will be "Summary or trimmed". The default trim length is 600 (characters), but you can change it to whatever you want and Save the new value.

However, I want to know where (i.e. in which table or variable) this value is saved.

(I need this information in order to find out what trim length to use when comments are emailed to users that subscribe to comment notifications. The project specification requests comment notifications to be trimmed to same length as the content type they're attached to.)

In Drupal 7, field settings are saved into {field_config_instance} and {field_config} database table.

Trim length for a body field is saved in the data column in the {field_config_instance} table.  The data column is stored in BLOB format, so you are not able to see the value of this.

You can use the field_info_instance() function to extract information about a particular field in a particular entity bundle/type:

$body = field_info_instance('node', 'body', 'page');
print_r($body);


How to debug ajax in form? I have a form that uses ajax submit "method", the ajax submit handler returns ajax response with complete form(the form has ajax wrapper outside of itself so no issue there) and it is not working for anonymous users. I am using dynamic_page_cache only at this point.

I am displaying this form via field formatter that I have on an entity(imagine comment form) and I am using lazy builder.

The thing is that the form works for anonymous users if there are multiple forms like this on a single page(imagine taxonomy term page listing entities) but it is not working when there is only one form(entity page..imagine node/1). By not working I mean the form will submit but not with ajax but traditionally via normal post method.

I have checked the form structure, wrapper, drupalSettings.ajax entries, JS errors, watchdog..everything, but I just cannot figure out why the form does not utilize ajax but will submit as normal form instead. I have compared loaded JS with anonymous and logged in user, nothing significant there. The only thing that I have found that differs is missing form_token input in the form compared to logged-in user but I have checked the FormBuilder and this is on purpose + when I'm listing multiple entities with this form the ajax works just fine without it.

And so since there are no errors anywhere I have nothing to grab on to for debugging.

So my question is how could/should I try to debug this issue?

This question is a follow-up from Does caching has to be manually disabled for ajaxified forms?

Eureka!

So, I still am not sure what the issue was 100% but I am guessing that there was a name collision with multiple different forms and since Drupal uses name "op" for every submit button since the dark ages of the internet I guess the ajax was trying to get itself applied to the other form that had submit button as well(named op as well) but that did not work of course so that resulted in this weird behavior.

So the way I have fixed this was by setting the #name AND #id attributes on the submit button in my form. I have set the #id which I normally don't do in ajax forms because I would get wrong drupalSettings.ajax entry.

I didn't do this in the first place because the form was working just fine for logged-in users + just fine for anonymous users on entity listings so it didn't made any sense but hey, the more you know.


Add specific CSS class to form elements from the address field I try to add a custom css class to a form element inside my address field for e.g the postal_code field and another class to the given_name and family_name field.

I tried it with a my_theme_theme_suggestions_form_element_alter. But then I have to extend all the twig files like form-element--equal-width-column.html.twig, for just adding the css class.

function my_theme_theme_suggestions_form_element_alter(array &$suggestions, array $variables, $hook) {

  if (in_array($variables['element']['#attributes']['class']['0'], ['family-name', 'given-name'])) {
    $suggestions[] = $hook . '__equal_width_column';
  }
}

Is it possible to just add a css class to specific form-elements div's, so I don't have to extend all those twig files?

You can use the hook_form_FORMID_alter in order to add classes to the fields you want to.

/**
* Implements hook_form_FORM_ID_alter();
*/
function hook_form_FORM_ID_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {
  $form['my_custom_field']['#attributes']['classe'][] = "my-custom-class"
}


(search) form without redirect or submit handler Use case:
Search field e.g. in the header, that leads to a url with GET query string.

The usual flow of forms built with Drupal 7 form API is like this:

User visits a page with the form.
User submits, $_POST or $_GET
Validate + submit handlers are called
Redirect to a new page.

What i would like instead:

User visits page with the form, that was built with form API.
User submits, resulting in a $_GET request, e.g. example.com/search?query=foo+bar.
The page example.com/search?query=foo+bar is served, without thinking about form API.

So, I want to use form API to build the form HTML (cause it's convenient), but not any submit magic.

Ideas?
Maybe I could find an example in existing modules, but I am looking for a "big picture" or documentation.

Not sure what you're exactly asking but everything should be well documented on Form API

I've recently done a form like this so I can give you an example of a GET method form:

/**
 * Form function for iwm_collections_search_form block
 */
function mymodule_search_form($form, &$form_state) {
  $form['#action'] = url(MYMODULE_SEARCH_PATH);
  $form['#method'] = 'get';
  $form['#attributes'] = array('class' => array('form-main'));
  $form['#after_build'][] = 'mymodule_search_form_after_build';
  $form['query'] = array(
    '#type' => 'textfield',
    '#title' => t('Keywords'),
    '#default_value' => '',
    '#size' => 30,
  );

  $form['submit'] = array(
    '#type' => 'submit',
    '#name' => '',
    '#value' => '',
    '#attributes' => array(
      'class' => array(
        'submit',
      ),
    ),
  );

  return $form;
}

You need an #after_build function to remove the unnecessary hidden fields so that it doesn't clutter the address bar:

/**
 * After build callback for mymodule_search_form
 */
function mymodule_search_form_after_build($form) {
  unset($form['form_token']);
  unset($form['form_build_id']);
  unset($form['form_id']);
  return $form;
}

No javascript, no submit handlers, easy.


How to create a Category Article listing with subcategories? I am new to drupal 7 and I want following page:

  Main Category

  (1) Subcategory1
    - post1
      Details
    - post 2
      Details
  (2) Subcategory2
    - post1
      Details
    - post 2
      Details

How can I do that? I think I can use Views but I need some further details.

Drupal Taxonomy is used to Categorize Content... Please have a look @ detailed tutorial here how to use taxonomy concept in Drupal to create categories and tag contents with categories.

You need to use views module to display the content by category.

Hope it helps.


Setting up remote drush aliases for aegir I have an aegir platform and I need to set up a drush alias file for all of the sites for our developers. I can't seem to figure out the best practice to do this. Normally we would set our 'remote-user' and that user would have access to drush but on aegir, drush is limited to the aegir user. I've follow these instructions http://community.aegirproject.org/node/427 to make is so certain users can also use aegir but I keep getting 'drush needs a higher bootstrap' error.

I have considered just setting the 'remote-user' user to aegir and then useing passwd to set a password for the aegir user but I'm not sure what secondary effects that could have. Presently we just su as the aegir user when we need drush.

Am I approaching this the correct way or is there a better way to approach this problem?

In BOA you can create sub-accounts (clients) with access limited to only associated sites, plus SSH and Drush available both locally and over SSH, with Drush aliases for all associated sites automatically created and updated for you.


Using a file extension (.htm) in Views contextual filter path When I add a file extension after the contextual filter in my view's path it no longer works. The path with wildcard is: "section/%.htm"; can this be done or do I have to write some custom PHP to trim the URL of the file extension?

Please note that this is a legacy site which is rolling out section changes in phases, so there can be absolutely no URL changes while we convert the site to Drupal.

Why not use the redirect module (or just plain ol' .htaccess 301 redirects) to redirect /section/file.html to /section/file ?

I understand the client doesn't want URLs to change, but doing a proper 301 redirect would preserve any SEO rankings they are trying to retain.


Should I use separated servers? I have to use Solr to improve my customer search engine, on Drupal 7 website.

On the development environment, I've set Tomcat and web server on the same machine and it works, but I did not inject the whole content database. It contains about 25,000 nodes; I'm not sure if I need to deploy the SolR instance (Tomcat + Solr + configs) on a separated server, or if this won't be useful.

In terms of Drupal integration with solr or its performance it does not matter you host solr on same instance or not.

However, to decide you might want to consider following:-

Your server resources and its consumption: You need to evaluate if your server resources are well enough to serve the traffic on your website, since solr is going to share the same resources.
Maintenance of solr: Running solr instance will require some level of maintenance in terms of monitoring its running status, tweaking the solr  configuration as per your need, running it as background process.
Cost: Of course, it has cost implications hosting solr on separate instance or subscribing to paid solr hosting services will cost you extra bucks.

Hope that helps!


Why are routing files filled with underscores? What is the deal with all the parameters with, and without, a prefixed underscore character?

Where does Drupal decide how to process these parameters?

Was this concept introduced from Symfony, or is it new to Drupal?

Example (node.routing.yml):

node.overview_types:
  path: '/admin/structure/types'
  defaults:
    _controller: '\Drupal\Core\Entity\Controller\EntityListController::listing'
    entity_type: 'node_type'
    _title: 'Content types'
  requirements:
    _permission: 'administer content types'

Here comes a hopefully good explanation behind the idea of the routing system
as well as the drupal specific additions to it.

General overview

The Symfony components have two important concepts here. The http kernel is a system which gets the request, somehow ask other systems to produce to define the
piece of code which produces the requested output (a response object) and send the response back to the client. This piece of code is called controller,
so this can be either a pure php4 like function, a method on an object or even a anonymous function.

The system that knows which controller is responsible for the current request is the routing system.

Basic routing file

As module developer you define the list of routes and the corresponding controllers.

Here is an example for a json response:

taxonomy.autocomplete_vid:
  path: '/taxonomy/autocomplete_vid/{taxonomy_vocabulary}'
  defaults:
    _controller: '\Drupal\taxonomy\Controller\TermAutocompleteController::autocompletePerVid'
  requirements:
    taxonomy_vocabulary: \d+

Most symfony documentation mention pattern, but drupal decided to just allow the non-deprecated "path" key in its routing file.

The key concept is the controller which gets some parameters from the system
and converts them to the response. In this example you have the parameter
'taxonomy_vocabulary'. So everything without an underscore is considered to
be a parameter to the controller. If you want to specify a default value,
you put it into the defaults array. In the same yml array you
specify the class and method connected with '::' to tell the system where to look
up stuff. Every other property has nothing to do with the controller parameters
and so are considered to be internal and so have an underscore as prefix.

Symfony itself also allows you to define regular expressions to validate
that the incoming parameter is valid (using 'requirements'). Here it would match to only numbers.

Controller resolver

Once symfony found out which controller is active on the current request,
it asks the so called controller resolver to create an instance of the controller,
that can be executed via call_user_func_array. The controller resolver has one
method to get the controller callable (object + method, anonymous function)
and one method to get the parameters passed to the controller, see Controller resolver

Drupal extensions

This is basically what symfony gives you.

Drupal though is slightly more complicated:

You can check access to the route. For example calling user_access() was very common in Drupal 7 and below.
You don't want to convert the taxonomy_vocabulary to its actual entity object
You don't want to generate the full page response, but just the "main content".

Access check

Drupal has introduced a system on top of the symfony parts that checks whether
the user has access to the current route and alternative throw a 403 (access denied) exception. Access manager

In the routing file you specify this in the requirements part. The most common
bits are listed in the example:

  path: '/user/{user}'
  options:
    _access_mode: 'ANY'
  requirements:
    _permission: 'access user profiles'
    _entity_access: 'user.view'
    _role: 'administrator'

_permission defines a call to user_access(), _role ensures that the user has a certain role (you can specify multiple ones via , for OR and + for AND logic).
_entity_access asks the entity system whether you have access to view the user entity. Per default drupal ensures that you add access checkers allow you to proceed, but you can switch it in the options via the _access_mode.

Upcasting

As mentioned in the listing you don't want to take care about loading an entity,
see /user/{user} as example. For entities you basically just use the name of the entity type and it will execute a entity_load with the ID passed in the URL. Param converter manager

Page response

As written before the controller is responsible to generate the response object.
This would be horrible in Drupal as a page consists of so much more like all the blocks appearing in its regions, the html and page templates etc. Therefore drupal specified a different key to specify a controller which returns the content of a page:

user.page:
  path: '/user'
  defaults:
    _content: '\Drupal\user\Controller\UserController::userPage'
  requirements:
    _access: 'TRUE'

The string defined is the controller used to generate the render array for the main content region of your page.

Another addition is also the way how to deal with forms, as returning a page with a form is slightly
more complex than just a render array, so you can define _form with the FormInterface responsible for the current form.

user.pass:
  path: '/user/password'
  defaults:
    _form: '\Drupal\user\Form\UserPasswordForm'
  requirements:
    _access: 'TRUE'

Note: This covers the most important points from my perspective, though there are for sure many more points to talk about.

TL;DR

Underscores are specified for everything which are not parameters to the controller. This is coming as a sort of "standard" from symfony.
These parameters are upcasted via the param converter and passed to the controller using the controller resolver
Drupal has some additions to make it easier for people to interact with the symfony routing system.


Use the trans tag in Twig without escaping HTML I would like to use variables containing HTML inside a trans tag in my Twig template. (The variables contain the start and the end of a link which appears at different positions in the sentence for different languages.)

There is some documentation about "Drupal 8 Twig Templates and Translations" which explains that for variables inside the trans tag there is a |placeholder-filter and a |raw-filter (for older versions: |passthrough).

I see no difference in the output using these filters.
Here is my template:

{% set string = '&amp;' %}

  {% trans %}
    Escaped: {{ string }}
  {% endtrans %}

  {% trans %}
    Pass-through: {{ string|raw }}
  {% endtrans %}

  {% trans %}
    Placeholder: {{ string|placeholder }}
  {% endtrans %}

And here ist the output:

Escaped: &amp;
Pass-through: &amp;
Placeholder: &amp;

Is there any filter that will switch off escaping?

AFAIK the Twig trans tag in Drupal 8 was implemented to ease translations to themers that were already familiar with Twig.

Under the hood, it's working with the same kind of translation strings as the regular Drupal translation function t() or the Drupal Twig filter |t, whereas all variables you are using within the trans block are handled as @variable or %variable placeholder within the translation strings.

These placeholders within the translation function always escape HTML before being inserted to the translation. No matter how you try to not escape the values you pass in, except you pass in a FormattableMarkup object.

Unsanitized variables ({{ variable|raw }} in Twig templates or !variable in translation strings) are deprecated for Drupal 8 translations and won't work in latest 8.x Drupal versions. The translation API description is a little outdated.

For your use case, you may just add the HTML link tag to your translation string and make the link URL itself the variable. Unfortunately, the Twig trans tag doesn't support that kind of variable yet. (Compare this core issue.) So you should use the t filter instead:

{{ 'A link example in a translation.'|t({ ':url': url }) }}

The above example matches the translation strings:

en: A link example in a translation.

de: Ein Beispiel-Link in einer Übersetzung.


restrict blocks in multilanguages site I want create a multi language website, I have some problems,
according my search about menu link in multilanguage  drupal website ( I did this job in some year ago but forget it(because some personal life change I abandon drupal form 1 year) ) it is better to create  seperate  menu type and put them in menu block (with menu block moudle ).but I have some problesm,
first How can I restrict block  shows in only specify language , I want did it in cofiguration of block in pages section limit it by something like
en/*  but in front page of my two languages not work correctly,
please tell me how can I restrict blocks in languages.

You can use The Block languages module, part of the Internationalization (i18n) package allows you to configure for which languages each block is visible. The settings for visibility per language are provided under Visibility Settings via the Languages tab when configuring a block.


Ubercart Coupon - only allow one coupon per order, but always apply the most recently entered one Currently when someone adds a coupon to a cart which already has a coupon applied, we get the message "This coupon combination is not allowed", leaving the original coupon on the order.

How do we change that behavior so that newly added coupons get applied to the order, while the previous one gets deleted?  There is never a case in which two coupons would be allowed on an order.

The answer is very simple but will only work if you do not want to allow multiple coupons per order.

Visit /admin/store/settings/coupon and uncheck "Allow multiple coupons to apply to a single order"; Save the configuration.  Now the most recently applied coupon will be the only one added to the order.


How can I implement Schema.org on my Drupal 6 site? I can't seem to find a straight-forward answer to implementing this - http://googleblog.blogspot.com/2011/06/introducing-schemaorg-search-engines.html - on my Drupal site.

I've found lots of Drupal discussion about microformats, RDF and RDFa, as well as support for RDF in Drupal 7 core, but I can't find a module that will help me to take advantage of Schema.org in Drupal 6.

As a non-developer, how can I easily start to work with Schema.org on my Drupal 6 site?

Anyone coming across this looking for this in Drupal 7 (I know the question is for D6), see the Schema.org module. Using this module sites administrators can specify what schema.org terms they want to associate with their content types (e.g. Art Gallery, House, Event, Person, etc.) and their fields (description, participants, etc).

Although this project is syntax agnostic, the schema.org types and properties selected by the site administrator will be used as part of the native Drupal 7 RDFa markup.

You can also use the Microdata module. Microdata is a module which takes care of embedding schema.org terms in HTML per the microdata spec. Core does it via the RDFa 1.0 spec. There is a UI for schema.org in microdata so that it does not have to depend on other modules for the UI (Drupal core does not include such UI).