yii2 validate form error on submit - yii2

My Problem : I'm trying to validate user input using on certain fields. I have created rules on certain fields. When submit the form, it display the error message in json format and stop there.
Error that i got after submit the form
sample error
View page :
<?php $form = ActiveForm::begin([
'id'=>'create_company',
'method'=>'post',
//'enableAjaxValidation' => true,
'enableClientValidation' => true,
]); ?>
<?php echo $form->errorSummary(array($model,$memberPlan)); ?>
<h4><?php echo Yii::t('app', 'Personal Information'); ?></h4>
<div class='container-fluid'>
<div class='col-sm-4'>
<?= $form->field($model, 'name')->textInput(['maxlength' => true]) ?>
</div>
Model :
public function rules()
{
return [
[['parent_id', 'gender_id', 'marital_status_id', 'id_type', 'company_id', 'department_id', 'designation_id', 'employment_type_id', 'dependent_type_id', 'cost_centre_id', 'location_id', 'waiting_period', 'relation_id', 'state_id', 'region_id', 'bank_id', 'record_status_id', 'hms_uid', 'status_id', 'created_by', 'modified_by'], 'integer'],
[['name', 'company_id', 'department_id', 'designation_id', 'policy_no', 'plan_name','effective_coverage_date'], 'required'],
[['dob', 'hired_date', 'confirmation_date', 'first_issue_date', 'effective_coverage_date', 'fullfledge_date', 'reinstatement_date', 'reject_date', 'take_over_date', 'due_date', 'termination_date', 'file_received_date', 'record_status_date', 'created_time', 'modified_time'], 'safe'],
[['race', 'grade', 'division', 'employee_no', 'termination_reason', 'member_no', 'client_member_id', 'address1', 'address2', 'address3', 'city', 'postcode', 'account_no', 'payee_name', 'policy_no', 'plan_name', 'product_type', 'plan_code', 'decission_flag', 'card_no', 'vip_remark', 'remarks', 'dba_remarks', 'file_name', 'supervisor_code', 'hr_code'], 'string'],
[['salary'], 'number'],
[['vip'], 'boolean'],
[['name'], 'string', 'max' => 120],
[['nationality', 'coverage'], 'string', 'max' => 2],
[['id_no', 'alternate_id_no'], 'string', 'max' => 24],
[['phone', 'mobile', 'fax'], 'string', 'max' => 20],
[['email', 'alternate_email'], 'string', 'max' => 100],
['effective_coverage_date','checkEffectiveCoverageDate', 'on'=>'create'],
['first_issue_date','checkFirstIssueDate', 'on'=>'create'],
['termination_date','checkTerminationDate', 'on'=>'create'],
['email','email'],
['termination_date','checkTerminationDate', 'on'=>'update'],
];
}
public function checkEffectiveCoverageDate($attribute, $params) {
if ( !empty($this->effective_coverage_date) AND $this->policy_id != '' ) {
if (!$this->withinPolicyStartAndEndDate($this->policy_id, $this->effective_coverage_date) ) {
$this->addError($attribute, 'Effective Coverage Date cannot be before policy start and end date');
}
}
}
Controller :
if ( $model->load(Yii::$app->request->post()) && $memberPlan->load(Yii::$app->request->post())) {
$plan = Plan::find()->where('id = :id',['id'=>$memberPlan->plan_id])->one();
$policy = Policy::find()->where('id = :id',['id'=>$plan->policy_id])->one();
$model->plan_name = $plan->name;
$model->policy_no = $policy->policy_no;
$model->policy_id = $policy->id;
$model->created_by = $userid;
$model->created_time = 'now()';
$valid = $model->validate();
$valid = $memberPlan->validate() && $valid;
if ( $valid ) {
$transaction = \Yii::$app->db->beginTransaction();
try {
$model->setSearchPath($userLogin->getClientCode());
$model->save();
$memberPlan->member_id = $model->id;
$memberPlan->plan_id = $memberPlan->plan_id;
$memberPlan->start_date = $model->effective_coverage_date;
$memberPlan->created_by = $userid;
$memberPlan->created_time = 'now()';
$memberPlan->save();
$transaction->commit();
return $this->redirect(['view', 'id' => $model->id]);
} catch (Exception $e) {
$transaction->rollBack();
}
} else {
if (Yii::$app->request->isAjax && $model->load(Yii::$app->request->post()) &&
$memberPlan->load(Yii::$app->request->post())) {
Yii::$app->response->format = 'json';
return array_merge(ActiveForm::validate($model),ActiveForm::validate($memberPlan) );
} else {
Yii::$app->response->format = 'json';
$error = ActiveForm::validate($model);
return array_merge($error, ActiveForm::validate($memberPlan) );
}
}

The order of the operations you have is wrong. First of all you do not use ajax validation, so there is no point in your check.
if (Yii::$app->request->isAjax
This will never be right because you do not use ajax.
Afterwards you are doing
Yii::$app->response->format = 'json';
$error = ActiveForm::validate($model);
return array_merge($error, ActiveForm::validate($memberPlan) );
You are explicitly making the response ajax and sending it back. It works exactly how you told it to.
Probably you want to remove
} else {
Yii::$app->response->format = 'json';
$error = ActiveForm::validate($model);
return array_merge($error, ActiveForm::validate($memberPlan) );
If you remove this else the invalid models will be passed to the view (assuming you are rendering a view after this code) and errors will show up under each field.
If you do want to enable ajax validation, you can just change the controller code to:
//check ajax validation first
if (Yii::$app->request->isAjax && $model->load(Yii::$app->request->post()) && $memberPlan->load(Yii::$app->request->post())) {
Yii::$app->response->format = 'json';
return array_merge(ActiveForm::validate($model),ActiveForm::validate($memberPlan) );
}
//normal check second
if ( $model->load(Yii::$app->request->post()) && $memberPlan->load(Yii::$app->request->post())) {
$plan = Plan::find()->where('id = :id',['id'=>$memberPlan->plan_id])->one();
$policy = Policy::find()->where('id = :id',['id'=>$plan->policy_id])->one();
$model->plan_name = $plan->name;
$model->policy_no = $policy->policy_no;
$model->policy_id = $policy->id;
$model->created_by = $userid;
$model->created_time = 'now()';
$valid = $model->validate();
$valid = $memberPlan->validate() && $valid;
if ( $valid ) {
$transaction = \Yii::$app->db->beginTransaction();
try {
$model->setSearchPath($userLogin->getClientCode());
$model->save();
$memberPlan->member_id = $model->id;
$memberPlan->plan_id = $memberPlan->plan_id;
$memberPlan->start_date = $model->effective_coverage_date;
$memberPlan->created_by = $userid;
$memberPlan->created_time = 'now()';
$memberPlan->save();
$transaction->commit();
return $this->redirect(['view', 'id' => $model->id]);
} catch (Exception $e) {
$transaction->rollBack();
}
}
The point is that if $valid = false it will show the page again with errors on it because you already validated the models.
1 more thing, I do not think this will work
$model->created_time = 'now()';
You probably want to do
$model->created_time = new \yii\db\Expression('NOW()');

Related

Edit records CodeIgniter

I'm developing a basic crud application using PHP Codeigniter 3 with MySQL database.
I have done add and list method successfully but now I want to edit the record and have included an edit button in the records table in view. when I click on the button it will go to my edit record view but it shows some errors. I checked everything but I fail to resolve it.
This is my controller
<?php
class User extends CI_controller
{
public function index()
{
$this->load->model('User_model');
$users = $this->User_model->getUsers();
// print_r($users);
$data = array();
$data['users'] = $users;
$this->load->view('users/list',$data);
}
public function create()
{
//load model here
$this->load->model('User_model');
//load library
$this->load->library('form_validation');
$this->load->library('ckeditor');
$this->load->library('ckfinder');
//set rules
$this->form_validation->set_rules('name', 'Name', 'required');
$this->form_validation->set_rules('projectname', 'Projectname', 'required');
$this->form_validation->set_rules('projecttype', 'Projecttype', 'required');
$this->form_validation->set_rules('phone', 'Phone', 'required');
$this->form_validation->set_rules('email', 'Email', 'required|valid_email');
$this->form_validation->set_rules('address', 'Address', 'required');
$this->form_validation->set_rules('projectdescription', 'Projectdescription', 'required');
// $this->form_validation->set_rules('termname', 'Termname', 'required');
// $this->form_validation->set_rules('termdescription', 'Termdescription', 'required');
$this->form_validation->set_rules('article_description', 'Article_description', 'required');
if ($this->form_validation->run() == true) {
// print_r($_POST);
// Array ( [name] => muhammad zawish [projectname] => test [projecttype] => Hardware [phone] => 03206270391 [email] => muhammadzawish#gmail.com [address] => Gondal Road, Sialkot, Punjab, Pakistan [projectdescription] => aaaaaaaaaa [termname] => aaaaaa [termdescription] => aaaaaaaa )
$name = $this->input->post('name');
$projectname = $this->input->post('projectname');
$projecttype = $this->input->post('projecttype');
$phone = $this->input->post('phone');
$email = $this->input->post('email');
$address = $this->input->post('address');
$projectdescription = $this->input->post('projectdescription');
// $termname = $this->input->post('termname');
// $termdescription = $this->input->post('termdescription');
$article_description = $this->input->post('article_description');
// $formData = array('name' => $name, 'projectname' => $projectname, 'projecttype' => $projecttype, 'phone' => $phone, 'email' => $email, 'address' => $address, 'projectdescription' => $projectdescription, 'termname' => $termname, 'termdescription' => $termdescription,);
$formData = array('name' => $name, 'projectname' => $projectname, 'projecttype' => $projecttype, 'phone' => $phone, 'email' => $email, 'address' => $address, 'projectdescription' => $projectdescription, 'article_description' => $article_description);
//ck editor files
$this->ckeditor->basePath = base_url() . 'asset/ckeditor/';
$this->ckeditor->config['toolbar'] = array(
array('Source', '-', 'Bold', 'Italic', 'Underline', '-', 'Cut', 'Copy', 'Paste', 'PasteText', 'PasteFromWord', '-', 'Undo', 'Redo', '-', 'NumberedList', 'BulletedList')
);
$this->ckeditor->config['language'] = 'it';
$this->ckeditor->config['width'] = '730px';
$this->ckeditor->config['height'] = '300px';
//Add Ckfinder to Ckeditor
$this->ckfinder->SetupCKEditor($this->ckeditor, '../../asset/ckfinder/');
$this->User_model->add_user($formData);
$this->session->set_flashdata('message', 'Record has been added successfully');
redirect(base_url('user/index'));
} else {
$this->load->view('users/create');
}
}
function edit($id){
$this->load->model('User_model');
$row = $this->User_model->getUser($id);
$data1 = array();
$data1['row'] = $row;
$this->load->view('users/edit', $data1);
}
}
this is my model
<?php
class User_model extends CI_Model{
public function add_user($formArray){
// $this->load->library('session');
$this->db->insert('users', $formArray);
}
//for view data fetch from database
public function getUsers(){
$users = $this->db->get('users')->result_array();
return $users;
}
//for edit record
function getUser($id){
$this->db->where('id', $id);
$row = $this->db->get('users')->row_array();
return $row;
}
}
?>
when I access my edit.php view
404 Page Not Found
The page you requested was not found.

image not insert in mysql using codeigniter

I am trying to insert images in mysql database with other data but its shows error.
its shows the $msg of not saved & repeat data of view file maybe due to $error which i set.
PS: I set 'image' datatype varchar in database.
here is my view file:
<input type="file" class="form-control-file" name="image" id="exampleInputFile" >
this is my controller:
public function save()
{
$this->load->model('Partner_model');
$feature = $this->input->post('feature');
$config['upload_path'] = './uploads/files';
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = 100;
$config['max_width'] = 1024;
$config['max_height'] = 768;
$this->load->library('upload', $config);
if ( ! $this->upload->do_upload('image'))
{
$error = array('error' => $this->upload->display_errors());
$this->load->view('partner_profile', $error);
}
else
{
$user_data= array(
'pname' => $this->input->post('pname'),
'type' => $this->input->post('type'),
'address' => $this->input->post('address'),
'about' => $this->input->post('about'),
'city' => $this->input->post('city'),
'code' => $this->input->post('code'),
'state'=>$this->input->post('state'),
// 'image'=>$this->upload->do_upload('image')
'feature'=>implode(",",$feature),
'image' => $this->upload->data()
);
}
if($this->Partner_model->save($user_data))
{
$msg = "save sucesss" ;
}
else
{
$msg = "not save";
}
$this->session->set_flashdata('msg', $msg);
$this->load->view('partner_profile');
}
}
& this is my model:
public function save($data)
{
return $this->db->insert('property', $data);
}
Your form must have the multipart attribute in HTML file like below :
If you're using form helper, then it should be
<?php echo form_open_multipart('/save');?>
Else your form should have the enctype attribute like below
<form enctype="multipart/form-data">
Then the uploaded data result $this->upload->data() will come in array. So you can't store your array in mysql column. So you need to get the filename from $this->upload->data() and store it in a variable like below.
Your Controller should be
public function save(){
$this->load->model('Partner_model');
$feature = $this->input->post('feature');
$config['upload_path'] = './uploads/files';
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = 100;
$config['max_width'] = 1024;
$config['max_height'] = 768;
$this->load->library('upload', $config);
if ( ! $this->upload->do_upload('image')){
$error = array('error' => $this->upload->display_errors());
$this->load->view('partner_profile', $error);
}else{
$imageArray = $this->upload->data();
$image = $imageArray['file_name'];
$user_data= array(
'pname' => $this->input->post('pname'),
'type' => $this->input->post('type'),
'address' => $this->input->post('address'),
'about' => $this->input->post('about'),
'city' => $this->input->post('city'),
'code' => $this->input->post('code'),
'state'=>$this->input->post('state'),
'feature'=>implode(",",$feature),
'image' => $image
);
}
if($this->Partner_model->save($user_data)) {
$msg = "save sucesss" ;
}else {
$msg = "not save";
}
$this->session->set_flashdata('msg', $msg);
$this->load->view('partner_profile');
}

captcha not working using scenarios in yii2

I am trying to add captcha validation based on scenario, for which I am first retrieving number of failed attempts from database. For which I am using checkattempts() function. Based on the result I am displaying captcha in view and adding scenario condition in controller as below.
In LoginForm model:
public function rules()
{
return [
[['username', 'password'], 'required', 'on'=>'loginpage'],
[['username', 'password'], 'required', 'on'=>'withCaptcha'],
[['reference_url'], 'safe'],
[['verifyCode'], 'captcha', 'skipOnEmpty' => true,'on'=>'withCaptcha'],
['username','email', 'on'=>'loginpage', 'message'=> 'Please enter a valid email address'],
['password', 'validatePassword', 'on'=>'loginpage'],
['password', 'validatePassword', 'on'=>'withCaptcha'],
];
}
public function checkattempts($uname)
{
$user = \frontend\models\User::findByEmail($uname);
$ip = $this->get_client_ip();
if($user){
$data = (new Query())->select('*')
->from('login_attempts')
->where(['ip' => $ip])->andWhere(['user_ref_id' => $user->id])
->one();
if($data["attempts"] >=3){
return true;
}else{
return false;
}
}
return false;
}
in SiteController.php controller
public function actionLogin() {
if (!\Yii::$app->user->isGuest) {
return $this->redirect(Yii::$app->getUrlManager()->getBaseUrl() . '/../../');
}
$model = new \common\models\LoginForm();
$model->scenario = 'loginpage';
$captcha = false;
if(Yii::$app->request->post()){
$post_variables =Yii::$app->request->post('LoginForm');
if ($model->checkattempts($post_variables['username'])) {
$model->scenario = 'withCaptcha';
$captcha = true;
}
}
if ($model->load(Yii::$app->request->post()) && $model->validate()) {
$model->login(); print_r($model->getErrors()); exit;
} else {
return $this->render('login', [
'model' => $model, 'captcha' => $captcha,
]);
}
In my login.php view:
<?php if($captcha) { ?>
<?= $form->field($model, 'verifyCode')->widget(Captcha::className(),
['template' => '<div class="captcha_img">{image}</div>'
. '<a class="refreshcaptcha" href="#">'
. Html::img('/images/imageName.png',[]).'</a>'
. 'Verification Code{input}',
])->label(FALSE); ?>
<?php } ?>
In my controller when I am tring to print model errors at $model->login() function it is giving below error everytime even though the verification code is correct.
Array ( [verifycode] => Array ( [0] => The verification code is incorrect. ) )
Why is it failing every time. Is there any mistake in the code written?
Thanks in advance

Selected Value is not showing in Kartik Select2 multiple select

This is my view file:
<?php
$data = array();
echo '<label class="control-label">Attribute Group Name</label>';
echo Select2::widget([
'name' => 'attribute_grp_name',
'data' => $attribute_group_name, // initial value
'options' => ['placeholder' => 'Please Enter Attribute Group Name', 'multiple' => true],
'pluginOptions' => [
'attribute_grp_name' => true,
'maximumInputLength' => 100,
],
]);
?>
In my view here selected data is not showing.
This is my controller for create and update function:
public function actionCreate()
{
$model = new AttributeSet();
$attribute_group = AttributeGroupLang::find()->select('*')->all();
$attribute_group_name = ArrayHelper::map($attribute_group, 'id_attribute_group', 'name');
if ($model->load(Yii::$app->request->post()) && $model->save()) {
$post_array = Yii::$app->request->post();
foreach ($post_array['attribute_grp_name'] as $key => $value) {
$attribute_set_group_combination = new AttributeSetGroupCombination();
$attribute_set_group_combination->id_attribute_set = $model->id_attribute_set;
$attribute_set_group_combination->id_attribute_group = $value;
$attribute_set_group_combination->save(false);
}
return $this->redirect(['view', 'id' => $model->id_attribute_set]);
} else {
return $this->render('create', [
'model' => $model,
'attribute_group_name' => $attribute_group_name,
]);
}
}
This is update function:
public function actionUpdate($id)
{
$model = $this->findModel($id);
$attribute_set_group_combination = AttributeSetGroupCombination::find()->where(['id_attribute_set' => $id])->all();
if ($model->load(Yii::$app->request->post()) && $model->save()) {
$post_array = Yii::$app->request->post();
if(!empty($post_array['attribute_grp_name'])){
AttributeSetGroupCombination::deleteAll('id_attribute_set = '.$id);
foreach ($post_array['attribute_grp_name'] as $key => $value) {
$attribute_set_group_combination = new AttributeSetGroupCombination();
$attribute_set_group_combination->id_attribute_set = $model->id_attribute_set;
$attribute_set_group_combination->id_attribute_group = $value;
$attribute_set_group_combination->save(false);
}
}
return $this->redirect(['view', 'id' => $model->id_attribute_set]);
} else {
return $this->render('update', [
'model' => $model,
'attribute_set_group_combination' => $attribute_set_group_combination,
'attribute_group_name' => $this->getExistAttrSet($id),
]);
}
}
public function getExistAttrSet($id){
$query = new Query;
$query->select(['attribute_group_lang.name AS attribute_group_name','attribute_group_lang.id_attribute_group'])
->from('attribute_set_group_combination')
->join('LEFT OUTER JOIN', 'attribute_set', 'attribute_set.id_attribute_set =attribute_set_group_combination.id_attribute_set')
->join('LEFT OUTER JOIN', 'attribute_group_lang', 'attribute_group_lang.id_attribute_group =attribute_set_group_combination.id_attribute_group')
->where('attribute_set.id_attribute_set='.$id)
->all();
$command = $query->createCommand();
$model = $command->queryAll();
$data = array();
foreach ($model as $attrsetlist[]) {
$data = ArrayHelper::map($attrsetlist, 'id_attribute_group', 'attribute_group_name');
}
return $data;
}
Can anyone help me that how can i show the selected value in the multiple select field.
You just need to pass in model value:
<?php
echo kartik\select2\Select2::widget([
'name' => 'some_field_name',
// ----------------------
'value' => 'a',
//'value' => ['a', 'b'],
//'value' => $model->some_value,
// ----------------------
'data' => ['a'=>'a', 'b'=>'b', 'c'=>'c'],
'options' => ['placeholder' => 'Select menu items ...', ],
]);
?>

cant import data csv to database in yii2

I am very new to web development.
I'm newbie in here, my first question in stackoverflow..
i am confused what error on code, Code will be store data array csv to a database,
sorry my bad english.
Controller
public function actionUpload()
{
$model = new Skt();
//error_reporting(E_ALL);
//ini_set('display_error', 1);
if ($model->load(Yii::$app->request->post())) {
$file = UploadedFile::getInstance($model, 'file');
$filename = 'Data.' . $file->extension;
$upload = $file->saveAs('uploads/' . $filename);
if ($upload) {
define('CSV_PATH', 'uploads/');
$csv_file = CSV_PATH . $filename;
$filecsv = file($csv_file);
foreach ($filecsv as $data) {
$modelnew = new Skt();
$hasil = explode(",", $data);
$no_surat= $hasil[0];
$posisi= $hasil[1];
$nama= $hasil[2];
$tgl_permanen= $hasil[3];
$grade= $hasil[4];
$tgl_surat= $hasil[5];
$from_date = $hasil[6];
$to_date = $hasil[7];
$modelnew->no_surat = $no_surat;
$modelnew->posisi = $posisi;
$modelnew->nama = $nama;
$modelnew->tgl_permanen = $tgl_permanen;
$modelnew->grade = $grade;
$modelnew->tgl_surat = $tgl_surat;
$modelnew->from_date = $from_date;
$modelnew->to_date = $to_date;
$modelnew->save();
//print_r($modelnew->validate());exit;
}
unlink('uploads/'.$filename);
return $this->redirect(['site/index']);
}
}else{
return $this->render('upload',['model'=>$model]);
}
return $this->redirect(['upload']);
}
Model
class Skt extends \yii\db\ActiveRecord
{
public static function tableName()
{
return 'skt';
}
public $file;
public function rules()
{
return [
[['file'], 'required'],
[['file'], 'file', 'extensions' => 'csv', 'maxSize' => 1024*1024*5],
[['no_surat'], 'required'],
[['tgl_surat', 'from_date', 'to_date'], 'string'],
[['no_surat', 'posisi', 'nama', 'tgl_permanen', 'grade'], 'string', 'max' => 255],
];
}
public function attributeLabels()
{
return [
'no_surat' => 'No Surat',
'posisi' => 'Posisi',
'nama' => 'Nama',
'tgl_permanen' => 'Tgl Permanen',
'grade' => 'Grade',
'tgl_surat' => 'Tgl Surat',
'from_date' => 'From Date',
'to_date' => 'To Date',
'file' => 'Select File'
];
}
}
thanks for helping..
change your code to the following to output the errors which could happen when you try to save. Errors could occur depending on your model rules.
if (!$modelnew->save()) {
var_dump($modelnew->getErrors());
}
getErrors() from Api
A better approach is to use exceptions to throw and catch errors on your import. Depends if you want to skip csv lines on errors or not.
finally it working with change this $hasil = explode(";", $data);