How can i use ActiveForm with these requirements?
Submit form with ajax.
Before submitting with ajax: Check if error exits.
After submitting: Display error of field under field's input if the server responses unsuccess saving result.
This is your form in view. I prefer use different actions for validation and saving. You can join them into single method.
<?php $form = \yii\widgets\ActiveForm::begin([
'id' => 'my-form-id',
'action' => 'save-url',
'enableAjaxValidation' => true,
'validationUrl' => 'validation-rul',
]); ?>
<?= $form->field($model, 'email')->textInput(); ?>
<?= Html::submitButton('Submit'); ?>
<?php $form->end(); ?>
In validation action you should write. It validates your form and returns list of errrs to client. :
public function actionValidate()
{
$model = new MyModel();
$request = \Yii::$app->getRequest();
if ($request->isPost && $model->load($request->post())) {
\Yii::$app->response->format = Response::FORMAT_JSON;
return ActiveForm::validate($model);
}
}
And this is save action. In validate input data for security:
public function actionSave()
{
$model = new MyModel();
$request = \Yii::$app->getRequest();
if ($request->isPost && $model->load($request->post())) {
\Yii::$app->response->format = Response::FORMAT_JSON;
return ['success' => $model->save()];
}
return $this->renderAjax('registration', [
'model' => $model,
]);
}
This code will validate your form in actionValidate() and. For submitting your form via AJAX use beforeSubmit event. In your javascript file write:
$(document).on("beforeSubmit", "#my-form-id", function () {
// send data to actionSave by ajax request.
return false; // Cancel form submitting.
});
That's all.
Submit form with ajax.
Before submitting with ajax: Check if error exits. yii display error if any by default....... :)
use yii\helpers\Html;
use yii\bootstrap\ActiveForm;
use yii\widgets\Pjax;
/* #var $this yii\web\View */
/* #var $model backend\models\search\JobSearch */
/* #var $form yii\bootstrap\ActiveForm */
?>
<div class="job-search">
<?php $form = ActiveForm::begin([
'action' => ['index'],
//'method' => 'get',
'options' => ['id' => 'dynamic-form111']
]); ?>
<?php echo $form->field($searchModel, 'id') ?>
<?php echo $form->field($searchModel, 'user_id') ?>
<?php echo $form->field($searchModel, 'com_id') ?>
<?php echo $form->field($searchModel, 'job_no') ?>
<?php echo $form->field($searchModel, 'court_id') ?>
<?php // echo $form->field($model, 'case_no') ?>
<?php // echo $form->field($model, 'plainttiff') ?>
<?php // echo $form->field($model, 'defendant') ?>
<?php // echo $form->field($model, 'date_fill') ?>
<?php // echo $form->field($model, 'court_date') ?>
<?php // echo $form->field($model, 'status_id') ?>
<?php // echo $form->field($model, 'created_at') ?>
<?php // echo $form->field($model, 'updated_at') ?>
<div class="form-group">
<?php echo Html::submitButton('Search', ['class' => 'btn btn-primary','id'=>'submit_id']) ?>
<?php echo Html::resetButton('Reset', ['class' => 'btn btn-default']) ?>
</div>
<?php ActiveForm::end(); ?>
</div>
<script type="text/javascript">
$(document).ready(function () {
$('body').on('beforeSubmit', 'form#dynamic-form111', function () {
var form = $(this);
// return false if form still have some validation errors
if (form.find('.has-error').length)
{
return false;
}
// submit form
$.ajax({
url : form.attr('action'),
type : 'get',
data : form.serialize(),
success: function (response)
{
var getupdatedata = $(response).find('#filter_id_test');
// $.pjax.reload('#note_update_id'); for pjax update
$('#yiiikap').html(getupdatedata);
//console.log(getupdatedata);
},
error : function ()
{
console.log('internal server error');
}
});
return false;
});
});
</script>
Related
I was trying to create a newsletter module using Yii2 basic.
This is my scenario,
If a predefined template is available, I have to select that template.
If template is selected the subject and content should be loaded automatically.
For this I am using an Ajax.My Ajax is working perfectly and I appended the newsletter subject with Ajax success,Problem occurred when I tried to append the newsletter content.Hence I am using CKeditor.
My Form
<?php
use yii\helpers\Html;
use yii\widgets\ActiveForm;
use yii\helpers\ArrayHelper;
use app\modules\admin\models\NewsletterTemplates;
/* #var $this yii\web\View */
/* #var $model app\modules\admin\models\Letter */
/* #var $form yii\widgets\ActiveForm */
?>
<div class="letter-form form_style " >
<?php $form = ActiveForm::begin(); ?>
<?= $form->field($model, 'letter_template_id')->dropDownList(
ArrayHelper::map(NewsletterTemplates::find()->all(),'newsletter_temp_id','newsletter_temp_subject'),
['prompt' => 'Select','class'=>'form-contol','onchange'=>'
$.post( "'.Yii::$app->urlManager->createUrl('admin/letter/temp?id=').'"+$(this).val(), function( data ) {
var message = data.split("::");
//alert(message[1]);
$( "#letter-letter_sub" ).val( message[0] );
$( "#letter-letter_content" ).val( message[1] );
});'
]);
?>
<?php //echo $form->field($model, 'letter_template_id')->textInput(['class'=>'form-contol']) ?>
<?= $form->field($model, 'letter_to')->textInput(['class'=>'form-contol']) ?>
<?= $form->field($model, 'letter_sub')->textInput(['class'=>'form-contol']) ?>
<?= $form->field($model, 'letter_content')->textarea(['class'=>'ckeditor']) ?>
<div class="form-group">
<?= Html::submitButton($model->isNewRecord ? 'Send' : 'Update', ['class' => $model->isNewRecord ? 'btn btn-success' : 'btn btn-primary']) ?>
</div>
<?php ActiveForm::end(); ?>
</div>
Can anyone help with this......
Thanks in advance....
Hi Guys I found out the answer
I just replace the instances of the CKeditor.
<?= $form->field($model, 'letter_template_id')->dropDownList(
ArrayHelper::map(NewsletterTemplates::find()->all(),'newsletter_temp_id','newsletter_temp_subject'),
['prompt' => 'Select','class'=>'form-contol','onchange'=>'
$.post( "'.Yii::$app->urlManager->createUrl('admin/letter/temp?id=').'"+$(this).val(), function( data ) {
var message = data.split("::");
$( "#letter-letter_sub" ).val( message[0] );
CKEDITOR.instances["letter-letter_content"].destroy(true);
CKEDITOR.replace( "letter-letter_content" );
var editor = CKEDITOR.instances[ "letter-letter_content" ];
editor.setData(message[1]);
});'
]);
?>
Thank you for your supports
I have trouble with loading the table to the form_dropdown. I have tried any solution from the same trouble with me but its not working.
Here's the controller code:
<?php
class Registrasi extends Superuser_Controller
{
public $data = array(
'halaman' => 'registrasi',
'main_view' => 'program/administrasi/registrasi_list',
'title' => 'Data Registrasi',
);
public function __construct()
{
parent::__construct();
$this->load->model('program/administrasi/Registrasi_model', 'registrasi_model');
}
public function index()
{
$registrasi = $this->registrasi_model->get_all_registrasi_data();
$this->data['registrasiData'] = $registrasi;
$this->load->view($this->layout, $this->data);
}
public function tambah()
{
$this->data['namaNegara'] = $this->registrasi_model->get_nama_negara();
$this->data['main_view'] = 'program/administrasi/registrasi_form';
$this->data['form_action'] = site_url('program/administrasi/registrasi/tambah');
// Data untuk form.
if (! $_POST) {
$registrasi = (object) $this->registrasi_model->default_value;
} else {
$registrasi = $this->input->post(null, true);
}
// Validasi.
if (! $this->registrasi_model->validate('form_rules')) {
$this->data['values'] = (object) $registrasi;
$this->load->view($this->layout, $this->data);
return;
}
}
}
Here's the model code:
<?php
class Registrasi_model extends MY_Model
{
protected $_tabel = 'tb_registrasi';
protected $form_rules = array(
array(
'field' => 'Negara_Tujuan',
'label' => 'Negara Tujuan',
'rules' => 'trim|xss_clean|required|max_length[50]'
)
);
public $default_value = array(
'Negara_Tujuan' => ''
);
public function get_nama_negara()
{
$query = $this->db->query('SELECT Nama_Negara FROM tb_negara_tujuan');
return $query->result();
}
}
Here's the view code:
<div class="container">
<h2>Form Registrasi</h2>
<hr>
<?php echo form_open($form_action, array('id'=>'myform', 'class'=>'myform', 'role'=>'form')) ?>
<div class="container">
<div class="row">
<div class="form-group has-feedback <?php set_validation_style('Negara_Tujuan')?>">
<?php echo form_label('Negara Tujuan', 'negara_tujuan', array('class' => 'control-label')) ?>
<?php
foreach($namaNegara as $row)
{
echo form_dropdown('NegaraTujuan', $row->Nama_Negara);
}
?>
<?php set_validation_icon('Negara_Tujuan') ?>
<?php echo form_error('Negara_Tujuan', '<span class="help-block">', '</span>');?>
</div>
<?php echo form_button(array('content'=>'Simpan', 'type'=>'submit', 'class'=>'btn btn-primary', 'data-confirm'=>'Anda yakin akan menyimpan data ini?')) ?>
</div>
</div>
<?php echo form_close() ?>
</div>
The trouble I'm having is: Invalid argument supplied for foreach()
Your controller code must be :-
public function tambah()
{
$namaNegara[''] = 'select a option';
$namaNegaras = $this->registrasi_model->get_nama_negara();
foreach($namaNegaras as $namaNegaranew)
{
$namaNegara[$namaNegaranew->id] = $namaNegaranew->Nama_Negara ;
}
$this->data['namaNegara'] = $namaNegara;
$this->data['main_view'] = 'program/administrasi/registrasi_form';
$this->data['form_action'] = site_url('program/administrasi/registrasi/tambah');
// Data untuk form.
if (! $_POST) {
$registrasi = (object) $this->registrasi_model->default_value;
} else {
$registrasi = $this->input->post(null, true);
}
// Validasi.
if (! $this->registrasi_model->validate('form_rules')) {
$this->data['values'] = (object) $registrasi;
$this->load->view($this->layout, $this->data);
return;
}
}
And in view in place of
<?php
foreach($namaNegara as $row)
{
echo form_dropdown('NegaraTujuan', $row->Nama_Negara);
}
?>
Simply use
<?php echo form_dropdown('NegaraTujuan', $namaNegara , set_value('NegaraTujuan')); ?>
I think i have the answer for my problem:
Controller code (still same, no change whatsoever)
Model code: change the function into
public function get_nama_negara()
{
$query = $this->db->query('SELECT Nama_Negara FROM tb_negara_tujuan');
$dropdowns = $query->result();
foreach ($dropdowns as $dropdown)
{
$dropdownlist[$dropdown->Nama_Negara] = $dropdown->Nama_Negara;
}
$finaldropdown = $dropdownlist;
return $finaldropdown;
}
View code:
<div class="container">
<h2>Form Registrasi</h2>
<hr>
<?php echo form_open($form_action, array('id'=>'myform', 'class'=>'myform', 'role'=>'form')) ?>
<div class="container">
<div class="row">
<div class="form-group has-feedback <?php set_validation_style('Negara_Tujuan')?>">
<?php echo form_label('Negara Tujuan', 'negara_tujuan', array('class' => 'control-label')) ?>
<?php echo form_dropdown('NegaraTujuan', $namaNegara, set_value('NegaraTujuan'), 'class="dropdown"'); ?>
<?php set_validation_icon('Negara_Tujuan') ?>
<?php echo form_error('Negara_Tujuan', '<span class="help-block">', '</span>');?>
</div>
<?php echo form_button(array('content'=>'Simpan', 'type'=>'submit', 'class'=>'btn btn-primary', 'data-confirm'=>'Anda yakin akan menyimpan data ini?')) ?>
</div>
</div>
<?php echo form_close() ?>
</div>
I don't get any error, nothing, but image isn't being uploaded, like controller isn't called at all, when I add in contruct function log_message I do not see anything in log file, not sure what is the problem. By the way I'm using this library(http://jeromejaglale.com/doc/php/codeigniter_i18n) to manage languages, so I have in url http://getit.mysite/en
Here is my controller function
<?php
if (!defined('BASEPATH'))
exit('No direct script access allowed');
class FileUpload extends CI_Controller {
public $view_data = array();
private $upload_config;
function __construct() {
parent::__construct();
}
public function do_upload() {
$this->load->library('upload');
$image_upload_folder = base_url() . 'uploads/';
if (!file_exists($image_upload_folder)) {
mkdir($image_upload_folder, DIR_WRITE_MODE, true);
}
$this->upload_config = array(
'upload_path' => $image_upload_folder,
'allowed_types' => 'png|jpg|jpeg|bmp|tiff',
'max_size' => 2048,
'remove_space' => TRUE,
'encrypt_name' => TRUE,
);
$this->upload->initialize($this->upload_config);
if (!$this->upload->do_upload()) {
$upload_error = $this->upload->display_errors();
echo json_encode($upload_error);
} else {
$file_info = $this->upload->data();
echo json_encode($file_info);
}
}
}
?>
and js
jQuery(document).ready(function($) {
var base_url = 'http://getit.mycom/';
$('#upload-file').click(function(e) {
e.preventDefault();
$('#userfile').uploadify('upload', '*');
});
$('#userfile').uploadify({
'auto': false,
'swf': base_url + 'js/uploadify/uploadify.swf',
'cancelImg': base_url + 'js/uploadify/uploadify-cancel.png',
'uploader': base_url + 'fileupload/do_upload',
'fileTypeExts': '*.jpg;*.bmp;*.png;*.tif',
'fileTypeDesc': 'Image Files (.jpg,.bmp,.png,.tif)',
'fileSizeLimit': '8MB',
'fileObjName': 'userfile',
'buttonText': 'Select Photo(s)',
'multi': true,
'removeCompleted': false
});
});
and view file(add user) :
<?php echo form_open_multipart(); ?>
<ul class="unstyled">
<li>
<?php echo form_upload('userfile', '', 'id="userfile"'); ?>
<?php echo (isset($error)) ? $error : ''; ?>
</li>
<li>
<?php echo form_button(array('content' => 'Upload', 'id' => 'upload-file', 'class' => 'btn btn-large btn-primary')); ?>
</li>
</ul>
<?php echo form_close(); ?>
At the controller code, change if (!$this->upload->do_upload()) to if (!$this->upload->do_upload('Filedata')). Just try.
I'm trying to implement an ajax search in my CGridView and I'm not having much luck getting it to work.
My Grid:
<?php $this->widget('zii.widgets.grid.CGridView', array(
'id'=>'talent-grid',
'dataProvider'=>$model->searchTalent(),
'hideHeader'=>true,
'template' => '{pager}{items}{pager}',
'pager'=>array('cssFile'=>'/css/pager.css','header' => '',),
'cssFile'=>'/css/client-grid.css',
'columns'=>array(
array(
'name'=>'talent_id',
'type'=>'raw',
'value'=>'$data->getTalentGridRow($data)',
),
),
)); ?>
Search form:
<?php $form=$this->beginWidget('CActiveForm', array(
'action'=>Yii::app()->createUrl($this->route),
'method'=>'get',
)); ?>
<div class="row">
<?php echo $form->label($model,'full_name',array('class'=>'inline')); ?>
<?php echo $form->textField($model,'full_name',array('size'=>60,'maxlength'=>64)); ?>
</div>
<div class="row">
<?php echo $form->label($model,'gender_id',array('class'=>'inline')); ?>
<?php echo $form->checkBoxList($model, 'gender_id',CHtml::listData(Gender::model()->findAll(), 'gender_id', 'name'),array('separator'=>' ')); ?>
<?php echo $form->error($model,'gender_id'); ?>
</div>
<div class="row buttons">
<?php echo CHtml::submitButton('Submit'); ?>
</div>
<?php $this->endWidget(); ?>
The search model:
public function searchTalent() {
$criteria=new CDbCriteria;
$criteria->compare('full_name',$this->full_name,true);
if ($this->gender_id != "") {
$criteria->compare('gender_id',$this->gender_id);
}
return new CActiveDataProvider($this, array(
'criteria'=>$criteria,
'pagination'=>array(
'pageSize'=>30,
),
));
}
The javascript:
Yii::app()->clientScript->registerScript('searchTalent', "
$('#search-form form').submit(function(){
$.fn.yiiGridView.update('talent-list', {
data: $(this).serialize()
});
return false;
});
");
The controller:
public function actionClients() {
$model = new Talent('search');
$model->unsetAttributes(); // clear any default values
if (isset($_GET['Talent'])) {
$model->attributes = $_GET['Talent'];
}
$this->render('clients', array(
'model' => $model,
'pages' => 10
));
}
the js submit fires, but the grid doesn't get updated. Not sure why.
You have specified the id of gridview in js as talent-list but the original id is talent-grid as specified in widget initialization call . So change the line as
Yii::app()->clientScript->registerScript('searchTalent', "
$('#search-form form').submit(function(){
$.fn.yiiGridView.update('talent-grid', {
data: $(this).serialize()
});
return false;
});
");
i'm loading a post with ajax.
The code is
$(document).ready(function(){
loadPostsFun = function(){
$.ajax({
url: "http://lab1.koalamedia.es/ajax/",
//url: "/random/",
success: function(response){
$("#randomPost").html( response );
}
});
};
$("#another").click(function(){
loadPostsFun();
return false;
});
});
The response is generated by a custom template with this code:
<?php
query_posts('showposts=1&orderby=rand');
the_post();
$args = array( 'numberposts' => 1, 'orderby' => 'date' );
$rand_posts = get_posts( $args );
?>
<?php
foreach( $rand_posts as $post ) : setup_postdata($post);
?>
<div id="post-<?php the_ID(); ?>" <?php post_class(); ?>>
<?php if ( is_front_page() ) { ?>
<h2 class="entry-title"><?php the_title(); ?></h2>
<?php } else { ?>
<h1 class="entry-title"><?php the_title(); ?></h1>
<?php } ?>
<div class="entry-content">
<?php the_content(); ?>
<?php wp_link_pages( array( 'before' => '<div class="page-link">' . __( 'Pages:', 'twentyten' ), 'after' => '</div>' ) ); ?>
<?php comments_popup_link(__('Comments (0)'), __('Comments (1)'), __('Comments (%)')); ?>
</div><!-- .entry-content -->
</div><!-- #post-## -->
<?php
//comments_template( '', true ); //this doesn't work
comment_form();
//wp_list_comments(''); //this doesn't work
?>
<?php endforeach; ?>
The ajax request works but the comments doesn't show.All the post data is there.
How can i show the comments?
neither comments_template or wp_list_comments work.
You can view a demo or download the template sample i've done here
Without much tweaking wp_list_comments() works in a comments template (usually comments.php) only.
Use get_comments(), pass the post ID as parameter:
$comments = get_comments(array ( 'post_id' => $post->ID );
if ( $comments )
{
foreach ( $comments as $comment )
{
print "<li>$comment->comment_author<br>$comment->comment_content</li>";
}
}
i've found the problem, i forgot to set the global variable:
global $withcomments;
i was using
$withcomments = true;
comments_template();
but without the global it didn't work.
Now works like normal comments do.