Dev version connects to the live site database despite settings.php I've made a dev copy of the site to perform some tests and bug fixes:

copied site files to the separate directory
copied database under the same user, so I'm able to see both DBs in the phpmyadmin
edited settings.php to point dev to the copied database
created new nginx conf to serve dev.mysite.com

BUT, the dev version is still communicates with the production DB somehow.

Server configuration:
Ubuntu, Varnish front, Nginx back, MariaDB, opcache

Site configuration: Drupal7, single-site setup

And of course, I've double checked settings.php

Christmas mystery?

You did not edit your sites.php file or name the new site directory in such a way that Drupal can discover it.


Products do not show under category in Commerce Kickstart I am building a site on top of Commerce Kickstart, no demo.
I created a category, but when creating a product of that content type it does not show under the category.
I do provide a menu link to the product but it still does not show.
I can see it from Manage Products.
What am I missing?

Here's the proper steps for creating a new product type with matching product display (so you always have a 1:1 relationship of content type to product variation type.)

When making a variant it will ask to create a matching content type for the product display - which it sounds like you've opted for this.

On your created Product Display content type, make sure you add the existing Product Category term reference field. The Commerce Kickstart 2 catalog is very specific to its initial setup (demo or no demo, regardless.) It does some work to hijack the callback path for the provided taxonomy vocabulary.

In fact, for best results you should make sure the new content type mimics the default product display until you're familiar with how it all works.

Lastly, Commerce Kickstart 2 comes with the Inline Entity Form module. It is opinionated that products will always be created from the node form, not individually. So make sure you're creating nodes and populating the products through there.


Is Drupal 7 a good fit for my site? I started creating my site in Wordpress 3.1, and I have hit a speed bump. I am considering switching to EE or Drupal 7, in hopes of achieving my vision of the site.

The problem I am having is excluding terms in the dropdown menu query. Currently I have taxonomies for CarMake, CarModel, Year, etc... My problem is when I select Honda, the  menu does not exclude non Honda cars, so you get a giant list of car models.

The search menu then would return all "posts" that include those taxonomy terms in the "Videos" custom post type. Each "post" was essentially a blog post with a very short description and a youtube video.

Before I invest countless hours learning Drupal or EE, I would like to find out how hard this menu/search would be to implement. An example of the menu I would like to re-create is here

The Hierarchical Select module does exactly what you describe. Here is a demo that even uses car brands as the example.


what does $styles means in drupal? I am new in drupal.. please let me know what is the meaning of

$styles

in drupal html.tpl.php file..
If we want to add new css and js from where we can add this..

PLeas help me..

$styles is a variable. It's initialised and made available to the template via the core template_process_html() function.

To add CSS you can use drupal_add_css(), and to add JS you can use drupal_add_js(). Either can also be accomplished using the #attached property in a render array (which is actually the recommended approach these days), or by including scripts/stylesheets keys in your theme's .info file.

Where you can add it depends on what context you need to add it in. This could be page callback, one of many alter hooks, a process or preprocess function, and so on. If your new CSS applies to every page, it might make sense to use the info file method.

Alternatively, if you want to override the CSS of an existing theme, you can create a sub-theme and simply modify the appropriate CSS files without having to use the API.

If you're brand new to Drupal there are a few concepts you need to understand before any of this will make sense. I recommend reading the following:

Theming Guide
Preprocess and process functions
Render Arrays in Drupal 7
Writing theme .info files
Creating a sub-theme


How do I utilize Drupal commerce to sell large files stored on Amazon S3 I am working on a project for work that involves replacing a current "tape and staple" file delivery system. It's a Drupal site, but with many many third party outdated VERY unstable software. However, it successfully sells very large files from S3.

My job is to use Drupal 7 with Drupal Commerce Module set, Commerce file Module 7.x-2.0, AmazonS3 7.x-2.0 Module. Also, the files that will be associated with one specific field live in various S3 Buckets.

I successfully got all of the above modules working as advertised. But my functionality is not complete.

What I need:

The ability to choose buckets within the field when creating a product.
link to an existing .zip file already stored on S3

About Bucket Selection: I have files located in various buckets. These files relate to the same Content type and product type. (at the time the business started they didn't understand what buckets meant. so files are a bit disorganized) I need to have the file attachment field have the ability to select a file from S3, from various buckets. Example: Product A has a file in Bucket A. Product B has a file in Bucket B. Etc... So when creating a product, the file field (that will contain the file being sold) will need to have the ability to attach an S3 file located in various buckets

Am I on the right path? Are the above modules the correct ones to have? Is there another one i need to make my connection complete or will I have to design one to get my final needs?

Update: I just found the Amazon S3 File System Module Is this something that would help me?

You really want to use the Drupal License and License Billing modules to sell access to Commerce Files.

It might take a little custom code (a few simple objects and a few hooks) to make sure your amazon S3 links are getting licensed correctly to the right user.

In terms of your two requests:

The ability to choose buckets within the field when creating a product.
link to an existing .zip file already stored on S3

Yeah, it looks like s3 file system module is the way to go for S3 API ... they even have a migrate module and a proxy module that could make a simple file on your website, load to an s3 of your choice and still be linked to your local.

If you installed the S3 module mentioned above, you could:

Use hook_form_alter() to modify the file field
Use hook_form_alter() to add pre-empt the normal submit handler
Use your new submit handler to save the file to your preferred bucket.


Set a main-menu item as active with custom code I want to set a menu item of the main menu as active (class="active").

I'm specifically looking for a hook or function, not a contrib module.

I have seen recommendations for Context, and I have looked in the module code, but it uses hooks which I cannot find on the API-Site.

If you simply want to add the 'active' class to a menu item you could do it in the code before printing the menu.
If you want the menu item to also act like an active item you could use menu_tree_set_path() that was supposedly added in Drupal 7.9.

In earlier versions and Drupal 6 I used this:

function mymodule_init() {
  $item = menu_get_item($_GET['q']);
  $item['href'] = 'node/1';
  menu_set_item(NULL, $item);
}

However both options just add the 'active-trail' (not 'active') class(es), but that should suffice in most cases.


Custom username paths? I want to be able to create paths like this:

/guy1
/guy2
/guy3

It's easy enough if I want /profile/guy1 ... then I can just do this:

gg_profile.viewUserProfile:
  path: '/profile/{username}'
  defaults:
    _controller: '\Drupal\gg_profile\Controller\GGProfileController::viewUserProfile'

But I want it to work with the /profile bit. Changing it as follows doesn't work:

  path: '/{username}'

How do I make it work without having the extra /profile bit?

You cannot: The part of the path after the first slash cannot be dynamic, so you cannot use /{username} as path. This is explicitly stated in Structure of routes, which describes path as follows.

  path (required): The URL to the route, with a leading forward slash (e.g., path: '/book'). You can use dynamic properties by including them in curly braces. (e.g., path: '/node/{node}/outline'). These will be passed along as arguments via parameter converters to the controller/form (see below). Note that the first item of the path must not be dynamic.

You can use /profile/{username}, but /{username} doesn't work.


How to get all term descriptions from a specific taxonomy vocabulary? I have a block that displays an imagemap, and each map area represents a taxonomy term. All terms are in the same vocabulary.

For each map area, I know the term name and want to pull the term description using a Drupal function. I know I can do something like this:

<?php $myTerm = taxonomy_get_term_by_name('1'); ?>
<area shape="poly" title="<?php echo $myTerm[0]->description; ?>" coords="1,2,3" href="link2" />

But it's quite clunky and means making a function call for every map area.

Is there an API function that gets every term in a vocabulary (like taxonomy_node_get_terms_by_vocabulary() but without referencing a node?)...

Or should I make a module for this..?

I think you could use taxonomy_get_tree or just write your own query_function with the following query: db_query('SELECT description FROM {term_data} where vid = %s',$vid).


Get node in custom token to be used in Pathauto url alias pattern I'm attempting to use a custom made token for url alias patterns. I've been able to custom tokens using node information just fine. But it just occurred to me that I don't know how I could possibly use it with url alias patterns.

function mymodule_plugins_tokens($type, $tokens, array $data, array $options, \Drupal\Core\Render\BubbleableMetadata $bubbleable_metadata){
  $token_service = \Drupal::token();
  $replacements = array();
  if($type == 'mymodule_tokens') {
    foreach($tokens as $name => $original){
      switch($name){
        case 'current_nid':
        $node = \Drupal::routeMatch()->getParameter('node');
        $title = (!empty($node)) ? $node->id() : 'This is a test';
        $replacements[$original] = $title;
        break;
      }
    }
  }
  return $replacements;
}

It works fine if I'm using it on a node page. But what if I want to use it in a url alias pattern in the pathauto module?

$node = \Drupal::routeMatch()->getParameter('node');

I know here it gets the node based on the current page it's on. But if it's used in a url alias pattern it's not on any page at the time of url alias construction.
I have a feeling this is possible since there are already tokens like [node:title] that work.  Also is there any weird thing I can do like this?

[mymodule_tokens:current_nid[node:nid]]

Where I pass a token within a token? And if I can how would I access that extra parameter within my custom token. (p.s. I understand that my example is just getting the current_nid and that there are already tokens for it. I'm just using that as an example)

Is there anyway I can get the node from my custom token to be used in a url alias pattern?

You get the node from $data:

  if (!empty($data['node'])) {
    /* @var \Drupal\node\NodeInterface $node */
    $node = $data['node'];
  }

It is the responsibility of the code which calls replace() to provide the correct context (in case of Pathauto the node for which it's building the alias).


How to create a drupal view using sql Is there anyway for me to create a Drupal view from two sql queries and have two separate outputs. Here is the two SQL queries I want to create a view from:

SELECT f.delta      AS field_data_field_session_start_date_delta
     , f.entity_id  AS date_id_date_filter
     , f.delta      AS date_delta_date_filter
     , n.title      AS node_title
     , n.nid        AS nid
     , n.language   AS node_language
     , f.field_session_start_date_value AS field_data_field_session_start_date_field_session_start_date
     , f.field_session_start_date_value2 AS field_data_field_session_start_date_field_session_start_date2
     , 'node'       AS field_data_field_session_start_date_node_entity_type
  FROM node n
  JOIN field_data_field_session_start_date f
    ON f.entity_id = n.nid
   AND f.entity_type = 'node'
   AND f.deleted = '0'
   AND f.field_session_start_date_value >= NOW()
WHERE n.status = '1'
ORDER
    BY f.field_session_start_date_value ASC
LIMIT 3 OFFSET 0

SELECT f.delta      AS field_data_field_session_start_date_delta
     , f.entity_id  AS date_id_date_filter
     , f.delta      AS date_delta_date_filter
     , n.title      AS node_title
     , n.nid        AS nid
     , n.language   AS node_language
     , f.field_session_start_date_value AS field_data_field_session_start_date_field_session_start_date
     , f.field_session_start_date_value2 AS field_data_field_session_start_date_field_session_start_date2
     , 'node'       AS field_data_field_session_start_date_node_entity_type
  FROM node n
  JOIN field_data_field_session_start_date f
    ON f.entity_id = n.nid
   AND f.entity_type = 'node'
   AND f.deleted = '0'
   AND f.field_session_start_date_value <= NOW()
   AND f.field_session_start_date_value2 > NOW()
WHERE n.status = '1'
ORDER
    BY f.field_session_start_date_value ASC
LIMIT 3 OFFSET 0

I think the easiest way to create this in views will be to just manually read it and re-create using the views UI.


how to create separate contextual filters for pages in views I have created a view and it has a block and two pages say page1 and page2. If I set the contextual filter it applies for both page1 and page2. I have configured two contextual filters and I want first contextual filter to be applied for page1 and other for page2. Is it possible to do so? If not is there any alternative where I can have separate contextual filters for separate pages.

While filtering a views page it should evaluate only one contextual filter. Is it possible to do that?

After setting everything the way you want it on the first page, switch to the other display and change those settings, but for each one make sure you have the This page (override) drop-down selected.


Using multiple parameters in Forena I'm trying to pass multiple parameters from one Forena report to another one.
Currently my link looks like this:

reports/aen_multi?startdate={eventdate}&enddate={eventdate}

but this does not work ("Invalid or malformed report document").

For links with only one parameter this works:

reports/aen_multi?startdate={eventdate}

What is the correct way of linking to a report with several parameters?

After searching a lot more, I came across this discussion which shows that & needs to be encoded as &amp;.
So the working link is:

 reports/aen_multi?startdate={eventdate}&amp;enddate={eventdate}

I'll leave the question up as this might help others.


Convert an already created custom content type into a new module Is there a tool that automates (or helps) the creation of a module based on a current custom content type ?
I have two new content types (forms) created using the Drupal user interface, now I realize I need to customize it further and would like to create a module to pack them all. Since I already done a lot of work building the (big) forms I was wandering if there is some kind of trick (or module) to accomplish this.

Use Features. It's main job is to export such configuration into code. While not primarily intended to be manipulated afterwards, it's definitely possible, as I've done so several times myself.

You can even add custom directly into the generated .module file and features will respect and keep that if you do further changes from the UI later.

This way you can keep using the UI to make most of the changes to the content type, yet keep custom logic in the same module.


Rules: action before a user gets deleted I'm trying to fetch a user's profile before the user account gets deleted.

I'm using the rule 'when user get's deleted' but once it gets deleted i cannot obviously access his profile.

Is there a way to get the profile 'before' the user gets deleted ?

Pulling my hairs out; any ideas ? Thanks folks !

(i'm using drupal 6)

I may need a bit more info on what you're trying to access and what conditions or actions you're trying to perform on the deleted user, but I'll give it a shot.

You should have access to the deleted user's data when using the "User has been deleted" trigger. If by profile you mean data connected to the user using something like the Content Profile module, then you may want to instead use the "After deleting content" trigger, since Content Profiles are actually just regular nodes.

If that doesn't help, let me know more specifics on what you're trying to do and I'll see if I can help.


Best method of pushing content changes that contains paragraph fields from dev to production? I manage a very big site with over 30k nodes and these nodes have many fields in them including paragaph fields with many sub fields in them too. Currently when testing and adding in content. I have to manually input them into the dev site and once the client approves, I have to manually do this again on prod. The import feeds module doesnt support paragraphs and neither do others from what I researched.

What would be the best method of deploying content changes from dev to prod that contain paragraph fields data?

One recommendation is to use "Features" to generate:

a Feature export of any config changes to the content types, paragraph bundles, and fields
a separate Feature export of the content/nodes themselves

To accomplish this, you'll need:

"Features" module:  https://www.drupal.org/project/features
"Features Extra" module:  https://www.drupal.org/project/features_extra
"UUID  Features" module:  https://www.drupal.org/project/uuid_features
"Strongarm" module:  https://www.drupal.org/project/strongarm
"Diff" module: https://www.drupal.org/project/diff

NOTE:  this approach generally works well, as long as the effected content/node IDs between production and your staging/dev environment are the same.


How to set one region over the other (and not beside it) in Omega theme? I´m using Omega theme in a Drupal 7 installation, and don´t know how to put the sidebar second right below the sidebar first.

Under Zone and region configuration I have the content section, with the content zone inside it.
Content zone has 12 columns.
Inside it I have 2 regions:
content (6 cols).
sidebar second (3 cols).

If I add there another region, (sidebar first in my case) Omega puts it along the other two, and I can only set the weight of each one to determine wich one will appear first.
But what if I want one region under the other?

I´m using delta module to create different layouts according to some variables, but every time I try to set one region over the other it fails. Is there any way to do that?

Thanks!

UPDATE: How may I use context to do that in case it is possible?

The side bars are used to create columns and not for placing it one on top of the other.

If you want a single column then you would go for one of the three. If you want two columns go with any two of them and if you want three columns go for all three.

As for placing contents one on top of the other the blocks should be used for that. Let us say you have two blocks one to show the latest articles and another to place the login box and you want the articles to be on top of the login box then you would go with one of the side bars and content and place both the blocks in the same sidebar and arrange it as you would want it.


SQL query cck fields I want to query if a specific content type has a photo in a custom cck field. I could probably create a View to find this? My mock up query is below. the photo is inside the table 'content_field_photo' in the row 'field_photo_data' inside this table is another row called 'nid' and this nid value should be present in the content type table called 'content_type_contenttype'

 SELECT * from content_field_photo WHERE
content_field_photo.field_photo_data IS NOT NULL AND nid is in
content_type_contenttype.nid

You could use the Forena module to create a report using the data block that matches your "mock up query". While doing so, you could also use the WYSIWYG query writing facilities to further tune your query if needed (think of it as using PhpMyAdmin integrated within your Drupal site).

Visit the demo site samples for more details, and/or refer to 2 types of documentation that's available:

Community documentation, which includes a child page Video demos and tutorials.
Documentation that comes with Forena, which you can access right after install and enable of the module. Checkout the demo site for an online example of it.

Disclosure: I'm a (co-)maintainer of Forena.


Webform 8 - How can I make a text field value be A if a select value is 1? In Webform 8 I am trying to figure out how to populate a text field with a value based on what is chosen on a drop down.

For example:
Select Value are states
If user selects Deleware then the value for the text field Ratified is equal to 1.

How can I achieve this in Webform 8x?

In Webform 7x I am able to do this with the Conditionals tab but can't seem to be able to figure out how to do this in Webform 8.

You have to use JS, go to settings - CSS/JS tab, write code in CUSTOM JAVASCRIPT textarea.

Some code for reference. I got a text input (id is edit-name), a select (id is edit-gender), the id you find enter 'F12' to see. ID is automatically generated by Webform.
When I select male, the text input will appear male.

(function ($, Drupal) {'use strict';$(document).ready(function(){
  'use strict';
  var name = $("#edit-name");
  var gender = $("#edit-gender");
  var duty = $("#edit-duty-select");
  function ab() {if (gender.val()==='male'){name.val("male");} else {name.val("girl")}};
  gender.change(ab);  // add a Listener to select
});
})(jQuery, Drupal);


How can I allow authenticated users to edit their nodes only while they are unpublished? I have a site in which content must be approved by an administrator before it is published.  Authenticated users have the ability to submit content, which is unpublished by default.  I would also like to be able to have them view and edit content while it is in the unpublished state (for cases in which they realize they made a mistake and would like to correct the submission, etc.)

However, I do not want them to be able to edit the content once it is published, so I don't want to give them blanket edit permissions.

How can I allow them to edit nodes of a given content type only so long as such nodes are in an unpublished state?

You could implement a special hook_node_access to return TRUE or FALSE based on the node status.


?format=json returns 'Not acceptable format: json' I am trying to set up the REST module for Drupal8.2.7. Install went through without problems.

I tried to follow this documentation page https://www.drupal.org/docs/8/api/restful-web-services-api/restful-web-services-api-overview to set up a simple resource for getting nodes.

I followed the descriptions for 'Drupal 8.2 & Later: ' and created this yml file in the this folder  \Drupal\rest\RestResourceConfigInterface

id: entity.node
plugin_id: 'entity:node'
granularity: method
configuration:
  GET:
    supported_formats:
      - json
    supported_auth:
      - basic_auth
      - cookie

Once that was done I cleared the cache and expected to be able to get node 1 as json using this url:

/node/1?_format=json

However, all I receive is:
    {"message":"Not acceptable format: json"}

What am I missing here?

Update:
I went to here
    /admin/config/development/configuration/single/export
and exported
    entity.node

uuid: d44c745b-d69b-4893-8f31-b65d0fe80bf0
langcode: en
status: true
dependencies:
  module:
    - basic_auth
    - hal
    - node
  _core:
    default_config_hash: t_jfECmZhJqBOJuSOFn87EOi_TWi-_fRYTuJgd19vgg
  id: entity.node
    plugin_id: 'entity:node'
    granularity: resource
  configuration:
    methods:
      - GET
      - POST
      - PATCH
      - DELETE
    formats:
      - json
      - hal_json
    authentication:
      - basic_auth
    GET:
      supported_formats:
        - json
        - xml
      supported_auth:
        - basic_auth
        - cookie
    POST:
      supported_formats:
        - hal_json
        - json
        - xml
      supported_auth:
        - basic_auth
        - cookie
   DELETE:
     supported_formats:
       - hal_json
       - json
       - xml
  supported_auth:
    - basic_auth
    - cookie
  PATCH:
    supported_formats:
      - hal_json
      - json
      - xml
    supported_auth:
      - basic_auth
      - cookie

However, trying to get my node via the mentioned url '/node/1?_format=json' still returns {"message":"Not acceptable format: json"}

\Drupal\rest\RestResourceConfigInterface is a namespace not a directory structure.

Configuration files need to be imported into the active configuration which is stored in the database.

In the case of a single config file:

Go to the
page /admin/config/development/configuration/single/import
Under "Configuration type" select "REST resource configuration" In the box
At "Paste your configuration here" paste your REST YAML configuration

Configuration can be exported and imported using the config directory, as specified in settings.php with the line $config_directories['sync'] = 'sites/default/config';.

To export the current active configuration to files in the sync directory use the drush command: drush config-export

To import configuration from files in the sync directory and overwrite your current active configuration, go to the page /admin/config/development/configuration.

Another option is to use the REST UI module to configure your REST services.


Programmatically accessing block content Could anyone tell me how to programmatically access the field content of a custom block?

Thus far I've managed:

use Drupal\block\Entity\Block;
$block = Block::load($block_name);

if ($block) {
  $render = \Drupal::entityTypeManager()
    ->getViewBuilder('block')
    ->view($block);
}

However this doesn't give me access to the fields and their data.

Your code loads a configured block, not the content of a custom block.

This will load the field data of block content:

$custom_block = \Drupal::entityTypeManager()->getStorage('block_content')->load('1');
$fieldcontent = $custom_block->field_myfield->value;


How to check "Show as expanded" by default on the Add menu item page I need the 'Show as Expanded' checkbox on the Add menu item page to be selected by default.

I created a module, 'expand_menu_items', and tried a hook_form_alter function to get the id, apparently it's 'menu_link_content_menu_link_content_form'.

I know I'm looking for #default_value, there are a couple and tried setting them to 'TRUE' but it's not having an effect on the page (xdebug shows the value as true). What could I be doing wrong?

Similar questions exist here:

Drupal 8 Menu always show as expanded - Though I may use the sql query to fix existing menu items, I'm more concerned with new menu items.
How to set the default "Show as expanded" to true in a custom menu item - This seemed promising, although in this case, all the menu items were added by end users.

Here's the function code:

function expand_menu_items_form_alter($form, FormStateInterface &$form_state, $form_id) {
if ($form_id == 'menu_link_content_menu_link_content_form') {
    // $form['expanded']['#default_value'] = true; // Doesn't work.
    $form['expanded']['widget']['value']['#default_value'] = true; // Doesn't work either.

}

}

Attached below is an image to the form page in question.

To set a default value for the menu link entity use hook_ENTITY_TYPE_create:

use Drupal\menu_link_content\MenuLinkContentInterface;

/**
 * Implements hook_ENTITY_TYPE_create() for menu_link_content.
 */
function mymodule_menu_link_content_create(MenuLinkContentInterface $menu_link_content) {
  $menu_link_content->expanded->value = 1;
}


Sort by node or comment We have a Question and Answer setup on Drupal. Question is a node. The answer is a comment.

What we are trying to do is to order Questions by either the latest asked question or by the latest commented question.

So when a new comment it posted, that questions moves on top. I can do it for Question or comments. But can't combine the two together.

Is there any way to achieve this?

If you were building the SQL directly, you could do it in the ORDER BY clause with the CASE WHEN syntax where you do something like:

CASE WHEN comment_table.timestamp > node_table.timestamp then comment_table.timestamp else node_table.timestamp

Since there is no default Views core plugin for CASE WHEN sorting, you can either build a Views sort plugin that implements the syntax or use existing plugins that allow custom SQL with a notable security caveat that comes with storing code in your configuration.


Hide the term id on autocomplete widget Hide the term id on autocomplete widget

How can I hide the term id on autocomplete widget ?

I use drupal 8.

There is no built-in option to hide term ID from entity_autocomple form element. Its behavior is simple, if there is a term that match then shows (TID).


Adding content type field value to a taxonomy term? What I'm trying to say at the title is, I have this Select List field that gets its values from a taxonomy called "Thing".

The taxonomy term are (Thing-1,Thing-2,Other).
When "Other" is selected a text field called "Specify" will appear. What I'm trying to do is when the user submits the form. Whatever he placed on the "Specify" field will be added as a "Thing" Taxonomy term.

So the terms will be (Thing-1,Thing-2,New Thing,Other).

I might be over explaining this, but I can't find anything on google.

If you are using Select (or Other) module and it does not specifically need to be a taxonomy term, there is an option for exactly this:

On the field edit page, the "Other value as default value" allows you
to select how other will be handled:

Add the values to the other textfield-> store the value but don't
change the list

Append the values to the current list-> store the
value and add to the list attached to the node/user/entity

Append the values to the available options-> store the value and add the value to
the list so that it can be selected on other nodes/users/entities

Ignore the values-> do not store the value

EDIT (courtesy of DuaelFr)
You will need the 7.x-3.x-dev version to be able to use this module on a Taxonomy Reference Widget.


Changing the title of the Answers add answer form I want to change "Your answer" in the add answer form of the Answers module so that it says "Give [user who asked question] your answer".

Here is a snippet of code from answers.module that defines the value

// Add the form to the question page.
        $node->content['new_answer_form'] = $answer_form;
        $node->content['new_answer_form']['#weight'] = 150;
        $node->content['new_answer_form']['new_answer_form_title'] = array(
          '#theme' => 'html_tag',
          '#tag' => 'h2',
          '#attributes' => array('class' => 'new-answer-form-title'),
          '#value' => t('Your answer'),
          '#weight' => -100,
        );

I tried changing it to:

// Add the form to the question page.
        $node->content['new_answer_form'] = $answer_form;
        $node->content['new_answer_form']['#weight'] = 150;
        $node->content['new_answer_form']['new_answer_form_title'] = array(
          '#theme' => 'html_tag',
          '#tag' => 'h2',
          '#attributes' => array('class' => 'new-answer-form-title'),
          '#value' => t('Give ', $author, 'your answer'),
          '#weight' => -100,
        );

Not surprisingly, this didn't work. I'm not sure which variable to use for $author, and other changes, so that the username of the person who asked the question appears there.

Disclaimer: I apologize if the question is off, I work for a non-profit organization that isn't a tech company and am just trying to build us a new website but have a gluten for punishment and an interest in getting back in to the tech field. Thanks for your patience.

Edit: I created a helper module for customizations to other modules.

Since you have the node object, you can find its author via $node->uid. Then load the account and wrap it in format_username():

$uid = $node->uid;
$account = user_load($uid);
$account_name = format_username($account);

The hook you need depends on the function in which your snippet was found. In your case it is in hook_node_view, so you need hook_node_view_alter()

From there it is as simple as redefining the value. Something like this:

MODULENAME_node_view_alter(&$build) {
  $node = &$build['#node'];

  $new_title = t("Give @author your answer", array('@author' => $account_name));

  $node->content['new_answer_form']['new_answer_form_title']['#value'] = $new_title.
}


Cannot login to my drupal site because of php version 5.6 I have installed drupal 7.36 and developed my site on localhost in XAMPP. After I logget out I'm not able to log in again even if name and password is correct. I have only one user created - admin. After I attempt to log in I get a message

  You are not authorized to access this page.

I can still log in. I have tried every solution I found on Internet:

Log in with another browsers
Clear all cookies of browser
Clear all caches
Truncate all cache_ tables, truncate sessions and flood tables
Set $cookie_domain = 'localhost' variable in settings.php
Add ini_set('session.cookie_domain', '127.0.0.1') to settings.php
Restart apache server
Create another user programatically and log in as new user
Log in programatically
Vacuum/reindex database in pgAdmin

Nothing worked for me. It's really simple drupal website. What exactly could cause this problem?

I've reinstalled my site (and lost my database data) and enabled again my theme and all the modules. I was able to log in and log out, repeatedly. But then I logged out one more time and closed the browser. After reopening the browser, I was not able to log in again, even with other browsers.

So finally I found that the problem is with php version 5.6 and workaround is:

function aikidolm_user_login(&$edit, $account) {
  $_SESSION['aikidolm']['ulogged'] = 1;
}

https://www.drupal.org/node/2363219#comment-9366567


Replace data from command line: site name I run in mysql:

update variable set value = replace(value,'SiteName','NewName');

and then clearing cache:

drush cache-clear

But I dont know why the site name become blank instead of NewName

I've tried this after replace in variable table, but not works:

update cache set data = replace(data,'SiteName','NewName');

I hope I can change any data from command line.

The values are serialized using the built in PHP function serialize() so setting them directly shouldn't work if I understand what you did correctly. You can use drush since it appears you have that available.

Simply use:

drush variable-set site_name "Some name here"

Otherwise you can always configure from the Drupal admin interface.


Display a block even if it is empty I am using a menu_block block that displays sub-menus depending on what page the user is. on some pages, there are no sub-menus, so my menu-block is automatically hidden by drupal. how do i force drupal to display my block even if it is empty?

thanks.

I agree with '2-Stroker'. Do this:

function HOOK_block_view_alter(&$data, $block) {
  if ($block->module == 'menu_block' && $block->delta == 'DELTA_OF_THE_BLOCK') {
    $data = array('subject' => 'TITLE OF BLOCK', 'content' => '&nbsp;');
  }
}


What hook function (is _form_alter correct?) do I use to alter the input submitted by the user into a views exposed filter form? I'm developing a views exposed filter form for searching for items in given geographic locations.

I want to restrict this to a particular country so that cities with the same name in other countries aren't shown in the View results. For example only London, UK not London, Ontario; Portsmouth UK not Portsmouth New Hampshire, USA.

(Note please don't close this topic as being too local - my question would apply to anyone who wants to do this whatever country they are in.)

The simplest approach I want to consider is suffix the user input with the country. For my example this would be Newcastle becomes Newcastle, UK.  Given that the site is focused on users in particular country, for user experience (UX) usability reasons I do not want the user to have to enter the country name at the end.

I had tried to add a function to do the suffixing by adding it as a callback in the form[#submit] array in _form_alter and implement the function in my custom module. But this did not alter my submitted input as required. Here is my code snippets:

function mymodule_form_alter(&$form, $form_state, $form_id) {

// keep the standard handler
$temp = $form['#submit'][0];

// put my handler in first
$form['#submit'][0] = '_mymodule_custom_handler_submit';

// restore the standard handler to appear in the array after mine
$form['#submit'][2] = $temp;
}

function _mymodule_custom_handler_submit(&$form, &$form_state) {
    $form['field_geofield_distance']['origin']['#value'] .= ", UK";
}

When I try this I find (using  dpm ) that the submitted input is not altered before it gets sent to the View for it to create the results - so I deduce that this code is not running before that, but instead after that.

Can you advise on what I might be doing wrong here?

Also, in the $form['#submit'] array, are the callback functions "chained" together - i.e. in that the first function in the array gets called, it modifies the form submitted input and this is then passed to the next callback. If this were the case I would have expected my code to work.

Is _form_alter the right hook to use for this problem?

Update

Now using debugger (Komodo IDE) connected to my Vagrant VM-based local development environment that's running the site to investigate a solution:

Thanks.

Update 2:

I don't think this form handler approach is going to work, the screenshot below shows a callstack - see bottom right, showing that the views execute display function (presumably the view itself) runs before my code to modify the input

First if you want to add submit handler as first in form_alter do

//prepend the handler to array
array_unshift($form['#submit'], '_mymodule_custom_handler_submit');

So you dont overwrite any other callback by some other module.

Second, check that the form input elements dont have overriding submit handlers ("
submit action on the buttons")

Third, try to assign the value with form_set_value

$oldValue = $form_state['values']['field_geofield_distance']['origin'];
$value = array('origin' => array('#value' => $oldValue. ', UK')
form_set_value($form['field_geofield_distance'], $value, $form_state);

Syntax above is not correct, but without knowing the structure of the field its impossible to know what kind of array it requires. For example Link module fields can be modified with following.

    // Set first link of the field pointing to google, most likely
    //unsets all the following ones
  $link = array(
    0 => array(
      'title' => 'Google',
      'url' => 'google.com'
    )
  );
  form_set_value($form['field_link'], $link)), $form_state);

Last but not least, use additional form validation callback instead submit handler, that way its sure that the values get passed to all "targeted(see second)" submit handlers.

Long story short. When form is being built, add input validator to it. Validator will get called after user sends the form and there you can modify values before they get submitted to submit handlers.

Summary interpretating view flow

While the view is being built first time it calls the form (which runs through standard drupal hooks like form_alter) and gets the values from it just in case it has some defaults or accepts 0 filters.

After that it runs the queries, renders the form and the result. When finished you get the view including all the elements without user input. Like clean plate (mayby some contextual filters and stuff is applied but thats irrelevant?).

Next when the user sends the form with custom input, drupal (field widgets/handlers) transforms input to values and store them in $form_state and passes them to validators. Here the custom validator can modify the user input values in $form_state and attach them with form_set_value.

If the validation passes correctly $form_state values(modified) get passed to submit handlers. Most likely views will start building itself from them. Heres more exact flow(pdf)


Updating my very first install of Drupal I'm getting emails to update my very first install. How should I go about updating? Should I download the file and drag and drop using Filezilla, or should I use command prompt on my server? http://drupal.org/project/drush/

If you can use Drush, do. It makes life very easy. If memory serves it's as simple as issuing a drush up drupal command, and following the prompts.

If you can't use Drush then copying the core Drupal files over the top of the old ones is the way to go, but make sure you don't replace the /sites folder. On most production servers the /.htaccess file will also have been modified so make sure you don't overwrite it if there have been changes made.

Either way, make sure you take a backup of the code and database before upgrading so you can easily rollback if something goes wrong.

You may find the Update your Drupal site from one minor 7.x version to another minor 7.x version page a particularly useful read before getting started.

Also, as Kalabro points out in the comments, never run an update on a production server without having tested it on your dev/staging environment first.


client side validation I am trying to enable client side validation on my web forms. I installed & enabled the modules as per the Drupal.org link:
https://www.drupal.org/node/1324924
& then went into the Configuration > Client Side Validation & inserted the form ids I had in my HTML code.

However, I am unable to get the client side validation to work (errors are not recognised in the input fields), the attached screenshot shows the modules view.

The only module that seems to be missing is the 'IFE' module which I cannot find / install.

You need to download, install and enable the IFE  (aka. "Inline Form Errors") module.

Like all Drupal modules, its project page is immediately below https://www.drupal.org/project/.

Here is a link to the project page where you can download it:  IFE project page.


creating multi-country website, where each country's site is multilingual I understand that you can create translations in many language for one website.
But what if I want to create one website not just simply to be multilingual but for multi-countries and each country's website can be bilingual or trilingual.

For example, let's I have website example.com and its default country is USA.
It will have 2 languages: English and Spanish
When I click any of them it will take me to the corresponding page:

For English version: example.com/us/en/
For Spanish version: example.com/us/es

On the top menu I will have a menu called "Countries".
When I click on "Countries", it can be take me to a "Countries" page that will show all the countries and languages they have, for example:

United States - English - Español
Japan - English - 日本語

Or "Countries" can be a drop-down list showing above.

Can someone please share with ideas to implement this?

UPDATE 1

I feel like this is related to MultiSite feature, but was not able to see any good working example on the web.

You need a mix of (at least) 3 modules to do this:

Domain : to create the 3 sites USA, Japan and France
Internationalization : to create the different languages
Domain locale : to enable languages per Domain


Adding Ajax to Webforms in Drupal 7 - Ajax Submit I'm using Webforms 3.x and Drupal 7.x.

I'd like to be able to use Drupal 7's Ajax features to provide a confirmation message via Ajax on submit.

To achieve this, I'm hoping to modify my form using a HOOK_form_alter.

The $form array provides the submit element at $form['actions']['submit']. If I add an ['#ajax'] attribute here, the action takes effect when submit is actioned by the use, and the callback function specified is called.

It seems that webform initiates two callbacks from

$form['#submit'][0] = webform_client_form_pages

$form['#submit'][1] = webform_client_form_submit

My question is, how can I initiate the necessary webform callbacks on Ajax submit?  I'm not totally familiar with webform, or how it deviates from standard FAPI (or if it does at all).

Any advice appreciated.


Entity reference view I have an entity reference view setup that currently pre-populates a content authors user name into the content form. This field has to stay the same no matter which user edits it in the future.

It works however it only works for editing content, nothing is pre-populated when creating new content with the form. I've tried adding the current user ID to the form but that will only work for creating new content and it is overridden each time the node is edited.

I can figure out how to do both the things I need but they refuse to play together. It seems like it's has to be one or the other. But there must be a way!

How would I filter the view to show the content author and the current logged(or original author) in user for use on both the edit and create new content pages?
Here is a screenshot of my view:
And the contextual filter settings:

The problem is (as your comment indicated) the user id from route. That uses the node id, or user id from the url. On an edit page that is node/123/edit, so it can load the node and obtain the user. For the create page node/create, there is no such id.

Can't you use the User ID from logged in user filter instead? That should work.


What happens to URL alias when a node is unpublished? We have many pages where we set "Generate automatic URL alias" to true and false. Then we will eventually unpublish some of the pages. Looking at Webmaster tools, we have found the URLs are still indexed and cached so when any unpublished page is crawled again it is generating a 404.

Given that in the Path settings we have set the Update action set to "Create new alias. Delete old alias", we need assistance in figuring out what happens to url aliases once the page is unpublished in the scenario where "Generate automatic URL alias" is set to true or false.

Nothing happens and nothing should.

An alias only exists on the URL level. It simply aliases "/blog/2018-01-23/my-awesome-article" to "/node/27", does a lookup for what when a request is coming in and that's it. After that, the routing and entity (access) systems are taking over to figure out what to display and who is allowed to see it.

If you unpublished node 27, then it still exists and admins can still access it, using that alias. In theory, it wouldn't even care if node 27 is deleted, it would still de-alias it to "/node/27" and then the routing system would return a 404 page as there is no node 27 anymore. This actually doesn't happen with nodes because there is code that listens on nodes being deleted and deletes aliases pointing to them as well.

It also doesn't matter if you use a manual alias or generated one using pathauto, that only differs while saving the node and telling pathauto if it should generate one dynamically or not.

But that's actually not your question, because what you're really asking is how  google updates its index when you unpublish content. And what you describe is exactly what should happen, eventually google will re-index your content, see that it no longer exists and removes it from its index. There isn't really anything else you can do directly. You could use a sitemap.xml to tell Google index your content more or less frequently but that's about it.


Show node links in modal buttonpane I want to show some node fields in buttonpane when I open node in modal.
As far as I know, it will automatically show there inputs with type submit and links with class button, but I added class button on email field link, anchor rendered is like:
Send email

but it's not showing in buttonpane.
Any idea why and how to fix it?

Ah, I just figured out from core/misc/dialog/dialog.ajax.js that I need wrapper with class form-actions.

  Send email


Correct Database settings for pushing a Drupal site live I have a Drupal 7 site.

I have it working fine on localhost and my own test domain, with individual settings folders setup such as:

sites/localhost
sites/test.mydomain.co.uk

I am now putting it up onto a site where there is no domain set, but I can access it by visiting:
sitename.org/folder1/folder2

i have duplicate settings files in;
sites/folder1.folder2
sites/www.upcomingfinaldomainname.com

Have I got these right?

I keep getting the message:

PDOException: SQLSTATE[HY000] [2013] Lost connection to MySQL server at 'reading initial communication packet', system error: 111 in db_table_exists()

I'm using the user and pass I have been provided, and the correct db names. I have also set host as localhost and removed the port number.

Any suggestions?

If your connection parameters were incorrect, you would get a different error from MySQL.

I have seen connection problems on Drupal systems for a few different reasons.

Overloaded server
Low timeout values on a busy server
Low value for max_allowed_packet (this normally is a 2006 or 2020, though, in my experience).

Assuming other sites work, then the first two likely aren't the problem.  I would check your max_allowed_packet and see if that helps matters.  I typically use 32M; large values can help with restoring backups.


I'm using CiviContribute and need CAPTCHA I'm new to Drupal and CiviCRM. I work mostly with Blackbaud/NetCommunity. I'm operating a website that using CiviContribute for donations. Our Payment Processor is Paypal Payments Pro.

I'm trying to add in a CAPTCHA or verification method to our donation part. I can't find how to add a CAPTCHA or any verification to the donation form. I don't see any customizable options on the payment page.

Is it possible to add a CAPTCHA on a CiviContribute donation form?

You should probably be asking this on the CiviCRM stack.

You can set a catpcha on a Profile. So check which Profiles you have set for the Contribution page. Then edit the Advanced settings for that Profile where you can set captcha.

Check answer here too


How to approve comments from a user with previously approved comments WordPress has a useful option for comment moderation in its Discussion Settings panel called "Before a comment appears: Comment author must have a previously approved comment".

How can one configure Drupal to approve future comments if a user has a previously approved comment in the site?

This is a follow-up from an unresolved post on Drupal.org: Auto-publish comments after that anonymous user’s previous comments have been approved [X] number of times

If you don't have programming skills use the Rules module.


Form theme function is not invoked for a block content Have a custom module with a block. Added form and form theme functions. Using hook_theme() to register  form theme function.

Trying to put form content in the _block_view() function into block content.
But finaly it doesn't use form theme function - theme_mymodule_custom_form()

The form is displayed on a block, but theme function is not in use,
Have no idea how to make this work.
Found a good sample here http://www.jaypan.com/comment/1758, but it didn't help me.

 function mymodule_block_view($delta = '') {
  switch($delta){
    case 'mymodule':
      if(user_access('access content')){
        $block['subject'] = 'Block header';
        $block['content'] = drupal_get_form('mymodule_custom_form');
      }
    return $block;
  }
 }

function mymodule_theme()
{
    return array
    (
        'mymodule_custom_form' => array
        (
            'render element' => 'form'
        ),
    );
}

/**
*  Create a form
*/
function mymodule_custom_form($form, $form_state) {
  // Form elements
  $form = array();

  // Text field
  $form['Input'] = array(
    '#title' => t('Input field'),
    '#type' => 'textfield',
    '#required' => TRUE,
  );

  // Submit
  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => 'Search',
  );

    // Get the path to the module
    $path = drupal_get_path('module', 'mymodule');
    $form['#attached'] = array
    (
        'css' => array
        (
            'type' => 'file',
            'data' => $path . '/css/style.css',
        ),
        'js' => array
        (
            'type' => 'file',
            'data' => $path . '/js/sample.js',
        )
    );

  return $form;
}

function theme_mymodule_custom_form($variables )
{
    // Isolate the form definition form the $variables array
    $form = $variables['form'];
    $output = '
Themed form
';
    $output .= drupal_render($form['Input']);
    $output .= drupal_render_children($form);
    return $output;
}

Somehow, this started working on my localhost. I think this was a cache issue. If you have the same problem, try clearing the cache.


Adjust viewability of content based on the value of a field for a specific user For my website, I have a view (created using the Views module), let's call it View1, that displays content types that have field of user entity references (as in, it's a select list with all the users for the website on there).

I have a separate view (Views module), let's call it View2, that is used by non-admin users. I would like that view to be populated by content types that have been assigned to them by the admin. The admin uses the select list mentioned above to assign users to a certain user.

Is there a way to filter content types in View2 so that it only displays content that has been assigned to you from View1?

You can just create non-admin view which display all given content types, then users can see specific content types based on their role permissions. This can be achieved by adding Nodeaccess.

For example:

user1 has role ct1
user2 has role ct2
assign view permission Nodeaccess:

ct1 role can view ct1 type, but not ct2
ct2 role can view ct2 type, but not ct1
to extend the access using field references, try: Node access node reference,

create a view which lists ct1 & ct2 and users will see the right content based on their roles.

You other few options to investigate:

in your non-admin view configure relationships, so field can point to the right content type (also check: Bundle Name Reference + EVA)
in your users's View, create sub-views where you can override the fields (if your Style is set to Fields),
create multiple views for each content type and implement Viewfield, so admin can assign the view based on the its value,
create a non-admin view with rendered entity Style, create a template, write a logic in preprocess function and assign to the template variable.


How to avoid Exif data rotating images automatically after upload? an image has been taken upside down, then rotated with any software, then uploaded to my Drupal website and it shows how it was originally taken because it read the Exif metadata.

Is there a way to avoid this?

or, if that's not possible,

how can I add a rotation Image Style drop down that the editor can select when creating the node?

Based on the picture preview, after uploading the picture, the editor would select an Image Style that would set the orientation of the picture right. if the picture is upside down, the editor could selec

Please read this article - no module will be able to correctly interpret EXIF orientation, because there are too many "correct", widely used but contradicting interpretations. Even biggest brands have problems with this. Even if your site will not rotate image, browser still can.

To go around this problem, you can use Formatter Field module:

  For example, say you have a page node with an image field. Normally, you would select an image style as the formatter, and all page nodes would use that same image style. With this module, you can add a formatter field to page nodes, which is hooked up to the image field. Then when the node is created or edited, the image style can be selected per-node.

It's officially still in beta, but that's the best solution I know if you have no control over user's uploads. If you are the only one who uploades, just strip EXIF data (at least orientation part) and make sure you save your files without any, when preparing them for upload.


Can't click link added to header of a block In Drupal 7 I created a views page, and I want users to have the option to view the results either as a list, or with thumbnails (like on a lot of websites). The only way I can think of doing that is creating one page with the results as a list, and having a link to another page with the results that have thumbnails.

But my question is, how do I add just a random link to the top of my block page that will direct users to the 'thumbnail' page?

I tried to use 'unfiltered text' in the header and put the html for a link in there, and when I went to the page it looked like a link, but I couldn't click it. Any suggestions?

If I understand the question correctly, this can easily be done using Views alone with a nice tabbed menu:

Create your view page as normal, with the default information provided, except for the url - set that to whatever you want, in my example /tabs
change the Display name under Page details to: Base (just to make things easier to read later on)

Add a Page
Change the Display name to the format type of the default page, presumably 'List View'
set up the format, show, fields, filter, sort, etc. how you want the list view to be displayed - be sure to change the 'For' drop down from All displays to 'This page (override)' - or the changes you make will be set for all the pages, but you want different settings for each page
set Path: tabs/list
set Menu: Default menu tab, Title: View as List, Parent: already exists

Add a Page
Change the Display name to the format type of the second page, presumably 'Thumbnail View'
set up the format, show, fields, filter, sort, etc. how you want the thumbnail view to be displayed - be sure to change the 'For' drop down from All displays to 'This page (override)' - or the changes you make will be set for all the pages, but you want different settings for each page
set Path: tabs/thumbnail
set Menu: menu tab, Title: View as Thumbnails, Menu: Navigation

This should create a tabbed menu at the top of your view for easy navigation by users:


How to create a link to a file in a module? In Drupal 7 I have a custom module that create a file in public://company/my.csv but in my module admin interface I want to create link to this file in a status message :

drupal_set_message('download your ' . l('file', $url));

To link the file I tried

$url = file_create_url('public://company/my.csv');
$url = drupal_get_path('file', 'my.csv');

I tried also to make myself the link to sites/default/files etc but it doesn't run. Sometimes I get 404 not found and sometimes "You cannot access to this directory".

(I have already checked that the file is well created in the good folder)

Any help is appreciated.

file_create_url() is right choice. Check the url it generates and try to open it directly in browser. If it fails do one of these:

Check if file is exists in right folder
If yes, check if it readable (filesystem permissions). Also check permissions for files/ directory.
If file exists and is readable, check your server setup. It should allow to view files from files/ directory. Probably you have wrong mod_rewrite config (apache) or wrong nginx config.


How can I list Drupal 8 Content Moderation draft I'm able to write a "draft" as an admin so it's visible as unpublished content on the content list.

The problem is that I can not make list visible to other "editors" (Who even can access the node as "draft" and even edit it and store again).

In short words admin only is able to view all contents including drafts, other user see only published contents.

How can I make people able to browse full content list, including the drafted nodes?

Out of the box, on Drupal, only users with the Bypass content access control permission can see every unpublished post, but that is a permission to give to a very small set of users, such as administrator users.
The other users can only see the unpublished nodes they created.

You can create a module that defines a new permission (e.g. View unpublished content), and implement hook_node_access_records_alter()/hook_node_grants_alter() to grant the view access to those users with the new permission.


How do we re-use Paragraph items? Paragraph items are only available to their parent entities. But is there any known way to make it possible to re-use existing Paragraph items?

Paragraphs is focused on reusing layouts not content. The most obvious implication is on revisions.

In a standard reference field you reference the latest revision of the target. When you roll back the parent the target keeps the actual content. Paragraphs on the other hand keeps track of the revisions and allows you to rollback an entity including the content of the paragraphs that are owned by the entity. And that's the problem, if Paragraphs would allow reusing, how a rollback should be handled for paragraphs that are shared among multiple host entities.

So Paragraphs is by design not a tool for reusing content.

But there is good news, there will be a library entity, which will make this possible:

  Implement Library entity type

  We want to make this separate entity type:
  - Autosync with bundles + fields of Paragraphs
  - Still add a label (plus more administrational fields if needed for managing them).

  A reusable paragraph will be typically stored as a clone of a previous
  paragraph. It is NOT a composite of the original. Reusable paragraphs
  have an own separate edit form and can also be creted independently
  through the Add form.

  A user can click the action "Add to library" that makes a paragraph
  reusable. This clones the paragraph and the original host entity will
  have a new paragraph instance added that contains a reference to the
  effective reusable paragraph.

  The paragraph type "From Library" contains nothing but a entity
  reference to the reusable paragraph. Initially, using autocomplete
  widget here is fine.

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


hook_user_insert get form values? I defined a field myField through admin/configuration/manage fields. Then I implemented hook_user_insert because I want to do something with this field after the user registration. How can I access to myField value? I was trying with $edit['field_myField'] but I get an array.

Any help will be appreciated.

Field data is stored in arrays.

Here is a sample user account information I save from information retrieved elsewhere:

 $roles = user_roles();
 $userinfo = array(
      'name' => $name,
      'pass' => user_password(),
      'init' => $name,
      'status' => 1,
      'access' => REQUEST_TIME,
      'roles'        => array(array_search('student', $roles) => 1),
      'field_first_name'   => array(LANGUAGE_NONE => array( 0 => array('value' => $ldap_details['first_name']))),
      'field_last_name'    => array(LANGUAGE_NONE => array( 0 => array('value' => $ldap_details['last_name']))),
      'field_secret_number'  => array(LANGUAGE_NONE => array( 0 => array('value' => $ldap_details['secret_number']))),
      'mail' => $ldap_details['mail'],
    );

So as you can see field data is stored as:
array(LANGUAGE_KEY => array(INDEX => array('value' => 'SOMETHING HERE')));

You just access/set it as you would any PHP array.

You may get stuck if you find your fields arent in the user record -- attached fields are not eagerly loaded you have to call a function to be sure they are attached to the User entity:

// For speed, typically Drupal does not attach additional fields to $user
// objects, if they are not found we request attached fields now.
if (!isset($account->field_first_name ) || !isset($account->field_last_name)) {
  field_attach_load('user', array($account->uid => $account));
}


Page Manager Error: The requested page "/xxxx" could not be found I am working almost 4 hours on the following problem, and can't solve it (Drupal 7).

I tried to build a new simple page in the page manager as I did few times before.
I entered a simple path as /xxxx
Then, after I saved the page, and tried to load it, I got the following error message:

  The requested page "/xxxx" could not be found

Can somebody help me figure out why I can't create new page?

In addition, when I tried to disabled the page on the page manager, I got the following error:

  Notice: Undefined offset: 1 in
  template_preprocess_page_manager_edit_page() (line 42 of
  D:\MYSITE\sites\all\modules\ctools\page_manager\theme\page_manager.theme.inc

Does someone knows what is the problem, and how can I fix it?

Thanks!

Are you using the stable version of the ctools and panels module, this error doesn't seems to be in the issue queue of the respective modules.

As @David as mentioned the problem could be of selection rule or the access rule.

Have a look at the use tutorial for creating the page with page manager: http://nodeone.se/en/learn-page-manager-part-1-overview

Also check the documentation of the page manager module: https://drupal.org/node/1862908


Views exposed filter resets to first selected value I have a view on this site's homepage (at the bottom, under Recent Watsits).
http://wats.it/

When you filter by category (term id), it works great - once. After that, it just resets to the first selected filter's value.

If I for example, load the page and then select "Animal" from the exposed category filter, it shows contests in the Animal category. But if I then go to select "Mineral," it just reloads the view and displays the contests in the Animal category again, and resets the filter drop down back to "Animal." I can however, select "Any" at any time

How do I fix this problem?

Derp derp derp. I had to turn off caching on the view.


What does it mean to "Use rendered output to group rows?" Is the alternative to use raw output?
To what grouping is it referring?
Does this affect the sort order of rows?

Say you have a node with a taxonomy term, then a normal list would look like this

Title: A, Term 1
Title: B, Term 2
Title: C, Term 1
Title: D, Term 3
Title: E, Term 2
Title: F, Term 1
Title: G, Term 3

If you group them on the term, you would instead get something like this

Term 1

Title A
Title C
Title F

Term 2

Title B
Title E

Term 3

Title D
Title G

Rendered is not related to raw/safe values. It's just a way of explaining that it's the rendered (displayed) values that are used as grouping field.


Notice: Undefined index I copy the site files to my local testing environment(win7, not linux os). The site cannot run normaly. The error notes show below:

Notice: Undefined index: sidebar_first in include() (Line 138 of C:\xampp\htdocs\web\modules\system\page.tpl.php).
Notice: Undefined index: sidebar_second in include() (Line 144 of C:\xampp\htdocs\web\modules\system\page.tpl.php).
Warning: file_put_contents(temporary://fil5572.tmp): failed to open stream: "DrupalTemporaryStreamWrapper::stream_open" call failed in file_unmanaged_save_data() (Line 1938 of C:\xampp\htdocs\web\includes\file.inc).
cannot be created.
Warning: file_put_contents(temporary://fil55A2.tmp): failed to open stream: "DrupalTemporaryStreamWrapper::stream_open" call failed in file_unmanaged_save_data() (Line 1938 of C:\xampp\htdocs\web\includes\file.inc).
cannot be created.
Warning: file_put_contents(temporary://fil55B2.tmp): failed to open stream: "DrupalTemporaryStreamWrapper::stream_open" call failed in file_unmanaged_save_data() (Line 1938 of C:\xampp\htdocs\web\includes\file.inc).
cannot be created.
Warning: file_put_contents(temporary://fil55C3.tmp): failed to open stream: "DrupalTemporaryStreamWrapper::stream_open" call failed in file_unmanaged_save_data() (Line 1938 of C:\xampp\htdocs\web\includes\file.inc).cannot be created.
Warning: file_put_contents(temporary://fil55E3.tmp): failed to open stream: "DrupalTemporaryStreamWrapper::stream_open" call failed in file_unmanaged_save_data() (Line 1938 of C:\xampp\htdocs\web\includes\file.inc). cannot be created.
Warning: file_put_contents(temporary://fil55E4.tmp): failed to open stream: "DrupalTemporaryStreamWrapper::stream_open" call failed in file_unmanaged_save_data() (Line 1938 of C:\xampp\htdocs\web\includes\file.inc).cannot be created.

I need your help to solve this problem.

This is most probably a problem with settings for the temporary directory, which is a typical issue moving from Linux OS to Windows or vice versa (this goes for the warning messages that you described)

You should go to: admin/config/media/file-system and set the temporary directory correctly for your local system.

The first two messages are PHP notices which are not critical, but indicating that there is a minor issue within your template files not correctly verifying variables. This is something that would normally be suppresed in a production environment and therefore you might not see this on your other server but it is there too.

By the way: I doubt that you are using Drupal 8 as you are indicating in tags, because page.tpl.php is something that clearly points to Drupal 7.


Display a value for an empty CCK Field without setting a default value? I have a few fields in one of my content types that will not always have values entered for them. One such field is "Booking Contact." When content is created, if the author does not know the booking contact, then they are supposed to leave the field blank. However, this means that the field data is empty, and the field does not display in the node at all. I'd like to display a message for these empty fields-- similar to Views' no results text -- so that users can see that there is not a value assigned to the field. What would be the best way to go about doing this?

EDIT: I'd like to avoid using "default value" to define this. The message I want displayed doesn't make as much sense in the creation form, and will likely be confusing to users. Unless, of course, there's a way to hide the default value in the creation form.

The empty_fields modules will help in this case


How to add page restrictions for blocks in frontpage? I have several blocks in my homepage : 2 statics and 1 with a pager.

I want to hide a static block when paging my homepage (after page "0").

I saw something similar in How can I show a block in a view page, excluding it's paginated pages but I do not know exactly what to put in the PHP code regarding the homepage : '' or '/' (instead of 'news' in this example) ?

<?php
$url = request_uri();
$pos = strpos($url, "page");
if ($pos === false && arg(0) =='news') {
return TRUE;
}
?>

I tried also this code that I saw on this answser : How to add page restrictions for blocks in drupal? but it does not work for me.

<?php
if (arg(0)=='/' && is_numeric(arg(1))) {
return TRUE;
} else {
return FALSE;
}
?>

My website is : http://femme.bonsplansdemarc.fr/

Your suggestions both involve using the PHP setting for block visibility, which isn't available by default and isn't recommended for security reasons. If you already have PHP filter enabled and want to use it, you can probably use the code:

<?php
  if (drupal_is_front_page() && !isset($_GET['page'])) {
      return TRUE;
  }
  return FALSE;
?>

The option I would recommend (which avoids using PHP filter) would be to install the context module (with this patch https://drupal.org/node/904416) and position the blocks using that. You can set it to appear in all circumstances except when on the home page with query string '*shs_term_node_tid_depth=*'.

If you don't know how to use context module, there are lots of tutorials and it's fairly simple.


Remove height of empty fields in Views I have setup some Structure/Views for items that I am pushing to the front page.
I have 2 separate link items (1 displays facebook icon, 1 displays arrow icon)
some instances will have both links, some instances will have 1,
currently if I leave the facebook link field blank, the display still leaves the space for that item.

It seems related to the font awesome "fas" class that needs to be added to the Views setting in order to load the icons (icons are used in "content:" in css). Once I remove the "fas" class the height of the empty link field removes itself from the page.
How do I retain "fas" class on the: View (structures/views/ (item) / link field;
but remove the height of empty fields?

code:

Read More

The below screenshot shows how the class is applied to the View/Field, with "Hide if Empty" applied.

The cleanest solution would be to hide a field that has no content.

Go into the configuration of each field you output on the view and under No results behaviour check hide if empty


How to show a view with 2 columns on the front page? I need in the front page on my website to show a view with two columns : the left column will show the two latest content from a category, and the same for the right column.

How can I achieve this?

There are many ways to do this:

Create a block for each of your views, then add the blocks to the
content area and select to show on front only (all done via block
UI), and set it side by side via CSS.
Create a content type for the front page. Then create a new instance
of that content type. Run it through panels and choose two column
layout, then add views of your liking to the left and right panel.
Create a content type for the front page. Manage the display of this
content type via Display Suite and use two column layout. Add a
dynamic field for each of the left and right columns, and set the
dynamic field to display a view of your liking.
Implement hook_menu_alter for the front page in a custom module.
Return the output of 2 views_embed_view() calls wrapped in HTML for
the columns, or in a render array that will suit your layout.
Create a content type for the front page or use an existing type.
Then create a new instance of that content type. Note the path of
this content (node/ID). In configuration - site information, set it
as the front page. Edit this content type's body element, and using
the PHP filter embed the views with calls to views_embed_view().

Methods 2 and 3 are in my opinion preferable, with method 5 the least preferable method. Method 1 is perhaps the easiest.


Embedding a view for search and redirection I have set up a view for searching using Search API. In my specific setup, I need this search to be context sensitive, i.e. I have several pages /foo/search, /bar/search, ... and these return different results.

Currently, I do this by making a content type which has a field containing the necessary information and additionally a search processor, which alters the query accordingly.

Additionally, I use Twig Tweak to embed the search view in this content type as described here. This works if I load the search with the query string, e.g. localhost/foo/search?search_api_fulltext=something.

My problem is now that if I click the "Apply" button in the search, I am being redirect to the page created by the view. This page is lacking the content type's data and I no longer get the context sensitive search results.

Is it possible to change this behaviour of the view's Apply button or do you know another way this could be implemented?

Thanks!

Following this reply on drupal.org and this answer on SO, I added a hook:

function my_module_views_pre_build(ViewExecutable $view) {
  if ($view->id() == 'my_view_id') {
    $view->override_url = Url::fromRoute('<current>');
  }
}

Some of the assumptions in Drupal and the workarounds are so annoying. Days wasted. :(


Join or create group on registration When people register for my site I want them to either join an existing group or create a new one if it doesn't exist. They can only be a member of one group, and there's only one group type used on the site.

I've got the autocomplete widget set and I want to alter it's functionality so instead of throwing an error message it creates a group. I presume altering og.module is not a good idea as it wouldn't be easy to make my particular changes generic enough to work for lots of use cases so am I right in thinking I would create a custom module to hook into the pre-save functionality of the user entity and do my checking to see if exists, if not then create group and create membership there or is there another way?

I tried using taxonomy as my group content and using a term reference autocomplete field on my user profile, but og doesn't seem to work fully with taxonomy at the moment, and I had other problems with attached field data not saving on taxonomy so gone back to using a node type as my group content type.

I think your general premise is sound. I'd be tempted to use hook_user_insert() instead, which is called after the user has been created, rather than before, since:

Your module can't actually fail to create a group or insert a new one.
hook_user_presave is really for modules that want to serialize (simple) data to be stored in the users table itself, which isn't what you're doing.

The necessary hooks in OG7 are all there for checking and creating groups and inserting users.


Confirmation Email from Webform Submission How would I send a confirmation email to the email address entered in a Contact Us form created with the Webform module?

This functionality is available out of the box with Webform.

On the webform node page, click on the "Webform" tab
From the webform tab, click on the "E-mails" tab
Click on the "Component value" radio button and select the component of the webform that captures the email address.
Click on the "Add" button
On the next page, you can set the Subject, From Address, From Name, and E-mail contents.


How to enable Database search & autocomplete live search? Found a great article of how to enable live search on drupal 7 http://www.stevepolitodesign.com/blog/create-live-search-results-search-you-type-drupal

But seems all modules are not yet available for drupal 8. Can anyone show some  light on this please of how a similar thing can be done on drupal 8?

You'll probably have to write a custom module for this.

Here's the basic idea:

You should decide with which search mechanism you want this to work. For the sake of simplicity, I'll use the core Search module as an example.
Declare a new autocomplete field with your custom callback path; it might work if you just alter the search field type, turn it into autocomplete and add your custom callback path. I'm not sure if this will work in D8 though.
Whenever user changes the input, your module should query the database and see if there are any matching keywords stored in the search module. You can include any additional logic here, e.g. limit the search to nodes only, give some criteria higher visibility, exclude some keywords, etc.
Return back the similar keywords so user can choose some of them.
When search is submitted, display search results from core search module. If it's possible, the best would be to alter the search input field, so you don't have to much else to handle form submission, etc.

I didn't check much, but this should get you going. For more info on D8 form API, check this out. If you need to see how is this done in the core, check out the code for referencing the users (e.g. author field in node forms).

Hope this helps.


entity Reference with select list doesn't show results i'v created a content type with a entity reference field - select list.
in the field settings i'v choose the desired content types for the select list. the preview select list was populated with all the wanted data.
when i create a new content of the above content type the select list of the entity reference is not populated. the only option i have is -none-.
any suggestions?

Ok, the problem was due to the fact that the site has two languages. had to enable the second language in order to make the it work properly.


Drupal 7 Multiple Display Types Different Options? I have one view with two display types (two blocks), for one of them I want to limit it to 1 result, for the other I want it to show all the results.

How can I do this? I can't seem to figure out how to allow one display type to override the other. They keep to copy eachother.

With the Panels module, you can build pages using views blocks.
When you select a block you are looking for to include, you can alter on the fly the paging mecanism.
So for the first one : only 1 row, and for the second one : all rows ...

Alternatively setting the paging parameter for a specific block is done into a popin in the Views backoffice. On left top corner of this popin you have a select box which allow you to select "This block (override)". Doing this, will setup different parameters for only this block. All parameters in views can be setup like this : global or override.


Custom form, input with ajax autocomplete not working I have developed a module with a custom form but I don't know why ajax autocomplete doesn't work. The form works good, but in one of the input field I'd like to have a autocomplete function. The next is part of my code:

src\Form\Mycustomform.php

...
public function buildForm(array $form, FormStateInterface $form_state, $parameter = NULL) {
...
    $form['customer'] = array(
      '#type' => 'textfield',
      '#title' => t('Customer'),
      '#id' => 'inpCustomer',
      '#autocomplete_route_name' => 'mymodule.autocomplete',
    );
....

mymodule.routing.yml

mymodule:
  path: 'mycustompath'
  defaults:
    _form: '\Drupal\mymodule\Form\Mycustomform'
    _title: 'Records'
  requirements:
    _permission: mycustompermission

mymodule.autocomplete:
  path: 'autocomplete'
  defaults:
    _controller: '\Drupal\mymodule\Controller\MyModuleController::autocomplete'
    _format: json
  requirements:
    _permission: 'access content'

\src\Controller\MyModuleController.php

...
class MyModuleController extends ControllerBase {

    public function autocomplete(Request $request)
    {
        $string = $request->query->get('q');
        $matches = array();
        \Drupal:logger('autocomplete')->notice($string);
        $query = \Drupal::entityQuery('node');
        $query->condition('type','customers');
        $query->condition('title', '%'.$string.'%', 'like');
        $query->sort('title');
        $query->range(0,20);
        $entity = $query->execute();
        $nodos = \Drupal::entityTypeManager()->getStorage('node')->loadMultiple($entity);
        foreach ($nodos as $row) {
            $matches[] = array('value' => $row->getTitle(), 'label' => $row->getTitle());
        }

        return new JsonResponse($matches);
    }
}

If I see drupal log, I never get a register as expected. But if I see conosole log, I don't see ajax request. How could I find where is the problem? I think there isn't an ajax call when I write some letters on the input field. I don't see the circle on the right of the input that is shown when autocomplete is working.

After some tests I have found the problem. My code is right and it works good. The problem was the template file input--textfield.html.twig. Input textfield needs some automplete classes to work and this template deleted them to add some other classes. The required classes are: form-autocomplete form-text ui-autocomplete-input. I have changed this template file to add a new class I need but without deleting the other, and then, autocomplete works.


Add html class to body I've got a block created with views, which displaying a slider.
The slider is created as an unpublished content type with two field collections:

Settings[one value]:

selectors type: thumbs or bullets
slider class: fixed position, faded etc.

Slider content[multiple values]:

slide class
content class
Image
content

I do not use views slideshow module
I'm using views-view--slider-block.tpl.php file to customize the output

All works, but I have stuck with one specific setting "fixed position" - this setting should add to html a special class, which I guess can be added only by preprocess_html function:

function MYTHEME_preprocess_html(&$variables) {
    if ( SLIDER HAS "fixed" SETTING ){
        $variables['classes_array'][] = 'slider_fixed';
    }
}

the problem is:

how to compose the if statement?
Did I have to load $view object which allows me to check what
setting is used?

I'm looking for the solution which has the lowest influence on the performance.

any suggestions?

The Context API allow to pass a variable from view.tpl to template.php file

Example:

In view.tpl file :

context_set('slider_settings', 'slider_class', 'fixed_position');

In theme template file :

function MYTHEME_preprocess_html(&$variables) {

$slider_class = context_get('slider_settings', 'slider_class');
if ($slider_class == 'fixed_position'){
    $variables['classes_array'][] = 'slider_fixed';
}

}

It is an aswer for my own question, because I found a solution by myself, and it might be useful for someone I think..


All "administration pages" in English and admin menu always LTR? I added a RTL language translation file (e.g. Arabic, Persian, Farsi) to my Drupal 8 site. I want all the administration menus to always be in English and LTR. On the other hand, I want the front-end pages of my site to be in another language (e.g. Persian, Farsi).

I did the following.

I enabled the Language module, and set up one additional language. Installation was done in English; I added Persian.

I configured the administration language using the following settings.

/admin/config/regional/language/detection
Account administration pages: enabled

Admin >> Edit Profile >> Edit

This works properly for all the administration pages. Those are in English and LTR except the front page, user/1/, and admin/structure/block/demo/[theme name] where the administration menu is in Persian and RTL.

After you change default site language to Farsi, and admin pages language to English, go to your user:admin page and change the admin's language to English as well to bring it in accordance with the management backend language (English).

Maybe flushing of cache will be needed; In any case if it didn't work then it's a bug and should be reported at Drupal.org ...


Why do many functions now require more code than the equivalent functions of the previous version? Every time I read about how to convert code from D7 to D8 is seems like the D8 version is longer.

For example drupal_goto was:

drupal_goto('user');

and the D8 equivalent is:

return new RedirectResponse(\Drupal::url('user.page'));

And an example hook_init in D7:

function mymodule_init() {
  if (!empty($_GET['redirect-me'])) {
    drupal_goto('http://example.com/');
  }
}

And the equivalent is D8 is:

mymodule.services.yml

services:
  mymodule_event_subscriber:
    class: Drupal\mymodule\EventSubscriber\MymoduleSubscriber
    tags:
      - {name: event_subscriber}

and then also:

namespace Drupal\mymodule\EventSubscriber;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\HttpKernel\Event\GetResponseEvent;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
class MymoduleSubscriber implements EventSubscriberInterface {
  public function checkForRedirection(GetResponseEvent $event) {
    if ($event->getRequest()->query->get('redirect-me')) {
      $event->setResponse(new RedirectResponse('http://example.com/'));
    }
  }
  /**
   * {@inheritdoc}
   */
  static function getSubscribedEvents() {
    $events[KernelEvents::REQUEST][] = array('checkForRedirection');
    return $events;
  }
}

This is only a couple of examples but it seems that to achieve anything is D8 is going to take far more code.

Is this actually the case or am I misinterpreting whats happening.
If this is the case then what is the advantage?
Would it be possible / desirable to use lots of wrapper functions to reduce the amount of code to achieve simple tasks?

Is this actually the case or am I misinterpreting whats happening.

Yep, a lot of D8 stuff is more verbose than that of its predecessor. A huge chunk of the codebase has moved to OO based on PSR-0, so you're always going to be writing more code, more files, creating more folders to put those files in, etc.

  If this is the case then what is the advantage?

You can't directly apply an 'advantage' or 'disadvantage' to the concept of "D8 will use more code" (if that's indeed even true when you average it all out); it's simply an inevitability - the D8 page request has completely changed with the introduction of Symfony, so what was possible in a few lines in D7 just isn't possible with the same code now. The overall advantage is that Drupal gets all the power of Symfony driving it, and Symfony's framework/request lifecycle is generally considered to be stable and to use good practice. Plus, introducing a strict DI methodology to any kind of project is a big win in my opinion.

  Would it be possible / desirable to use lots of wrapper functions to reduce the amount of code to achieve simple tasks?

Possible? Of course. Desirable? Depends on your opinion, and what you're creating a wrapper for. If it's something you do 10 times a day, and you can shorten 10 lines to 1 or 2 lines, then you'd be mad not to do it. Obviously that attitude transcends Drupal/PHP and should apply to any language/technology.

  This is only a couple of examples but it seems that to achieve anything is D8 is going to take far more code.

The anything there isn't true - some things will be more verbose, some things less, it depends on exactly what you're looking to do.


How can I mock a class during a functional request that is called from within a controller? I am working on a custom module that from a controller calls Elastic search and returns a search result.  I am trying to write a simple Functional Php Unit test just to make sure the results are displaying correctly.

Here is a simplified version of my funtional php unit test code:

public function testSearchResulsShowUp() {
  $account = $this->drupalCreateUser(['access content']);
  $this->drupalLogin($account);
  $this->drupalGet('/search/term1');
  $this->assertResponse(200);
  $this->assertText('Term 1');
}

Here is a simplified version of my controller:

/**
 * Search controller.
 */
class SearchController extends ControllerBase {

  public function getContent(search) {
    $client = Client::getClient();

    // Client connects to Elastic search and then returns
    // a result.

    ...
    ...

    // Will return Term 1
  }

}

Here is a simplified version of my Client class:

/**
 * Class Client.
 */
class Client {

  /**
   * Get client.
   */
  public static function getClient() {
    $cluster_id = \Drupal::state()->get('elasticsearch_connector_get_default_connector');
    $elasticsearchCluster = \Drupal::entityManager()->getStorage('elasticsearch_cluster')->load($cluster_id);
    $clientManager = \Drupal::service('elasticsearch_connector.client_manager');
    $client = $clientManager->getClientForCluster($elasticsearchCluster);
    return $client;
  }
}

I would like to be able to somehow mock my getClient method so when it is called in the Controller or anywhere going forward it would call the mock instead of the original method.  I know that if this was a true Unit test we would be able to do it but since it is a functional test I am not sure how to do it.

Since the request your test is making spins up a completely new PHP process to deliver the contents of that request, nothing you do in-memory during the execution of the test will be reflected in the new HTTP request process.

Fortunately there are some techniques to create HTTP clients that can be used inside functional tests that span longer than a single request. The technique involves creating a test module, which replaces the HTTP client in the container, for all requests that happen while the module is enabled.

Your test may then:

Switch the module on during setup.
Use the new HTTP client in HTTP requests during the lifetime of the test.
Switch the module off, if you're required to clean-up.

The key parts of a test module like this are:

my_module/tests/modules/my_module_http_client/services.yml

services:
  my_module_http_client.http_client:
    decorates: 'http_client'
    class: 'Drupal\my_module_http_client\MockHttpClient'

my_module/tests/modules/my_module_http_client/src/TestHttpClient

<?php

namespace Drupal\my_module_http_client;

use GuzzleHttp\Client;
use GuzzleHttp\Psr7\Response;

/**
 * Test HTTP client for the air quality test.
 */
class TestHttpClient extends Client {

  /**
   * {@inheritdoc}
   */
  public function get($uri, array $options = []) {
    return new Response(200, ['type' => 'text/xml'], file_get_contents(__DIR__ . '/some-test-fixture.xml'));
  }

}

Of course in the body of ::get, you can program any logic you like. A common pattern is to use the state API to allow the test to specify a behavior for the client. An example might be something like, setting which response fixture to return.

These kind of functional tests are really valuable to ensure your whole system is working end to end. I would however caveat this with saying, it is also valuable to identify units in your controller which can be tested in isolation. Unit tests can often test a lot more scenarios at a might higher speed than a fully bootstrapped implementation might be able to.


Set drush alias for current path Is it possible to associate a path with a specific drush alias?

Use case:

I'm on my local dev machine and I'm in /var/www/site1 when I run drush I want it to run as drush @site1 without me having to append @site1 every time.

My alias files are all stored in the my local home directory.

If you store settings.php in the default folder, then Drush will already behave as you desire.  If settings.php is in some other folder (e.g. 'site1'), see the site-set command (drush help site-set)


Changing output format of displayed body text I imported node and comment body fields as "Full HTML" (they are coming from a trusted site).

Now I want to display those body fields differently, for example strip certain HTML tags. Do I just change the filters for "Full HTML" and use "Full HTML" as my "custom" input format? I could change the name of it, just want to make sure it have special significance in Drupal.

Or do I have to manually change them in the DB?

You can safely make changes to the regular "Full HTML" filter. It has no special significance in the system. It is simply created by the "Standard" install profile because it is convenient for end users. If you install a minimal profile you won't have it at all.

Obviously changing the full html filter will affect other nodes as well that use this filter.


How do you render the View, Edit, Delete, and Revisions tabs in a specific location on node/page? What is the Drupal 8 equivalent of the following code?

<?php if (!empty($tabs)): ?>
<?php print render($tabs); ?>
<?php endif; ?>

I don't want/prefer {{ content }} as there are other fields in the page which get rendered at the same position and corrupt my template.

The tabs are in a block now. Go to the block layout (/admin/structure/block) and move the block Tabs to another position.

If you don't find an existing region for what you want to do, add a new region to your theme and place this region in the page template page--node.html.twig, so that you can integrate the tabs inside of your html structure. If you need the tabs in different positions you can add multiple instances of the tabs block and configure the visibility.

Try not to put tabs in nodes, combine those two on the page level in a custom page template for nodes if possible.

But, in case you need them between the content of the node. you can do it on node.html.twig. It is not the best practice but can be done if required, but you need to take care, that the caching is working and that the tabs don't appear when the node is used in other places.