diff --git a/framework/CHANGELOG.md b/framework/CHANGELOG.md index 1d6d7f8..0aa0e4b 100644 --- a/framework/CHANGELOG.md +++ b/framework/CHANGELOG.md @@ -57,6 +57,7 @@ Yii Framework 2 Change Log - Enh #9901: Default `Cache.SerializerPermissions` configuration option for `HTMLPurifier` is set to `0775` (klimov-paul) - Enh #10056: Allowed any callable to be passed to `ActionColumn::$urlCreator` (freezy-sk) - Enh #10061: `yii\helpers\BaseInflector::transliterate()` is now public. Introduced different levels of transliteration strictness (silverfire) +- Enh #10078: Added `csrf` option to `Html::beginForm()` to allow disabling the hidden csrf field generation (machour) - Enh #10098: Changed `yii.confirm` context to the event's target DOM element which is triggered by clickable or changeable elements (lichunqiang) - Enh #10118: Allow easy extension of slug generation in `yii\behaviors\SluggableBehavior` (cebe, hesna) - Enh #10149: Made `yii\db\Connection` serializable (Sam Mousa) diff --git a/framework/helpers/BaseHtml.php b/framework/helpers/BaseHtml.php index 59d053b..40f8884 100644 --- a/framework/helpers/BaseHtml.php +++ b/framework/helpers/BaseHtml.php @@ -300,6 +300,8 @@ class BaseHtml * the attributes of the resulting tag. The values will be HTML-encoded using [[encode()]]. * If a value is null, the corresponding attribute will not be rendered. * See [[renderTagAttributes()]] for details on how attributes are being rendered. + * Special options: + * - `csrf`: whether to generate the CSRF hidden input. When is not defined, defaults to true. * @return string the generated form start tag. * @see endForm() */ @@ -316,7 +318,9 @@ class BaseHtml $hiddenInputs[] = static::hiddenInput($request->methodParam, $method); $method = 'post'; } - if ($request->enableCsrfValidation && !strcasecmp($method, 'post')) { + $csrf = ArrayHelper::remove($options, 'csrf', true); + + if ($csrf && $request->enableCsrfValidation && strcasecmp($method, 'post') === 0) { $hiddenInputs[] = static::hiddenInput($request->csrfParam, $request->getCsrfToken()); } } diff --git a/tests/framework/helpers/HtmlTest.php b/tests/framework/helpers/HtmlTest.php index 63c2867..a47bb9d 100644 --- a/tests/framework/helpers/HtmlTest.php +++ b/tests/framework/helpers/HtmlTest.php @@ -859,6 +859,25 @@ EOD; $model->description = $value; $this->assertEquals($expectedHtml, Html::activeTextArea($model, 'description', $options)); } + + /** + * Fixes #10078 + */ + public function testCsrfDisable() + { + Yii::$app->request->enableCsrfValidation = true; + Yii::$app->request->cookieValidationKey = 'foobar'; + + $csrfForm = Html::beginForm('/index.php', 'post', ['id' => 'mycsrfform']); + $this->assertEquals( + '
' + . "\n" . '', + $csrfForm + ); + + $noCsrfForm = Html::beginForm('/index.php', 'post', ['csrf' => false, 'id' => 'myform']); + $this->assertEquals('', $noCsrfForm); + } } class HtmlTestModel extends Model