model not displaying validation errors - javascript
I am new to yii. My ActiveRecord doesn't validate when save() is called.
model codes:
public function rules()
{
// NOTE: you should only define rules for those attributes that
// will receive user inputs.
return array(
array('firstName, secondName, lastName, gender, phoneNumber, email, address, education_background, basicSalary, departmentID, roleID, contractID, employed_by, reports_to, date_employed', 'required'),
array('phoneNumber, departmentID, roleID, contractID', 'numerical', 'integerOnly'=>true),
array('firstName, secondName, lastName', 'length', 'max'=>20),
array('firstName, secondName, lastName','type', 'type'=>'char','message'=>'This field accepts characters only'),
array('email','email'),
);
}
controller codes:
public function actionCreate()
{
$model=new Employee;
$message="email already exists";
// Uncomment the following line if AJAX validation is needed
// $this->performAjaxValidation($model);
if(isset($_POST['Employee']))
{
$model->attributes=$_POST['Employee'];
$model->password=md5(strtolower($model->firstName.'123'));
$to=$model->email;
$mailmessage="Dear ".$model->lastName." ".$model->firstName."<br> Thanks for your interest in working for XXX Company.
<br>Please note your login details are :- Email:".$model->email." Password: ".$model->firstName."123<br>
You can change password to your preference choice when you login.<br>
Kindly Regards<br>
HRMS administrator";
//echo $model->password; exit;
$criteria=new CDbCriteria();
$criteria->select='email';
$criteria->condition='email=:email';
$criteria->params=array(':email'=>$model->email);
if($check=Employee::model()->exists($criteria)){
$this->render('create',array(
'model'=>$model,'message'=>$message));
exit;
}else{
$model->save();
/*if($model->validate()){
echo 'valideted';
exit;
}
else {
echo 'not valid';
print_r($model->getErrors());
}
exit;
//$model->getErrors();*/
/*if(){
echo 'saved';
}
else{
print_r($model->getErrors());
}
exit;*/
$this->mailsend($to,$mailmessage);
// $cmd=Yii::app()->db->createCommand('select max(employee.employeeID),role.roleName,employee.departmentID FROM employee JOIN role ON employee.roleID=role.roleID');
$cmd=Yii::app()->db->createCommand('select employee.employeeID,role.roleName,department.departmentName FROM employee JOIN department ON employee.departmentID=department.departmentID JOIN role ON employee.roleID=role.roleID
ORDER BY employee.employeeID DESC LIMIT 1');
$rstid=$cmd->queryRow(false);
$id=$rstid[0];
$role=$rstid[1];
$dep=$rstid[2];
$history=Yii::app()->db->createCommand();
$history->insert('history',array(
'employeeID'=>$id,
'action_to'=>'as '.$role,
'department'=>$dep,
'reports_to'=>$model->reports_to,
'date'=>$model->date_employed,
));
Yii::app()->session['id']=$model->employeeID;
$this->redirect(array('view','id'=>$model->employeeID));
}
}
$this->render('create',array(
'model'=>$model,'message'=>''
));
}
view codes
<div class="form">
<?php $form=$this->beginWidget('CActiveForm', array(
'id'=>'employee-form',
// Please note: When you enable ajax validation, make sure the corresponding
// controller action is handling ajax validation correctly.
// There is a call to performAjaxValidation() commented in generated controller code.
// See class documentation of CActiveForm for details on this.
'enableAjaxValidation'=>false,
)); ?>
<p class="note">Fields with <span class="required">*</span> are required.</p>
<?php echo $form->errorSummary($model); ?>
<table>
<tr><td><?php echo $form->labelEx($model,'firstName'); ?></td>
<td><?php echo $form->textField($model,'firstName',array('size'=>20,'maxlength'=>20)); ?></td>
<td><?php echo $form->error($model,'firstName'); ?></td></tr>
<tr><td><?php echo $form->labelEx($model,'secondName'); ?></td>
<td><?php echo $form->textField($model,'secondName',array('size'=>20,'maxlength'=>20)); ?></td>
<td><?php echo $form->error($model,'secondName'); ?></td></tr>
<tr><td><?php echo $form->labelEx($model,'lastName'); ?></td>
<td><?php echo $form->textField($model,'lastName',array('size'=>20,'maxlength'=>20)); ?></td>
<td><?php echo $form->error($model,'lastName'); ?></td></tr>
<tr><td><?php echo $form->labelEx($model,'gender'); ?></td>
<td><?php echo $form->dropDownList($model,'gender',array('Male'=>'Male','Female'=>'Female')); ?></td>
<td><?php echo $form->error($model,'gender'); ?></td></tr>
<tr><td><?php echo $form->labelEx($model,'phoneNumber'); ?></td>
<td><?php echo $form->textField($model,'phoneNumber'); ?></td>
<td><?php echo $form->error($model,'phoneNumber'); ?></td></tr>
<tr><td><?php echo $form->labelEx($model,'email'); ?>
</td>
<td><?php echo $form->textField($model,'email',array('size'=>50,'maxlength'=>50)); ?></td>
<td style='color:red;'><?php echo $form->error($model,'email'); ?>
<?php echo $message; ?></td></tr>
<tr><td><?php echo $form->labelEx($model,'address'); ?></td>
<td><?php echo $form->textArea($model,'address',array('size'=>60,'maxlength'=>100)); ?></td>
<td><?php echo $form->error($model,'address'); ?></td></tr>
<tr><td><?php echo $form->labelEx($model,'education_background'); ?></td>
<td><?php echo $form->textArea($model,'education_background',array('size'=>60,'maxlength'=>300)); ?></td>
<td><?php echo $form->error($model,'education_background'); ?></td></tr>
<tr><td><?php echo $form->labelEx($model,'roleID'); ?></td>
<td><?php echo $form->dropDownList($model,'roleID',CHtml::listData(Role::model()->findAll(),'roleID','roleName'),
array(
'ajax' => array(
'type'=>'POST',
'dataType'=>'json',
'url'=>CController::createUrl('employee/getSalary'),
'success'=>'function(data){
$("#Employee_basicSalary").val(data.data1);
}'),
'prompt'=>'select'
)); ?></td>
<td><?php echo $form->error($model,'roleID'); ?></td></tr>
<tr>
<td><?php echo $form->labelEx($model,'basicSalary'); ?></td>
<td>
<?php echo $form->textField($model,'basicSalary',array('size'=>10,'maxlength'=>10)); ?>
</td>
<td><?php echo $form->error($model,'basicSalary'); ?></td>
</tr>
<tr><td><?php echo $form->labelEx($model,'departmentID'); ?></td>
<td><?php echo $form->dropDownList($model,'departmentID',CHtml::listData(Department::model()->findAll(),'departmentID','departmentName')); ?></td>
<td><?php echo $form->error($model,'departmentID'); ?></td></tr>
<tr><td><?php echo $form->labelEx($model,'date_employed'); ?></td>
<td> <?php $this->widget('zii.widgets.jui.CJuiDatePicker',array(
'name'=>'Employee[date_employed]',
'id'=>'Employee_date_employed',
'value'=>$model->date_employed,
'options'=>array(
'dateFormat'=>'yy-mm-dd',
'showAnim'=>'fold',
),
'htmlOptions'=>array(
'style'=>'height:20px;'
),
));
?></td>
<td><?php echo $form->error($model,'date_employed'); ?>
</td></tr>
<tr><td><?php echo $form->labelEx($model,'contractID'); ?></td>
<td> <?php echo $form->dropDownList($model,'contractID',CHtml::listData(Contract::model()->findAll(),'contractID','contractName'),
array(
'ajax' => array(
'type'=>'POST',
'dataType'=>'json',
'url'=>CController::createUrl('employee/getContDate'),
'success'=>'function(data){
$("#Employee_endcontract").val(data.data1);
}'),
'prompt'=>'select'
)); ?></td>
<td><?php echo $form->error($model,'contractID'); ?></td></tr>
<tr><td><?php echo $form->labelEx($model,'endcontract'); ?></td><td><?php echo $form->textField($model,'endcontract');?></td></tr>
<tr><td><?php echo $form->labelEx($model,'employed_by'); ?></td>
<td><?php echo $form->textField($model,'employed_by',array('size'=>50,'maxlength'=>50)); ?></td>
<td><?php echo $form->error($model,'employed_by'); ?></td></tr>
<tr><td><?php echo $form->labelEx($model,'reports_to'); ?></td>
<td><?php echo $form->dropDownList($model,'reports_to',array('Senior Manager'=>'Senior Manager','Assistant Manager'=>'Assistant Manager','System Administrator'=>'System Administrator')); ?></td>
<td><?php echo $form->error($model,'reports_to'); ?></td></tr>
<tr><td></td><td> <?php echo CHtml::submitButton($model->isNewRecord ? 'Create' : 'Save'); ?></td><td></td></tr>
</table>
<?php $this->endWidget(); ?>
</div><!-- form -->
This model does not validate and also doesn't display errors. Any help please?
You can check uniqueness of email in model (will be good to use scenarios).
You can create relations with department and role tables in your model.
Model code:
public function rules() {
// it will be good to use scenarios
return array(
array('firstName, secondName, lastName, gender, phoneNumber, email, address, education_background, basicSalary, departmentID, roleID, contractID, employed_by, reports_to, date_employed', 'required'),
array('phoneNumber, departmentID, roleID, contractID', 'numerical', 'integerOnly'=>true),
array('firstName, secondName, lastName', 'length', 'max'=>20),
array('firstName, secondName, lastName','type', 'type'=>'char','message'=>'This field accepts characters only'),
array('email','email'),
array('email','unique'),
);
}
public function relations() {
return array(
'department' => array(self::BELONGS_TO, 'Department', 'departmentID'), // Department CActivRecord model of `department` table
'role' => array(self::BELONGS_TO, 'Role', 'roleID'), // Role CActivRecord model of `role` table
);
}
Controller create action code:
public function actionCreate() {
$model=new Employee;
// Uncomment the following line if AJAX validation is needed
// $this->performAjaxValidation($model);
if(isset($_POST['Employee'])) {
$model->attributes=$_POST['Employee'];
$model->password=md5(strtolower($model->firstName.'123'));
if($model->save()) {
$mailmessage="Dear ".$model->lastName." ".$model->firstName."<br> Thanks for your interest in working for XXX Company.
<br>Please note your login details are :- Email:".$model->email." Password: ".$model->firstName."123<br>
You can change password to your preference choice when you login.<br>
Kindly Regards<br>
HRMS administrator";
$this->mailsend($model->email, $mailmessage);
Yii::app()->db->createCommand()->insert('history',array(
'employeeID'=>$model->employeeID,
'action_to'=>'as '.$model->role->roleName,
'department'=>$model->department->departmentName,
'reports_to'=>$model->reports_to,
'date'=>$model->date_employed,
));
Yii::app()->session['id']=$model->employeeID;
$this->redirect(array('view','id'=>$model->employeeID));
}
}
$this->render('create',array(
'model'=>$model,
));
}
Also you can set enableClientValidation to true in CActiveForm widget to enable js validation.
Related
I cant run condition IF [closed]
Closed. This question needs details or clarity. It is not currently accepting answers. Want to improve this question? Add details and clarify the problem by editing this post. Closed 2 years ago. Improve this question I have code to filter by dates, I have 2 condition, First condition: get 'tanggal' from date picker on view Second condition: variable 'tanggal' isNull However, the code only runs the second condition, even though the condition variable date is given This is the code: View: .... some code .... <form method="POST"> <div class="form-group"> <label>Date</label> <div class="input-group date"> <div class="input-group-addon"> <span class="glyphicon glyphicon-th"></span> </div> <form method="get"> <input type="date" name="tanggal"> <input type="submit" value="FILTER"> </form> .... some code .... <tbody> <?php foreach ((array)$getDepartDetail as $us) { ?> <tr> <td><?php echo $us->Name ?></td> <td><?php echo $us->NIK ?></td> <td><?php echo $us->gender ?></td> <td><?php echo $us->PositionDesc ?></td> <td><?php echo $us->Shift ?></td> <td><?php echo $us->tgl ?></td> <td><?php echo $us->Attendance ?></td> <td><a class="btn btn-info" href="<?php echo site_url('data_detail/detail_datas/vieworc/' . $us->NIK); ?>">Detail</a></td> </tr> <?php } ?> </tbody> .... some code .... Model: .... some code .... public function get_allDprtDetail($DepartmentID) { if(isset($_GET['tanggal'])){ $tgl = $_GET['tanggal']; $datas = " SELECT DISTINCT .... some code .... FROM emp0001 INNER JOIN emp0003 ON emp0003.DepartmentID = emp0001.DepartmentID LEFT JOIN v_dvc0004_test ON emp0003.NIK = v_dvc0004_test.NIK AND DATE(v_dvc0004_test.Enroll) = '$tgl' JOIN emp0002 ON emp0002.PositionID = emp0003.PositionID LEFT JOIN shift ON emp0003.Shift_ID = shift.Shift_ID WHERE emp0001.DepartmentID = '$DepartmentID' AND emp0003.IsActive = 'T' ORDER BY v_dvc0004_test.Enroll ASC ";} else{ $datas = " SELECT DISTINCT .... some code .... } $query = $this->db->query($datas); return $query->result() ;}
Firstly you should add a check for the results count ... <tbody> <?php if(count($getDepartDetail)> 0){ ?> <?php foreach ($getDepartDetail as $us) { ?> <tr> <td><?php echo $us->Name ?></td> <td><?php echo $us->NIK ?></td> <td><?php echo $us->gender ?></td> <td><?php echo $us->PositionDesc ?></td> <td><?php echo $us->Shift ?></td> <td><?php echo $us->tgl ?></td> <td><?php echo $us->Attendance ?></td> <td><a class="btn btn-info" href="<?php echo site_url('data_detail/detail_datas/vieworc/' . $us->NIK); ?>">Detail</a></td> </tr> <?php } ?> <?php } ?> </tbody>
Function get_allDprtDetail can return null if $_GET['tanggal'] doesn't set set. You may try to return empty array, like that public function get_allDprtDetail($DepartmentID) { if(isset($_GET['tanggal'])){ some code } return []; }
Delete from database using javascript
I have a page containing a database table with all the rows and columns. What I am trying to do is to select all the rows I want and then delete them when I click on the button. This is what I've done so far in the table.php page: <?php include "config.php"; //connection to database incude "home.js"; $funcao="Select * from palavras"; $result=mysqli_query($link, $funcao); ?> <button id="button_apaga" type="button" onclick="delete()" > DELETE </button> <?php if($result->num_rows > 0) { ?> <table class="table"> <tr> <th>IdPalavra</th> <th>Palavra</th> <th>Grau de Dificuldade</th> <th>Data</th> <th>Hora</th> <th>Selecionar</th> </tr> <?php while($row = mysqli_fetch_assoc($result)) { ?> <tr role="row"> <td><?php echo $row['idpalavras']; ?></td> <td><?php echo $row['palavra']; ?></td> <td><?php echo $row['graudificuldade']; ?></td> <td><?php echo $row['data']; ?></td> <td><?php echo $row['hora']; ?></td> <td><input type="checkbox" name="check" id="checkbox" /></td> </tr> <?php } ?> </table> <?php } else{ echo "0 resultados"; } ?> JavaScript Page (home.js): function delete(id){ var check = document.getElementById('checkbox'); if(check.checked) { // sql query } My question is how can I do que sql query considering it's in a different page. Can I just open php and put the query inside? Also how can I receive all the IDs from the selected rows to the function? Thank you in advance.
One approach would be to use AJAX. For the purpose of condensing the code, I'm going to also incorporate jQuery into this solution. I am also going to change your checkbox to an individual button link for the sake of making this a bit less code. A solution to delete multiple at the same time could work similarly to this, but since you're using AJAX most likely this is going to be easier for your users. Modify table.php <?php include "config.php"; //connection to database incude "home.js"; $funcao="Select * from palavras"; $result=mysqli_query($link, $funcao); ?> <?php if($result->num_rows > 0) { ?> <table class="table"> <tr> <th>IdPalavra</th> <th>Palavra</th> <th>Grau de Dificuldade</th> <th>Data</th> <th>Hora</th> <th>Selecionar</th> </tr> <?php while($row = mysqli_fetch_assoc($result)) { ?> <tr role="row" class="palavras_row"> <td><?php echo $row['idpalavras']; ?></td> <td><?php echo $row['palavra']; ?></td> <td><?php echo $row['graudificuldade']; ?></td> <td><?php echo $row['data']; ?></td> <td><?php echo $row['hora']; ?></td> <td>Delete</td> </tr> <?php } ?> </table> <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js?ver=3.3.1"></script> <script type="text/javascript"> (function($) { $(document).on('click', '.palavras_row a.palavras_delete', function() { var _id = $(this).attr('data-id'); var _row = $(this).parent().parent(); $.ajax({ url: 'delete.php', data: { idpalavras: _id }, type: 'POST', dataType: 'json', success: function(__resp) { if (__resp.success) { _row.remove(); // Deletes the row from the table } } }); }); })(jQuery); </script> Create a new file in the same folder as your table.php and name it delete.php <?php $idpalavras = filter_input(INPUT_POST, 'idpalavras', FILTER_SANITIZE_NUMBER_INT); $success = false; if ($idpalavras) { include "config.php"; //connection to database $funcao="delete from palavras where idpalavras = " . $idpalavras; $result=mysqli_query($link, $funcao); $success = true; } header('Content-Type: application/json'); echo json_encode(array('success' => $success)); The solution above sends a simple command to your PHP backend where the delete query can be run by PHP. You cannot run a mysql command directly from javascript since that is frontend code. This code is a functional solution, but it is abbreviated; a more complete solution would have more detailed handling of potential errors (either via AJAX or processing your delete query). It should also have some security on your delete.php to make sure unauthorized users aren't able to delete records without the proper permission to do so.
disable checkbox/textbox dynamically after insert
I've been trying to disable checkbox(which I fetched using while loop in php) after form submit. Any help would be appreciated. <td><?php echo $num['roomno']; ?></td> <td><?php echo $num['regno']; ?></td> <td><?php echo $num['pname']; ?></td> <td><input type="checkbox" name="diet" id="diet" value="<? echo $num['regno'];?>" <?php if(($regno!="") && ($thiss == $regno)) { echo 'disabled'; } ?> /> </td> This is the php section to get the value from checked checkbox. I dont know if I'm doing the right way. <? $regno = isset($_REQUEST['diet'])?$_REQUEST['diet']:""; if(isset($regno)) { $selec = "select regno from roomlist where regno='".$regno."'"; $sql = mysqli_query($con,$selec); if(!$sql) { echo "Error : ".mysqli_error($sql); exit(); } $num = mysqli_fetch_array($sql,MYSQLI_ASSOC); $thiss = $num['regno']; }
Retrieve data from DataTable plugin using javascript
I am using DataTable plugin for generating data from database using javascript. I am showing that data in table tag like foreach ($data as $row) { $total += $row->price; ?> <tr> <td><?php echo $row->id; ?></td> <td><?php echo $row->created_date; ?></td> <td><?php echo $row->vender; ?></td> <td><?php echo $row->usertype; ?></td> <td><?php echo $row->price; ?></td> <td><?php echo $row->payment_type; ?></td> <td><?php echo $row->vender_inv; ?></td> <td><?php echo $row->note; ?></td> <td><a class="example-image-link" href="<?php echo $row->image; ?>" data-lightbox="example-1"><img style="width:100px !important; height:100px !important;" class="example-image" src="<?php echo $row->image; ?>" alt="image-1" /></a> </td> </tr> <?php } Now I want to retrieve individual rows from it, I am trying to do it like this var table = $('#myTable').DataTable(); table.column(4).eq(0).each( function ( colIdx ) { console.log( colIdx, table.column( colIdx ).search() ); } );
Look at the rows() API: https://datatables.net/reference/api/rows().every() table.rows().every( function ( rowIdx, tableLoop, rowLoop ) { var data = this.data(); // ... do something with data(), or this.node(), etc } );
Disable button when db is populated enable when null on javascript
I have my database table named material material: mat_id mat_name status 1 bolts 2 steel approved How can I make my button or maybe href link disable when status = 'approved' on my html table? like: option mat_id material name show button 1 bolts no button 2 steel my code for html/php: <?php $resource=mysql_query("Select * from material",$con); while($result2=mysql_fetch_array($resource)) { ?> <tr> <th>option</th> <th>mat_id</th> <th>material name</th> </tr> <tr> <td align="center"> <?php $id = $rows['reqraw_id']; if($rows['status']=="") { echo '<a href="addstockout.php?id=$id" > Update </a>'; } ?> </td> <td><?php echo $result2['mat_id']; ?></td> <td><?php echo $result2['mat_name']; ?></td> </tr> <?php };?> There is a problem on this line echo '<a href="addstockout.php?id=$id" > Update </a>'; It doesn't get the id array from the db.
... <?php if($result2['status'] == 'approved') { ?> <td><button disabled="true">Button</button></td> <?php } else{ ?> <td><button>Button</button></td> <?php } ?> ...
if($result2['status']=="" OR $result2['status']===NULL) { echo '<button type="button">Click Me!</button>'; }else{ echo '<button type="button" disabled>Click Me!</button>'; }
<td><?php echo ($result2['status']===NULL)?"button here":"disabled"; ?></td>
I think this should do it: Instead of <td>button</td> put: <?php echo '<td><button '; if(!($result2['status']==="approved")) { echo 'disabled="true"'; } echo '>Click</button></td>'; ?>