Changes
Title
unchanged
Render Form in popup via AJAX (Create and Update) with ajax validation & Also load any page via ajax Yii 2.0 (2.3)
Category
unchanged
How-tos
Yii version
changed
2.0
Tags
changed
AJAX, modal, ajax modal, bootstrap, yii2, ajax modal,lifedup
Content
changed
[...]
First we will create the JS you can either add it to your main layout as script tags or add it to your App Assets
To add it to App Assets you will create a file in your web directory ie. frontend/web/js/ajax-modal-popup.js. If you want to include your script inline the skip two code blocks.
```php
$(function(){
//get the click of modal button to create / update item[...]
```php
class AppAsset extends AssetBundle {[...]
```php
<script type="text/javascript">
//get the click of modal button to create / update item[...]
}
});
</script>
```[...]
```php
<?php
yii\bootstrap\Modal::begin([[...]
```
You can also put a loading Gif in the content show until the content is loaded
```php
<?php
yii\bootstrap\Modal::begin([[...]
If you want be able to view a page with either ajax or direct URL (going to yoursite.com/youraction in the url) you must put a check in the controller to use either ajax or standard render.
```php
public function actionSomeAction($id) {
$model = $this->findModel($id);[...]
The same action as above with just ajax and would never use direct access via url would be
```php
public function actionSomeAction($id) {
$model = $this->findModel($id);[...]
Next you need to tell each and every form to still use inline validation. Things you must do here!
**1. All forms MUST have an ID
2. You must enable client validation manually**
if both of those are not set the form will NOT do client/ajax validation.
```php
<?php
$form = ActiveForm::begin([
'options' => [
'id' => 'create-product-form'
,
'enableClentValidtaion' => true,
]
]);[...]
here are examples of both loading content with or without variables
```php
use yii\helpers\Html;
use yii\helpers\Url;[...]
```php
$(function(){
//load the current page with the conten indicated by 'value' attribute for a given button.[...]
```php
<div class="content" id="main-content">;
<?= $content ?>[...]
use the buttons just like i did above just change the class to loadMainContent
```php
<?= Html::button('Create New Company', ['value' => Url::to(['companies/create']), 'title' => 'Creating New Company', 'class' => 'loadMainContent btn btn-success']); ?>
```[...]
```php
<?= Html::a('title', FALSE, ['value' => Url::to(['create/company', 'type' => 'company']), 'class' => 'loadMainContent']); ?>
```[...]
You can also alter the js to use the url instead of value like
```php
$('#main-content').load($(this).attr('href'));
```
but I'd recommend using pjax for page content. I'll write one of these using pjax instead of ajax. The main benefit is that pjax will keep intact back buttons / forward buttons/ allows for links to be properly booked marked etc.[...]