Date field as dynamic source for contextual filter I need a views block with a contextual date filter, based upon a date field of the currently viewed node.

What I've got so far:

I already have created my base view with base filters and sorting.
I've added a relation to the current node ("Get the actual content from a content revision")
I've added a contextual filter Content ID, using Content ID from URL as default value

But I don't want the current node in my views block, I need the next two nodes in my views block, and I don't know how to do this part of the contextual filter:

views_node.field_date > contextual_node.field_date

Concrete use case:

I'm displaying the full view of "event node A", and on that full view of node A, I want to embed a views block, showing the next two "event nodes B and C" after the date of event node A (for selecting and ordering nodes B and C I want something similar to this pseudo-query: select * from view_nodes where view_nodes.field_mydate > context_node.field_mydate order by view_nodes.field_mydate limit 2)

Use hook_views_query_alter to alter query filter based on current node id or created date of node and put limit 2.

Where clause will be Like:

nid > current_nid
created date > current node created date (this may create issue if we have imported node in bulk)

Also we can do it from contextual filter as well just add contextual filter for current node id, greater than current node id.


How to filter the values of an array in drupal In drupal we have check_plain function to filter the unwanted codes from a text, I have an array which I am storing directly, in that case, I need to check each value before storing, is there a function to which we can pass the array and it should filter and reset the array.

Ex - I have a form where users can add as many names as they want using (multiple textfield) the name of the textfield is - guarantors[]

So I have an array where all the userinput is there, inorder to filter, I need to filter each value of array using foreach.

is there a function or way, so that I can directly pass the array to a function and it should return me an array with safe values, i.e each values should be parsed using check_plain function.

I think an expample may help you answer better, here is my example array.

Array
(
[0] => Array
    (
        [keyword] => lucidus
        [color] => #00ff00
    )

[1] => Array
    (
        [keyword] => commoveo
        [color] => #998899
    )

[2] => Array
    (
        [keyword] => dolus
        [color] => #ff0099
    )

)

NOTE :: keyword and color are user input values. And those needs to be filtered, it is and can be a multidimensional array.

Many Thanks

This is an old question, but there didn't seem to be a decent answer yet...

There is no out-of-the-box solution but it's easy to write a function that recursively walks the array and applies a filter function to the keys and values.

<?php
function clean_array($array, $filter = 'check_plain') {
  $clean = array();
  foreach ($array as $key => $val) {
    if (is_array($val)) {
      $clean[$filter($key)] = clean_array($val, $filter);
    }
    else {
      $clean[$filter($key)] = $filter($val);
    }
  }
  return $clean;
}
?>

This also gives you the flexibility to use filter_xss or check_markup instead.

Hope that helps.


How to have one node's access dependent on another node's access? I've got two content types. One we'll call "company"; the other, we'll call "project".  Companies can have projects, managed by a field in the project.  Companies and projects can also have fields that determine their visibility; each of them can be marked "public" or "private".  Node access rules are used to control access to the nodes, based on the value of that field.  All of this is working fine.

What I'd like to do is make it so that, if a company is marked "private", all of its projects also become private, in the sense that people other than the company's owner get access_denied if they try to look them.  However, if the company's access is returned to "public", the access rights of the projects are restored to whatever their own visibility setting specifies.

Here's what works for me at the moment.  My concern is that it requires directly hacking the node_access table, which, aside from the fact that it works, bothers me...

Add two bits of code to the company's _node_access_records() handler:

When the company's visibility changes from public to private, for each of the company's projects: blow away the entries for the project in the node_access table and insert a "only the author can access" right.
When the company's visibility changes from private to public, for each of the company's projects: again blow away the entries for the project in node_access, but this time get the access rights for the project by calling its node_access_records() handler and insert the corresponding rights into node_access for that project.

Any other ideas out there, perhaps something that (in particular) avoids the direct hacking of node_access?

Create a custom module.

Use hook_node_view to run some code whenever a project node is viewed.

In that custom hook, find the company nid by looking at the field of the current node.

Then use node_load to get a node object of the company, check the company's access and then call drupal_access_denied if the current user does not have access to that company.


HTML escapes appearing in node titles on bespoke content type — substitutions? I have a bespoke Content Type pertaining to venues. These are not user-creatable; they are all created from importing a trusted third-party feed, which sanitised the titles before they come to me (so there's no risk of XSS or SQL Injection here). The titles might, however, contain accented characters (é, ô etc), apostrophes (') or ampersands (&); these are coming out as HTML escapes (so &#039; instead of an apostrophe, &amp; instead of an ampersand, etc).

The Content Type Venue has a field title, which is a Node module element, so doesn't allow me to mess with its display settings. In the Node template page, I can use substitutions in the display of this title, but I can't work out how to make it be the raw text version. The title is currently set to display as %node:title and I tried using %node:title:raw and %node:title-raw in case one of those would magically work, but they had no effect.

I saw something that looks like a potential solution at Custom HTML in Drupal Node Titles on zerotodrupal.posterous.com, which attaches to the hooks hook_preprocess_page and hook_preprocess_node, creating a new method like

function hhhdarkelegance_custom_title($node) {
    return check_markup(strip_tags($node->title, '<em><em>'));
}

but, while that blog post looks like it will work well for named HTML tags, I'm not sure it will necessarily deal with HTML entities, which are what my problem is here. I suppose I could do the opposite to the blog-post code and replace out &amp; to & before display, but that feels really kludgy and, frankly, it would be nice to be able to do this just using a substitution, if possible.

Is there some way of achieving this that doesn't involve cutting code? If so, is strip_tags what is causing the HTML escapes? (The function description reads as though it's only causing the removal of HTML tags, which I am fine with either way — they won't occur in my node titles. I am wanting to stop escaping the HTML escapes, however.)

So how can I (on a specific Content Type, without worrying about security concerns) prevent Node titles from rendering HTML escape characters to the usual and just write the damn output to the page?

I did scan through several pages of similar-looking questions before posting and I couldn't find one that addressed this, so my apologies if someone has asked this already; if you point me towards it I'll be suitably embarrassed and try even harder next time. Thanks for your help, everyone!

Whilst Jon's suggestion of htmlspecialchars_decode got me part of the way there, it turns out that the sample code from Custom HTML in Drupal Node Titles was less helpful.

Whereas that blog post suggested I do something like:

function modulename_preprocess_page(&$vars, $hook) {
    $node = &$vars['node'];
    if($node->type == 'my_content_type') {
            $vars['title'] = htmlspecialchars_decode($vars['title']);
            $vars['head_title'] = $vars['title'];
    }
}

I actually needed to do this:

function modulename_preprocess_page(&$vars, $hook) {
    $node = &$vars['node'];

    if ($node->type == 'my_content_type') {
        drupal_set_title(htmlspecialchars_decode(drupal_get_title()), PASS_THROUGH);
    }
}

Problem solved!


General architectural approach to Drupal for a project Apologies for the inspecific title, but my question is a relatively generic one!

I'm relatively new to Drupal, and because I've historically had a very different approach to CMS implementation, I think I may be missing the point of the architectural qualities of Drupal.

I'm a .NET developer who's used Umbraco and EPiServer a lot, but had limited experience in Drupal.

What Umbraco offers is a way for users to organise their content in the admin panel, such that items will happily sit in a tree structure under other items.

In the case that you have a news section, you would have the following structure in Umbraco:

News landing page
- News story 1
- News story 2
- News story 3

This hierarchical approach is also easily transferrable to organising other types of content, such as slideshows for a specific page. You could have a homepage which would consist of a slideshow with four slides in it, and that slideshow could be specific to that homepage. This would look like this:

Homepage

- Slideshow
+ Slide 1
+ Slide 2
+ Slide 3
+ Slide 4

In Drupal, I've noticed that all pages sit together in a sort of "page soup" as someone else coined, and an implementation of a taxonomy is relied upon to ensure that content is organised on the front-end.

I'm aware that Drupal offers a menu structure which allows you to form this structure, but it seems like if you want to organise actual content rather than memory references to content, you're a bit lost.

Another feature I found extremely useful in Umbraco is the ability to programmatically fetch page objects, and to have access to an API allowing me to get the children of that page, and display them within the markup the way that I see fit. The filesystem for this would look like this:

Homepage.aspx
- Slideshow.ascx

This allows you to drag that slideshow.ascx control onto any page, and the control will go and get the children of its parent, and display those slideshow items automatically.

Is all of this possible within Drupal? Am I missing the point entirely? I would love a bit of direction on this, as I've been floating around the general area of content for a little while now!

Thanks for any help!

This is a common grey area for new developers to Drupal. The root for every "page" is index.php. There is no "page" per se, every dynamically generated "page" is a container. Regions (found in either /themes/bartik/bartik.info file in Drupal 7 installations without any changes or additions to Drupal core yet) establish the sections of the container that you can add different types of content (i.e., blocks, menus, views, etal.) I would recommend reading about the bootstrap process for Drupal, it is during bootstrap that everything gets called on a url by url basis. Using the Drupal interface and adding modules adds ways to "generate" or "contain" different types of content. There are over 10,000 modules (and counting) to add functionality to the Drupal enviroment. There are, generally, a handful of recommended modules that provide the most cohesive and robust ways to develop almost anything within your Drupal site that are recommended.  This ultimate flexibility takes a little time to grasp and work with but once you do, you never want to go back.


hierarchical select to display taxonomy tree I need a similar module as hierarchical select to display taxonomy tree in my view because hierarchical select to drupal 7 doesn't work with views module.

Please help me !

ASSIGN $child to an select list just set taxonomy id :
$taxonomy_vid = 3;
   /*** A HEADACHE CODE :p arrange the parent child taxonomies****/
 /*      $tree_type =  taxonomy_get_tree($taxonomy_vid);   // taxonomy id here
    $childs["selected"]="Select a Value";
    //$childs[45]="New Launches/Projects";
    foreach($tree_type as $key =>$value) {
$temp_ = taxonomy_term_load($value->parents[0]);       //IF parent is set already
                if($value->parents[0]==0) {                   //if no any parent taxonomy
                        if(is_object($temp_)==TRUE) {
                        if(isset($childs[$temp_->name])) {  //if array key is already set
                                if(is_array($key)!=FALSE) { //if value is not an array
                                    $childs[$temp_->name][$key]=array($key=>$value->name);  // set the parent child array
                                }
                        }else {
                                if(is_array($key)!=FALSE) {    //if value is not an array
                                    $childs[$temp_->name][$key]=array($key=>$value->name);  // set the parent child array
                                }
                            }
                        }else
                        {
                            $childs[$value->name]=array();
                            $childs[$value->name][$key]=$value->name;
                            //drupal_set_message("-------<pre>".$value->name."</pre>-------");
                            }
                    }else {
                        //$temp_ = taxonomy_term_load($value->parents[0]); //IF parent is set already
                        $childs[$temp_->name][$key]=$value->name;       //$childs[$temp_->tid]=$temp_->name;
                    }
        }


How do I profile a site that is on shared hosting? I run a commerce website in a shared hosting, from time to time it's being too slow, I tryied many ways to find the cause (css/js agreggation,enable caching, views caching, disabling some big modules :update manager,database logging,l10n,i18n, disabling no used modules, setting cron job to never) without result.
I'm not an experienced php developer, and I want to profile my website, I know that I have to install some tools in the server, so I want to ask if there is a way to do that in my shared hosting.
fortunately I'm allowed to enable many extentions and change some settings in my cpanel, below a screenshot of what I'm allowed to do.

Two of the most important optimizations to consider adding to optimize Drupal web server performance for ecommerce are APC & Memcached.

With Memcached, you will need to install the Drupal integration module & make some edits to the settings.php file. (tutorial)

With APC, there is also a Drupal integration module, but you need to edit the php.ini file on the web server. (tutorial)

You can also see if your web host supports Zend Opcache on shared hosting. Otherwise make sure to run Drupal 8 on PHP 7.x settings & upgrade to NGINX, Varnish Cache, & Redis solutions for the best web server performance for ecommerce.


One time login redirect to password change page In D7, How can i redirect the user when he/she use One time login. My target is after clicking one time login button user has to redirect to change password. Can any one help on this.....

hook_form_alter can be used to add a custom redirect rule. Do it in your custom module.

function MODULE_form_alter(&$form, &$form_state, $form_id){
    if ($form_id == 'user_pass_reset'){
        $form_state['redirect'] = array('path/to/redirect', array('param' => 'val'));
    }
}


Render menu in twig template In admin/structure/menu I created a menu. Is it possible to render this menu (with machinename: my_menu) in a twig template? Somehow like:

{{ my_menu }}

Simplify Menu sounds like what you'd want.

  The simplify_menu module uses a TwigExtension to gain access to
  Drupal's main menu's (or any other menu for that matter), render array
  so it can be accessed from a twig template. Among the many advantages
  of having full control of the menu's render array in a twig template
  is the ability to customize the markup for your menus to ensure they
  are accessible and comply with standards.

// Get menu items
{% set items = simplify_menu('main') %}

// Iterate menu tree

  {% for menu_item in items.menu_tree %}

      {{ menu_item.text }}

  {% endfor %}

Otherwise, there are a handful of menu-* twig templates to use when rendering a menu from a block. Turn on your Twig debugging settings in Drupal to see what the suggestions are.

However, you need to have pretty good knowledge of menu theming to get it exactly right (like handling child items and not flat menu structure as the example above displays) - that said, I would stick to letting a block render out the menu in a given region. Then, inspect menu.html.twig from your base theme (either classy or stable) to get an idea of what your options are if you want to modify markup.

Be sure to use a decent twig template suggestion and not just menu.html.twig - as that will affect every menu that gets rendered by Drupal... it is the default template.

I would also suggest to install Menu Block as that will grant extra flexibility in theming and twig file suggestions. It also makes rendering trees of a menu (like section based navigation in a sidebar) a breeze.


Show metatags on node add/edit pages on custom theme I have a user role which can add/edit metatags (Metatag module) and when I allow overlay and admin theme access for that user role - everything is OK. But if they are editing/adding node from my custom theme for some reason they cannot see fields for metatags, only tab with the label "Meta tags". Same thing is with the URL alias, only tab. I'm not sure what can be the cause or am I missing something.
Thanks

Actually it was related to Bootstrap custom theme and vertical tabs. So fields where only hidden in my theme and it was a style issue. Nothing to do with privileges.


Delay in code changes on custom pages in drupal 8 in a docker environment There is a delay between saving code changes in a controller and being able to view them in the browser.

This is frustrating (to say the least) and makes it very hard to develop and debug module code.

I have tried setting up a development environment in docker and it's working quite well except for this nasty and unpredictable delay.

For a minimal example I tried installing the Hello World example module from the Prepare a Module skeleton guide.

My (minimal, but complete) setup is available here: https://github.com/glaux/drupal8docker.

To replicate the delay

Get the site up and running.
Log in as admin with pass 123 on http://localhost:8090
Navigate to /hello
Change the markup in the file /docker/project/modules/D8HWexample/src/Controller/HelloController.php
Refresh /hello - the changes will show up after between 5 and 300 seconds.

What I've tried

I've tried disabling all the caches by following the official guides. When making css changes to a custom theme (not included in the minimal repo above) the code changes are visible immediately, so this is not a cache problem I believe.

This is also emphasized by the fact that rebuilding the cache via the interface, drush and/or drupal console seems to have no effect on this delay.

In a similar manner I've tried disabling the browser cache (by opening the dev console on chrome). This have no effect either, nor have clearing the browser cache manually.

How can I get rid of this delay, what am I doing wrong here?

Edit

I think Clive could be right that this is possibly on the file system level. Here is an excerpt from the docker-compose file:

volumes:
  - ./docker/project/modules:/var/www/html/modules
  - ./docker/project/themes:/var/www/html/themes
  - ./docker/project/libraries:/var/www/html/libraries
  - ./docker/project/profiles:/var/www/html/profiles
  - ./docker/project/sites:/var/www/html/sites
  # Add anonymous volumes to exclude cache files explicitly
  - /var/www/html/sites/default/files/js
  - /var/www/html/sites/default/files/css
  - /var/www/html/sites/default/files/php

The files are added as explicit volumes, and the changes I make to HelloController.php are reflected in the image. I'm running this on Windows 10. Could this be the culprit, and how can I test this?

Your image is based on drupal:8.4.3-apache, which sets an opcache revalidate frequency of 60 seconds:

# set recommended PHP.ini settings
# see https://secure.php.net/manual/en/opcache.installation.php
RUN { \
        echo 'opcache.memory_consumption=128'; \
        echo 'opcache.interned_strings_buffer=8'; \
        echo 'opcache.max_accelerated_files=4000'; \
        echo 'opcache.revalidate_freq=60'; \
        echo 'opcache.fast_shutdown=1'; \
        echo 'opcache.enable_cli=1'; \
    } > /usr/local/etc/php/conf.d/opcache-recommended.ini

This means that if you access the same file within 60 seconds, it will be served from RAM instead.


How Encrypt module actually works? I installed the Drupal Encrypt module and enabled it. However, I wonder how this module actually works. Does it encrypt all the submissions from the browser that the user/admin key in like 1) Login  2) Add/update node  3) Contact form/webform and decrypted again in the server before saving to the database ? Any tool to test this process? I'm looking a way to protect all the submissions or update over the internet which may be captured or exposed especially in the public area when using those free Wi-Fi. Please advise.

The Encrypt module:

  provides an application programming interface (API) for performing two-way data encryption. It allows modules to encrypt data such that it can be decrypted using the same key that was used to encrypt the data. This is useful for storing sensitive information.

Emphasis mine. That's its purpose, to provide an API that other modules can use to encrypt data before it's stored in the database (or elsewhere I guess).

As an API module, it provides no functionality unless you make explicit use of it; either by installing one of the modules listed that uses it, or by writing a custom module that does so. The emphasis is on you (or the writer of a contrib module) to actually do something useful with this module:

  It is up to the module calling encrypt() to manage and store the encrypted data.

The important thing to understand is that it doesn't (and couldn't) protect users from having their data sniffed over a public network. For that you'll need to use HTTPS, no exceptions. All this module does is offer an encryption/decryption service for your server-side app.


How can I login to my local drupal site 8.3.1 which was under maintence mode I just logout to see what will the home page look like. Now, I can't login into my local site.

You can also try to login by enter below url.

http://example.com/?q=admin
or
http://example.com/user


Drop Tables After Backup Migrate Restore I find myself using Backup and Migrate's Restore (from manual backups folder) when testing module sets or after a change to a project is problematic. I use Schema after the restore to check for extra tables left in the database during the restore process. Generally,  orphaned extra tables that are no longer wanted, needed or an issue are tables from modules or entity/content type fields being prototyped/tested. Module tables left in the database cause PDO Exception errors if I attempt to reinstall same module or alternate dev version after a restore. Extra field tables can get quite numerous and chaotic when rapid prototyping.

EXAMPLE
Match (107)
Hide Extra (11)
Tables in the database that are not present in the schema. This indicates previously installed modules that are disabled but not un-installed or modules that do not use the Schema API.

Schema report looks like:

Match (107) Tables for which the schema and database agree.
Extra () Tables in the database that are not present in the schema. This indicates previously installed modules that are disabled but not un-installed or modules that do not use the Schema API.

field_data_field_test_termsfruits   // fields for content types
field_data_field_test_code_and_api
field_data_field_test_drupal
field_revision_test_termsfruits
field_revision_test_terms_code_and_api
field_revision_test_terms_drupal
search_api_index                    // a module not being used
search_api_item
search_api_server
search_api_task

Seems that Backup and Migrate team is not ready to include drop tables options and the issue has been discussed in detail. I've also tried the Demonstration module which was great in D6 but just spits errors in D7 for me.

Aside from phpMyAdmin, MySQL GUI tools or command line to drop tables (and realizing security risk if permissions are compromised), what contributed modules or other PHP/API methods can I use from within the Drupal interface to drop specific tables?

As far as the API goes there's db_drop_table()

db_drop_table('table_name');


Exposed Filters in Entity Type Reference I have used and entity reference field in my content type Showrooms. The field references to another content type Cars.

Cars has a category field attached to it such as audi, mercedes, bmw etc. Each car has once category only. Now what i want is that the user can filter the cars on category. I have used a reference field, but it lists all the cars. I want the user to be able to filter it.

Should work some thing like this, the user first chooses the category and then from the other drop down should choose a car and that car should be referenced.

you can put your car categories in a taxomomy list and then use Hierarchical Select to filter the way you asked. quite straightforward.


How to create an RSS or Atom Feed in Drupal (source)? I have a website with Drupal 8 CMS and I have a second website without CMS.
I want to create an RSS or Atom Feed on my Drupal site (this will be the source).
I want to display the RSS or Atom Feed on the second site.
How to create an Atom or RSS Feed in Drupal 8 nodes to display it on the second site ?

Just use Views to create feed with content and fields you desire. A bit more up to date tutorial: https://yalesites.yale.edu/book/creating-rss-feed-views


Drupal 7 e-mail driven forum (mailcomment) I've been tasked to set up a forum on drupal 7 that can support outgoing e-mail notifications with incoming e-mail posting for a forum section akin to Google Groups. I.e. a fully e-mail integrated forum where content comments and threads can be generated and responded to entirely by e-mail.

My question is, how do I achieve this? In most cases, I'm finding deadends with dependencies as it does not seem mature on drupal 7; many of the modules only have recommended or released versions for drupal 6. In the first case I tried, my host (hostgator) did not support the required PHP module dependencies.

I have tried:

http://drupal.org/project/femail
Issue: Unable to install PECL MailParse a requirement of femail.  Our host (hostgator) won't support: 'not compatible' apparently.

Listhandler
Issue: Untried. No D7 version.

and the most promising route:

Mailhandler/Mailcomment with Notifications and Messaging
Guides:
hyperlinkhttp: drupal.org/node/1045918
hyperlinkhttp: peterthorndycraft.com/tutorial/mailhandler

Issue: Depenendies that cannot be met.

From the mailcomment INSTALL.txt:

Dependencies:
- Mailhandler (matching version required - i.e., if you are using Mail Comment
  7.x-2.0-alpha5, you must use Mailhandler 7.x-2.0-alpha5)
- Notifications and Messaging (7.x-4.x branch)

The 7.x-4.x branch appears to not exist: http://drupal.org/project/messaging

I have tried it with the 7.x-1.0 version but without success.

EDIT: My issue is identical (the OP is not me) to:
http:// drupal.org/node/1889550

EDIT: I have managed to be able to create nodes via e-mail using the mailhandler/notif+messaging framework, but as of yet, unable to get replies from e-mails to trigger new comments.

My question is really: is achieving this aim possible with D7? What framework have people achieved this in in other D7 sites? I'm reasonably new to Drupal, so sorry if there is something obvious I haven't tried.

Thanks

PS: Couldn't post all the hypoerlinks i was referencing. J

This is in no way trivial since you will need to setup an email SERVER to react to certain emails and trigger a drupal 7 process. I have been tinkering with a bunch of modules and the most promising is og_mailinglist Within the module you will find a lot of information and Documentation of how to achieve this. You might even want to read through this to meet the makers

Even so the requirements are really tough and it is a project of several weeks if not months. most customers think this should be easy, well it is not. And it has security implications that have to be thoroughly solved. You are allowing an email to add content!

Good luck.


Setting a field value on node save I have a note type 'team' with a body field and a checkbox field (checked by default). I want to automatically check the box on save IF there is content in the body field. Is there a way to do that programmatically?

Yes, this is possible with hook_ENTITY_TYPE_presave

/**
 * Auto check checkbox whatever, etc, etc.
 *
 * Implements hook_ENTITY_TYPE_presave()
 */
function my_module_node_presave($entity) {
  if ($entity->bundle() == 'team') {
    // Check if there is content in the body field.
    if (!empty($entity->body->value)) {
      // Set checkbox field.
      $entity->set('my_checkbox_field', 1);
    }
  }
}

Then, you'll probably want to remove the checkbox field from your form display on the Manage Form Display screen and also update the field settings so it's not checked by default since you'll be programmatically checking it if your body field has a value.


how to managed form '#type' => 'text_format' toolbar I have a simple form:

$form['module']['name'] = array(
        '#type' => 'text_format',
        '#title' => t('Name'),
        '#description' => $this->t('Some notes'),
        '#required' => FALSE,
        '#default_value' => '',
        '#format' => 'full_html',
        '#allowed_formats' => array('full_html'),
    );

and it gives me:

Which is good, but then, i want to manage the toolbar to remove certain buttons (e.g. only allow bold, italic, and strikethrough and remove remaining)

Can this be achieved from my custom module?

You need to +Add new text format over at /admin/config/content/formats

Then Configure your new text format and remove those icons by grabing them and dragging them from the active toolbar to the available buttons section

Lastly, instead of full_html, use your custom format for your custom module.


Contextual filter - day of week in url I'm looking for a way to only show elements related to a specific day in the week. Let's assume that the url to the view is: /program/schedule. What I would like is that when you go to: /program/schedule/monday,  only the info related to the monday is displayed.

Now I already figured out the contextual filters and that I can limit the valid values to: monday, tuesday, wednesday, et cetera. This is not the problem. The problem that I'm having is that it seems that my date time field needs to have an input of a specific date like 20130902.

I also need to point out that I am able to format my date time field to only show as a day of the week (with date formatting), but this does not seem to impact the contextual filter.

Is there a way to achieve this? Maybe with hooks or something custom?

Views Day of Week provides a simple filter plugin for Views 3 to enable filtering content that should be visible based on the current day of the week.

  Example: With this module you can select that some content should be
  visible only on Mondays, some on Tuesdays and Thursdays and some only
  on Fridays.


How to display calculated values in Drupal 8 views? Lets say I have an account field called euro-budget, and I have a content type exchange rate including the field usd-value" which import the USD exchange rate every 2 hours. In the view which displays all users including the field euro-budget. I want to have a calculated field which multiplies the field euro-budget with the latest usd-value field. What is the easiest way to do this? I already tried Views PHP but it is somehow not compatible with the latest Drupal 8 version.

Create a field formatter for your euro-budget field and then select that for your field in your view.


Display a message when no results are returned from an exposed filter How do I add a message, or change the view's behaviour when there is no result returned from a view's exposed filter?

When you edit your view (D7), under 'Advanced' you will find an item labelled 'No Results Behavior' which gives you a selection of options. The usual is to select 'Global Text Area' and return a no results found message.


Restoring accidentally deleted content type I am an absolute Drupal newbie, so please forgive my ignorance.

I have got an old Drupal site to manage (Drupal version 6.22).

While playing with the site I defined a new content type called My page and based on page.

After playing with it a bit I deleted it, from then on all my pages lost their content type and became uneditable.

After a lot of googling I realized that because My page was based on page, after deleting it I lost page type too. Seems a very strange logic to me, but not going to argue.

How can I restore the "page" content type? I tried to add it again, it was added OK, still all old pages remained typeless and uneditable.

The last site backup is from a couple of month ago and is irrelevant, as a lot of user content was added since.

I have an access as admin to the site's Drupal system, however I do not have a  remote access to the server. Should I request it? Where should I go and what should I change?

If a content type has been deleted, possibly all content of that type have lost their type setting, and so even if the content type is recreated, they might not be recognized as belonging to that type.

This should go without saying, but clearly that's not the case. Take a backup, before you happen to make things even worse.

You'll need to manually update the type column of the node table to the machine name of the content type.


Organic groups users cant leave groups I cant find a link where I can add for people in a group to be able to leave the group.

back in the older version it was something like og/member/group_id, but that doesnt work anymore.

I'm using drupal 7 with OG version = "7.x-2.0-alpha2"

It's /og/%/%/unsubscribe. See og_ui_unsubscribe() in og_ui.pages.inc to learn what are the arguments passed onto this.


Unexpected error when trying to view revisions A website I maintain can't view revisions without receiving an unexpected error. The log file points to this code in the .theme file but I have no idea what it does. When I commented it out, the website seems to function fine and revisions are viewable.

function themename_preprocess_page(&$variables) {
  $current_path = \Drupal::service('path.current')->getPath();
  $path_args = explode('/', $current_path);
  $node = \Drupal::routeMatch()->getParameter('node');
  if($node) {
    $node_info = \Drupal\node\Entity\Node::load($node->id());
    if($node_info->hasField('field_component')) {
      $paragraph = $node_info->field_component->getValue();
      if($paragraph) {
        foreach ( $paragraph as $element ) {
          $p = \Drupal\paragraphs\Entity\Paragraph::load( $element['target_id'] );
        }
        $variables['hero_banner'] = $p;
      }
    }
  }
}

The log particularly points to the 6th line above as the error. It mentions "Error: Call to a member function id()".

Does anyone have any clue? Thanks!

You need to add a check and also no need to $node_info = Node::load as the node is already loaded. The first two lines inside the function are not even getting used, so I removed them.

function themename_preprocess_page(&$variables) {
  $node = \Drupal::routeMatch()->getParameter('node');
  if ($node instanceof \Drupal\node\NodeInterface) { // check it's a node
    if($node->hasField('field_component')) {
      $paragraph = $node->field_component->getValue();
      if($paragraph) {
        foreach ( $paragraph as $element ) {
          $p = \Drupal\paragraphs\Entity\Paragraph::load( $element['target_id'] );
        }
        $variables['hero_banner'] = $p;
      }
    }
  }
}


Attaching CKEditor to E-mails subject and body? I have installed Mime Mail and am looking at formatting my emails (at admin/config/people/accounts) before sending them to users. How do I attach CKEditor to the E-mail subject and body sections?

Cheers

Looks like there is no any way to attach it. I used only html tags to format this notifications and their subjects.


How do I use theme('links') with nested arrays? I want to render the following output:

link 1

link 2

sub-link 3

link 4

I was expecting this to be pretty straightforward:

$list = array(
  'item1' => array('title' => 'link 1', 'href' => 'url1'),
  'item2' => array(
    'title' => 'link 2', 'href' => 'url2',
    array(
      'item3' => array('title' => 'sub-link 3', 'href' => 'url3'),
    ),
  ),
  'item4' => array('title' => 'link 4', 'href' => 'url4' ),
);

$output = theme('links', array('links' => $list));

This outputs the following however, ignoring item3:

link 1

link 2

link 4

You need to add the sub items to a 'children' key of the array. Here is an example:

$list = array(
  'item1' => t('Item 1'),
  'item2' => array(
    'data' => t('Item 2'),
    'children' => array(
      t('Item 3'),
    ),
  ),
  'item4' => t('Item 4'),
);

return theme('item_list', array('items' =>  $list));


Drupal_goto => POST $result as node Title In order to be able to add a new node whenever a searched string is not found, I've added the following code in my theme directory as search-results.tpl.php.

<?php if ($search_results): ?>

<?php print t('Search results');?>

  <ol class="search-results <?php print $module; ?>-results">
    <?php print $search_results; ?>

  <?php print $pager; ?>
<?php else: ?>
  <?php drupal_goto('node/add'); ?>
<?php endif; ?>

After clearing the cache, this works fine.

Is it possible to POST the searched string to the node/add section? For example, if I am looking for "car" and the string is not found, I should be redirected to node/add  with "car" showed as node title.

You add this line before your code:

$search_term = arg(2);

Send it in your drupal_goto, but you need to specify which content type to add (here i chose "article"):

<?php drupal_goto('node/add/article', array('query'=>array('title'=>$search_term))); ?>

And hook your node form in a custom module (here I chose content type "Article") :

function MY_MODULE_form_node_form_alter(&$form, &$form_state, $form_id) {
  // Find the content type of the node we are editing.
  $content_type = $form['#node']->type;
  if ($content_type == 'article') {
    if(isset($_GET['title'])){
      $form['title']['#default_value'] = $_GET['title'];
    }
  }
}


customizing an info window with geolocation views I have been beating myself up a lot with this problem.  I can't for the life of me figure it out.

I am using Drupal 7, using the geolocation module, specifically the views part.

I am essentially trying to put a view for each node within this map view.

It works really well, however, it doesn't render in a particularly nice way for the user.

I am guessing that I can sort this out in css.  However, I can't for the life of me figure out which div class to alter.  The one that I think I want to alter is just a standard Div tag.  I am sure I am missing something, but I just can't work it out.  I tried altering the .balloon class, but got some weird results.

Thanks in advance,

Mark.

Having clarified this with the developer, you need to alter the  ip_geoloc_gmap_multi_loc.js file at line
165.  This relates to the infoWindow maxWidth setting.  Essentially I have
tried to increase this massively.

This sorts out the problem for me, and the developer advised me that this should not cause a problem.

I couldn't work out how to do this with css.  Might be possible...but I couldn't work it out...

...hope this helps someone in the future, as it caused me quite a headache!

Thanks again for your posts,

Mark.


how to get user name in a view instead of uid I have a drupal 7 website that uses a view to show the content.  The Content UID shows as a field I can display, but I want to display the username instead.  It says "The user authoring the content. If you need more fields than the uid add the content: author relationship"  , which I don't understand .  Where do I add the content author relationship?
thank you,

it's in the advanced configuration (click on add relationship):

search and select the uid field (this applies also for entity references for instance)

add a new field to the output, select User: name

select the relationship you created earlier (you can have multiple relationships, e.g. if you have multiple entity references)


Can I get the Node's content type in hook_flag_alter In the following code, I'm changing a flag with a short title of "Follow" to include the name of Content Type. Is it possible to add the content type so that I can not say Follow node but perhaps Follow Question, Follow Person, FOllow Group?

function hook_flag_alter(&$flag) {

    //node, taxonomy_term, user,  comment
    $extra_text_of_type = "";
    switch ($flag->content_type) {
      case 'node':
        $extra_text_of_type = "node";
        break;
      default:
    }

    $flag->flag_short = $flag->flag_short . ' ' . $extra_text_of_type;
  }

If you're using flag 2.x with Drupal 7, then this should give you what you want.

function hook_flag_alter(&$flag) {
    $type_text = "";
    switch($flag->entity_type) {
      case 'node':
        switch(reset($flag->types)) {
          case 'page':
            $type_text = t('Page');
            break;
          case 'blog':
            $type_text = t('Blog Post');
            break;
          default:
            $type_text = t('Node');
        }
        break;
      case 'user':
        $type_text = ('User');
        break;
      default:
    }

    $flag->flag_short = t('Follow @type', array('@type' => $type_text));
    $flag->unflag_short = t('Unfollow @type', array('@type' => $type_text));
}

Note: This code assumes that each flag only applies for a single content type.


Is there an efficient easy way to test Drupal code while developing it? While writing code making sure, for example, I'm access the correct array property I keep refreshing the browser.(Or, that I didn't make a semantic mistake like that last sentence but in code) Is there a very simple and quick why to set up tests to do this instead? Simple test module seems like a huge deal and overkill. I love using Grunt watch while working with node.js. Is there an equivalent in Drupal?

As you're comfortable with Grunt, I've got a Gruntfile that I wrote that I use as a stub for most projects. You can find it here github.com/Chapabu/grunt-drupal-standards/. Just clone it to your project root and follow the installation instructions.

There are Drupal specific tasks there for doing to following:

PHP linting of any custom code
JS linting
CSS linting
Automatic clearing of theme registry when new templates are found
PHP_CodeSniffer tasks to ensure your code mets the Drupal Coding Standards

I need to make a few updates (i.e. remove Casper stuff, remove Compass tasks as I now use Libsass etc) but the tasks that are there should be enough to get you started.

There are also Grunt tasks for running PHPUnit tests or PHP Mess Detector (to name a couple of helpful suites) so it's pretty easy to add tasks to watches.


Can I change the HTTP user agent when writing browser tests? My module has some special functionality based on the user agent of the request. I want to write tests for this functionality based on D8's BrowserTestBase, but it doesn't seem possible to change the user agent string.

The prepareRequest method of BrowserTestBase sets the user agent to the value of drupal_generate_test_ua($this->databasePrefix).

For a test, I tried changing this value to something else, and it breaks the tests.

Now I realize that there appears to be some functionality built into core based on this value that drupal_generate_test_ua returns and there's checks all over core to detect if Drupal is running within a test or not.

Is there a workaround or any hope for writing tests with a custom user agent?

No, you can't.

BrowserTestBase, just like other other tests that support web requests uses the user agent to identify which test environment you're in (there could be multiple, parallel ones). Changing the user agent would result in your request being sent against the main site.

The only workaround that I see is to send another header (if that's actually possible through the API, not sure). In your could you would then look at that header instead. It's not perfect and it requires you to write special code for tests, but I can't really see another way if you really rely on the user agent.


Displaying multiple nodes inside a single view block I am somewhat new to drupal.

My goal is to display the 5 most recent nodes with a specific tag ("slideshow") in a, well, slideshow.

I am trying to use a views block in order to do that. But when I add the block to the main page, it shows nothing. I've also tried modifying the template 'archive' view, but it shows a link to a different page with the contents of a specific month instead of the posts themselves:

How can I have it so the content themselves are all displayed in this block?

Create a new View (rather than trying to alter an existing one like Archive).
Add a Block display.
Set the "Number of items to display" to 5
Add filter(s) so that only the nodes you want are displayed
Add a sort by the created date of the node, descending, so the ones at the top of the list are the most recent.


Menu Block disappear when changed the access control permission I have "Menu Block" and "Content Access" modules installed. The menu button of that page disappear when I set that page not to view by "anonymous user". How can I show the Menu Block to everyone but not the page content?

PS: I don't wanna create another menu block

Thanks!

Drupal will show / remove pages from the menu depending on whether or not a specific role has access to it. If you want to show the page in the menu but not the content to a specific role such as anonymous there are a couple of different routes you can go.

There is a module called field permissions which would allow you to set the page itself to be visible by everyone but you could hide specific fields from visitors. From drupal.org

The Field Permissions module allows site administrators to set field-level permissions to edit, view and create fields on any entity.

You could also achieve something similar if you were to use the panels module. You could set visibility based on role, thus hiding sections of content but still having your menu items visible.


Is vbo respect the order set by view while performing operation? or is there a way to tell it to perform in same order as result In a simple vbo I needed to set field_serial_no to row no of view's result. By default view result is ordered by title in ascending and order cannot be modified (not exposed to user).
When these entities are passed to VBO, will it be aware of order of entities always? if yes I can directly access the index and save it in field_no. I not is there any method?

It actually depends an the specific action. VBO gives the data in the same order as the view. But the action can rearrange the id's. Although most just process it the way they got it.


How can I add extra classes to the title of a node? I want to add more classes to the title of a node using the following code.

{{ node.label }}

It doesn't work, despite the fact title_attributes is described as follows.

  title_attributes: Same as attributes, except applied to the main title tag that appears in the template.

I know that is possible to add classes straightly with code similar to the following one.

{{ node.label }}

I'm eager to know the standard way of doing this, and I don't want to miss anything.

My class names follow the BEM Name Convention rules and it's hard for me to break and behave contrary to those rules and change my class names.

You have to enclose the class in single quotes:

{{ title_attributes.addClass('article-full__title') }}

Otherwise this is interpreted as a variable name. In Twig unknown variables don't trigger an error, they return silently NULL.


Drupal 7 Fields, when adding an existing field during content type creation, how to tell where else its used? I just realized that if you use an existing field that is used in another content type and you change the field settings, you end up changing it on the other content types that share the same field. Is there a way to tell where else an existing field is being used?

Example: I have a field called "field_image" and using it in my basic page content type. Now I use it for my blog content type. How can I tell my basic page content type was using that same field?

There's no UI for this anymore. The UI is in admin/reports/fields (h/t Clive)

Here's a good stack about how to find this info with drush:
Is there a listing of Drupal fields?

Or you can grab it from the database:

SELECT entity_type, bundle FROM field_config_instance WHERE field_name = '$MY_FIELDNAME'


Switching from Search API Database to Solr i have a site which is already using Search API database and Facets search hosted on Acquia. The site main search (recipe search) is a  view with exposed filters to display search and similar content etc. And the site is in 2 languages ( EN and Arabic )

I need to implement spellcheck (did you mean) in the site and this module is only available for Solr.

I have no experience with Solr search. My question is how easy it will be to switch to Solr? Will i have to create different VIEW etc?

I have done a lot of theming, i am afraid of doing that all work again.

What is your expert opinion.

thanks :)

You will need to switch search server for your search index. But I think your view can stay as configured now as it targets a index (which only will change server).

You will also need the module Search API Spellcheck. Then add the "Search: Spellcheck" field to the header of your view. This will output the message “Did you mean "something" in the header if a suggestion is returned by Solr.

You will find the setting for which server your index should use under your index.


Remove left sidebar shopping cart I know the shopping cart is generated by the view shopping cart form. But how do I remove the shopping cart block on left sidebar of the home page and still maintain the the view on /cart page? I have tried disabling the view entirely, that didn't work as it seems the block is hardcoded.

As far as I understand you could restrict block from being shown in front page, from block visibility settings. Alternatively, you could also make a custom template for the front page.


Apache URL aliases not working with the visibility settings for blocks I have a page like example.com/abcd.php?url=efg with Apache aliasing it to example.com/product/efg. I don't want certain blocks to be visible on this page; when I use  product/efg in the block section, it does not take any effect. I wanted to know how to go about this issue.

If example.com/product/efg is a path alias, then you need to use the path that uses that alias in the block visibility settings.

For example, if example.com/product/efg is the alias for example.com/node/1, then you need to add node/1 in the list of pages where the block should not be shown.

If you have more path aliases for the same internal URL, then instead of setting the pages where the block should not be shown, you need to use PHP code that returns TRUE when the block needs to be shown. Code similar to the following one should work:

<?php
  return request_uri() != '/product/efg';
?>

If Drupal is executed in a subdirectory of the web server root directory, e.g. dr6, the code needs to be modified as follows:

<?php
  return request_uri() != '/dr61/product/efg';
?>

The reason I didn't use drupal_get_path_alias() is that the function returns just one of the path aliases existing for the internal path passed as argument; in the case there are more path aliases, this would be a problem.


How do modules end up in the profiles directory in distributions? I'm building a basic distribution and I cannot find any information on how contributed modules that are included in a distribution get placed into the drupal-root/profiles/profile-name/modules directory.

I've looked at a number of distributions, both hosted on drupal.org and not, trying to find some line(s) of code that does this, but there doesn't seem to be any. It has got to be happening "automatically" somehow, but it isn't working for me. When I add modules to my make file, they always end up in sites/all/modules.

I've spent hours trying to ask Google this question but every form I can come up with just gives me information on how to install a module, or how to move modules from the profile of a distribution into sites/all/modules - both of which I am well aware of...

So, can anyone direct me to documentation that can help me out? I'm sure it is out there, but I've hit a wall trying to find it.

I found the problem.

I have two make files - drupal-org.make.yml & build-xq42_d7_sk.make.yml. I was including the following in the build-xq42_d7_sk.make.yml:

includes:
  - drupal-org.make.yml

Turns out this caused the problem. There's no need to include any reference to that file at all in the build-profile-name.make.yml file.

This is the first make file I've built and I created it by reading documentation and looking at existing make files for other projects. I saw this line in one of the make files I used as an example and assumed it was OK.

Now I know...!


Best practices for page layouts I'm trying to figure out what the best practices are for page layouts in Drupal.  Many pages have several different elements on them like main content, a header image, etc.  I'm not looking at creating a 'basic page' or anything similar (ie one node for the whole page).

Is it good to use panels for every page and them drop blocks into them?  I could drop views, possibly a node, a contact form, etc...

Panels is a great module, but it can also be complex and it can take a while before you completely understand it. If you're interested in using panels for every page, the Panels Everywhere module is an interesting project.

Another great project that provides more flexible layouts is Display Suite.

Although people tend to use either Panels or DS, they are not competitors. They can be even used together as you can read on the blog of the author/maintainer of DS: Using panels on view modes in Drupal 7.


How do I sort by node authored on date? In Drupal 7, I have created a view to show a list of nodes I need to sort by node authored on date.

Does anybody know how to do this?

In your view, go to section: SORT CRITERIA.
Add field "Content: Post date"
Sort ascending or Sort descending.


Next link on node page based on its taxonomy term So here is what I'd like to achieve:

I'd like to put a Next link to every content of a type, that links to the next content with the same taxonomy term.

So for examle if I have A, B and C products with the term 'clothing' on them, I need a link A product that points to B, one link on B that points to C and so on.

How is this possible to do?

It's only in Alpha but the Treewalk Previous / Next module appears to have that functionality:

  Previous/Next (Back/Forward) links for entity and other pages, that allow to visit them in a sequence.

  Unlike with the existing back/forward module, the sequence of items (entities etc) is not based on a view, but on hierarchical information already present in your site.

  It provides a configurable block with prev/next links based on menu trees. The block is named "Treewalk Prev/Next (Menu)"
  It provides Display suite fields with prev/next links based on entityreference / taxonomy_term_reference fields. The ds fields are named as "Treewalk Prev/Next (...)".

I've never used it but it might at least be a starting point to implement the logic yourself.


Rewrite output of a field and include another one templated As a newbie with Drupal 7, I'm wondering if it is possible to rewrite the output of a field, including another field templated.

Right now, my rewrite looks like :

[field_a] [field_b]

And it is displaying field_b as a raw value and not using its template.

Is it possible to display [field_b] using its template ?

Thanks !

As you might excluded the field from display which bypasses the template file that build the display of the field.

So you have to use .tpl file to build the markup you need or put the markup in the rewrite which is not the best solution but may be accepted if you just write simple markup of one tag and classes to let css style apply.


Node access-control modules for members-only pages I am building a straightforward Drupal 7 site that has public pages and members-only pages. There is just one kind of member. Right now access control does not need to be finer than that. It seems my choices are the modules Content Access, Nodeaccess, Simple Access, node privacy byrole, Taxonomy Access Control and Taxonomy Access Control Lite. To achieve what I need, I could control access either by role, or by using a taxonomy term like "members-only". Both would work.

All these modules are still under development for D7, and are in varying stages of (un)completion and bugginess. For some, development seems erratic or stalled. In addition, their UX's are of varying complexity for the non-sophisticated content editor.

(Another alternative to all of these modules is to create a separate content type for members-only pages, and just use the built-in content-type permissions. That seems inflexible and duplicative, but it is a way out.)

My question is a practical one, given the current reality: which one would you choose for use now or in the next few months, for this use case, and which one seems to have the brightest future?

FOLLOWUP (7 months later): After trying Content Access (CA) and Taxonomy Access Control (TAC), I settled on TAC. Content Access can do by-node access control, but the UX is not simple, and I wouldn't want to subject my editors to it. I find that using a taxonomy term to designate access can essentially be an abstraction mechanism: a single term can represent a complicated set of access choices. For one content type (calendar events), I vary the the access based on taxonomy. For another (members-only pages), I just use a one-term taxonomy vocabulary that is a required field (so its value can't change). So for me, TAC's functionality is a superset of CA. I also needed Field Permissions to selectively expose the fields in calendar events.

Obviously there are a lot of factors that you should consider before deciding whether a module has a "bright" future or not. A very good blog post that describes all the factors that should be considered can be found here (it's based on the old theme of drupal.org but you can still get the point).

The final decision that you'll take is kind of a "feeling" that you'll get after you 've spent a lot of hours testing modules and banging your head against the wall, only to realize that the module that you picked is not the correct one. However, I will give you the results of a small script that I have and I run in such cases. It gives you the usage count of the modules that you provide as an input, and here they are:

content_access: 24939 users
node_access: 1295 users
simple_access: 1623 users
node_privacy_byrole: 3399 users
taxonomy_access: 6037 users
tac_lite: 3397 users

Note that these results are just information pulled from the drupal.org website and you should not use them to compare the modules. They are just indications that tell you how other users "feel" about those modules that you are examining.

So, to answer your question, I would go for content access module since it supports the per-role access that you mentioned, there are tons of sites that are using it (meaning that it is highly unlikely to be discontinued), its author is someone that has done remarkable work for drupal and the D7 version was updated -relatively- recently.

P.S: if you want the script, lemme know. It's proven very handy in many cases.


How do I add a  over a paragraph's field, depending on another field of this paragraph? I have a paragraph (from the paragraphs module) which has two fields :

field_title (text)
field_title_level (list text)

The field_title_level can have either h2, h3, or h4 as a value.
What I would like to do is to surround the title text with a h2/h3/h4 div.
I tried using templates (paragraph, or field). With the field one, I managed to add a div over the title, but I didn't manage to access the field_title_level in order to add the correct div. And using the paragraph template, I didn't manage to add any div over the title.
Any clue?

Don't use the field template -- you'll find it difficult to change the formatting of one field based on the value of another field at that level. You'll want to use the paragraph template (or sometimes even the node template containing the paragraphs entity reference revisions field) so that the values of both fields are in scope at the same time.
Something like this might work in the paragraph template:
{% if content.field_title_level.value == "h2" %}

{{ content.field_title }}

{% endif %}
{% if content.field_title_level.value == "h3" %}

{{ content.field_title }}

{% endif %}
{% if content.field_title_level.value == "h4" %}

{{ content.field_title }}

{% endif %}

You could use {% if %}{% elseif %}{% else %}{% endif %} instead of consecutive ifs to provide a default ... I don't know what your data structure looks like.
You did mention that you want to use
 elements, so maybe you want something more like this instead:
{% if content.field_title_level.value == "h2" %}

{{ content.field_title }}

{% endif %}
{% if content.field_title_level.value == "h3" %}

{{ content.field_title }}

{% endif %}
{% if content.field_title_level.value == "h4" %}

{{ content.field_title }}

{% endif %}

Be aware, though, that
 elements are not semantic HTML like the header tags. (Even though they may be visually styled to appear like HTML headers, they will not be treated the same way by assistive technologies, like screen readers for the blind.)
Finally, note that you can do some very cool tricks by rendering Paragraphs content in the node template, by iterating through the items in the Paragraphs entity reference revisions field like so:
{% if node.field_paragraphs_items %}
  {% for item in node.field_paragraphs_items %}
    {% if item.entity.field_title %}
      {% if item.entity.field_title_level_value == "h2" %}

{{ item.entity.field_title }}

      {% endif %}
      {% if item.entity.field_title_level_value == "h3" %}

{{ item.entity.field_title }}

      {% endif %}
      {% if item.entity.field_title_level_value == "h4" %}

{{ item.entity.field_title }}

      {% endif %}
    {% endif %}
  {% endfor %}
{% endif %}

(Markdown syntax highlighting does not like my Twig, so there may be some errors in this example but hopefully you get the idea.)
Note the use of item.entity (in the node template) instead of content (in the paragraph template.) Just as pulling back from the field template to the paragraph template brought more field values into scope, rendering paragraphs entity references in the node template in this way will give you access to field values from the node as well as those in the paragraph.
There are pros and cons to both approaches. Keeping paragraph markup in the paragraph templates will keep your Twig tidier, so I generally recommend it unless your business logic requires you to render Paragraphs conditionally based on values in the parent node.


How can I fix the "Could not delete temporary file"? I'm getting below error when run cron:

  The specified file could not be deleted, because it is not a valid URI. More information is available in the system log.

Due to TMP files, my site will be crashed, again we will restored site and unable to clean TMP files in my live site.

Change to another tmp folder destination? Configuration -> file system

I not sure will this help you.


Drupal 6: using template based on browser version Is it possible to serve up a specific page template based on browser version? If I can satisfy my IE 7 requirements with a special template, I'd prefer that rather than loading a bunch of extra css only used when IE7 is being used.

I have a special drop-down menu and though on its own will work in IE7, once it's a block and assigned to a region, issues start with height. I can put it in another region within a page template but then I'm changing all the css for all other browsers so I'd just as soon as have a template for the specific pages.

thanks

Normally that would be done with conditional css e.g. conditional_styles and that approach is recommended first.

Mainly because why change the entire template when only the CSS needs changing?

However, if you really need separate tpls ( e.g for new HTML markup ), you could probably use template suggestions in hook_preprocess_page after checking the browser user agent.

Something like this in template.php

/**
 * Implements hook_preprocess_page
 */
THEMENAME_preprocess_page(&$variables){
  // Requires browscap.ini, check PHP docs for details, else use $_SERVER['HTTP_USER_AGENT']
  $browser = get_browser();
  if($browser->browser == 'IE' && $browser->majorver == 7) {
    $variables['template_files'][] = 'page-ie7';
  }
}

After clearing all caches, you could then use page-ie7.tpl.php for IE7.

See the note on http://php.net/manual/en/function.get-browser.php for info else use $_SERVER['HTTP_USER_AGENT'] to check browser from request. You'll also need to make sure your cache varies on user agent as well.


Placing result count below Views exposed filters? I have a View, and I want to display result summary below the exposed filters. Currently I am modifying views-view--view_name.tpl.php.

How I can render result summary header just below the exposed filters?

Ad summary of the result in the head of the vieuw and reposition this div with css to the place where you want to put it.


What is the hook to alter links in the Book Outline tree? What is the theme hook to alter links in the book outline like theme_menu_link__menu does for menus?  Or is there a way to make theme_menu_link__menu apply changes to a tree view of the Books?  Not the book navigation but the Outline.

Turns out there isn't one.  Had to go back to an ajax approach and update the book outline in the client browser.


How to properly use two contextual filter for taxonomy this is my case:

I have a content type called "norm".
Each norm has two fields with taxonomy terms: "issuing institution" and "norm type".
Each taxonomy field has its own vocabulary.

I'm making a View that will:

Filter all the "norms" that are issued by "institution A" or "institution B".
Has two contextual filters. One for "insitution", second for "norm type".
If the first parameter is not given, just show a summary with the instituions (in this case, just two institutions). [This is working]
Then, if the second parameter is not given, just show a summary with the "norm type". I mean this will be a list of norm types that has been issued by institution %1 (first parameter).

But, the last is not working. It shows again the instituion.

How can I do this kind of thing?

This happens because the views checks the first parameter and the first parameter overrides the second parameter. In your case, if you rearrange parameters so that parameter 2 comes before parameter 1, you will see this time views working with parameter 2 and not with parameter 1.

You can fix this behavior by creating two separate pages in views and each page will override the behavior of the other by selecting For:"This page(override)" option.

In the first page add the two contextual filters(parameter 1 and parameter 2). While adding the contextual filters you have to select For:"This page(override)".

In the second page of the views, add the two contextual parameters, this time add parameter 2 before parameter 1. In this case also, while adding the parameters you have to select For:"This page(override)".

Good luck!


CKEditor doesn't show JavaScript I have Drupal 7 with CKEditor 3.6.2.7275 under Wysiwyg module. In configs of Wysiwyg I unchecked all the checkboxes for "Cleanup and output" category. Plus unchecked "Limit allowed HTML tags" for Full HTML text format.

When I try to edit the page, containing javascript inside, the <script type="text/javascript"> is inside the <textarea> for content editing. But it's not shown by CKEditor when I click source button. So it's undoubtedly CKEditor filtering.

What should I do to make CKEditor show javascript?

Drupal, like most Content Management Systems, has security systems in place to filter most javascript during submission so site members can’t do ugly things via scripting. In most cases, that’s a good thing. When you’re scratching your head trying to figure out a way around it, not so much.

You can hard-code a script into the template, if you need it on all the pages and it works. But just adding a a single, inline javascript into a Drupal node is not as easy as it seems.

There may well be a prettier way to do this, but here is a quick way out in case you need it:

First,  put the script on your server, someplace it’s easy to find. I usually have a  “scripts” folder in my sites/all folder.

Second, when do your post, set your input filter to PHP

Third, do a php include where you’d like to place the script. Something like this:

<?php include('sites/all/scripts/my_javascript.js'); ?>

And there you go. Inline javascript. I guess in the most common scenarios Drupal is used for, having <script> available without filtering would be very foolish security wise. Unfiltered js in a webform makes for a very insecure setup.


right drupal sql query what is the right sql query for drupal 7 if the query like this

SELECT MAX(nopeserta)
FROM `1_jp_peserta`
WHERE jpke=$q1 AND lomba=$q2 AND kelamin=$q3

i have tried in drupal like this

$q4 = db_query("SELECT MAX(nopeserta) AS nopeserta FROM {1_jp_peserta}
WHERE jpke=:q1 AND lomba=:q2 AND kelamin=:q3",
array(':q1'=>'$q1',':q2'=>'$q2',':q3'=>'$q3'))->execute()->fetchAssoc();

but the result is

PDOException: SQLSTATE[HY093]: Invalid parameter number: no parameters
were bound in jpeserta_form_submit()

When you use db_query() the query is executed for you, I think the error you're getting is because you're re-running execute() on it. Also it looks like you're trying to interpolate variables into a string using single quotes, when you need to use double quotes (or none at all in your case).

Try this:

$q4 = db_query("
  SELECT MAX(nopeserta) AS nopeserta FROM {1_jp_peserta} WHERE jpke=:q1 AND lomba=:q2 AND kelamin=:q3", array(':q1'=>$q1,':q2'=>$q2,':q3'=>$q3))->fetchAssoc();


How to Disable new terms (free tagging) with Taxonomies? I have a "term reference" field, in a form that uses an auto-complete widget.
I want to limit user input to terms in the vocabulary only, and output a message when a user tries to enter a non existing term.

I found the Content taxonomy module. However this does not work with forms that contain a field collection or a field group.

There is also a contributed patch 1078878-DisableAutoCreation-D7-UTF-8.patch. But I was wondering whether there was a simpler/cleaner solution like a module or maybe I missed an already existing way of doing it with latest drupal and taxonomy versions.

There seem to be two possible solutions which are mentioned here http://fooninja.net/2012/08/03/drupal-autocomplete-term-widget-disable-creation/ and you have also mentioned them in your question.

Excerpt from the post,

  There are in fact two solutions. One is the Content Taxonomy
  module. However, I didn’t feel like installing yet another module
  for such a simple thing. The second solution is patching the core
  taxonomy module:

  A kind soul on the Drupal forum, j.stuyts, posted a small patch
  that adds an option to disallow autocreation. All you need to do is
  download the patch (1078878-DisableAutoCreation-D7-UTF-8.patch)
  to the Drupal 7 root directory and run.

  If you then go to Structure » Content types » [Your content type] and
  edit a Term reference field that uses the Autocomplete term widget,
  you’ll see a new option at the bottom: “Allow autocreation of new
  terms” (checked by default).

Although hacking in core is never recommended but you can use patch till the time you get better solution.


Override a node page of specific content with views page I want to create a views for overriding the node page for specific content. For example, when I click the link of a node in a list page, by default , it will go to the node page (e.g node/1), but I want to display a views page, so I can customize the views by views rather than customize the display in content type.

How can I do that?

Create a views of content, set path of it to something like mynode/%(or what you want(yourpath/%)), add contextual filter Nid, set default value Get Content ID from Url,and then customize views fields with what you want.
 This link can help you about how to pass Nid to views


Show exposed filter value when returning results I can't seem to figure this one out. I have a view that returns nodes with a set of taxonomy term exposed filters. What I would like to do is show the selection the user has made on the screen (e.g "Showing results for..."), preferably using a text field in the views header else through the views template files. Can anyone help me please?

a bit tricky, but works:

Add a field (term) Taxonomy term: Name (Name)
in settings check: exclude from display
Add header:  Global: Unfiltered text
check: Use replacement tokens from the first row
set the text area with the available token: e.g "Showing results for [name]"

Screenshot:


Weird Drupal Error (The character encoding of the HTML document was not declared) I have Drupal 7 with multiple taxonomies and recently for only one (the largest one) when I go to the following taxonomy page:

www.site.com/taxonomy/term/216746

all is fine.

Then when I click edit:

www.site.com/taxonomy/term/216746/edit

My screen goes blank and I see in the console that I get this error:

  The character encoding of the HTML document was not declared.  The
  document will render with garbled text in some browser
  configurations if the document contains characters from outside the
  US-ASCII range.  The character encoding of the page must to be
  declared in the document or in the transfer protocol.

This does not happen with any other taxonomy term and suggestions would be great. Also, I looked in the database and I notice any differences between the terms.

I turned on errors in the settings.php with ini_set('display_errors', 1); and I found it was a memory issue.

I added ini_set('memory_limit', '500M'); to the settings.php file, and all works.


How can I implement a custom display widget for an existing field? Basically I want to have my own widget as a choice in the widget drop down of an existing field type; and/or I want to be able to call field_view_field on a field and have it display the way I need, using info from the field itself and elsewhere.

I can probabaly do what I need with template_preprocess_field but I would prefer to hook the existing admin interface for selecting the output of the form.

I'm assuming that a solution is available that would allow the output of the field to be the way I configure it any place the field can be displayed, Views, etc.

Thanks in advance.

The Examples project on drupal.org has a field example, showing how to implement a widget.

Basically you need to implement hook_field_widget_info(), and for 'field types' include the field type your widget is for.


User password Reset without sending an email I know by default Drupal provides 'Forgot password' option which allows user to enter their username/Email. If that's valid, sends a password reset link to their Email.

But I would like to do the same process without involving an email, which allows users to logged in immediately in one or two steps (by validating some checks).

How can I achieve that in Drupal?

I found a module called Password Reset. This is what I was looking for. I've tested this module and working great!.

  The password_reset module allows for passwords to be reset without involving e-mail addresses through the use of security questions. This module would typically be used on sites that do not require users to enter their e-mail addresses or prefer not having to deal with spam folder issues etc.


how to create manual reports and graphical represntation as content type Hello guys any Module which can provide tools so that we can manually input data and output them as graphical representation. I have tried Data visualization module but its complex to add JSON data.

Try to use any of these modules :

Google Analytics Report

  Google Analytics Reports provides graphical reporting of your site's
  tracking data. Graphical reports include a dashboard widget for
  admins, a small path-based report in blocks, and a full path-based
  report.

Forena Reports

  Forena is database report writing software built on the Drupal
  platform. Forena is built of the idea that if you can write the SQL
  necessary to get the data out of a database, it should take very
  little work to get that data out on the web. It is designed to
  leverage knowledge of HTML, CSS, SQL and Java Script to help you
  create rich interactive web reports.

Charts & Graphs

  Charts and Graphs is an API for developers. It can easily be extended
  by third-party modules that want to add their own charting
  implementations. It does nothing by itself.


Content tab takes a very long time to load I have about 350 000 records in node table and about 600 000 in node_access and domain_access tables.

When I try to open content tab it takes about a minute to load.

As I found out with Devel module this query takes about 32 seconds to execute:

SELECT DISTINCT node.nid          AS nid,
                node.title        AS node_title,
                node.language     AS node_language,
                history.timestamp AS history_timestamp,
                node.created      AS node_created,
                node.changed      AS node_changed,
                node.type         AS node_type,
                users_node.name   AS users_node_name,
                users_node.uid    AS users_node_uid,
                node.status       AS node_status
FROM node node
         LEFT JOIN users users_node ON node.uid = users_node.uid
         LEFT JOIN taxonomy_index taxonomy_index ON node.nid = taxonomy_index.nid
         LEFT JOIN taxonomy_term_data taxonomy_term_data_node ON taxonomy_index.tid = taxonomy_term_data_node.tid
         LEFT JOIN history history ON node.nid = history.nid AND history.uid = :views_join_condition_
ORDER BY node_changed DESC
LIMIT 50 OFFSET 0

And this one takes 20 seconds:

SELECT COUNT(*) AS expression
FROM (SELECT DISTINCT node.nid          AS nid,
                      node.title        AS node_title,
                      node.language     AS node_language,
                      history.timestamp AS history_timestamp,
                      node.created      AS node_created,
                      node.changed      AS node_changed,
                      node.type         AS node_type,
                      users_node.name   AS users_node_name,
                      users_node.uid    AS users_node_uid,
                      node.status       AS node_status,
                      1                 AS expression
      FROM node node
               LEFT JOIN users users_node ON node.uid = users_node.uid
               LEFT JOIN taxonomy_index taxonomy_index ON node.nid = taxonomy_index.nid
               LEFT JOIN taxonomy_term_data taxonomy_term_data_node ON taxonomy_index.tid = taxonomy_term_data_node.tid
               LEFT JOIN history history ON node.nid = history.nid AND history.uid = :views_join_condition_1) subquery

I tested the first query and found out that the ORDER_BY causes the slowness.

Is there any way to make it fast?

I am not exactly sure if it is the best solution but it works for me.
I changed default nodes view to use GROUP BY (without any aggregation function) instead of DISTINCT and it works 40 times faster in my case.


How to provide upload function for users Possible Duplicate:
  How to allow users upload images to existing nodes?

How might I go about providing a page for authenticated users to upload image files to the server?

You have a few options:

Use a contributed module.  Take a look at this link for a list of modules: File Uploading and Managing. A few that are definitely worth taking a look at are: FileDepot, WebFM, and ELfinder
Create a content type where you can upload files (using the core image module if D7 or if D6, the Image or ImageField modules)
Create a custom module to your exact specifications.  This is definitely the most customizable option, but involves more work and a familiarity with the API. To get started creating a custom module, take a look at the Module developer's guide, the Forms API Reference, and the Form API Quickstart Guide


Change node content after logging in under the same URL alias (showing other content for authenticated users) I would like to change node content under some specific URL aliases after the user logs in, to show some other contents for authenticated users.
With a really simple example, there's a node which can be reached under the URL alias http://<mysite>/something, and this content contains the string "You have to be logged in, because this would be good to you", but after logging in, the same URL alias would show "OK, now you're logged in".

Another user wrote here that

  "in views we can setup same url for different views that is one for
  anonymous and another for registered."

Is this the right solution?
If yes, how should I do this in practice?
If no, what else can you suggest?

Thank you in advance!

You can do this with views using the technique in this blog post: Making a view show different content to different users based on role


Last modified date in menu link I have a book with some child pages and I'd like to show the last modified date of each corresponding node near them in their menu tree links, or a red badge near the nodes updated during eg. the last 3 days...
How to pass the changed_date of nodes to menu links?

Thank you

Hook insert/update

The Book module update the book menu title during node insert/update.

You can implement hook_node_insert and hook_node_update to update the title in place.

/**
 * Implements hook_node_insert().
 */
function my_custom_module_node_insert($node) {
  if (!empty($node->book['bid'])) {
    $node->title = $node->title . format_date($node->changed, 'custom', 'M j, Y');
    _book_update_outline($node);
  }
}

/**
 * Implements hook_node_update().
 */
function my_custom_module_node_update($node) {
  if (!empty($node->book['bid'])) {
    $node->title = $node->title . format_date($node->changed, 'custom', 'M j, Y');
    _book_update_outline($node);
  }
}

Using preprocess

You can do that by override template_preprocess_book_navigation which contain a call for book_children function. The aim of override is to provide custom version of book_children function which add the node date to the title before calling the render method.

/**
 * Processes variables for book-navigation.tpl.php.
 *
 * Override theme_preprocess_book_navigation
 */
function my_custom_module_preprocess_book_navigation(&$variables) {
  $book_link = $variables['book_link'];
  if ($book_link['mlid']) {
    $variables['tree'] = custom_book_children($book_link);
  }
}

/**
 * Formats the menu links for the child pages of the current page.
 *
 * A custom version of book_children to add date suffix to link title.
 */
function custom_book_children($book_link) {
  $flat = book_get_flat_menu($book_link);

  $children = array();

  if ($book_link['has_children']) {
    // Walk through the array until we find the current page.
    do {
      $link = array_shift($flat);
    }
    while ($link && ($link['mlid'] != $book_link['mlid']));
    // Continue though the array and collect the links whose parent is this page.
    while (($link = array_shift($flat)) && $link['plid'] == $book_link['mlid']) {
      // Get node object.
      $node = menu_get_object('node', 1, $link['link_path']);
      // Add date to link title.
      $link['title'] = $link['title'] . ' - ' . format_date($node->changed, 'custom', 'M j, Y');
      $data['link'] = $link;
      $data['below'] = '';
      $children[] = $data;
    }
  }

  if ($children) {
    $elements = menu_tree_output($children);
    return drupal_render($elements);
  }
  return '';
}


Getting the uid from user name for a view argument I'm loading content from a third party system to Drupal using the Feeds and Data modules. Drupal will be used as an intranet, the users will be able to log in and see their account records (the data I'm getting into Drupal). One of the fields has the user name (not the user id), so in the external system a record can be referenced to each user.

In views is posible use the uid as an argument and show content that references to that uid. Is there a way that I can use the user name as an argument and show the content if that user is logged in or viewing his/her user profile?

Data module does not allow relationships when creating a view.

I suppose I can insert PHP code, use the user name then load de uid, and use de uid as validator in views, I'm not a PHP expert and I'm not sure if that is the correct way to do it.

Thanks in advance for your advices.

Use the Data name argument to filter the results by. Each content field has it's own argument that you can choose to filter the results by.

(edit: reply to comment) Let's say that your drupal username is user3 with a UID of 3. The user ID of the external data will be user3? So when the user goes to mysite.com/user/3 the argument will be 3 which doesn't help with the external data because that needs to be mapped to user3? If the user ID of the external data is 3 then you can use data: field_userID or whatever it is and get arg(1) using provide default value from PHP code, page manager or Views Arguments from Context. Now, if you to map the Drupal username to the external data username/user ID which is user3 then use provide default value from PHP code, get the global $user variable and use $user->name for the argument. This maps the user's name to the database column in the data table and returns (filters) all results/ database rows with that username in that column.

Don't validate it until you get it working.

global $user;
return $user->name;

or

return arg(1);


RewriteBase /folder issues on IIS for broken images I have a Drupal 7 site hosted under a subdirectory say http://example.com/drupal. I am using IIS and SQLSRV. But all the images could not be loaded on the site as these images pointing to http://example.com/sites/default/files...
I have added $base_url in settings.php but .htaccess could not be recognised by IIS. When I try to import rules from .htaccess, it does not allow RewriteBase /drupal rule as it is not supported by IIS.

Please help me out in this scenario. What could be the equivalent rule of RewriteBase /drupal?

Okay, so problem is IIS does not understand our .htaccess file and has its own set of rewrite rules. If someone's facing broken images problem, best is to create an outbound rule which will add your subdirectory into the URL. something like "/sites/all/..." to be rewritten to "/drupal/sites/all/...".


How do I perform a redirect to the cart? I'm trying to redirect the user to the cart from a custom page using the following code.

return new RedirectResponse(\Drupal::url('cart'));

Is there a function to go directly to the cartrce? If not, what is the route name for the cart page?

If you use the Devel module, you could also find the right routes on "/devel/routes".

An then do something like:

  $url = Url::fromRoute('commerce_cart.page');

  //$url->toString();
  $form_state->setRedirectUrl($url);


How to install drush extension / addon globally? I want to install drush-toolbox project globaly on my linux server box so all users can use it. How can I do it?

Put it in /usr/share/drush/commands for global accessibility.  On Windows, Drush will look in the folder named Drush/share/drush/commands inside the location specified by the ALLUSERSPROFILE environment variable.

After adding new commands, you will need to run drush cc drush to clear the Drush command cache, so that Drush will once again scan its command searchpath.


EventSubscriber endless redirect I have Drupal 8.5.1 and I am trying to force a redirect for anonymous users to the CAS login page. First I thought that the issue was related with the firing of the checkAuthStatus function below, however, the issue seems related to an endless redirect:

namespace Drupal\my_custom_module\EventSubscriber;

use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\HttpKernel\Event\GetResponseEvent;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;

/**
 * Event subscriber subscribing to KernelEvents::REQUEST.
 */
class RedirectAnonymousSubscriber implements EventSubscriberInterface {

  public function __construct() {
    $this->account = \Drupal::currentUser();
  }

  public function checkAuthStatus(GetResponseEvent $event) {
    \Drupal::logger('my_custom_module')->error('THIS IS A TEST');
    if ($this->account->isAnonymous()
        && \Drupal::routeMatch()->getRouteName() != 'cas.legacy_login'
        && \Drupal::routeMatch()->getRouteName() != 'cas.service') {
      $response = new RedirectResponse('/cas', 301);
      $response->send();
    }
  }

  public static function getSubscribedEvents() {
    $events[KernelEvents::REQUEST][] = ['checkAuthStatus', 27];
    return $events;
  }

}

What could be the issue?

Finally I have solved the issue thanks to the comments I received on my question. Here is the solution I found:

namespace Drupal\my_custom_module\EventSubscriber;

use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\HttpKernel\Event\GetResponseEvent;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;

/**
 * Event subscriber subscribing to KernelEvents::REQUEST.
 */
class RedirectAnonymousSubscriber implements EventSubscriberInterface {

  public function __construct() {
    $this->account = \Drupal::currentUser();
  }

  public function checkAuthStatus(GetResponseEvent $event) {
    if ($this->account->isAnonymous()
      && \Drupal::service('path.current')->getPath() != '/cas'
      && \Drupal::service('path.current')->getPath() != '/casservice') {
      $response = new RedirectResponse('/cas', 301);
      $event->setResponse($response);
    }
    return;
  }

  public static function getSubscribedEvents() {
    $events[KernelEvents::REQUEST][] = ['checkAuthStatus', 100];
    return $events;
  }

}

In short, the issue was related with the path checking and the RedirectResponse object management.


How can I add a custom form to the output of a controller class? I have a controller in my custom module.  Inside this controller I need to render a whole bunch of different things (some basic html, multiple forms, etc).  My main problem is I can't figure out how to

Properly load a Drupal 8 custom form
Then get that form into an acceptable format to pass to the #markup output of the controller.
Keep in mind this form is mixed in with other html that will be a mish-mash of lots of stuff not shown here (I've trimmed it down to show a basic example)

My controller code looks like this currently:

<?php

namespace Drupal\my_module\Controller;
use Drupal\Core\Controller\ControllerBase;

class SingleNodeProcessor extends ControllerBase {

  public function processSingle($nid) {
    $markup = '
' . $this->t('My custom Form Is below but there will be alot more html than just the form. So this is just an example.') . '
';

    $form = $this->formBuilder()->getForm('Drupal\my_module\Form\MyFormClassGoesHere', $nid);
    $markup .= $form; //this is a render array, how do I turn it to html so it can pass to #markup??

    return [
      '#type' => 'markup',
      '#markup' => $markup,
    ];
  }
}

I think you want to return a render array, instead of markup. Because the from needs to stay as a render array, your best bet it to bring your content content to the same format instead of the other way. In your example:

public function processSingle($nid) {
  $build = [];
  $build['heading'] = [
    '#type' => 'markup',
    '#markup' => '
' . $this->t('My custom Form Is below but there will be alot more html than just the form. So this is just an example.') . '
',
  ];
  $build['form'] = $this->formBuilder()->getForm('Drupal\my_module\Form\MyFormClassGoesHere', $nid);
  return $build;
}


Make almost duplicate copy of node when submitting We have a meeting room booking system that needs one extra feature added. Meeting rooms 1 and 2 have a removable wall so people can book Room 1, Room 2 or Rooms 1 and 2. What I need is a way during booking for the option to book one or both rooms.

My plan: Offering separate booking forms for Room 1 and Room 2 and just have a field where they can check off if they need the other room booked with it. If this box is checked, it will create a duplicate booking with a new ID and the room number (Term reference list) changed.

From my reading, I think I need to use node_save() to do this? I am not sure where to call this from though. I assume I need to call it from one of the hook_node_* things (as we already do for some other custom code)?

Basically, how do I create a duplicate node when submitting a form with almost identical data but one field is changed before it saves the copy?

Thanks!

Drupal core doesn't provide hook after a node has been saved, but you can use hook_node_presave() like

<?php
function mymodule_node_presave() {
  $var = $node->original->field_my_field['und'][0]['value'];
  // field_my_field could be the checkbox value, if both rooms should be booked
  if ($var == true) { make_a_copy_but_change_a_value(); }
}
?>

Using this hook, you can look for your extra checkbox value (if the second room should be booked, too) and create a copy of the node object. But beware, at this point (hook_node_presave) the original node is not yet fully written to the database. However, the cool thing is that it fires both on node save and node update, so if you need to do something both on the creation and the updating of a node (e.g. if a booking of both rooms changes).

To actually use a hook after node insertion, you may want to try the Hook Post Action module as it provides special hooks. Drupal core does not provide such hooks, hook_node_insert and hook_node_update are both fired after the sql query for insertion is scheduled for execution but due to the transactional system the data is not yet in the database.


How do I create a link to the author's profile on the node that user created? I want a create a link on each node page, which redirects to the profile page of the user who created that particular node.

How can I achieve this?

Create a custom block with this:

/**
 * Implements hook_block_info().
 */
function mymodule_block_info() {
  $blocks = array();
  $blocks['author'] = array(
    'info' => t('author'),
  );

  return $blocks;
}

/**
 * Implements hook_block_view().
 */
function mymodule_block_view($delta='') {
  $block = array();

  switch($delta) {
    case 'author' :
      $block['title'] = NULL;

      ////////////////////////////////////////////
      $link = NULL;
      if (arg(0) == 'node' && is_numeric(arg(1)) {
        $node = arg(1);
        if (!empty($node->uid)) {
          $link = l('view all work', 'user/' $node->uid);
        }
      }
      //////////////////////////////////////////

      $block['content'] = $link;

      break;
  }

  return $block;
}

And set this block to nodes page with context, panels or native drupal blocks page.


Where do custom Drush hooks go? I am attempting to sanitize my database as described in this Acquia guide.

For my site, I need to sanitize all the usernames as well; I would like to sanitize the usernames exactly the same as the e-mail addresses.

The guide suggests using a hook such as this:

<?php
/**
* Implementation of hook_drush_sql_sync_sanitize().
*/
function modulename_drush_sql_sync_sanitize($source) {
    $query = "UPDATE content_type_profile SET field_primary_email_email = CONCAT(SUBSTRING_INDEX(field_primary_email_email,'@', 1), '@example.com');";

    $query .= "UPDATE content_type_profile SET field_work_phone_value = SUBSTRING(FLOOR(RAND() * 1000000000000) WHERE uid NOT IN  SELECT uid FROM users_roles WHERE rid=3) AND uid > 0 FROM 1 FOR 12)  WHERE field_work_phone_value IS NOT NULL;";

   drush_sql_register_post_sync_op('my-sanitize-id', dt('Sanitize email addresses and phone numbers'), $query);
}
?>

But since this is for Drush, I don't know where to put the hook.  I tried modifying the code and  adding it to an enabled module on my site, but when I ran sql-sanitize, it didn't pick up the hook.

This is what I did.  In MYMODULE/MYMODULE.module, I added the following code:

/**
* Implementation of hook_drush_sql_sync_sanitize().
*/
function MYMODULE_drush_sql_sync_sanitize($source) {
    $query = "UPDATE user SET name = CONCAT(SUBSTRING_INDEX(name,'@', 1), '@example.com');";

   drush_sql_register_post_sync_op('my-sanitize-id', dt('Sanitize user names'), $query);
}
?>

Looking at the drush code this is the function that looks for the "hooks"

drush_command_invoke_all('drush_sql_sync_sanitize', 'default');

following the path at the end is calling to:

drush_commandfile_list()

which is going to look for hooks implementations in the next folders:

The "/path/to/drush/commands" folder.
Folders listed in the 'include' option (see example.drushrc.php).
The system-wide drush commands folder, e.g. /usr/share/drush/commands
The ".drush" folder in the user's HOME folder.
/drush and sites/all/drush in current Drupal site.
Folders belonging to enabled modules in the current Drupal site.

So as @Clive suggested probably MYMODULE.drush.inc and MYMODULE_drush_sql_sync_sanitize should work.