How to put client side validation in TbActiveForm in Yii bootstrap? - php

I have created a form using widget -bootstrap.widgets.TbActiveForm with form elements like textFieldRow, TbTypeahead, CJuiDatePicker and TbButton. I have implemented ajax form submission and it works fine. And I have included a simple client side validation,the rules are defined in the EmployeeRegister model. Its a simple validation for empty fields only. The problem is that when I submit the form with required fields empty, the form get submitted. That is, no validation is performed. But it displays error message "Name cannot be blank." or "Address cannot be blank.". Can anyone help me to fix this issue??
I am attaching my code below.
// MOdel- EmployeeRegister
class EmployeeRegister extends CActiveRecord{
public $name;
public $address;
public $position;
public $joinDate;
public $age;
public $phone;
public $search;
public $id;
private $_identity;
public function rules(){
return array(
array('name,address,position,phone','required'),
array('joinDate,age,search,id','safe'),
);
}
public static function model($className=__CLASS__)
{
return parent::model($className);
}
public function tableName()
{
return 'emp_registration';
}
//View- edit.php
$form = $this->beginWidget('bootstrap.widgets.TbActiveForm', array(
'id'=>'employeeregister-form',
//'enableAjaxValidation'=>true,
'enableClientValidation'=>true,
'clientOptions'=>array('validateOnSubmit'=>true),
'htmlOptions'=>array('class'=>'well',),
)); ?>
<?php echo $form->textFieldRow($model, 'name',array('class'=>'span3','style'=>'height:30px','id'=>'emp_name')); ?>
<?php echo $form->textFieldRow($model, 'address', array('class'=>'span3','style'=>'height:30px','id'=>'emp_address')); ?>
<?php // echo $form->textFieldRow($model, 'position', array('class'=>'span3','value'=>$result['position'],'style'=>'height:30px')); ?>
<?php echo "<br/> Position <br/>";?>
<?php $this->widget('bootstrap.widgets.TbTypeahead', array(
'model'=>$model,
'htmlOptions'=>array('style'=>'height:30px','id'=>'emp_position'),
'attribute'=>'position',
'options'=>array(
'source'=>array(
'Junior Software Engineer','Software Engineer','Designer'),
'items'=>4,
'matcher'=>"js:function(item) {
return ~item.toLowerCase().indexOf(this.query.toLowerCase());
}",
)));
?>
<?php //echo $form->textFieldRow($model, 'joinDate', array('class'=>'span3','value'=>$result['joinDate'],'id'=>'datepicker')); ?>
<?php echo "<br/> Join Date <br/>";?>
<?php $this->widget('zii.widgets.jui.CJuiDatePicker',array(
'model'=>$model,
'attribute'=>'joinDate',
//'value'=>$result['joinDate'] ? $result['joinDate'] : "",
// additional javascript options for the date picker plugin
'options'=>array(
'showAnim'=>'fold',
'dateFormat'=>'yy-mm-dd',
),
'htmlOptions'=>array(
'style'=>'height:30px;','id'=>'emp_date'
)
)); ?>
<?php echo $form->textFieldRow($model, 'age', array('class'=>'span3','style'=>'height:30px','id'=>'emp_age')); ?>
<?php echo $form->textFieldRow($model, 'phone', array('class'=>'span3','style'=>'height:30px','id'=>'emp_phone')); ?>
<?php echo $form->textFieldRow($model, 'id', array('class'=>'span3','style'=>'height:30px; display:none;','id'=>'emp_id')); ?>
<?php echo "<br/>";?>
<?php $this->widget('bootstrap.widgets.TbButton', array('buttonType'=>'ajaxSubmit', 'label'=>'Update','type'=>'primary','htmlOptions'=>array('name'=>'update_button',),
'url'=>CController::createUrl('site/update'),
'ajaxOptions'=>array(
'type'=>'POST',
'dataType'=>'json',
'data'=>'js:$("#employeeregister-form").serialize()',
'success'=>'js:function(data){
//$("#update_err").html(data);
alert(data);
}',
'async' => true,
)); ?>
<?php //echo $form->error($model,'name,address,position,phone'); ?>
<?php $this->endWidget(); ?>
<div id="update_err"></div>
<?php echo CHtml::link('Back to List',array('site/index')); ?>
//Controller
$model= new EmployeeRegister();
$model->attributes = $_POST['EmployeeRegister'];
if(Yii::app()->getRequest()->getIsAjaxRequest()) {
echo CActiveForm::validate( array( $model));
Yii::app()->end();
}
$update_id= $model->id;
$name = $model->name;
$address = $model->address;
$position = $model->position;
$joinDate = $model->joinDate;
$age = $model->age;
$phone = $model->phone;
if(EmployeeRegister::model()->updateByPk($update_id, array('id'=>$update_id,'name'=>$name,'address'=>$address,'position'=>$position,'joinDate'=>$joinDate,'age'=>$age,'phone'=>$phone)))
echo $name."'s details updated successfully";
else
echo "Update failed";

use Latest version of yii framework that may solve your problem you may refer to this page

Related

yii 1 CJuiDatePicker inside custom widget

I create new widget like this:
class Schedule extends CWidget
{
public $address = null;
public $order = null;//order
public function init()
{
if(isset($this->order))
$this->address = $this->order->address;
}
public function run()
{
$city = City::model()->findAll(array('condition'=>'is_active = 1','order'=>'name ASC'));
$this->render('my_schedule',array('city'=>$city));
}
}
and view for this widget:
<?php
$form = new CActiveForm();
$form->id = 'checkout-form';
$form->enableAjaxValidation = true;
$form->clientOptions = array(
'validateOnSubmit' => true,
'validateOnChange' => false);
$order->address = $address;
?>
<?php if(is_array($city) && count($city) > 0) : ?>
<section class="persent70">
<p>
<?php
$this->widget('zii.widgets.jui.CJuiDatePicker',array(
'model'=>$order,
'attribute'=>'delivery',
'name'=>'delivery',
'options'=>array(
'showAnim'=>'slide',
'htmlOptions'=>array(
'class'=>'form-control',
'id' => 'delivery',
),
));
?>
<?php echo $form->error($order, 'delivery'); ?>
</p>
In this case calendar doesn't open, but when i use CJuiDatePicker in a simple view this datepicker works fine.
Try to use $this->getController()->widget('zii.widgets.jui.CJuiDatePicker', array(....));.

CUploadedFile in yii

my problem is with two or more files.
this codes is form Yii application development cookbook(2nd edition), chapter 4
i use Yii 1.1.14
controller:
<?php
class UploadController extends Controller
{
function actionIndex()
{
$dir = Yii::getPathOfAlias('application.uploads');
$uploaded = false;
$model=new Upload();
if(isset($_POST['Upload']))
{
$model->attributes=$_POST['Upload'];
$files=CUploadedFile::getInstances($model,'file');
if($model->validate()){
foreach($files as $file)
$file->saveAs($dir.'/'.$file->getName());
}
}
$this->render('index', array(
'model' => $model,
'dir' => $dir,
));
}
}
model:
<?php
class Upload extends CFormModel
{
public $file;
public function rules()
{
return [
['file', 'file', 'types'=>'jpg'],
];
}
}
view:
<?php if($uploaded):?>
<p>File was uploaded. Check <?php echo $dir?>.</p>
<?php endif ?>
<?php echo CHtml::beginForm('','post',array('enctype'=>'multipart/form- data'))?>
<?php echo CHtml::error($model, 'file')?>
<?php echo CHtml::activeFileField($model, "[0]file")?>
<?php echo CHtml::activeFileField($model, "[1]file")?>
<?php echo CHtml::submitButton('Upload')?>
<?php echo CHtml::endForm()?>
help me, please
You should fix form enctype, use multipart/form-data instead of multipart/form- data.
You could use CMultiFileUpload
controller:
$images = CUploadedFile::getInstancesByName('image');
foreach ($images as $image => $pic) {
}
view:
$this->widget('CMultiFileUpload', array(
'name' => 'image',
'accept' => 'jpeg|jpg|gif|png',
'duplicate' => 'Duplicate file!',
'denied' => 'Invalid file type',
));
Add to model 'maxFiles' param, if you need validation to work properly for multifiles upload.
public function rules()
{
return array(
array('image', 'file', 'types'=>'jpg,gif,png', 'maxSize'=>'204800', 'allowEmpty'=>true, 'maxFiles'=>4),
);
}

cakephp save() creating blank entry to database

I am new to CakePHP, i am creating simple form to add/edit/delete post as it is explain on its official website, my issue, while adding post to database it is not saving data,it is creating blank entries to database
Here is Code for Postscontroller.php
<?php
class PostsController extends AppController {
public $helpers = array('Html', 'Form');
public $components = array('Session');
public function add() {
if ($this->request->is('post')) {
$this->Post->create();
if ($this->Post->save($this->request->data)) {
$this->Session->setFlash(__('Your post has been saved.'));
return $this->redirect(array('action' => 'index'));
}
//debug($this->Post->validationErrors);
$this->Session->setFlash(__('Unable to add your post.'));
}
}
}
?>
Here is Code for Model Post.php :
<?php
class Post extends AppModel {
public $validate = array(
'title' => array(
'rule' => 'notEmpty'
),
'body' => array(
'rule' => 'notEmpty'
)
);
}
?>
Here is code for View add.ctp :
<h1>Add Post</h1>
<?php
echo $this->Form->create('post');
echo $this->Form->input('title');
echo $this->Form->input('body');
echo $this->Form->end('Save Post');
?>
can anyone suggest me what is causing blank entries to database ?
In the add.ctp :
The form name is Post not post...
<h1>Add Post</h1>
<?php
echo $this->Form->create('Post');
echo $this->Form->input('title');
echo $this->Form->input('body');
echo $this->Form->end('Save Post');
?>
In config/core.php file change the debug label to 2.(Configure::write('debug', 2)) and try saving again. The model name should be Post in the form. Please check the post data before saving.
debug($this->request->data);
exit;

yii captcha not validating properly

Im trying to add a captcha using yii to my contact form, but there is some problem with validation.
My model
class ContactForm extends CFormModel
{
public $verifyCode;
public function rules()
{
return array(
array('verifyCode', 'captcha', 'allowEmpty'=>!CCaptcha::checkRequirements(),'on'=>'captchaRequired'),
array('verifyCode', 'safe'),
);
}
}
Code in my controller
public function filters()
{
return array(
'accessControl',
);
}
public function accessRules()
{
return array(
array( 'allow', //allow all users to perform advertise and index action
'actions' => array('advertise','index', 'captcha'),
'users' => array('*'),
),
);
}
public function actions() {
return array(
// captcha action renders the CAPTCHA image displayed on the contact page
'captcha' => array(
'class' => 'CCaptchaAction',
'backColor' => 0xFFFFFF,
'testLimit'=> '2',
),
)
}
public actionAdvertise()
{ $model = new ContactForm;
$model->scenario = 'captchaRequired';
if($model->validate()){
//some code
} else {
$this->render('advertise', array('model' => $model));
}
}
}
Code in my advertise.php view
<form action="" method="post">
<?php
$form=$this->beginWidget('CActiveForm',array(
'id'=>'contact-form',
'enableAjaxValidation'=>false,
));
?>
<?php if(CCaptcha::checkRequirements()){ ?>
<div class="row">
<div class="contact_field_wrapper">
<?php echo '<b>ARE YOU HUMAN?</b><br />'.$form->labelEx($model, 'verifyCode'); ?>
<div class="captcha user-captcha">
<?php $this->widget('CCaptcha',array( 'captchaAction'=>'site/captcha' ));
?>
<?php echo $form->error($model, 'verifyCode'); ?>
<?php echo '<br />'.$form->textField($model,'verifyCode'); ?>
<div class="hint">Please enter the letters as they are shown in the image above.<br/>
Letters are not case-sensitive.
</div>
</div>
</div>
</div>
<?php } ?>
<?php $this->endWidget(); ?>
</form>
The problem is that $model->validate() returns false when correct code in inputted.
$model->getErrors() is always returning 'Verification code is incorrect'.
your model is empty , because you didn't pass any value to $model->attriburtes
Do this :
if($_POST['ContactForm'])
{
$model->attributes() = $_POST['ContactForm'];
if($model->validate())
{
//some code
}
}
$this->render('advertise', array('model' => $model));

Add data to the database using codeigniter

I am currently trying to add data to the database using codeigniter. I have already set up a registration page using the active method and attempted to use the same method for the add news form but was unsuccessful.
When I click submit it is saying page cannot be found and the url shows the controller function name. This is the same when i purposely leave any fields blank. I have checked my database and no records have been added and no php log errors.
Here is my snippets of code:
View:
<?php echo form_open('add/add_article'); ?>
<?php echo form_input('title', set_value('title', 'Title')); ?><br />
<?php echo form_textarea('content', set_value('content', 'Content')); ?><br />
<?php echo form_input('author', set_value('author', 'Author')); ?>
<?php echo form_submit('submit', 'Add Article'); ?>
<?php echo validation_errors('<p class="error">' );?>
<?php echo form_close(); ?>
Controller:
class Add extends CI_Controller {
public function __construct() {
parent::__construct();
}
public function index() {
$this->load->view('admin/add');
}
public function add_article() {
$this->load->library('form_validation');
$this->form_validation->set_rules('title', 'Title', 'trim|required');
$this->form_validation->set_rules('content', 'Content', 'trim|required');
$this->form_validation->set_rules('author', 'Author', 'trim|required');
if($this->form_validation->run() == FALSE) {
$this->index();
}else{
$this->load->model('news_model');
if($query = $this->news_model->addArticle()) {
$this->load->view('news');
}else {
$this->load->view('news');
}
}
}
}
Model:
public function __construct() {
parent::__construct();
}
function addArticle() {
$data =array(
'title' => $this->input->post('title'),
'content' => $this->input->post('content'),
'author' => $this->input->post('author'),
'username' => $this->input->post('username'));
$insert = $this->db->insert('news', $data);
return $insert;
}
}
If it's the server that's throwing the page not found it's almost certainly a URL issue as opposed to a CI/PHP issue.
Is your base url defined properly in the config file? Is your .htaccess configured properly (an old configuration could be routing /add requests away from CI)?
Try adding the following action to the Add controller, and navigating to it directly at http://[base]/add/thetest
public function thetest() {
echo 'Controller accessed';
die;
}
If it still says page not found it's not your code, it's your config (either server config or CI).
Instead of insert use update in your model like:
$insert = $this->db->update('news', $data);
return $insert;
And I think that this part of your code in controller is wrong too (wrong if statement and no data send to model):
if($query = $this->news_model->addArticle()) {
$this->load->view('news');
}else {
$this->load->view('news');
}
try this:
$data =array(
'title' => $this->input->post('title'),
'content' => $this->input->post('content'),
'author' => $this->input->post('author'),
'username' => $this->input->post('username')
);
$query = $this->news_model->addArticle($data);
if($query)
{
// query ok
$this->load->view('news');
}
else {
// no query
$this->load->view('news');
}

Categories