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>
Related
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 have a following code below:
<?= $form->field($model, 'date') ->widget(yii\jui\DatePicker::className(),['clientOptions' => [ 'placeholder' => 'dd/mm/yyyy',
'id' => 'form',
'autocomplete' => 'off',
'value' => date('m/d/Y'),
'autoclose'=>true,
]]) ?>
That will result in HTML in following way:
<div class="form-group has-icon has-label">
<label for="formSearchUpLocation">Picking Up Location</label>
<input type="text" class="form-control" id="formSearchUpLocation" placeholder="Airport or Anywhere">
<span class="form-control-icon"><i class="fa fa-map-marker"></i></span>
</div>
My question is as following:
How can I integrate the css and bootstrap classes in HTML below into yii2 active form above?
Thank you for your help.
if you are looking to add the class to all the group divs mean all the div that have the class form-group then you can use the fieldConfig option of the ActiveForm or if you want it for one specific field then you can use the options option of the $form->field() as the 3rd parameter
For the whole Form
$form = yii\widgets\ActiveForm::begin([
'fieldConfig' => [
'options' => [
'class' => 'my-group'
]
]
]);
For Single Field
echo $form->field($model, 'name', ['options' => ['class' => 'my-class']])->textInput();
Conversion
About converting your above HTML using ActiveForm the following should work you can use template option of the $form->field() 3rd parameter to add your custom icon after the input, along with other, see below will create your desired HTML
echo $form->field($model, 'date', [
'options' => [
'class' => 'form-group has-icon has-label'
],
'inputOptions' => [
'class' => 'form-control'
],
'template' => '{label}{input}<span class="form-control-icon"><i class="fa fa-map-marker"></i></span>{error}'
])->widget(yii\jui\DatePicker::class, [
'id' => 'created_at',
'options' => [
'placeholder' => 'Airport or Anywhere'
]
]);
You will have something like below
<?= $form->field($model, 'date') ->widget(yii\jui\DatePicker::className(),['clientOptions' => [ 'placeholder' => 'dd/mm/yyyy',
'id' => 'form',
'class' => 'WRITE-YOUR-CLASS'
'autocomplete' => 'off',
'value' => date('m/d/Y'),
'autoclose'=>true,
]]) ?>
just input your class name in 'class' section it will work.
example : 'class' => 'fa fa-map-marker'
You could try something like the code bellow to concat your calendar icon with the widget:
<?php
$addon = '<span class="input-group-addon">
<i class="fa fa-calendar-alt"></i>
</span>';
echo $addon.$form->field($model, 'date')->widget(yii\jui\DatePicker::className(),['clientOptions' => [ 'placeholder' => 'dd/mm/yyyy',
'id' => 'form',
'autocomplete' => 'off',
'value' => date('m/d/Y'),
'autoclose'=>true,
]]);
?>
Or you can try search more on the plugin you are using, some widgets have his own attribute to render the calendar icon.
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'],
],
],
So I have created a simple search form, and created the query within my controller (I am aware this isn't the best way to do it and should be done in my model/search model however for the time being it will do).
I was wondering how can I add an option to my form within the two dropdown with the label All which if passed will mean that that part of the query isn't applied.
Below is my view
<?php $form = ActiveForm::begin(['id' => 'home-search','method' => 'post', 'action' => Url::to(['productitem/search'])]); ?>
<?= $form->field($productitem, 'name')->textInput(array('placeholder' => 'What are you looking for?'))->label(false) ?>
<?= $form->field($productitem, 'brand_id')->dropDownList(
ArrayHelper::map(ProductBrand::find()->all(),'id','name'),
['prompt'=>'Select Brand']
)->label(false) ?>
<?= $form->field($productitem, 'category_id')->dropDownList(
ArrayHelper::map(ProductCategory::find()->all(),'id','name'),
['prompt'=>'Select Department']
)->label(false) ?>
<div class="form-group search-button">
<button type="submit" class="btn btn-primary" name="login-button">Search <i class="fa fa-lg fa-arrow-circle-o-right"></i></button>
</div>
<?php ActiveForm::end(); ?>
Below is my controller/query
public function actionSearch()
{
$query = ProductItem::find()
->andFilterWhere(['like', 'name', $_POST['ProductItem']['name']])
->andFilterWhere(['in', 'brand_id', $_POST['ProductItem']['brand_id']])
->andFilterWhere(['in', 'category_id', $_POST['ProductItem']['category_id']]);
$dataProvider = new ActiveDataProvider([
'query' => $query
]);
return $this->render('search', [
'dataProvider' => $dataProvider,
]);
}
hope this will offer some reference.
<?= $form->field($model, 'categoryid1')->widget(Select2::className(), [
'id' => 'categoryid1',
'name' => 'categoryid1',
'data' => ArrayHelper::map(Category::getCategoryByPid(0), 'id', 'name'),
'options' => [
'placeholder' => 'choose first',
],
'pluginOptions' => [
'allowClear' => true
],
])->label('first') ?>
<?= $form->field($model, 'categoryid2')->widget(DepDrop::className(), [
'type' => DepDrop::TYPE_SELECT2,
'id' => 'categoryid2',
'name' => 'categoryid2',
'data' => $model->categoryid1 ? ArrayHelper::map(Category::getCategoryByPid($model->categoryid1), 'id', 'name') : [],
'pluginOptions' => [
'depends' => ['product-categoryid1'],
'placeholder' => 'choose second',
'url' => Url::to(['/category/second'])
]
])->label('second'); ?>
<?= $form->field($model, 'categoryid')->widget(DepDrop::className(), [
'type' => DepDrop::TYPE_SELECT2,
'data' => $model->categoryid2 ? ArrayHelper::map(Category::getCategoryByPid($model->categoryid2), 'id', 'name') : [],
'pluginOptions' => [
'depends' => ['product-categoryid1', 'product-categoryid2'],
'placeholder' => 'third',
'url' => Url::to(['/category/third'])
]
])->label('third'); ?>
<?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(); ?>