Reputation: 315
I would like to have a form available on every page in my web app. So I created a widget with a form.
class AddNewURL extends Widget{
public $model;
public function init()
{
parent::init();
if ($this->model === null) {
$this->model = new ProductUrlForm();
}
}
public function run()
{
return $this->render('addNewURLForm', [
'model' => $this->model,
]);
}
}
and widget view
<div class="modal fade bs-example-modal-lg" id="newURL" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
<div class="modal-dialog modal-lg" role="document">
<div class="modal-content">
<?php Pjax::begin(); ?>
<?php $form = ActiveForm::begin([
'action' => Url::to(['site/new-url']),
'options' => ['data' => ['pjax' => true]],
]) ?>
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span>
</button>
<h4 class="modal-title" id="myModalLabel">Add new URL</h4>
</div>
<div class="modal-body">
<div class="row">
<div class="col-md-12">
<?= $form->field($model, 'url', ['errorOptions' => ['class' => 'help-block', 'encode' => false]])
->textInput(['maxlength' => false])
?>
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button type="submit" class="btn btn-primary">Add</button>
</div>
<?php ActiveForm::end() ?>
<?php Pjax::end(); ?>
</div>
</div>
</div>
and this how I use this widget in my layouts/main.php
<?= \app\widgets\AddNewURL::widget() ?>
in my site/new-url action I have
public function actionNewUrl()
{
$model = new ProductUrlForm();
$model->status = STATUS_NEW;
if ($model->load(Yii::$app->request->post()) && $model->save()) {
//return success message
}
return $this->render('index', [
'model' => $model,
]);
}
and now when I submit form data goes to my action, the form is reset and that's all. How to show validation error or success message using pjax? In my model I have few custom validation rules.
Maybe there is better solution to use one form on all pages?
Upvotes: 1
Views: 68
Reputation: 1314
Action actionNewUrl()
must render view addNewURLForm
so Pjax can replace old form with new html recieved from the action.
It is better to place your widget, controller and form model to separate module.
Upvotes: 1