Problem/Motivation

Problem

  • When #states is attached to a form element that contains #markup the following notice occurs:

    Notice: Undefined index: #type in drupal_process_states() (line 583 of core/includes/common.inc).

Cause

  • This happens because a #markup element does not require the #type to be set.

Steps to reproduce #97

  • Unzip drupal_process_states_test.zip, and install module drupal_process_states_test
  • Visit /drupal_process_states_test/form/default
  • Visit /admin/reports/dblog, the notice shows Notice: Undefined index: #type in Drupal\Core\Form\…

Proposed resolution

  1. Fix the PHP notice.
  2. Add a regression (kernel) test to ensure that this bug does not reappear in the future.

Notes

  • There are no PHP/backend tests for #states right now, because the "functionality" on the PHP side is in essence just a json_encode(), so nothing worth to test.

Remaining tasks

  • Confirm the patch addresses the issue following the steps to reproduce.

User interface changes

No.

API changes

No.

Data model changes

No

CommentFileSizeAuthor
#134 2700667.133a_133b.interdiff.txt835 bytesdww
#133 2700667-133b.patch2.54 KBdww
#133 2700667-133a.patch2.35 KBdww
#133 2700667-133.test-only.patch1.05 KBdww
#132 2700667_D9_130.patch820 bytesravi.khetri
#130 2700667_D9_130.patch852 bytesravi.khetri
#119 collapsed_paragraphs.png33.08 KBcarolpettirossi
#109 Screen Shot 2020-07-11 at 7.13.33 PM.png292.09 KBtanubansal
#104 before.png231.87 KBjungle
#104 before_and_after.png413.81 KBjungle
#104 interdiff-101-104.txt989 bytesjungle
#104 2700667-104.patch2.36 KBjungle
#101 2700667-101-test-only.patch1.06 KBjungle
#101 2700667-101.patch2.36 KBjungle
#99 2700667-99.patch1.3 KBjungle
#97 drupal_process_states_test.zip3.54 KBjungle
#92 2700667-91.patch822 bytesami.nair
#90 2700667-89.patch2.37 KBlammensj
#74 interdiff_71-74.txt676 bytesvacho
#74 2700667-74.patch2.15 KBvacho
#71 2700667-71.patch2.15 KBvoleger
#64 2700667-64.patch2.15 KBoriol_e9g
#59 drupal-process-states-notice-2700667-58.patch2.22 KBkalyansamanta
#58 drupal-process-states-notice-2700667-58.patch2.22 KBnickdickinsonwilde
#41 drupal-process-states-notice-2700667-41.patch1.72 KBbdlangton
#41 drupal-process-states-notice-2700667-41-test-only.patch1 KBbdlangton
#39 drupal-process-states-notice-2700667-39.patch1.72 KBbdlangton
#37 drupal-process-states-notice-2700667-36.patch1.66 KBbdlangton
#35 drupal-process-states-notice-2700667-35.patch1.7 KBbdlangton
#29 2700667-29.patch727 byteskanav_7
#28 2700667-28.patch809 byteskanav_7
#22 undefined_index_type_states-2700667-22.patch727 bytespk188
#5 undefined_index_type_states-2700667-5.patch727 byteszuhair_ak
#2 undefined_index_type_states-2700667-2.patch725 byteszuhair_ak

Issue fork drupal-2700667

Command icon Show commands

Start within a Git clone of the project using the version control instructions.

Or, if you do not have SSH keys set up on git.drupalcode.org:

Comments

pfrenssen created an issue. See original summary.

zuhair_ak’s picture

StatusFileSize
new725 bytes

Just added an isset test for the #type index in line 580 of core/includes/common.inc. Dont know if this is the correct way.

zuhair_ak’s picture

Status: Active » Needs review

Status: Needs review » Needs work

The last submitted patch, 2: undefined_index_type_states-2700667-2.patch, failed testing.

zuhair_ak’s picture

Status: Needs work » Needs review
StatusFileSize
new727 bytes

There was no newline at the end of patch.Fixed it.

msypes’s picture

Hi,
Michael & Joe are working on this patch at the NoLa 2016 sprint

Checked by attempting a temporary hack with the Account Settings form (admin/config/people/accounts), but couldn't fully reproduce the problem with a markup element. I can confirm that commenting out the #type for the Logo Settings in the Appearance settings form ( /admin/appearance/settings) does break the expected Javascript functionality as well as generate the error in the recent logs.
The patch is straightforward and corrects the described issue.

msypes’s picture

Status: Needs review » Reviewed & tested by the community
pfrenssen’s picture

This looks good to me. This doesn't require a test IMO. RTBC+1, thanks!

esod’s picture

Where can I recreate the bug? /admin/config/people/accounts doesn't print the undefined index notice. There's nothing in the log. Thanks.

alexpott’s picture

Priority: Minor » Normal
Status: Reviewed & tested by the community » Needs work
Issue tags: +Needs tests

I definitely think this could use a test - it would be easy to produce a regression.

msypes’s picture

@esod: To be clear, the error doesn't normally occur on the page I referenced (admin/config/people/accounts). I tried modifying that admin form by adding a #markup element whose display would depend on the checking of another form element on the page. I couldn't get such a thing to work, which would have duplicated the originally described issue/problem.
On the other hand, commenting out the #type for the Logo Settings in the Appearance settings form ( /admin/appearance/settings) does break the expected Javascript functionality as well as generate the error in the recent logs.

ankitasharma13’s picture

Status: Needs work » Needs review
Issue tags: +Tested

I have applied the above patch and tested and its working fine.There is nothing in the error log.

dcam’s picture

Status: Needs review » Needs work
Issue tags: -Tested

Thank you for the review, @ankitasharma13!

Unfortunately, this issue still needs work. @alexpott's comment in #10 and the "Needs tests" tag are intended to indicate that this patch should be expanded to include automated tests.

zuhair_ak’s picture

I am new to writing Unit tests, can someone give an example to write tests for core/includes/common.inc functions like here in drupal_process_states function? Is there examples for that in core?

Version: 8.2.x-dev » 8.3.x-dev

Drupal 8.2.0-beta1 was released on August 3, 2016, which means new developments and disruptive changes should now be targeted against the 8.3.x-dev branch. For more information see the Drupal 8 minor version schedule and the Allowed changes during the Drupal 8 release cycle.

mradcliffe’s picture

Issue tags: +Dublin2016

This probably needs a re-roll as well these days.

finn lewis’s picture

I'm looking at this at the DrupalCon mentored sprints.
I'll run through https://www.drupal.org/contributor-tasks/reroll

finn lewis’s picture

The patch applies cleanly on 8.3.x.
Not too sure where to start with writing tests, so I'll leave this for someone else.

Version: 8.3.x-dev » 8.4.x-dev

Drupal 8.3.0-alpha1 will be released the week of January 30, 2017, which means new developments and disruptive changes should now be targeted against the 8.4.x-dev branch. For more information see the Drupal 8 minor version schedule and the Allowed changes during the Drupal 8 release cycle.

ajmantis’s picture

Retest to 8.4

sun’s picture

pk188’s picture

Status: Needs work » Needs review
StatusFileSize
new727 bytes

Adding patch to retest #5.

Version: 8.4.x-dev » 8.5.x-dev

Drupal 8.4.0-alpha1 will be released the week of July 31, 2017, which means new developments and disruptive changes should now be targeted against the 8.5.x-dev branch. For more information see the Drupal 8 minor version schedule and the Allowed changes during the Drupal 8 release cycle.

Version: 8.5.x-dev » 8.6.x-dev

Drupal 8.5.0-alpha1 will be released the week of January 17, 2018, which means new developments and disruptive changes should now be targeted against the 8.6.x-dev branch. For more information see the Drupal 8 minor version schedule and the Allowed changes during the Drupal 8 release cycle.

alezu’s picture

The patch applies well on 8.4.4. Thank you.

mradcliffe’s picture

Issue summary: View changes
Status: Needs review » Needs work

Updated issue summary to state remaining tasks.

It looks like the patch needs a test before any further review can be done so I am setting this back to Needs Work.

himerus’s picture

I can confirm this works against 8.5.0 as well.

kanav_7’s picture

StatusFileSize
new809 bytes

Rerolled in 8.6.x

kanav_7’s picture

StatusFileSize
new727 bytes

Corrected #28

savkaviktor16@gmail.com’s picture

Status: Needs work » Needs review
pifagor’s picture

Status: Needs review » Reviewed & tested by the community

.

dcam’s picture

Status: Reviewed & tested by the community » Needs work

The issue is tagged as needing tests. It cannot be RTBC until they are written.

pifagor’s picture

I apologize, I just mistakenly did not choose that status.

dcam’s picture

No apology necessary.

bdlangton’s picture

Status: Needs work » Needs review
Issue tags: -Needs tests
StatusFileSize
new1.7 KB

I've updated the patch to have a KernelTest. Let me know if this looks good.

Status: Needs review » Needs work

The last submitted patch, 35: drupal-process-states-notice-2700667-35.patch, failed testing. View results

bdlangton’s picture

Status: Needs work » Needs review
StatusFileSize
new1.66 KB

Messed up that patch file. Here's the correct one.

mradcliffe’s picture

Status: Needs review » Needs work
+++ b/core/tests/Drupal/KernelTests/Core/Common/DrupalProcessStatesTest.php
@@ -0,0 +1,29 @@
+    drupal_process_states($form_element);

I think a simple $this->assertArrayHasKey('#attributes', $form_element); would make sense here.

bdlangton’s picture

Status: Needs work » Needs review
StatusFileSize
new1.72 KB

Added the assertion. Thanks.

dcam’s picture

Status: Needs review » Needs work

@bdlangton
Thank you very much for your work on this. It is appreciated. You can do one more thing that would be helpful though - provide a tests-only patch. Uploading a patch file without the fix allows reviewers to see at a glance that there is an issue and the fix resolves it. Also it allows us to confirm that the test itself is working and testing for the right thing.

Typically we would upload the tests-only patch and then the full patch to the same comment. Doing so ensures that Testbot will leave the issue status as "Needs Review" instead of marking the issue as "Needs Work" because the test-only patch failed (which is exactly what we want).

bdlangton’s picture

Status: Needs work » Needs review
StatusFileSize
new1 KB
new1.72 KB

@dcam thanks for the notes. I think this should do it.

dcam’s picture

Status: Needs review » Reviewed & tested by the community

It's been a while since I've done a patch review, but the test looks good to me. I don't see anything wrong with it. Thank you, @bdlangton.

alexpott’s picture

Status: Reviewed & tested by the community » Needs work
  // Elements of '#type' => 'item' are not actual form input elements, but we
  // still want to be able to show/hide them. Since there's no actual HTML input
  // element available, setting #attributes does not make sense, but a wrapper
  // is available, so setting #wrapper_attributes makes it work.

The code in drupal_process_states() has the above comment in it. With #markup don't we have the same problem. In fact if someone uses #states on #markup I don't see how it is going to work.

See the following output from a REPL.

>>> $a = ['#markup' => 'test', '#states' => ['visible' => [':select[name="method"]' => ['value' => 'email']]]];
=> [
     "#markup" => "test",
     "#states" => [
       "visible" => [
         ":select[name="method"]" => [
           "value" => "email",
         ],
       ],
     ],
   ]
>>> drupal_process_states($a);
=> null
>>> $a;
=> [
     "#markup" => "test",
     "#states" => [
       "visible" => [
         ":select[name="method"]" => [
           "value" => "email",
         ],
       ],
     ],
     "#attached" => [
       "library" => [
         "core/drupal.states",
       ],
     ],
     "#attributes" => [
       "data-drupal-states" => "{"visible":{":select[name=\u0022method\u0022]":{"value":"email"}}}",
     ],
   ]
>>> (string) \Drupal::service('renderer')->renderPlain($a);
=> "test"
rakesh.gectcr’s picture

Issue tags: +Nwdug_may18
mrpauldriver’s picture

I am not a coder but found this issue because I have been working on a form_alter (using states) which has been returning a very similar error - See pastebin. The error seemed so similar to the one mentioned here that thought I would try this patch.

After applying patch 42 to Drupal 8.5.4 , my error immediately goes away, but the patch seems to undo the work being done by another core patch that I am using. See https://www.drupal.org/project/drupal/issues/2923701

As you will realise from this stackexchange post, I am very much a learner, but it may provide some background about the form_alter that I was working on.

Version: 8.6.x-dev » 8.7.x-dev

Drupal 8.6.0-alpha1 will be released the week of July 16, 2018, which means new developments and disruptive changes should now be targeted against the 8.7.x-dev branch. For more information see the Drupal 8 minor version schedule and the Allowed changes during the Drupal 8 release cycle.

dunebl’s picture

I confirm #41 solve the issue

akalata’s picture

Re #44, I'm seeing this happen for fields that aren't markup, but that are first-level $form elements that server as wrappers/containers for inner widgets that do have a #type.

I am adjusting states using the contrib Field States UI module, so it may be the module is applying the States API incorrectly?

nickdickinsonwilde’s picture

Status: Needs work » Needs review

@alexpott re #2700667-44: Notice: Undefined index: #type in Drupal\Core\Form\FormHelper::processStates()
Yes, that is the case. However... that problem is I would say a separate issue. Specifically, #markup ignores any #attributes array.

>>> $a = ['#markup' => 'test', '#attributes' => new \Drupal\Core\Template\Attribute(['class' => ['example']])];
=> [
     "#markup" => "test",
     "#attributes" => Drupal\Core\Template\Attribute {#11074},
   ]
>>> (string) \Drupal::service('renderer')->renderPlain($a);
=> "test"
>>> $b = ['#type' => 'container', '#attributes' => new \Drupal\Core\Template\Attribute(['class' => ['example']])];
=> [
     "#type" => "container",
     "#attributes" => Drupal\Core\Template\Attribute {#11073},
   ]
>>> (string) \Drupal::service('renderer')->renderPlain($b);
=> "<div class="example"></div> "

This is expected behaviour to me - I'm providing the markup aren't I? So, I don't think it is a bug, but if it is a bug, I think it should be dealt with in a different ticket than this.

@akalata: Easily possible I'm doing something funny there. In anycase, I am partially done a significant rewrite of that - hopefully get it out this month, although if so, it will require some core patches/may have to wait until the next Core release.

nickdickinsonwilde’s picture

nickdickinsonwilde’s picture

Status: Needs review » Reviewed & tested by the community
Issue tags: +Contributed project soft blocker

As @akalata mentioned, Field States UI was sometimes triggering this. I've investigated and it isn't doing anything wrong. What is happening, is that the Multivalue Form array has a #theme key and not a #type key - and in some cases the multivalue form has to have states applied to it rather than its children.

It's only causing notices and only under some conditions, so not a hard blocker but not pretty.

So, given that and my other note about #markup being a special case, can you give this another look @alexpott? Setting to RTBC so it shows up higher in your list ;)

Status: Reviewed & tested by the community » Needs work

The last submitted patch, 41: drupal-process-states-notice-2700667-41.patch, failed testing. View results

nickdickinsonwilde’s picture

Status: Needs work » Reviewed & tested by the community

Testbot failure (selenium server unavailable?)

alexpott’s picture

Re @NickWilde but this fix widens the scope of what doesn't report an error with drupal_process_states(). Atm if you use with #markup you get an warning - which is good because it's not going to work. But afterwards no warning and you might think it'll work. Where is the multivalue field coming from?

nickdickinsonwilde’s picture

@alexpott hmm uhh. argh. Currently, behaviour is inconsistent - if you create an element with just #markup key, it will give said error (which is not *very* helpful either). However many people include '#type' => 'markup' despite it not being required (and there are examples of that in core); in which case it would silently not work already.

Do you think that #markup should have a (better) error message or be adjust to have attributes and states work?

Any multiple value form with multiple widgets; so autocomplete tag style Entity Reference widget would be fine, but another Entity Reference widget with with a cardinality > 1 would fail.

alexpott’s picture

Status: Reviewed & tested by the community » Needs work

I think a way forward here is better documentation. We need to document that this only works on renderable things that print the #attributes property. There are many that do not. The problem is we can't know if they do or they don't when this is called by the renderer.

So maybe for now we can improve the docs here:

 * @param $elements
 *   A renderable array element having a #states property as described above.

Since it's really a render array that supports #attributes. We probably also want to mention the #markup does not support #states.

nickdickinsonwilde’s picture

Status: Needs work » Needs review
StatusFileSize
new2.22 KB

Thanks for the feedback @alexpott. New patch attached with further documentation.

kalyansamanta’s picture

StatusFileSize
new2.22 KB

Sorry ! By mistake uploaded duplicate file.

mradcliffe’s picture

Please don't post duplicate patches, @kalyansamanta.

I've confirmed that the patch in #59 is the same as in #58 by running interdiff on those (after downloading the one in #59 with a different file name).

heykarthikwithu’s picture

@mradcliffe these duplicate patches are not done only for this tickets, I had came across couple more tickets where @kalyansamanta posting identical patches..

https://www.drupal.org/project/drupal/issues/2952488#comment-12864862
https://www.drupal.org/project/drupal/issues/2920395#comment-12863766

@alexpott you can have look into this.. Or can you please tag this user(@kalyansamanta) to appropriate guidelines.

alexpott’s picture

I've removed issue credit for @kalyansamanta - they've contacted me and appear to be aware of their mistake.

alexpott’s picture

  1. +++ b/core/includes/common.inc
    @@ -574,6 +574,13 @@ function drupal_js_defaults($data = NULL) {
    + * Drupal form elements are not required to support states. For states to work,
    + * the element has to print #attributes. Item elements work using
    + * #wrapper_attributes instead. Most elements should print #attibutes so most
    + * elements do work. The markup element is the only one that is known to not
    

    This is getting there. I think Most elements should print #attributes so most elements do work. The markup element is the only one that is known to not work. Is a bit verbose. Perhaps something like States are not supported by render array where #type is markup.

    The problem is that there is no markup element - it is a pseudo thing provided by the renderer service.

    Thinking about this some more have we considered triggering a warning if #markup or #type = 'markup' so developers can find this out without having to read docs?

  2. +++ b/core/includes/common.inc
    @@ -574,6 +574,13 @@ function drupal_js_defaults($data = NULL) {
    + * work.
    + *
    + *
    

    The multiple blank lines. There should only be one.

oriol_e9g’s picture

StatusFileSize
new2.15 KB

Version: 8.7.x-dev » 8.8.x-dev

Drupal 8.7.0-alpha1 will be released the week of March 11, 2019, which means new developments and disruptive changes should now be targeted against the 8.8.x-dev branch. For more information see the Drupal 8 minor version schedule and the Allowed changes during the Drupal 8 release cycle.

nwoodland’s picture

Patch from #64 on Drupal 8.6.13 and PHP 7.2.15 works great. Thanks!

oriol_e9g’s picture

@nwoodland RTBC?

mikelutz’s picture

Status: Needs review » Reviewed & tested by the community

I will. I've been using #58 in production on many sites for a long time with no issues, and can confirm #64 only updates coding standards and documentation.

I don't think a warning on #type=markup is appropriate. It's currently a notice and I'm hoping to get rid of THAT. This occurs regularly in the field widget and field formatter settings forms for contrib field types. As I understood it last I investigated (and correct me if I'm wrong, it's been a while) As you show/hide that part of the form, the hidden/visible state is applied to the wrapper and all the elements of the form. The markup is properly hidden because the parent is, but the state still bubbles down. If you are applying a hidden state to a parent and subelements, and one of the sub elements happens to be markup, then the behavior is as expected. I think there are enough situations like this where hidden/visible is applied to a whole subform that might include arbitrary markup which currently works. I'm not sure how a sub form that isn't controlling it's own states would declare that it's markup state is covered by the parent and doesn't need a warning.

I'm going to RTBC based on that, but I'm happy to continue the discussion if anyone disagrees.

joelpittet’s picture

RTBC++ fixes an issue with linked_field

publishing future’s picture

Cannot apply patch in #64 to Drupal 8.7. Is there an updated version available?

voleger’s picture

StatusFileSize
new2.15 KB

Just reroll

publishing future’s picture

Thank you, patch applied properly!

darrenwh’s picture

Status: Reviewed & tested by the community » Needs work
+++ b/core/includes/common.inc
@@ -597,7 +602,7 @@ function drupal_process_states(&$elements) {
+  $key = (isset($elements['#type']) && $elements['#type'] == 'item') ? '#wrapper_attributes' : '#attributes';

The logic does not need to be wrapped in brackets:

$key = isset($elements['#type']) && $elements['#type'] == 'item' ? '#wrapper_attributes' : '#attributes';

vacho’s picture

StatusFileSize
new2.15 KB
new676 bytes

Code refactor according to #73 suggestion.

oriol_e9g’s picture

Status: Needs work » Reviewed & tested by the community

This is a microupdate, still RTBC.

alexpott’s picture

From #68

The markup is properly hidden because the parent is, but the state still bubbles down.

Doesn't that imply that there is a better fix out there? I.e. to not bubble the state down to markup elements - I've tried to find out how this is happening but I can't see it.

It would be really awesome if someone could post steps to reproduce this with a contrib module.

publishing future’s picture

Unfortunately patch in #74 fails again with Drupal 8.7.1. Any updates?

vacho’s picture

@publishing-future I test the patch #74 at current 8.7.x version a this applies perfectly.

publishing future’s picture

Thanks, I now as able to apply it manually.

The last submitted patch, 71: 2700667-71.patch, failed testing. View results

The last submitted patch, 71: 2700667-71.patch, failed testing. View results

The last submitted patch, 71: 2700667-71.patch, failed testing. View results

The last submitted patch, 71: 2700667-71.patch, failed testing. View results

alexpott’s picture

Status: Reviewed & tested by the community » Needs work

It would be really awesome if someone could post steps to reproduce this with a contrib module.

I'm going to needs work the issue for this. It would be really if someone could provide these as I'm still concerned that we are fixing an effect rather than the cause.

bramdriesen’s picture

I got this error when using the "media_entity_browser" module for ckeditor. When opening the entity embed widget I was presented with this error. The patch resolved the issue for me though.

vacho’s picture

Status: Needs work » Needs review

Version: 8.8.x-dev » 8.9.x-dev

Drupal 8.8.0-alpha1 will be released the week of October 14th, 2019, which means new developments and disruptive changes should now be targeted against the 8.9.x-dev branch. (Any changes to 8.9.x will also be committed to 9.0.x in preparation for Drupal 9’s release, but some changes like significant feature additions will be deferred to 9.1.x.). For more information see the Drupal 8 and 9 minor version schedule and the Allowed changes during the Drupal 8 and 9 release cycles.

gido’s picture

We used the patch for a while but figured out that this was our "fault" by trying to use #states on a "field" without a proper #type (was more like a parent container containing inline form).

Using container for the type fixed our issue.

Is there any reason that #states stuff depend on a #type defined ?

SaraKlasson’s picture

It seems to me that neither 2700667-74.patch nor 2700667-71.patch applies after upgrading core to 8.8.0.

lammensj’s picture

StatusFileSize
new2.37 KB

I rewrote the patch for version 8.8.

ami.nair’s picture

I rewrote the patch for version 8.8.2. As 8.8.2 removed core/tests/Drupal/KernelTests/Core/Common/DrupalProcessStatesTest.php, the previous patches does not apply.

ami.nair’s picture

StatusFileSize
new822 bytes
dww’s picture

@ami.nair Re: #91 - thanks for your contribution.
However, DrupalProcessStatesTest.php is a new test being added in this issue.

As 8.8.2 removed core/tests/Drupal/KernelTests/Core/Common/DrupalProcessStatesTest.php, the previous patches does not apply.

Not true. The patch needs to add that file to core.

Also, please post an interdiff with any patch you upload based on a previous patch. This request applies to @LammensJ in #90, too.

NW for:
- A clean test-only patch uploaded here showing proper failure.
- A working test + fix patch with interdiffs from previous efforts.
- Better steps to reproduce this bug, ideally in the summary.

Thanks!
-Derek

p.s. Ping re: #2702233: [backport] Add JavaScript tests for Form API #states: required, visible, invisible, expanded, checked, unchecked Let's get that wrapped up and in! ;)

dww’s picture

Status: Needs review » Needs work

Sorry, meant to change the status, too.

ami.nair’s picture

@dww, I think the previous patch in #90 works for 8.8.2. It was some glitch in my system that it was not working. Thank you for the time

darrenwh’s picture

Hide obsolete patches

jungle’s picture

Issue summary: View changes
StatusFileSize
new3.54 KB

Made a tiny module to reproduce the issue. Steps to reproduce added to the issue summary.

Key code:

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

    $form['foo'] = [
      '#markup' => 'Foo',
      '#states' => [
        'visible' => [
          ':input[name="bar"]' => ['value' => 'bar'],
        ],
      ],
    ];

    $form['bar'] = [
      '#type' => 'textfield',
      '#title' => $this->t('Bar'),
      '#maxlength' => 64,
      '#size' => 64,
      '#weight' => '0',
    ];
jungle’s picture

Issue summary: View changes

wrong comment, removed, sorry

jungle’s picture

Status: Needs work » Needs review
StatusFileSize
new1.3 KB

A wrong patch, sorry

jungle’s picture

Status: Needs review » Needs work
jungle’s picture

StatusFileSize
new2.36 KB
new1.06 KB

As #92 dropped two parts from #90, I'd like to continue from #90 following #93

A clean test-only patch uploaded here showing proper failure.

Attached

- A working test + fix patch with interdiffs from previous efforts.

From #90

- Better steps to reproduce this bug, ideally in the summary.

See #97

jungle’s picture

Status: Needs work » Needs review
mradcliffe’s picture

Issue summary: View changes
Status: Needs review » Needs work
Issue tags: -Needs issue summary update

I removed the Needs issue summary update. Nice job adding the test module and steps, @jungle. The issue summary seems pretty clear to me what the next steps are.

I found a minor nit pick with a comment in the patch.

After that I think the next step would be for someone to manually test the patch following the steps to reproduce in the issue summary. I kept the Novice tag to help identify that.

+++ b/core/lib/Drupal/Core/Form/FormHelper.php
@@ -196,6 +196,11 @@ protected static function processStatesArray(array &$conditions, $search, $repla
+   * #wrapper_attributes instead. States are not supported by render array where
+   * #type is markup.

The last sentence here sounds a little awkward in English. I think making "render array" plural would help - "render arrays".

jungle’s picture

Status: Needs work » Needs review
StatusFileSize
new2.36 KB
new989 bytes
new413.81 KB
new231.87 KB

Thanks, @mradcliffe for reviewing!

The last sentence here sounds a little awkward in English. I think making "render array" plural would help - "render arrays".

Changed and manually tested

  1. A fresh installation
  2. Install the drupal_process_states_test module
  3. Visit /drupal_process_states_test/form/default with anonymous
  4. Apply the patch
  5. Visit again /drupal_process_states_test/form/default with anonymous
  6. Log in as user 1 (admin)
  7. Visit /admin/reports/dblog, only one php notice as expected (see screenshot before-and-after.png)
  8. Visit the log details page, make sure it's the notice exactly, Notice: Undefined index: #type in Drupal\Core\Form\FormHelper::processStates() (see screenshot before.png)
mradcliffe’s picture

I reviewed the patch based on the changes in #104. It would be nice if someone else could run through the manual-testing steps.

jungle’s picture

Re: #105, actually, I did do manual-testing in #104, with screenshots attached. And one more manual testing is fine for me if it's necessary.

mradcliffe’s picture

Yes, sorry. Usually we try to have someone who didn't write the latest patch do either a review or manual testing. Your steps to reproduce should help with that, @jungle. Thank you.

Version: 8.9.x-dev » 9.1.x-dev

Drupal 8.9.0-beta1 was released on March 20, 2020. 8.9.x is the final, long-term support (LTS) minor release of Drupal 8, which means new developments and disruptive changes should now be targeted against the 9.1.x-dev branch. For more information see the Drupal 8 and 9 minor version schedule and the Allowed changes during the Drupal 8 and 9 release cycles.

tanubansal’s picture

StatusFileSize
new292.09 KB

#97, Can someone share module.zip file compatible with Drupal 9.1

pratik_kamble’s picture

Issue tags: +DIACWJuly2020
jungle’s picture

Issue tags: +Global2020

Tagging Global2020 to see if this one gets viewed.

billywardrop’s picture

I'm at DrupalCon Global, I will test this

billywardrop’s picture

I modified the states test module to make it Drupal 9 compatible then I followed the steps in #104 and the patch is working as expected. I got an error in the Dblog before I applied the patch then no further errors after the patch was applied.

billywardrop’s picture

Status: Needs review » Reviewed & tested by the community
alexpott’s picture

Status: Reviewed & tested by the community » Needs work

#76 still needs to be addressed - if the render system is bubbling down #states to elements that don't support #states that is a problem. What we're doing here is masking. This is why we need concrete steps to reproduce this issue not a something that adds #states to a markup element since that is always wrong.

jungle’s picture

Status: Needs work » Reviewed & tested by the community
Issue tags: +Needs followup
The markup is properly hidden because the parent is, but the state still bubbles down.

Doesn't that imply that there is a better fix out there? I.e. to not bubble the state down to markup elements - I've tried to find out how this is happening but I can't see it.

Out of my ability to dig into details myself, So I would suggest landing this one first if possible. This is a real bug, at least, it got fixed. Even thorough, the way of fixing it is not the best way. Or keep waiting till someone finds out the better way. it's already 4 years old :p.

Tagging "Needs followup" for #76 and setting back to RTBC for a second chance.

Thanks!

alexpott’s picture

Status: Reviewed & tested by the community » Needs work

@jungle I've been pushing back on this for until we have a concrete set of steps to reproduce which are not add #states to a #markup element. Doing this does not work. Fixing this removes the one indication we have that something is wrong. People have said that there is a way that the field UI makes this occur but we are still waiting for steps to reproduce this. This is the bug.

jungle’s picture

Sorry, @alexpott, thanks for your time.

Tagging "Bug Smash Initiative" and send to the slack to see if anyone else could help.

carolpettirossi’s picture

StatusFileSize
new33.08 KB

I'm reproducing this error: Notice: Undefined index: #type in Drupal\Core\Form\FormHelper::processStates() (line 208 of core/lib/Drupal/Core/Form/FormHelper.php).
when I'm altering a paragraph to add #states.

I have a mymodule_field_widget_entity_reference_paragraphs_form_alter where I update some files to show/hide depending on a previous selected value.

$dependee_field_name = 'field_flexible_cta_type';
      $selector = sprintf('select[name="%s[%d][subform][%s]"]', $paragraph_entity_reference_field_name, $element['#delta'], $dependee_field_name);

      // Dependent fields.
      $element['subform']['field_flexible_cta_webform']['#states'] = [
        'visible' => [
          $selector => ['value' => 'webform'],
        ],
      ];

      $element['subform']['field_flexible_cta_link']['#states'] = [
        'visible' => [
          $selector => ['value' => 'link'],
        ],
      ];

      $element['subform']['field_virtual_experience_parag']['#states'] = [
        'visible' => [
          $selector => ['value' => 'virtual_experience'],
        ],
      ];

I'm using paragraphs experimental which collapse all the paragraph fields. This might be the issue here, but I'm not sure.

The patch #104 does fix the Notice though.

Version: 9.1.x-dev » 9.2.x-dev

Drupal 9.1.0-alpha1 will be released the week of October 19, 2020, which means new developments and disruptive changes should now be targeted for the 9.2.x-dev branch. For more information see the Drupal 9 minor version schedule and the Allowed changes during the Drupal 9 release cycle.

amneh.shawish’s picture

The below patch will fix this error (Notice: Undefined index: #type in drupal_process_states())
https://www.drupal.org/files/issues/2020-03-11/2700667-104.patch

pranav45’s picture

thanks. #104 that patch worked for me.

robertoperuzzo’s picture

Thanks jungle patch #104 works (OpenSocial 8.x-9.4, Drupal 8.8.10) .

NitinLama’s picture

@alexpott Agreed.

efrainh’s picture

Status: Needs work » Reviewed & tested by the community

I have the same as #119, but in this case it's a List (text) field in a paragraph which will make some other fields appear or hide according to the value selected:

This is a piece of the code:

  function mymodule_field_widget_paragraphs_form_alter(&$element, FormStateInterface $form_state, $context) {
      $field_definition = $context['items']->getFieldDefinition();
      $paragraph_entity_reference_field_name = $field_definition->getName();
...
      $dependee_field_name = 'field_hero_type';
      $selector = sprintf('select[name="%s[%d][subform][%s]"]', $paragraph_entity_reference_field_name, $element['#delta'], $dependee_field_name);
....
      // Dependent fields.
      $element['subform']['field_hero_form']['#states'] = [
        'visible' => [
          $selector => ['value' => 'form'],
        ],
      ];

I applied the patch in #104 and it fixed the problem, no more notice message.

alexpott’s picture

Status: Reviewed & tested by the community » Needs work

@efrainh can you provide some concrete steps to reproduce the PHP notice that someone without your code base can follow? I.e. Get these contrib modules, install standard, install such and such modules and do this configuration... and then we can see why this is happened.

The fix in #104 is not fixing the root cause. It's fixing an outcome of something not working or being in the expected state.

belba’s picture

In a hook form_views_exposed_form_alter I had the following lines of code for several fields :

$form['field_value'] = array(
    '#type' => 'checkbox',
    '#default_value' => FALSE,
    '#value' => 0,
    '#checked' => 'unchecked',
  );
  $form['field_one']['#states'] = array(
    'visible' => array(
     array(':input[name^="field_two"]' => array('checked' =>true)),
 ),
);

The code was working fine. But in all admin pages, I got an error :

Undefined index: #type in Drupal\Core\Form\FormHelper::processStates()type in Drupal\Core\Form\FormHelper::processStates()

I can confirm, that the patch #104 solved the issue.

https://www.drupal.org/files/issues/2020-03-11/2700667-104.patch

alexpott’s picture

@Belba this is a sign that your alter is not working as you expect to and potentially could break. Generic form alters need to test that any assumptions they are making are met. One of them needs to be whether or not using #states against an element that exists and actually has meaning. IF you are gettign this error it is because you're applying states on an element where it is not going to work.

Version: 9.2.x-dev » 9.3.x-dev

Drupal 9.2.0-alpha1 will be released the week of May 3, 2021, which means new developments and disruptive changes should now be targeted for the 9.3.x-dev branch. For more information see the Drupal core minor version schedule and the Allowed changes during the Drupal core release cycle.

ravi.khetri’s picture

StatusFileSize
new852 bytes

D9 compatible patch.

ravi.khetri’s picture

ravi.khetri’s picture

StatusFileSize
new820 bytes
dww’s picture

Status: Needs work » Needs review
StatusFileSize
new1.05 KB
new2.35 KB
new2.54 KB

I'm really torn on #128:

The fix in #104 is not fixing the root cause. It's fixing an outcome of something not working or being in the expected state.

That's true. And the DX of this is pretty harsh right now.

Could we do #104 now with a @todo to dig deeper? Punt it to a followup to explore #76?

@ravi.khetri: Thanks for your contribution, but your patches are excluding the new test file added with #104.

Here's a fresh re-roll for 9.2.x branch that includes the new test. Also a test-only version of it. And a version (b) with the @todo comment stubbed out (with an interdiff relative to version a). We only need to open the issue to get a nid for the comment if @alexpott is okay with that approach...

Thoughts?

Thanks,
-Derek

dww’s picture

StatusFileSize
new835 bytes

Interdiff didn't make it before I submitted. ;)

The interdiff btwn 133a and #104 is empty, it's only patch context changes. 104 still applies with fuzz using `patch -p1`.

The last submitted patch, 133: 2700667-133.test-only.patch, failed testing. View results

jor_kai’s picture

In my case this error came from trying to add #states to the wrong place. Maybe it will help someone else with a similar issue forgo the patch if they don't really need it. The field type was Text (formatted, long).

// Incorrect placement of #states.
$form['field_my_field_name']['widget']['0']['#states']

// Correct placement of #states.
$form['field_my_field_name']['#states']

Version: 9.3.x-dev » 9.4.x-dev

Drupal 9.3.0-rc1 was released on November 26, 2021, which means new developments and disruptive changes should now be targeted for the 9.4.x-dev branch. For more information see the Drupal core minor version schedule and the Allowed changes during the Drupal core release cycle.

vidorado’s picture

Status: Needs review » Reviewed & tested by the community

#136 is true, our states didn't work as expected until we placed them in the correct place.

Besides that, we were still getting the PHP notice, until we applied the patch in #133

alexpott’s picture

Status: Reviewed & tested by the community » Needs work

#138 basing an RTBC of the information in #136 is a bit odd. As #136 points out you get this error when you put #states in the wrong place. Making the change suggested by this issue makes that harder to discover NOT easier. As I've mentioned quite a few times before.

dieterholvoet’s picture

Title: Notice: Undefined index: #type in drupal_process_states() » Notice: Undefined index: #type in Drupal\Core\Form\FormHelper::processStates()

Version: 9.4.x-dev » 9.5.x-dev

Drupal 9.4.0-alpha1 was released on May 6, 2022, which means new developments and disruptive changes should now be targeted for the 9.5.x-dev branch. For more information see the Drupal core minor version schedule and the Allowed changes during the Drupal core release cycle.

maxstarkenburg’s picture

I encountered this notice in my dblog when encountering a very unexpected bug/error in the linkicon module (more details filed at #3304423: Format settings entirely disappear when clicking "Add the classes to the A tag"), namely when clicking a specific checkbox in the formatter options provided by that module, the entire list of formatter options suddenly disappears (short video of that). While there are indeed #states related to the visibility of the element in question, it's of type checkbox (and I don't believe any of the #markup elements added by that module have #states applied).

Those factors, along with the fact that the display:none in this case is showing up all the way up at .field-plugin-settings-edit-form, make me wonder if this is the kind of case that @mikelutz was describing in #68 and that @alexpott has been seeking an example of? (I did also try out the patch in #133 (oh hai, Derek!) and it does indeed just quiet/prevent the notice in the dblog while not preventing the linkicon bugginess.)

Version: 9.5.x-dev » 10.1.x-dev

Drupal 9.5.0-beta2 and Drupal 10.0.0-beta2 were released on September 29, 2022, which means new developments and disruptive changes should now be targeted for the 10.1.x-dev branch. For more information see the Drupal core minor version schedule and the Allowed changes during the Drupal core release cycle.

nathan tsai’s picture

Follow up to #136: if the field doesn't exist, the error also pops up.

(I did not test with any patch.)

Version: 10.1.x-dev » 11.x-dev

Drupal core is moving towards using a “main” branch. As an interim step, a new 11.x branch has been opened, as Drupal.org infrastructure cannot currently fully support a branch named main. New developments and disruptive changes should now be targeted for the 11.x branch, which currently accepts only minor-version allowed changes. For more information, see the Drupal core minor version schedule and the Allowed changes during the Drupal core release cycle.

taote’s picture

In my case this warning shows when in hook_form_alter I do something like:

$form['field_texto_cabecera']['#states'] = [
			    	'visible' => [
						'select[name="field_tipo_de_cabecera"]' => array(['value' => 'texto'], ['value' => 'image'], ['value' => 'video'], ['value' => 'slider'])
					]
				];

The patch works, but I need to patch the core everytime I update it. Is there another way to fix this without patching the core?

collinhaines’s picture

Recreation steps with contrib module smart_trim:

  1. Install standard profile, enable smart_trim module.
  2. Create a test view showing page content.
  3. Add the body field and in its formatter select Smart Trimmed.

The Browse available tokens link in newly generated More link section is generated based off the contrib token's token_tree_link theme. Because #themes do not require #type properties, this throws the undefined array key warning.

(This is also most likely reproduceable everywhere that formatter is placed, I just ran into it here.)

feyp’s picture

erwangel’s picture

I can confirm #147: with smart_trim module enabled, try to format a body field in views using smart_trim formatter and you get the error (D10.2.5).
The error also occurs with several other modules. I'm not using them but I landed on their issues while seeking a solution to this error message. I set some of them for reference in "relationships".

markie’s picture

Created a MR for smart_trim to resolve this by adding a '#type' key to the build. However it seems we should make it so if '#theme' is defined, '#type' should not be required.

https://www.drupal.org/project/smart_trim/issues/3451530#comment-15625318

Bhanu951 made their first commit to this issue’s fork.

bhanu951’s picture

Status: Needs work » Needs review

Got hit with this issue. Applying patch from #133 fixed the issue.

Re-rolled Patch from #133 against 11.x branch.

But there seems a test failure. Might not be related to this change. Test failure in DownloadTest.php#L138


    1)
    Drupal\Tests\file\Functional\DownloadTest::testPrivateFileTransferWithoutPageCache
    Correctly denied access to a file when file_test sets the header to -1.
    Failed asserting that 200 is identical to 403.
    
    /builds/issue/drupal-2700667/core/modules/file/tests/src/Functional/DownloadTest.php:138
    /builds/issue/drupal-2700667/core/modules/file/tests/src/Functional/DownloadTest.php:76
bhanu951’s picture

  Error message
  Warning: Undefined array key "#type" in Drupal\Core\Form\FormHelper::processStates() (line 211 of core/lib/Drupal/Core/Form/FormHelper.php).
  Drupal\Core\Form\FormHelper::processStates(Array) (Line: 412)
  Drupal\Core\Render\Renderer->doRender(Array) (Line: 458)
  Drupal\Core\Render\Renderer->doRender(Array, ) (Line: 204)
  Drupal\Core\Render\Renderer->render(Array) (Line: 474)
  Drupal\Core\Template\TwigExtension->escapeFilter(Object, Array, 'html', NULL, 1) (Line: 44)
  __TwigTemplate_335c6caddc004ce5ce1cc6eb323c5a5a->doDisplay(Array, Array) (Line: 394)
  Twig\Template->displayWithErrorHandling(Array, Array) (Line: 367)
  Twig\Template->display(Array) (Line: 379)
  Twig\Template->render(Array, Array) (Line: 40)
  Twig\TemplateWrapper->render(Array) (Line: 53)
  twig_render_template('core/themes/claro/templates/node-edit-form.html.twig', Array) (Line: 372)
  Drupal\Core\Theme\ThemeManager->render('node_edit_form', Array) (Line: 445)
  Drupal\Core\Render\Renderer->doRender(Array, ) (Line: 204)
  Drupal\Core\Render\Renderer->render(Array, ) (Line: 238)
  Drupal\Core\Render\MainContent\HtmlRenderer->Drupal\Core\Render\MainContent\{closure}() (Line: 592)
  Drupal\Core\Render\Renderer->executeInRenderContext(Object, Object) (Line: 231)
  Drupal\Core\Render\MainContent\HtmlRenderer->prepare(Array, Object, Object) (Line: 128)
  Drupal\Core\Render\MainContent\HtmlRenderer->renderResponse(Array, Object, Object) (Line: 90)
  Drupal\Core\EventSubscriber\MainContentViewSubscriber->onViewRenderArray(Object, 'kernel.view', Object)
  call_user_func(Array, Object, 'kernel.view', Object) (Line: 111)
  Drupal\Component\EventDispatcher\ContainerAwareEventDispatcher->dispatch(Object, 'kernel.view') (Line: 187)
  Symfony\Component\HttpKernel\HttpKernel->handleRaw(Object, 1) (Line: 76)
  Symfony\Component\HttpKernel\HttpKernel->handle(Object, 1, 1) (Line: 58)
  Drupal\Core\StackMiddleware\Session->handle(Object, 1, 1) (Line: 48)
  Drupal\Core\StackMiddleware\KernelPreHandle->handle(Object, 1, 1) (Line: 106)
  Drupal\page_cache\StackMiddleware\PageCache->pass(Object, 1, 1) (Line: 85)
  Drupal\page_cache\StackMiddleware\PageCache->handle(Object, 1, 1) (Line: 48)
  Drupal\Core\StackMiddleware\ReverseProxyMiddleware->handle(Object, 1, 1) (Line: 51)
  Drupal\Core\StackMiddleware\NegotiationMiddleware->handle(Object, 1, 1) (Line: 51)
  Drupal\Core\StackMiddleware\StackedHttpKernel->handle(Object, 1, 1) (Line: 704)
  Drupal\Core\DrupalKernel->handle(Object) (Line: 19)

Steps to Reproduce :

Added a field visibility condition using `#states` API

  $form['body']['#states'] = [
      'visible' => [
        ':input[name="field_article_type"]' => ['value' => 14833],
      ],
    ];

    $form['field_local_video']['#states'] = [
      'visible' => [
        ':input[name="field_article_type"]' => ['value' => 14832],
      ],
    ];
   
 

Among the above fields

body --> Default Body Field

field_local_video --> Media Entity Reference Field

field_article_type --> Taxonomy term field.

bhanu951’s picture

Seems the test failure from #153 is a random error. Re-running test did not re-produce it.

nicolas s.’s picture

Patch 2700667-133.test-only.patch works for me with a drupal 10.2.7 & php 8.2.x

alexpott’s picture

We should be fixing the affected modules and not hiding the error - as explained quite a few times this message is the sign of something expected to work that's not going to work. "Fixing" the code in core results in less information not more and it being harder and not easier to fix.

markie’s picture

So curious if you feel this should be closed WAD? Or the documentation should be updated to state that "#type" is required at all times even if you are using "#theme" which seems to be the main disconnect. (at least for me in smart_trim)

bramdriesen’s picture

@markie note that it's not only for theme functions. You can also trigger this by creating a markup field (see test in the MR).

It just seems very redundant needing to specify an element like this

$form_element = [
      '#type' => 'markup',
      '#markup' => 'Custom markup',
      '#states' => [
        'visible' => [
          ':select[name="method"]' => ['value' => 'email'],
        ],
      ],
    ];

Over just leaving off the #type part. If we should be fixing that, this issue would need to update the documentation to properly specify that #type is always required.

alexpott’s picture

@BramDriesen but that code does NOT actually work!

For the given form array

    $form['test'] = [
      '#type' => 'checkbox',
      '#title' => 'test',
    ];
    $form['blah'] = [
      '#type' => 'markup',
      '#markup' => 'Custom markup',
      '#states' => [
        'visible' => [
          ':input[name="test"]' => ['checked' => TRUE],
        ],
      ],
    ];
    $form['blah2'] = [
      '#type' => 'checkbox',
      '#title' => 'Blah 2',
      '#states' => [
        'visible' => [
          ':input[name="test"]' => ['checked' => TRUE],
        ],
      ],
    ];

only the Blah 2 checkbox with appear if the test checkbox is checked. The markup will always be present. As I've said before the system is trying to tell you that your expectations about what will work or not is incorrect and you need to fix the form array not this code.

smustgrave’s picture

Status: Needs review » Postponed (maintainer needs more info)

moving to PNMI for answer to #158, if this should be rescoped to update documentation or closed as WAD.

seanb’s picture

This issue might already be fixed since the code has changed in #1427838: password_confirm children do not pick up #states or #attributes

andreastkdf’s picture

littlecoding’s picture

It looks like the fix for issue #1427838 has been applied to the following branches: 10.3.x, 10.4.x, 11.0.x, and 11.x.

Can we confirm the resolution of this issue on those versions?

scott_euser’s picture

Status: Postponed (maintainer needs more info) » Closed (outdated)

Yep looks fixed

papagrande’s picture