Rendering dynamic hidden csrf input when using cache in yii2
I have a cached html snippet that contains a form in my opinion.
<?php $form = ActiveForm::begin(); ?>
<?php echo $form->field($model, 'name'); ?>
<?= Html::submitButton('Save') ?>
<?php ActiveForm::end() ?>
The problem with the CSRF validation token is it has to be dynamic (not static). Is there any other / better way to render without disabling and enabling it again?
<?php Yii::$app->request->enableCsrfValidation = false; ?>
<?php $form = ActiveForm::begin(); ?>
<?php Yii::$app->request->enableCsrfValidation = true; ?>
<input type="hidden" name="_csrf" value="<?php echo $this->renderDynamic('return Yii::$app->request->csrfToken;'); ?>">
<?php echo $form->field($model, 'name'); ?>
<?= Html::submitButton('Save') ?>
<?php ActiveForm::end() ?>
If I don't disable and enable CsrfValidation, I have two tokens in the html - first from the cache and the second is dynamic.
+3
source to share
2 answers
I just ran into this problem and finally after hours of working with different things, I came up with a way to change it using jQuery.
$this->registerJs("$(document).ready(function(){
$('input[name=_csrf]').val('".$this->renderDynamic('return Yii::$app->request->csrfToken;')."');
});", View::POS_END);
And then get rid of all the extra things you have in there
<?php $form = ActiveForm::begin(); ?>
<?php echo $form->field($model, 'name'); ?>
<?= Html::submitButton('Save') ?>
<?php ActiveForm::end() ?>
+1
source to share
Another way:
<?php $form = ActiveForm::begin(['options' => ['csrf' => false]]); ?>
<input type="hidden" name="<?= $this->renderDynamic('return Yii::$app->request->csrfParam;'); ?>" value="<?= $this->renderDynamic('return Yii::$app->request->csrfToken;'); ?>" />
<?php ActiveForm::end(); ?>
0
source to share