Skip to content

Fix singular/plural variable collision in baked templates#1075

Merged
dereuromark merged 3 commits into3.xfrom
fix-singular-plural-var-collision
Mar 21, 2026
Merged

Fix singular/plural variable collision in baked templates#1075
dereuromark merged 3 commits into3.xfrom
fix-singular-plural-var-collision

Conversation

@dereuromark
Copy link
Member

@dereuromark dereuromark commented Mar 17, 2026

Summary

  • Fixes template generation for models where singular and plural forms are identical (e.g., "news", "sheep", "fish")
  • Previously generated invalid code like foreach ($news as $news): which overwrites the collection variable
  • Now appends "Entity" suffix to the singular variable when collision detected: foreach ($news as $newsEntity):

Additional collision fixes

  • ControllerCommand: Same fix applied to controller action generation (view/edit/add/delete use $newsEntity)
  • view.twig: Related entity loops detect collision and append "Related" suffix
  • Controller add/edit templates: Association list variables detect collision and append "List" suffix

Refs https://discourse.cakephp.org/t/paginator-error/12806/4

When baking templates for models where the singular and plural forms are
identical (e.g., "news", "sheep", "fish"), the generated foreach loops
would incorrectly use the same variable for both the collection and the
iteration variable, producing invalid code like:

    foreach ($news as $news):

This fix appends "Item" to the singular variable name when a collision
is detected, producing valid code:

    foreach ($news as $newsItem):

Refs https://discourse.cakephp.org/t/paginator-error/12806/4
@dereuromark dereuromark added this to the 3.x (CakePHP 5) milestone Mar 17, 2026
- Change suffix from 'Item' to 'Entity' (less likely to collide with
  model names like 'NewsItem')
- Add same fix to ControllerCommand for controller action generation
- Add collision detection in view.twig for related entity loops
  (appends 'Related' suffix when otherSingularVar matches singularVar)
- Add collision detection in Controller/add.twig and edit.twig for
  association list variables (appends 'List' suffix when otherPlural
  matches singularName)
- Add test for ControllerCommand singular/plural collision handling
Ensures the NewsController.php is deleted if it exists from a previous
test run to avoid the "Do you want to overwrite?" prompt.
@dereuromark dereuromark merged commit 4fde09a into 3.x Mar 21, 2026
9 checks passed
@dereuromark dereuromark deleted the fix-singular-plural-var-collision branch March 21, 2026 01:01
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants