My form will validate on the client side but I'm trying to figure out why its not validating on the server side. I don't have my php complete but its not even bringing up the POST request in my console saying its submitting the form to the server.
jQuery:
$(document).ready(function()
{
/*
* Validate the form when it is submitted
*/
var validateform = $("#newArticleForm").validate({
invalidHandler: function(form, validator) {
var errors = validator.numberOfInvalids();
if (errors) {
var message = errors == 1
? 'You missed 1 field. It has been highlighted.'
: 'You missed ' + errors + ' fields. They have been highlighted.';
$('.box .content').removeAlertBoxes();
$('.box .content').alertBox(message, {type: 'warning', icon: true, noMargin: false});
$('.box .content .alert').css({
width: '100%',
margin: '0',
borderLeft: 'none',
borderRight: 'none',
borderRadius: 0
});
} else {
$('.box .content').removeAlertBoxes();
}
},
showErrors : function(errorMap, errorList) {
this.defaultShowErrors();
var self = this;
$.each(errorList, function() {
var $input = $(this.element);
var $label = $input.parent().find('label.error').hide();
$label.addClass('red');
$label.css('width', '');
$input.trigger('labeled');
$label.fadeIn();
});
},
submitHandler: function(form) {
var dataString = $('#newArticleForm').serialize();
$.ajax({
type: 'POST',
url: '/kowmanager/dashboard/articleSubmit',
data: dataString,
dataType: 'json',
success: function(data) {
if (data.error) {
$('.box .content').removeAlertBoxes();
$('.box .content').alertBox(data.message, {type: 'warning', icon: true, noMargin: false});
$('.box .content .alert').css({
width: '',
margin: '0',
borderLeft: 'none',
borderRight: 'none',
borderRadius: 0
});
}
else
{
$('.box .content').removeAlertBoxes();
$('.box .content').alertBox(data.message, {type: 'success', icon: true, noMargin: false});
$('.box .content .alert').css({
width: '',
margin: '0',
borderLeft: 'none',
borderRight: 'none',
borderRadius: 0
});
$(':input','#newArticleForm')
.not(':submit, :button, :hidden, :reset')
.val('');
}
}
});
}
});
});
Controller:
function articleSubmit()
{
$outputArray = array('error' => 'yes', 'message' => 'unproccessed');
$outputMsg = '';
// Sets validation rules for the login form
$this->form_validation->set_rules('title', 'Title',
'trim|required|xss_clean|alpha_numeric');
$this->form_validation->set_rules('category', 'Category',
'integer');
$this->form_validation->set_rules('isSticky', 'Is Sticky',
'integer');
$this->form_validation->set_rules('comments', 'Allow Comments',
'integer');
// Checks to see if login form was submitted properly
if (!$this->form_validation->run())
{
$outputArray['message'] =
'There was a problem submitting the form! Please refresh the window and try again!';
}
else
{
}
}
View:
<?php $attributes = array('class' => 'validate', 'id' => 'newArticleForm'); ?>
<?php echo form_open_multipart('', $attributes) ?>
<div class="content no-padding">
<div class="section _100">
<?php echo form_label('Title', 'title'); ?>
<div>
<?php echo form_input('title', '', 'class="required"'); ?>
</div>
</div>
<div class="section _100">
<?php echo form_label('Category', 'category'); ?>
<div>
<?php echo form_dropdown('category', $categories, '', 'class="required"'); ?>
</div>
</div>
<div class="section _100">
<?php echo form_label('Is Sticky', 'sticky'); ?>
<div>
<?php
$options = array(
'' => 'Please Select An Option',
'0' => 'No',
'1' => 'Yes',
);
?><?php echo form_dropdown('sticky', $options, '', 'class="required"'); ?>
</div>
</div>
<div class="section _100">
<?php echo form_label('Allow Comments', 'comments'); ?>
<div>
<?php
$options = array(
'' => 'Please Select An Option',
'0' => 'No',
'1' => 'Yes',
);
?><?php echo form_dropdown('comments', $options, '', 'class="required"'); ?>
</div>
</div>
<div class="section _100">
<?php echo form_label('Date Comments Expire', 'datetime'); ?>
<div>
<input id="datetime" type="datetime" class="required" />
</div>
</div>
<div class="section _100">
<?php echo form_label('Status', 'status'); ?>
<div>
<?php
$options = array(
'' => 'Please Select An Option',
'0' => 'Inactive',
'1' => 'Active',
);
?><?php echo form_dropdown('status', $options, '', 'class="required"'); ?>
</div>
</div>
<div class="section _100">
<?php echo form_label('Image', 'file'); ?>
<div>
<?php echo form_upload('file', '', 'class="required"'); ?>
</div>
</div>
<div class="section _100">
<?php echo form_label('Permalink', 'permalink'); ?>
<div>
<?php echo form_input('permalink', '', 'class="required"'); ?>
</div>
</div>
<div class="section _100">
<?php echo form_label('Article', 'article'); ?><?php $attributes = array('name' => 'article', 'cols' => '30', 'rows' => '5', 'id' => 'article', 'class' => 'required') ?>
<div>
<?php echo form_textarea($attributes); ?>
</div>
</div>
</div><!-- End of .content -->
<div class="actions">
<div class="actions-left">
<?php echo form_reset(array('id' => 'reset', 'name' => 'reset'), 'Reset'); ?>
</div>
<div class="actions-right">
<?php echo form_submit(array('id' => 'submit', 'name' => 'submit'), 'Submit'); ?>
</div>
</div><!-- End of .actions -->
<?php echo form_close(); ?>
EDIT:
I have other forms that use this jquery as well but wondering if anyone had any additional ideas?
I know the answer to this issue... and it drove me nuts so I am happy to help you with this one :))
Codeigniter works in a very special way with POST requests. If you do this but instead use a GET request you will see it works fine... so what's going on?
Codeigniter has a crsf token to make sure you POST your data in a safe way.
So make sure you send this crsf value with the rest of your data.
I will give you an example, this is what my POST ajax + codeigniter looks like:
$.ajax({
type: 'POST',
dataType: 'HTML',
data: {
somevalue : somevalue,
csrf_test_name : $.cookie('csrf_cookie_name')
},
...
As you can see, your crsf value is stored in a cookie. I use the jquery plugin cookie helper, but feel fry to use any other plugin.
However, keep in mind that the name 'csrf_test_name' is always expected by codeigniter when making a POST request
Have a nice day!
For those who want to read more a bout this, this is what I am talking about:
http://aymsystems.com/ajax-csrf-protection-codeigniter-20
Related
I am new to ajax, so I am learning, and I am stuck and have tried to search everywhere for what I need to no avail. I have a dropdown with a list of locations. However based on another dropdown I want to return a default location to the list. So if I pick asset A, its default location will autopopulate in the dropdown but still give me alternatives via the $locations list to choose another location. I can return the correct data to the div but I don't know how to populate it in a dropdown. Below is what I have that populates the div. Any help on how I would send it to the dropdown with the $locations list still intact but this value as the default selected would be appreciated.
Dropdowns
<div class="form-group">
<label class="control-label" for="asset_id" id="asset_id" >
Asset
</label>
<?php
echo $this->Form->input( 'WorkorderAsset.0.asset_id', array(
'type'=>'select',
'data-placeholder'=>'Select An Asset Type From Above...',
'class'=>'chzn-select form-control asset',
'empty' => true,
'id'=>'asset',
'label'=>false,
'after' => '<div class="input-group-addon"><i class="fa fa-exclamation text-
danger"></i></div></div>',
'between' => '<div class="input-group">',
));
?>
</div>
<div class="row">
<div class="col-md-6">
<?php
echo $this->Form->input( 'location_id', array(
'id'=> 'location',
'options'=>$locations,
'class'=>'chzn-select form-control',
'empty' => true,
'z'=>'Select A Location',
'required'=>false,
'between' => '<div class="input-group">',
'after' => '<div class="input-group-addon"><i class="fa fa-exclamation text-
danger"></i></div></div>',
));
?>
<div class="row">
<div class="col-md-6">
$('#asset').on('change', function() {
var id = $('#asset').val();
if (id != "") {
$.ajax({
type: 'POST',
url: '/workorders/workorders/getInfo/'+ id +'.json',
dataType: 'html',
beforeSend: function(xhr) {
$(".overlay").show();
xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
},
success: function( response ) {
console.log(response);
$('#location').html(response);
},
error: function (jqXHR, textStatus, errorThrown) {
console.log(jqXHR);
console.log(textStatus);
console.log(errorThrown);
},
complete: function() {
$(".overlay").hide();
},
});
}
else {
alert("Please select an asset");
}
});
In my controller
public function getInfo($id=null)
{
$locate = $this->request->data = $this->Asset->find('first', array(
'conditions'=>array(
'Asset.id' => $id
),
'contain'=>array(
'Location'=>array(
'fields'=>array('Location.name')
),
)
));
if ($this->request->is('ajax')) {
$this->set( 'locate', $locate);
}
}
In my JSON
<?php
$location = (!empty($locate['Location']['name'])) ? $locate['Location']['name'] : ' ';
?>
<div >
<? echo "Default Asset Location:" . " " . $location ?>
</div>
I figured it out. The answer is as follows.
View:
<div class="form-group">
<label class="control-label" for="asset_id" id="asset_id" >
Asset
</label>
<?php
echo $this->Form->input( 'WorkorderAsset.0.asset_id', array(
'type'=>'select',
'data-placeholder'=>'Select An Asset Type From Above...',
'class'=>'chzn-select form-control asset',
'empty' => true,
'id'=>'asset',
'label'=>false,
'after' => '<div class="input-group-addon"><i class="fa fa-exclamation
text-
danger"></i></div></div>',
'between' => '<div class="input-group">',
));
?>
</div>
<div class="row">
<div class="col-md-6">
<?php
echo $this->Form->input( 'location_id', array(
'id'=> 'location',
'options'=>$locations,
'class'=>'chzn-select form-control',
'empty' => true,
'z'=>'Select A Location',
'required'=>false,
'between' => '<div class="input-group">',
'after' => '<div class="input-group-addon"><i class="fa fa-exclamation
text-
danger"></i></div></div>',
));
?>
<div class="row">
<div class="col-md-6">
$('#asset').on('change', function() {
var id = $('#asset').val();
if (id != "") {
$.ajax({
type: 'POST',
url: '/workorders/workorders/getInfo/'+ id +'.json',
dataType: 'html',
success: function( response ) {
console.log(response);
$("#location").attr("data-placeholder", response);
$('#location' ).val('').trigger( 'chosen:updated' );
},
error: function (jqXHR, textStatus, errorThrown) {
console.log(jqXHR);
console.log(textStatus);
console.log(errorThrown);
},
complete: function() {
$(".overlay").hide();
},
});
}
else {
}
});
Controller:
public function getInfo($id=null)
{
if (!$id) {
throw new NotFoundException();
}
$locate = $this->Asset->find('first', array(
'conditions'=>array(
'Asset.id'=>$id
),
'contain'=>array(
'Location'=>array(
'fields'=>array(
'Location.id',
'Location.name',
),
'order'=>array('Location.name'=> 'asc')
)
)
));
#pr($groupSelection);
#exit;
$this->set(compact('locate'));
}
JSON
<?php
if (!empty($locate['Location'])) {
echo '<option value="' . $locate['Location']['id'] . '">' . $locate['Location']
['name'] . '</option>';
}
else {
echo '<option value="">' . __('No Options Available') . '</option>';
}
?>
I want call the javascript function into callback function of codeigniter controller.
Controller: Callback function
public function email_exist($id) {
$this->db->where('email', $id);
$query = $this->db->get('login');
if (!$query->num_rows() > 0) {
$this->form_validation->set_message(__FUNCTION__, $this->email_validate());
return FALSE;
} else {
return TRUE;
}
Javascript: Alert function
function email_validate(){
alert('Invalid Email Id');
}
An uncaught Exception was encountered
Type: Error
Message: Call to undefined method Login::email_validate()
Filename: C:\wamp64\www\CodeIgniterProject1\application\controllers\login.php
Line Number: 46
login_form.php
<?php echo validation_errors(); ?>
<?php echo form_open_multipart(); ?>
<form name="form">
<div class="loginform">
<?php echo form_label('LOGIN', 'login'); ?>
</div>
<div class="email">
<?php echo form_input('email', 'E-MAIL', set_value('email')); ?>
</div>
<div class="password">
<?php echo form_password('password', 'PASSWORD', set_value('password')); ?>
</div>
<div class='checkbox'>
<?php
echo form_checkbox(array(
'name' => 'remember',
'id' => 'remember',
'value' => 'REMEMBER ME',
'checked' => FALSE,
'style' => 'margin:1px'
)) . form_label('REMEMBER ME', 'remember');
?>
</div>
<div class='btnlogin'>
<?php echo form_submit('login', 'LOGIN'); ?>
</div>
</form>
you cant do that in Codeigniter, use Codeigniter default form validation library
View here
if you want to add css for validation errors then try set_error_delimeters()
if you have bootstrap then use
alert alert-danger
class, else create one class
$this->form_validation->set_error_delimiters('<div class="alert alert-danger">', '</div>');
see
[other suggestions]
instead of putting all error in the top, you can also try
<?php
echo form_error('email');
form_input('email', 'E-MAIL', set_value('email'));
?>
other options is jquery validation or js validation, write js in view or external .js file
<?php
data = array(
'name' => 'username',
'id' => 'username', //use the id for jquery validation $('#username').on('blur', function() { });
'value' => 'johndoe',
'maxlength' => '100',
'size' => '50',
'style' => 'width:50%'
'onBlur' => 'email_validate();' //use this for javascript validation
);
echo form_input($data);
?>
im unable to comment, thats why posting as answer
i`m making a search for products on the site. When you load the page the first time, you see all the products.
The product block is wrapped in pjax and pagination is carried out by the widget LinkPager.
A search request to the server is carried out through ajax, and a block of products found returns via renderPartial. If I try to switch to the next page, search results are reset and you see all the products again. It turns out that the widget LinkPager doesn’t work properly after carrying out of renderPartital.
view:
<div class="search-wrap">
<input type="text" class="search-input" id="search" placeholder="Поиск по названию" name="p">
<button type="submit" class="btn filter-search-btn-menu" id="btns">Поиск</button>
<script>
$('#btns').on('click', function(e){
var search = $('#search').val();
$.ajax({
type: 'POST',
url: "/person/notice",
data: { 'search': search },
cache: false,
success: function (data) {
$('#allnotice').html(data);
});
});
</script>
</div>
<div id="allnotice">
<?php yii\widgets\Pjax::begin();?>
<div id="up">
<?php if ($offerings) foreach($offerings as $one): ?>
<div class="preview-notice-wrap">
<div class="preview-notice-inner">
<h4><?php echo $one->title; ?></h4>
<div class="preview-notice">
<div>
<p><?php
$price = $one->start_price;
echo number_format($price) . ' ₽';
?></p>
</div>
<div>
<p><?php
$date = $one->created;
echo Yii::$app->formatter->asDate($date, 'd MMMM y');
?> </p>
</div>
</div>
</div>
</div>
<?php endforeach; ?>
<div class="notice-pagination-wrap preview-notice-pagination">
<?= \app\components\MyPager::widget([
'pagination' => $pages,
'maxButtonCount' =>7,
'prevPageLabel' => false,
'nextPageLabel' => false,
'activePageCssClass' => ['class' => 'page-active'],
'options' => ['class' => 'page-test'],
'linkOptions' => ['class' => 'page-link'],
]); ?>
</div>
</div>
<?php yii\widgets\Pjax::end(); ?>
</div>
controller:
public function actionNotice()
{
$user_id = Yii::$app->user->id;
$user = Person::findOne($user_id);
if (Yii::$app->request->isPost && Yii::$app->request->isAjax && Yii::$app->request->post()){
$s = \Yii::$app->request->post('search');
$count = \app\models\Offering::find()->where(['person_id' => $user->id])->andWhere(['like', 'title', $s])->count();
$query = \app\models\Offering::find()->where(['person_id' => $user->id])->andWhere(['like', 'title', $s])->orderBy('id DESC');
$pages = new \yii\data\Pagination(['totalCount' => $query->count(),'pageSize' => 4, 'pageParam' => 'page-top']);
$offerings = $query->offset($pages->offset)->limit($pages->limit)->all();
\Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
return $this->renderPartial('_notice, ['count' => $count, 'pages' => $pages, 'offerings' => $offerings]);
}
$count = \app\models\Offering::find()->where(['person_id' => $user->id])->count();
$query = \app\models\Offering::find()->where(['person_id' => $user->id])->orderBy('id DESC');
$pages = new \yii\data\Pagination(['totalCount' => $query->count(),'pageSize' => 4, 'pageParam' => 'page-top']);
$offerings = $query->offset($pages->offset)->limit($pages->limit)->all();
return $this->render('notice', ['count' => $count, 'pages' => $pages, 'offerings' => $offerings]);
}
I have one solution:
url: "/person/notice?search="+search,
put value in url.
$('#btns').on('click', function(e){
var search = $('#search').val();
$.ajax({
type: 'POST',
url: "/person/notice?search="+search,
data: { 'search': search },
cache: false,
success: function (data) {
$('#allnotice').html(data);
});
});
and you can catch it in controller
if(isset($_POST['search']))
$search_word = trim($_POST['search']);
if(isset($_GET['search']))
$search_word = trim($_GET['search']);
I am in the learning stage in php.Please help me with my update form.Advanced thanks. I have a form to update any user information with a button "Save" and "Reset" button.I update any information the version number increase.But the problem is when i do not update any information and click on "Save" button the version number increases.It should not increase.I am giving my Controller and form code....
public function actionCreate()
{
$model=new CvUpload;
$model2=new CvUpload;
$UserType=new UserType;
$CvHistory=new CvHistory;
$this->performAjaxValidation($model);
if(!empty($_POST))
{
$id = $_POST['CvUpload']['user_id'];
$cv_type = $_POST['CvUpload']['cv_type'];
$criteria = new CDbCriteria();
$criteria->condition = "user_id = $id AND is_current='yes' AND cv_type='$cv_type'";
$CvUploadmodel = CvUpload::model()->find($criteria);
if(!empty($CvUploadmodel))
{
$CvUploadmodel->is_current='no';
$CvUploadmodel->status='inactive';
if($CvUploadmodel->save(false)){
$model->attributes=$_POST['CvUpload'];
$model->upload_date = new CDbExpression("NOW()");
$model->update_date = new CDbExpression("NOW()");
$model->version_id = $CvUploadmodel->version_id+1;
if($model->save(false))
{
$CvHistory->cv_id = $model->cv_id;
$CvHistory->user_id = $model->user_id;
$CvHistory->job_title_id = $model->job_title_id;
$CvHistory->cv_type = $model->cv_type;
$CvHistory->version_id = $model->version_id;
$CvHistory->file_name = $model->file_name;
$CvHistory->upload_date = $model->upload_date;
$CvHistory->update_date = $model->update_date;
$CvHistory->is_current = $model->is_current;
$CvHistory->status = $model->status;
if($CvHistory->save(false))
{
$this->redirect(array('view','id'=>$model->cv_id));
}
}
}
}
else
{
$model->attributes=$_POST['CvUpload'];
$model->upload_date = new CDbExpression("NOW()");
$model->update_date = new CDbExpression("NOW()");
$model->version_id=1;
if($model->save())
{
$CvHistory->cv_id = $model->cv_id;
$CvHistory->user_id = $model->user_id;
$CvHistory->job_title_id = $model->job_title_id;
$CvHistory->cv_type = $model->cv_type;
$CvHistory->version_id = $model->version_id;
$CvHistory->file_name = $model->file_name;
$CvHistory->upload_date = $model->upload_date;
$CvHistory->update_date = $model->update_date;
$CvHistory->is_current = $model->is_current;
$CvHistory->status = $model->status;
if($CvHistory->save(false))
{
$this->redirect(array('view','id'=>$model->cv_id));
}
}
}
}
$this->render('create',array(
'model'=>$model,
'UserType'=>$UserType,
'CvHistory'=>$CvHistory,
));
}
public function actionUpdate($id)
{
$model=$this->loadModel($id);
$CvHistory=new CvHistory;
if(isset($_POST['CvUpload']))
{
$model->attributes=$_POST['CvUpload'];
if($model->save())
{
$criteria = new CDbCriteria();
$criteria->condition = "cv_id = $model->cv_id AND is_current = 'yes'";
$CvHistory = CvHistory::model()->find($criteria);
$CvHistory->is_current = 'no';
$CvHistory->status = 'inactive';
if($CvHistory->save(false))
{
$new_CvHistory=new CvHistory;
$new_CvHistory->cv_id = $model->cv_id;
$new_CvHistory->user_id = $model->user_id;
$new_CvHistory->job_title_id = $model->job_title_id;
$new_CvHistory->cv_type = $model->cv_type;
$new_CvHistory->version_id = $CvHistory->version_id+1;
$model->version_id = $new_CvHistory->version_id ;
$new_CvHistory->file_name = $model->file_name;
$new_CvHistory->upload_date = $model->upload_date;
$new_CvHistory->update_date = new CDbExpression("NOW()");
$model->update_date = $new_CvHistory->update_date ;
$new_CvHistory->status = $model->status;
$new_CvHistory->is_current = "yes";
$new_CvHistory->save(false);
$model->save(false);
if($new_CvHistory->save(false))$this->redirect(array('view','id'=>$model->cv_id));
}
}
}
$this->render('update',array(
'model'=>$model,
'CvHistory'=>$CvHistory,
));
}
MY form button code:
<style>
#type {
background-color:#f5f5f5;
font-family: 'Arial';
font-size: 20px;
text-decoration: none;
color:#b2b2b2;
border:none;
float: right;
}
div.form label {
display: block;
font-size: 1em;
font-weight: bold;
}
.types-add{
float: right;
}
#type:hover {
border: none;
}
</style>
<?php if (Yii::app()->user->hasFlash('created')): ?>
<div class="flash-success">
<?php echo Yii::app()->user->getFlash('created'); ?>
</div>
<?php endif; ?>
<div class="form">
<?php $form=$this->beginWidget(
'booster.widgets.TbActiveForm',
array(
'id'=>'CvUpload-form',
'type' => 'horizontal',
'htmlOptions' => array(
'class' => 'well',
'enctype' => 'multipart/form-data',
)
));
?>
<fieldset>
<h1 align="center">CV Upload</h1>
<p class="note">Fields with <span class="required">*</span> are required.</p>
<?php echo $form->errorSummary($model); ?>
<div class="row">
<?php
$criteria=new CDbCriteria();
echo $form->dropDownListGroup(
$model,
'user_id',
array(
'wrapperHtmlOptions' => array(
'class' => 'col-sm-5',
),
'widgetOptions' => array(
'data' => CHtml::listData(User::model()->findAll($criteria), 'id', 'user_id'),
'dataProvider'=>$model->searchByUserId(Yii::app()->user->getId()),
'htmlOptions' => array('prompt'=>'Select'),
)
)
); ?>
</div>
<div class="row" id="jobTitle">
<?php
$criteria = new CDbCriteria;
$criteria->condition = "status= 'active'";
echo $form->dropDownListGroup(
$model,
'job_title_id',
array(
'wrapperHtmlOptions' => array(
'class' => 'col-sm-5',
),
'widgetOptions' => array(
'data' => CHtml::listData(JobTitle::model()->findAll($criteria), 'id', 'name'),
'htmlOptions' => array('prompt'=>'Select job title'),
)
)
); ?>
</div>
<?php echo CHtml::form($this->createUrl('uploadreport'), 'post', array('enctype'=>'multipart/form-data'));?>
<label class="col-sm-3 control-label required" for="CvUpload_file_name">
Upload File
</label>
<div class="row" id="file_upload" style="margin-left:20%; margin-bottom:2%;">
<?php
$this->widget('CMultiFileUpload',array(
'name' => 'files',
'accept' => 'doc|docx|pdf',
'max' => 1,
'htmlOptions' => array('size' => 25),
));
echo CHtml::htmlButton('Upload',array(
'onclick'=>'javascript: send();', // on submit call JS send() function
'id'=> 'post-submit-btn', // button id 'newcreate'
'class'=>'btn btn-primary',
));
?>
</div>
<?php Yii::app()->clientScript->registerCoreScript("jquery"); ?>
<script src="http://code.jquery.com/jquery-migrate-1.2.0.js"></script>
<script>
function send(){
var formData = new FormData($("#CvUpload-form")[0]);
$.ajax({
url: '<?php echo Yii::app()->createUrl("CvUpload/upload"); ?>',
type: 'POST',
data: formData,
datatype:'json',
beforeSend: function() {
},
success: function (data) {
$("#CvUpload_file_name").val(data);
},
complete: function() {
},
error: function (data) {
alert("There may a error on uploading. Try again later");
},
cache: false,
contentType: false,
processData: false
});
return false;
}
</script>
<div class="row" id="file_name">
<?php echo $form->textFieldGroup(
$model,'file_name',
array(
'wrapperHtmlOptions' => array(
'class'=> 'col-sm-5',
),
)
);
?>
</div>
<div class="row" id="statustype">
<?php
$status = array('active'=>'Active', 'inactive'=>'Inactive');
echo $form->dropDownListGroup(
$model,
'status',
array(
'wrapperHtmlOptions' => array(
'class' => 'col-sm-5',
),
'widgetOptions' => array(
'data' => $status,
'htmlOptions' => array('prompt'=>'Select a status'),
)
)
); ?>
</div>
<div class="row" id="statustype">
<?php
$is_current = array('yes'=>'Yes', 'no'=>'No');
echo $form->dropDownListGroup(
$model,
'is_current',
array(
'wrapperHtmlOptions' => array(
'class' => 'col-sm-5',
),
'widgetOptions' => array(
'data' => $is_current,
'htmlOptions' => array('prompt'=>'Select a status'),
)
)
); ?>
</div>
<div class="row buttons">
<?php echo CHtml::submitButton($model->isNewRecord ? 'Create' : 'Save',array(
'class'=>'btn btn-primary',
'style'=>"position:relative; margin-left:25%",
'id'=> 'yt1', // button id
)); ?>
</div>
</fieldset>
<?php $this->endWidget(); ?>
</div><!-- form -->
<!--/*/*
<div class="form">
<?php $form=$this->beginWidget('CActiveForm', array(
'id'=>'cv-upload-form',
'enableAjaxValidation'=>false,
)); ?>
<p class="note">Fields with <span class="required">*</span> are required.</p>
<?php echo $form->errorSummary($model); ?>
<div class="row">
<?php echo $form->labelEx($model,'user_id'); ?>
<?php echo $form->textField($model,'user_id',array('size'=>20,'maxlength'=>20)); ?>
<?php echo $form->error($model,'user_id'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'upload_date');enter code here ?>
<?php echo $form->textField($model,'upload_date'); ?>
<?php echo $form->error($model,'upload_date'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'file_name'); ?>
<?php echo $form->textField($model,'file_name',array('size'=>60,'maxlength'=>150)); ?>
<?php echo $form->error($model,'file_name'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'file_location'); ?>
<?php echo $form->textField($model,'file_location',array('size'=>60,'maxlength'=>150)); ?>
<?php echo $form->error($model,'file_location'); ?>
</div>
<div class="row buttons">
<?php echo CHtml::submitButton($model->isNewRecord ? 'Create' : 'Save'); ?>
</div>
<?php $this->endWidget(); ?>
</div><!-- form -->
If you don't change form values, it doesn't mean that this data wouldn't be sended to server.
Here at least button save will sended, so this case will always true:
if(!empty($_POST))
You didn't show whole form, but I suggest that fields user_id and cv_type has values (no mater values where changed or not, if form has fields they will be submited)
$id = $_POST['CvUpload']['user_id'];
$cv_type = $_POST['CvUpload']['cv_type'];
That's why model $CvUploadmodel = CvUpload::model()->find($criteria); loads and increament version_id
I have a link in _form:
<?php echo CHtml::link('Add Child', '#', array('id' => 'loadChildByAjax')); ?>
Some code to renderPartial child _form:
<div id="children">
<?php
$index = 0;
foreach ($model->goodsservices as $id => $child):
$this->renderPartial('goods/_form', array(
'model' => $child,
'index' => $id,
'display' => 'block'
));
$index++;
endforeach;
?>
</div>
And script with AJAX:
<?php
Yii::app()->clientScript->registerScript('loadchild', '
var _index = ' . $index . ';
$("#loadChildByAjax").click(function(e){
e.preventDefault();
var _url = "' . Yii::app()->controller->createUrl("loadChildByAjax", array("load_for" => $this->action->id)) . '&index="+_index;
$.ajax({
url: _url,
success:function(response){
$("#children").append(response);
$("#children .crow").last().animate({
opacity : 1,
left: "+50",
height: "toggle"
});
}
});
_index++;
});
', CClientScript::POS_END);
?>
In my controller:
public function actionLoadChildByAjax($index)
{
$model = new AppGoodsServices;
$this->renderPartial('goods/_form', array(
'model' => $model,
'index' => $index,
), false, true);
}
And at last me child _form:
<div style="margin-bottom: 20px; display: <?php echo!empty($display) ? $display : 'none'; ?>; width:100%; clear:left;" class="crow">
<div class="row" style="float: left;">
<?php echo CHtml::activeLabelEx($model, '['.$index.']goods_and_services'); ?>
<?php echo CHtml::activeTextField($model, '['.$index.']goods_and_services', array('size' => 30, 'maxlength' => 150)); ?>
<?php echo CHtml::error($model, '['.$index .']goods_and_services'); ?>
</div>
<div class="row" style="float: left;">
<?php echo CHtml::activeLabelEx($model, '['.$index .']percentage'); ?>
<?php echo CHtml::activeTextField($model, '['.$index.']percentage', array('size' => 5)); ?>
<?php echo CHtml::error($model, '['.$index.']percentage'); ?>
</div>
<div style="clear: both;"></div>
<div class="row">
<?php echo CHtml::link('Delete', '#', array('onclick' => 'deleteChild(this, '.$index.'); return false;'));
?>
</div>
</div>
<div style="clear: both;"></div>
<?php
Yii::app()->clientScript->registerScript('deleteChild', "
function deleteChild(elm, index)
{
element=$(elm).parent().parent();
/* animate div */
$(element).animate(
{
opacity: 0.25,
left: '+=50',
height: 'toggle'
}, 500,
function() {
/* remove div */
$(element).remove();
});
}", CClientScript::POS_END);
?>
I need when my button being clicked, the child _form should be dynamically rendered, but id doesn't work. What do I miss here?
instead use the widget of yii
<?php echo CHtml::activeLabelEx($model, '['.$index.']goods_and_services'); ?>
<?php echo CHtml::activeTextField($model, '['.$index.']goods_and_services', array('size' => 30, 'maxlength' => 150)); ?>
<?php echo CHtml::error($model, '['.$index .']goods_and_services'); ?>
use only html, byexample
$(function(){
$("#add").click(function(){
if(5 > $(".attr").length) {
var cycleBlock = '<input type="text" id="CategoryMstExt_0_attributes" name="CategoryMstExt['+i+'][attributes]" class="attrName'+i+'" maxlength="100" size="44"> ';
var $cycleBlock = $(cycleBlock);
$('#fields').append($cycleBlock);
i++;
} else {
alert('Maximum attributes limit reached');
}
});
});