i want to execute action create in my view frontend, the code of actionCreate in site controller is correct , but it redirect me to index.php with this url "http://localhost/advanced/frontend/web/index.php?Subsidize%5Bname%5D..........."
knowing that i want to redirect to view.php after creating a new item in table "subsidize"
action create in siteController.php
public function actionView($id) {
$model = Subsidize::findOne($id);
if ($model === null) {
throw new NotFoundHttpException;
}
return $this->render('view', [
'model' => $model,
]);
}
public function actionCreate() {
$model = new Subsidize();
if ($model->load(Yii::$app->request->post()) && $model->save()) {
return $this->redirect(['view', 'id' => $model->subsidize_id]);
} else {
return $this->render('create', [
'model' => $model,
]);
}
}
code of submitButton in view "create.php"
<?= Html::submitButton($model->isNewRecord ? 'إرسال ' : 'Update', ['class' => $model->isNewRecord ? 'btn btn-success' : 'btn btn-primary']) ?>
also , function behaviors in siteController
public function behaviors() {
return [
'access' => [
'class' => AccessControl::className(),
'only' => ['create'],
'rules' => [
[
'actions' => ['login', 'error'],
'allow' => true,
],
[
'actions' => ['create', 'view'],
'allow' => true,
'roles' => ['#'],
],
[
//see captcha and error added here, this fixes the issue
'actions' => ['support', 'test', 'delete', 'update', 'create', 'view'],
'allow' => true,
'roles' => ['?', '#'],
],
],
],
'verbs' => [
'class' => VerbFilter::className(),
'actions' => [
'index' => ['get'],
'view' => ['get'],
'create' => ['get', 'post'],
'update' => ['get', 'put', 'post'],
'delete' => ['post', 'delete'],
],
],
];
}
code of my view : create.php
<?php use yii\helpers\Html; use yii\widgets\ActiveForm; $model = new app\models\Subsidize; ?> <section class="support">
<div class="container">
<form class="dialog-form row">
<?php $form = ActiveForm::begin() ?>
<div class="col-md-12">
<div class="form-group">
<?php echo $form->field($model, 'name', [
'inputOptions' => ['autofocus' => 'autofocus', 'class' => 'form-control transparent']
])->textInput()->input('name', ['placeholder' => "الإسم الكريم"])->label(false); ?>
</div><!--End Form-group-->
</div><!-- col -->
<div class="col-md-12">
<div class="form-group">
<?php echo $form->field($model, 'montant', [
'inputOptions' => ['autofocus' => 'autofocus', 'class' => 'form-control transparent']
])->textInput()->input('montant', ['placeholder' => "المبلغ "])->label(false); ?>
</div><!--End Form-group-->
</div><!-- col -->
<div class="col-md-12">
<div class="form-group">
<?php echo $form->field($model, 'date', [
'inputOptions' => ['autofocus' => 'autofocus', 'class' => 'form-control transparent']
])->textInput()->input('date', ['placeholder' => "تاريخ التذكير "])->label(false); ?>
</div><!--End Form-group-->
</div><!-- col -->
<div class="col-md-12">
<div class="form-group">
<?php echo $form->field($model, 'phone', [
'inputOptions' => ['autofocus' => 'autofocus', 'class' => 'form-control transparent']
])->textInput()->input('phone', ['placeholder' => "رقم الجوال"])->label(false); ?>
</div><!--End Form-group-->
</div><!-- col -->
<div class="col-md-12">
<div class="form-group">
<?php echo $form->field($model, 'remarks', [
'inputOptions' => ['autofocus' => 'autofocus', 'class' => 'form-control transparent']
])->textInput(['rows' =>6])->input('remarks', ['placeholder' => "ملاحظات"])->label(false); ?>
</div><!-- form-group -->
</div><!-- col -->
<div class="col-md-12">
<div class="form-group" style="text-align:center ">
<?= Html::submitButton($model->isNewRecord ? 'إرسال ' : 'Update', ['class' => $model->isNewRecord ? 'btn btn-success' : 'btn btn-primary']) ?>
</div><!-- form-group -->
</div><!-- col -->
<?php ActiveForm::end(); ?>
</form><!--End-->
</div><!-- container -->
Did you forget to specify method attribute of your HTML form?
<form method="POST" ...>
Looks like form just being submitted as GET request
Sorry for my english before. Can you edit your post and add your complete ActiveForm::begin() code. for alternate fix, you can try to remove the create action on your verb behavior like this :
'verbs' => [
'class' => VerbFilter::className(),
'actions' => [
'index' => ['get'],
'view' => ['get'],
'update' => ['get', 'put', 'post'],
'delete' => ['post', 'delete'],
],
],
Related
I am currently in the process of updating a (rather big) application from CakePHP 3 to 4.
I have this template:
<?= $this->Form->create(
$dmpLayer,
[
'url' => [
'controller' => 'DmpLayers',
'action' => 'edit',
],
]
); ?>
<div class="row">
<div class="col-4">
<?= $this->element('DataLayers/layer-table'); ?>
</div>
<div id="form-div" class="col-6">
<div class="layer-form">
<?= $this->element('DataLayers/form') ?>
</div>
</div>
<div class="col-2">
<div class="layer-form">
<h2>Form Actions</h2>
<?= $this->Form->submit('Create/Update Layer', ['class' => 'btn btn-success']); ?>
</div>
</div>
</div>
<?= $this->Form->end(); ?>
<?= $this->Html->script('data-layers'); ?>
which includes the DataLayers/form element:
<div class="row">
<div class="col-12">
<h4>Artist Layer</h4>
<?php
echo $this->Html->tag('fieldset', $this->element(
'actions/add',
[
'url' => [
'prefix' => 'Admin',
'plugin' => false,
'controller' => 'SegmentCores',
'action' => 'add',
],
]
)
. $this->Form->control('artist_layer.segment_cores[]', [
'multiple',
'options' => $segmentCores,
'label' => 'Segment Core',
'value' => $selectedValues['segment_cores'],
])
. $this->Form->control('artist_layer.segment_potentials[]', [
'multiple',
'options' => $segmentPotentials,
'label' => 'Segment Potential',
'value' => $selectedValues['segment_potentials'],
])
. $this->Form->control('artist_layer.layer_tags[]', [
'multiple',
'options' => $layerTags,
'label' => 'Artist Tag',
'value' => $selectedValues['artist_tags'],
])
. $this->Form->control('artist_layer.genres[]', [
'empty' => 'No genre set',
'options' => $genres,
'label' => 'Genre',
'value' => $selectedValues['genres'],
]);
?>
</div>
</div>
<?php
$this->Form->unlockField('artist_layer.genres');
$this->Form->unlockField('artist_layer.segment_cores');
$this->Form->unlockField('artist_layer.segment_potentials');
$this->Form->unlockField('artist_layer.layer_tags');
?>
In the initialize function of the AppController I have this:
$this->loadComponent('Security');
When I visit the page, it doesn't render and I immediately get this error:
FormProtector instance has not been created. Ensure you have loaded the FormProtectionComponent in your controller and called FormHelper::create() before calling FormHelper::unlockField()
This is the only form in my application for which this error happens. Every other form is working fine, and I am calling the Form->unlockField() function in many of them.
I am obviously calling Form->create() in my code, so is this because I am including an element to add fields to the form that is defined in the "main" template? Or is there some other explanation?
I have already attempted adding
$this->loadComponent('FormProtection');
to my AppController, but this causes a whole lot more problems in many other places in the app, and it doesn't solve the problem anyway (the page renders, but I get an error when submitting the form to save the data).
I have a form and I want to change my DynamicModel rule validations depedending on the value chosen in a specific select input. I've read this doc but I don't understand why my code doesn't work. I've tried the following with no results:
MyController
private function createFormModel(){
$model = new DynamicModel([
'indicador',
'mes'
]);
$model->addRule(['indicador'], 'required',['message' => 'This field is required']);
$model->addRule(['mes'], 'string');
$model->addRule(
'mes',
function ($attribute, $params, $validator) use ($model) {
if ($model->indicador == 'semana') {
$model->addError('mes', 'This field is required');
}
}
);
return $model;
}
MyView
<?php $form = ActiveForm::begin(); ?>
<!-- indicador -->
<div class="form-group">
<?= $form->field($model, 'indicador')->widget(Select2::class, [
'options' => ['id'=>'indicador'],
'data' => [
'dia' => 'Actividad por Día',
'semana' => 'Actividad por Semana',
'resumen' => 'Resumen de actividad'
],
'pluginOptions' => [
'placeholder'=>'Seleccionar indicador',
'allowClear' => true
],
]); ?>
</div>
<!-- /.indicador -->
<!-- mes -->
<div id = "semana" class="form-group hidden">
<?= $form->field($model, 'mes')->widget(DepDrop::class, [
'type' => DepDrop::TYPE_SELECT2,
'options' => ['id' => 'mes'],
'select2Options' => ['pluginOptions' => ['allowClear' => true]],
'pluginOptions' => [
'depends' => ['indicador'],
'placeholder'=>'Seleccionar mes',
'url' => Url::to(['/campus/subindicador']),
'loadingText' => 'Cargando ...',
'initialize' => true,
]
]);?>
</div>
<!-- /.mes -->
<?= Html::submitButton('Aplicar filtros', ['class' => 'btn btn-block btn-default']) ?>
<?php ActiveForm::end(); ?>
You need to use when with required validator.
$model = new DynamicModel(['indicador', 'mes']);
$model->addRule(['indicador'], 'required', ['message' => 'This field is required']);
$model->addRule(['mes'], 'string');
$model->addRule(['mes'], 'required', ['when' => function ($dModel) {
return $dModel->indicador == 'semana';
}, 'message' => 'This field is required']);
I am trying to use Yii2's conditional validator within DynamicModel clas, but the validator when is not working:
Controller
private function createFormModel(){
$model = new DynamicModel([
'indicador',
'departamento',
'mes'
]);
$model->addRule(['indicador'],'required',['message' => 'Este campo es obligatorio']);
$model->addRule(['departamento'], 'required', ['when' => function ($model) {
return $model->indicador == 'Semana';
}]);
return $model;
}
public function actionCuatrimestre()
{
$model = $this->createFormModel();
return $this->render('cuatrimestre',[
'model' => $model,
]);
}
Whether I select or not the "indicador" field which is a select field, the "departamento" field alwasys returns as required. I have algo try this way but with no results:
$model->addRule(['departamento'], 'required', ['when' => function ($model) {
return $model->indicador == 'Semana';
}], ['whenClient' => "function (attribute, value) {
return $('#indicador').val() == 'Semana';
}"]);
What I am missing here?
EDIT
My view code cuatrimestre.php
<?php $form = ActiveForm::begin(); ?>
<div class="form-group">
<?= $form->field($model, 'indicador')->widget(Select2::class, [
'options' => ['id'=>'indicador'],
'data' => ['Semana','Día','Resumen'],
]); ?>
</div>
<div class="form-group">
<?= $form->field($model, 'departamento')->widget(Select2::class, [
'options' => ['id'=>'departamento'],
'data' => Departamentos::getDepartamentosByUser(),
]); ?>
</div>
<div class="form-group">
<?= $form->field($model, 'curso')->widget(DepDrop::class, [
'type' => DepDrop::TYPE_SELECT2,
'options' => ['id' => 'curso-id'],
'select2Options' => ['pluginOptions' => ['allowClear' => true]],
'pluginOptions' => [
'depends' => ['departamento-id'],
'placeholder'=>'Seleccionar curso',
'url' => Url::to(['/campus-actividad/subcursos']),
'loadingText' => 'Cargando ...',
'initialize' => true,
]
]);?>
</div>
<div>
<?= Html::submitButton('Aplicar filtros', ['class' => 'btn btn-block btn-default']) ?>
<?php ActiveForm::end(); ?>
</div>
I have a form that is not submitting anytime the submit button is clicked but it is validating.
see the form below:
<?php
$form = ActiveForm::begin([
'id' => 'contact-form',
'action' => ['site/index'],
'options' => [
'class' => 'contact-form wow fadeInUp',
'data-row-duration' => '1s',
]
])
?>
<div class="form-validation alert">
<div class="form-group col-md-12">
<?=
$form->field($model, 'name', [
'options' => ['style' => 'margin:0;padding:0'],
'inputOptions' => [
'class' => 'form-control',
'placeholder' => 'Full Name',
'autocomplete' => 'off'
]
])->label(false)
?>
</div>
<div class="form-group col-md-6">
<?=
$form->field($model, 'email', [
'options' => ['style' => 'margin:0;padding:0'],
'inputOptions' => [
'class' => 'form-control',
'placeholder' => 'Email',
'autocomplete' => 'off'
]
])->label(false)
?>
</div>
<div class="form-group col-md-6">
<?=
$form->field($model, 'phone', [
'options' => ['style' => 'margin:0;padding:0'],
'inputOptions' => [
'class' => 'form-control',
'placeholder' => 'Phone',
'autocomplete' => 'off'
]
])->label(false)
?>
</div>
<div class="form-group col-md-12">
<?=
$form->field($model, 'name', [
'options' => ['style' => 'margin:0;padding:0'],
'inputOptions' => [
'class' => 'form-control',
'placeholder' => 'Message',
'autocomplete' => 'off',
'rows' => '5'
]
])->textarea()->label(false)
?>
</div>
<div class="form-group col-md-4 col-md-offset-8">
<?=Html::submitButton('Submit', ['class' => 'btn btn-primary', 'name' => 'contact-button']) ?>
</div>
<?php ActiveForm::end(); ?>
SiteController/actionIndex:
public function actionIndex() {
$model = new ContactForm;
if( $model->load(Yii::$app->request->post()) && $model->validate() ){
if( $model->sendEmail(Yii::$app->params['adminEmail']) ){
Yii::$app->session->setFlash('success', 'Thank you for reaching us. We will respond to you shortly');
} else{
Yii::$app->session->setFlash('error', 'Something went wrong. Message not send successfuly');
}
return $this->refresh();
} else{
return $this->render('index', ['model' => $model]);
}
}
NOTE: I'm not getting any error. it's validating but after filling the form to click on submit, the button doesn't work I even used die() in place of the Yii::$app->session->setFlash() still nothing happened. it is just not responding.
Apparently, you have an error but you are not noticing it because you are rendering the name field instead of the message field inside your ActiveForm, I am talking about the very last field before the submit button.
<div class="form-group col-md-12">
<?=
$form->field($model, 'name', [
'options' => ['style' => 'margin:0;padding:0'],
'inputOptions' => [
'class' => 'form-control',
'placeholder' => 'Message',
'autocomplete' => 'off',
'rows' => '5'
]
])->textarea()->label(false)
?>
</div>
and although you have a validation error when you call the $model->validate() against the message field but it is unable to display because it assigns the error to the attribute field that is used in the form but apparently there isn't any field with the name message in the form, so it does not display anything. If you add this line after the form declaration you will immediately see the error
<?= $form->errorSummary($model); ?>
So, change the last field to below and everything will work now.
<div class="form-group col-md-12">
<?=
$form->field($model, 'message', [
'options' => ['style' => 'margin:0;padding:0'],
'inputOptions' => [
'class' => 'form-control',
'placeholder' => 'Message',
'autocomplete' => 'off',
'rows' => '5'
]
])->textarea()->label(false)
?>
</div>
<?php $form = ActiveForm::begin(['id' => 'contact-form']); ?>
<?= $form->field($model, 'email', [
'inputOptions' => [ 'placeholder' => 'Ihre E-Mail Adresse', 'class' => 'newsletter-cta-mail' ]
])->label(false)->textInput(); ?>
<?= Html::submitButton('20€ Gutschein sichern', ['class' => 'green newsletter-cta-button', 'name' => 'contact-button', 'value' => 'hallo']) ?>
<?php ActiveForm::end(); ?>
results into:
<form id="contact-form" action="/" method="post" role="form">
<input type="hidden" name="_csrf" value="WFlFWnIwU1Y3HnQKSn06GG46PXcjQRUzNCA9KhRiYCxvFXQ9RHIiPA=="> <div class="form-group field-newsletterform-email required has-error">
<input type="text" id="newsletterform-email" class="newsletter-cta-mail" name="NewsletterForm[email]" placeholder="Ihre E-Mail Adresse">
<p class="help-block help-block-error">Verification Code cannot be blank.</p>
</div> <button type="submit" class="green newsletter-cta-button" name="contact-button" value="hallo">20€ Gutschein sichern</button></form>
But I dont need the wrapping
How to disable this?
You could simply use Html::activeTextInput() :
<?= Html::activeTextInput($model, 'email', ['placeholder' => 'Ihre E-Mail Adresse', 'class' => 'newsletter-cta-mail']); ?>
Or change ActiveForm::$fieldConfig configuration :
ActiveForm::begin([
'id' => 'contact-form',
'fieldConfig' => [
'options' => [
'tag' => false,
],
],
]);
or You could something like this (change div to span)
$form = ActiveForm::begin([
'id' => 'contact-form',
'fieldConfig' => [
'template' => "{input}",
'options' => [
'tag'=>'span'
]
]
]);
<?= $form->field($model, 'email', [
'template' => '{input}', // Leave only input (remove label, error and hint)
'options' => [
'tag' => false, // Don't wrap with "form-group" div
],
]) ?>
I have solved it like this....put tag as span.. also you can prepend icons infront of the box.
<div id="login-box-inner">
<?php $form = ActiveForm::begin([
'id' => 'login-form',
'options' => ['role'=>'form'],
'fieldConfig' => [
'options' => [
'tag' => 'span',
],
],
]); ?>
<?= $form->field($model, 'username',[
'template' => '
<div class="input-group">
<span class="input-group-addon"><i class="fa fa-user emerald"></i></span>
{input}
</div>
{error}',
'inputOptions' => [
'placeholder' => 'Username ...',
'class'=>'form-control',
]])
?>
<?= $form->field($model, 'password', [
'template' => '
<div class="input-group">
<span class="input-group-addon"><i class="fa fa-key emerald"></i></span>
{input}
</div>
{error}',
'inputOptions' => [
'placeholder' => 'Password ...',
'class'=>'form-control',
]])->input('password')
?>
<?php ActiveForm::end(); ?>