I do form validation in backend in codeigniter, on clientside every field alrets work fine but on image field the error persist even i attach the image... below is my code and i am attaching image screenshort for further detail. Please help in this regards.
Here is My Controller code
public function save(){
$res = array();
//form field validation rules
$this->form_validation->set_rules('titlemaster', 'Main Title', 'required');
if (!$this->form_validation->run()) {
echo json_encode(array('mes' => 'text-danger', 'msg' => 'Ourpeople Main Title Required'));
exit;
}
$this->form_validation->set_rules('detailmaster', 'Main Detail', 'required');
if (!$this->form_validation->run()) {
echo json_encode(array('mes' => 'text-danger', 'msg' => 'Oupeople Main Description Required'));
exit;
}
$config['upload_path'] = 'fassets/images/oupeople';
$config['allowed_types'] = 'jpg|jpeg|png|gif';
$config['file_name'] = $_FILES['userfile']['name'];
$config['overwrite'] = TRUE;
//Load upload library and initialize configuration
$this->load->library('upload', $config);
$ourpeoplesection = ($this->input->post('name')) . ($this->input->post('desig')) . ($this->input->post('aboutme')) . ($this->input->post('certification')) . ($this->upload->do_upload('userfile'));
if (!empty($ourpeoplesection))
{
$this->form_validation->set_rules('name', 'Name', 'required|max_length[25]');
if (!$this->form_validation->run()) {
echo json_encode(array('mes' => 'text-danger', 'msg' => 'Name Required'));
exit;
}
$this->form_validation->set_rules('desig', 'Designation', 'required|max_length[20]');
if (!$this->form_validation->run()) {
echo json_encode(array('mes' => 'text-danger', 'msg' => 'Designation Required'));
exit;
}
$this->form_validation->set_rules('aboutme', 'About Employee', 'required');
if (!$this->form_validation->run()) {
echo json_encode(array('mes' => 'text-danger', 'msg' => 'About Employee Required'));
exit;
}
$this->form_validation->set_rules('certification', 'Certification', 'required');
if (!$this->form_validation->run()) {
echo json_encode(array('mes' => 'text-danger', 'msg' => 'Certification Required'));
exit;
}
if(!$this->upload->do_upload('userfile'))
{
$error = 'Please upload Image file. <br>';
//$error = $this->upload->display_errors('', '<br>');
echo json_encode(array('mes' => 'alert-danger', 'msg' => $error));
exit;
}
$userData = array (
'name' => $this->input->post('name'),
'desig' => $this->input->post('desig'),
'aboutme' => $this->input->post('aboutme'),
'certification' => $this->input->post('certification'),
'facebook' => $this->input->post('facebook'),
'twitter' => $this->input->post('twitter'),
'instagram' => $this->input->post('instagram'),
'google' => $this->input->post('google'),
'userfile' => $this->upload->data('file_name'),
);
//Pass user data to model
$insertData = $this->Ourpeoplemodel->insert($userData);
}
$ourpeopleMaster = array(
'titlemaster' => $this->input->post('titlemaster') ,
'detailmaster' => $this->input->post('detailmaster')
);
$insertUserData = $this->Ourpeoplemodel->insert_main($ourpeopleMaster);
//Storing insertion status message.
if(($insertUserData && $insertData)){
$res = array(
'mes' => 'text-success',
'msg' => "Record has been saved successfully.",
);
echo json_encode($res);
} else {
$res = array(
'mes' => 'text-danger',
'msg' => "Record not saved",
);
echo json_encode($res);
}
}
here my html input
<div class="form-group row">
<div class="col-md-6 col-xs-12">
<?php if(isset($ourpeople_master)){;?>
<input type="text" class="form-control input-sm" name="titlemaster" value="<?php echo set_value('titlemaster', $ourpeople_master->titlemaster);?>" placeholder="Main Title | max 25 characters" required="required">
</div>
<div class="col-md-6 col-xs-12">
<input type="text" class="form-control input-sm" name="detailmaster" value="<?php echo set_value('detailmaster', $ourpeople_master->detailmaster);?>" placeholder="Main Decription." required="required">
</div>
<?php }?>
</div>
<div class="form-group row">
<div class="col-md-4 col-xs-12">
<input type="text" class="form-control input-sm" name="name" value="" placeholder="Name Required">
</div>
<div class="col-md-4 col-xs-12">
<input type="text" class="form-control input-sm" name="desig" value="" placeholder="Designation Required">
</div>
<div class="col-md-4 col-xs-12">
<input type="file" name="userfile" class="form-control input-sm">
</div>
</div>
<div class="form-group row">
<div class="col-md-12 col-sm-12">
<textarea name='aboutme' rows="1" class='form-control input-sm' placeholder="About Employee Detail"></textarea>
</div>
</div>
<div class="form-group row">
<div class="col-md-12 col-sm-12">
<textarea name='certification' rows="1" class='form-control input-sm' placeholder="Employee's Certifications Detail"></textarea>
</div>
</div>
<div class="form-group row">
<div class="col-md-3 col-xs-12">
<input type="text" class="form-control input-sm" name="facebook" placeholder="Facebook Profile Link Here">
</div>
<div class="col-md-3 col-xs-12">
<input type="text" class="form-control input-sm" name="twitter" placeholder="Twitter Profile Link Here">
</div>
<div class="col-md-3 col-xs-12">
<input type="text" class="form-control input-sm" name="instagram" placeholder="Instagram Profile Link Here">
</div>
<div class="col-md-3 col-xs-12">
<input type="text" class="form-control input-sm" name="google" placeholder="Google Plus Profile Link Here">
</div>
</div>
<div class="form-group row">
<div class="col-md-12 text-right">
<button type="submit" class="btn btn-success btn-sm" id="save"><i class="fa fa-save"></i> Save</button>
</div>
</div>
I think you got confused by my last answer - you can use $_FILES['userfile']['name'] you just have to wrap it in isset or in this case empty otherwise notices will fire (and affect your json response) if the file isn't uploaded.
$config['upload_path'] = 'fassets/images/oupeople';
$config['allowed_types'] = 'jpg|jpeg|png|gif';
//$config['file_name'] = $_FILES['userfile']['name'];
$config['overwrite'] = TRUE;
//Load upload library and initialize configuration
$this->load->library('upload', $config);
//$ourpeoplesection = ($this->input->post('name')) . ($this->input->post('desig')) . ($this->input->post('aboutme')) . ($this->input->post('certification')) . ($this->upload->do_upload('userfile'));
if (!empty($_FILES['userfile']['name']))
{
$this->form_validation->set_rules('name', 'Name', 'required|max_length[25]');
if (!$this->form_validation->run()) {
echo json_encode(array('mes' => 'text-danger', 'msg' => 'Name Required'));
exit;
}
$this->form_validation->set_rules('desig', 'Designation', 'required|max_length[20]');
if (!$this->form_validation->run()) {
echo json_encode(array('mes' => 'text-danger', 'msg' => 'Designation Required'));
exit;
}
$this->form_validation->set_rules('aboutme', 'About Employee', 'required');
if (!$this->form_validation->run()) {
echo json_encode(array('mes' => 'text-danger', 'msg' => 'About Employee Required'));
exit;
}
$this->form_validation->set_rules('certification', 'Certification', 'required');
if (!$this->form_validation->run()) {
echo json_encode(array('mes' => 'text-danger', 'msg' => 'Certification Required'));
exit;
}
if(!$this->upload->do_upload('userfile'))
{
$error = 'Please upload Image file. <br>';
//$error = $this->upload->display_errors('', '<br>');
echo json_encode(array('mes' => 'alert-danger', 'msg' => $error));
exit;
}
$userData = array (
'name' => $this->input->post('name'),
'desig' => $this->input->post('desig'),
'aboutme' => $this->input->post('aboutme'),
'certification' => $this->input->post('certification'),
'facebook' => $this->input->post('facebook'),
'twitter' => $this->input->post('twitter'),
'instagram' => $this->input->post('instagram'),
'google' => $this->input->post('google'),
'userfile' => $this->upload->data('file_name'),
);
//Pass user data to model
$insertData = $this->Ourpeoplemodel->insert($userData);
}
I would also like to suggest instead of having many different form validation conditions just have one...
$this->form_validation->set_rules('name', 'Name', 'required|max_length[25]');
$this->form_validation->set_rules('desig', 'Designation', 'required|max_length[20]');
$this->form_validation->set_rules('aboutme', 'About Employee', 'required');
$this->form_validation->set_rules('certification', 'Certification', 'required');
if (!$this->form_validation->run()) {
echo json_encode(array('mes' => 'text-danger', 'msg' => validation_errors()));
exit;
}
Related
I'm running codeigniter 4.1.5 and php 8.1.0 and when i try to input data this is the error i got
Uncaught ErrorException: strtolower(): Passing null to parameter #1 ($string) of type string is deprecated in C:\xampp\htdocs\cikaryawan\system\Validation\FormatRules.php:253
Stack trace:
#0 [internal function]: CodeIgniter\Debug\Exceptions->errorHandler()
#1 C:\xampp\htdocs\cikaryawan\system\Validation\FormatRules.php(253):
strtolower()
#2 C:\xampp\htdocs\cikaryawan\system\HTTP\RequestTrait.php(151): CodeIgniter\Validation\FormatRules->valid_ip()
#3 C:\xampp\htdocs\cikaryawan\app\Views\errors\html\error_exception.php(206):
CodeIgniter\HTTP\Request->getIPAddress()
#4 C:\xampp\htdocs\cikaryawan\system\Debug\Exceptions.php(229): include('...')
#5 C:\xampp\htdocs\cikaryawan\system\Debug\Exceptions.php(232): CodeIgniter\Debug\Exceptions->CodeIgniter\Debug{closure}()
#6 C:\xampp\htdocs\cikaryawan\system\Debug\Exceptions.php(116): CodeIgniter\Debug\Exceptions->render()
#7 [internal function]: CodeIgniter\Debug\Exceptions->exceptionHandler()
#8 {main}
in my .env folder
CI_ENVIRONMENT = development
database.default.hostname = localhost
database.default.database = cikaryawanauth
database.default.username = root
database.default.password =
database.default.DBDriver = MySQLi
database.default.DBPrefix =
this is my register.php
<body>
<div class="container">
<div class="row" style="margin-top:45px">
<div class="col-md-4 col-md-offset-4">
<h4>Sign Up</h4>
<hr>
<form action="<?= base_url('auth/save') ?>" method="post">
<?= csrf_field(); ?>
<div class="form-group">
<label for="">Name</label>
<input type="text" class="form-control" name="name" placeholder="Enter your name" value="<?= set_value('name'); ?>">
<span class="text-danger"><?= isset($validation) ? display_error($validation, 'name') : '' ?></span>
</div>
<div class="form-group">
<label for="">Email</label>
<input type="email" class="form-control" name="email" placeholder="Enter your email" value="<?= set_value('email'); ?>">
<span class=" text-danger"><?= isset($validation) ? display_error($validation, 'email') : '' ?></span>
</div>
<div class="form-group">
<label for="">Password</label>
<input type="password" class="form-control" name="password" placeholder="Enter password">
<span class="text-danger"><?= isset($validation) ? display_error($validation, 'password') : '' ?></span>
</div>
<div class="form-group">
<label for="">Confirm Password</label>
<input type="password" class="form-control" name="cpassword" placeholder="Confirm password">
<span class="text-danger"><?= isset($validation) ? display_error($validation, 'cpassword') : '' ?></span>
</div>
<div class="form-group">
<button class="btn btn-primary btn-block" type="submit">Sign Up</button>
</div>
I already have account, login now
</form>
</div>
</div>
</div>
</body>
this is my auth.php as controller
<?php
namespace App\Controllers;
class Auth extends BaseController
{
public function __construct()
{
helper(['url', 'form']);
}
public function index()
{
return view('auth/login');
}
public function register()
{
return view('auth/register');
}
public function save()
{
$validation = $this->validate([
'name' => [
'rules' => 'required',
'errors' => [
'required' => 'Your name is required'
]
],
'email' => [
'rules' => 'required|valid_emails|is_unique[users.email]',
'errors' => [
'required' => 'Email is required',
'valid_email' => 'You must enter a valid email',
'is_unique' => 'Email already taken'
]
],
'password' => [
'rules' => 'required|min_length[5]|max_length[12]',
'errors' => [
'required' => 'Password is required',
'min_lenght' => 'Password must have atleast 5 character',
'max_lenght' => 'Password must not exceed 12 character'
]
],
'cpassword' => [
'rules' => 'required|min_length[5]|max_length[12]|matches[password]',
'errors' => [
'required' => 'Password is required',
'min_lenght' => 'Password must have atleast 5 character',
'max_lenght' => 'Password must not exceed 12 character',
'matches' => 'Confirms password not matches to password'
]
]
]);
if (!$validation) {
return view('auth/register', ['validation' => $this->validator]);
} else {
$name = $this->request->getPost('name');
$email = $this->request->getPost('email');
$password = $this->request->getPost('password');
$values = [
'name' => $name,
'email' => $email,
'password' => $password,
];
$userModels = new \App\Models\UsersModel();
$query = $userModels->insert($values);
if (!$query) {
return redirect()->back()->with('fail', 'something went wrong');
} else {
return redirect()->to('register')->with('success', 'You are now registered');
}
}
}
}
this is what i put in form_helper.php in helpers folder
<?php
function display_error($validation, $field)
{
if ($validation->hasError($field)) {
return $validation->getError($field);
} else {
return false;
}
}
what did i do wrong?
CodeIgniter 4.1.5 does not support PHP 8.1 yet.
Please Use 8.0
or Use develop branch of CI4
https://github.com/codeigniter4/CodeIgniter4/pull/4883
https://github.com/codeigniter4/CodeIgniter4/issues/5436
https://forum.codeigniter.com/thread-80490-post-391352.html#pid391352
https://forum.codeigniter.com/thread-80413.html
You can add the null coalescing operator to this line of code:
$method = strtolower($method);
Replace it with:
$method = strtolower($method ?? '');
This change should be made in the library/RestController file line no 835
I'm working on a contact form with Codeigniter 4 and SQL Database. The form will submit through the button, so whenever it is clicked, it is validating, and if all of the fields are filled out, it has no trouble displaying the message and save the information to the database, but when the fields are empty, it does not display the error message, and it continues to state that the file does not exist.
Well, I'm stuck with the error message now. I'm not sure what wrong with the code. Am I missing something?
Can anybody help me with this? I appreciate all the help I can get.
Below are my codes:
App/config/Routes.php
$routes->get('contact', 'Contact::contact');
$routes->post('contact/save', 'Contact::save');
App/Controller/Contact.php
<?php
namespace App\Controllers;
use App\Models\ContactModel;
class Contact extends BaseController
{
public function __construct()
{
helper(['url', 'form']);
}
//CONTACT PAGE
public function contact()
{
$data = [
'meta_title' => 'Contact | MFD',
];
return view('page_templates/contact', $data);
}
//SAVE
public function save()
{
$validation = $this->validate([
'name' => [
'rules' => 'required',
'errors' => [
'required' => 'Your full name is required'
]
],
'email' => [
'rules' => 'required|valid_email|is_unique[users.email]',
'errors' => [
'required' => 'Email is required',
'valid_email' => 'You must enter a valid email',
]
],
'title' => [
'rules' => 'required',
'errors' => [
'required' => 'Title is required',
]
],
'content' => [
'rules' => 'required',
'errors' => [
'required' => 'Content is required',
]
],
]);
if (!$validation) {
return view('contact', ['validation' => $this->validator]);
} else {
// Let's Register user into db
$name = $this->request->getPost('name');
$email = $this->request->getPost('email');
$title = $this->request->getPost('title');
$content = $this->request->getPost('content');
$values = [
'name' => $name,
'email' => $email,
'title' => $title,
'content' => $content,
];
$contactModel = new ContactModel();
$query = $contactModel->insert($values);
if ($query) {
return redirect()->to('contact')->with('success', 'Your message are successful sent');
} else {
return redirect()->to('contact')->with('fail', 'Something went wrong');
}
}
}
}
App/Views/page_templates/contact.php
<form action="<?= base_url('contact/save'); ?>" method="post" role="form" class="php-email-form">
<?= csrf_field(); ?>
<?php if (!empty(session()->getFlashdata('error'))) : ?>
<div class="alert alert-danger"><?= session()->getFlashdata('error'); ?></div>
<?php endif ?>
<?php if (!empty(session()->getFlashdata('success'))) : ?>
<div class="alert alert-success"><?= session()->getFlashdata('success'); ?></div>
<?php endif ?>
<div class="row">
<div class="col-md-6 form-group">
<input type="text" name="name" class="form-control" id="name" placeholder="Your Name" value="<?= set_value('name'); ?>">
<span class="text-danger"><?= isset($validation) ? display_error($validation, 'name') : '' ?></span>
</div>
<div class="col-md-6 form-group mt-3 mt-md-0">
<input type="email" class="form-control" name="email" id="email" placeholder="Your Email" value="<?= set_value('email'); ?>">
<span class="text-danger"><?= isset($validation) ? display_error($validation, 'email') : '' ?></span>
</div>
</div>
<div class="form-group mt-3">
<input type="text" class="form-control" name="title" id="title" placeholder="Title">
<span class="text-danger"><?= isset($validation) ? display_error($validation, 'title') : '' ?></span>
</div>
<div class="form-group mt-3">
<textarea class="form-control" name="content" rows="5" wrap="hard" placeholder="Message"></textarea>
<span class="text-danger"><?= isset($validation) ? display_error($validation, 'content') : '' ?></span>
</div>
<div style="height: 10px;"></div>
<div class="text-left button">
<button type="submit" name="submit">Send Message</button>
</div>
<div style="height: 10px;"></div>
</form>
Okay, I have fixed the problem with my code. It's really is a small mistake or I could say careless mistake haha feel so dumb right now but all that I need to change and make it work.
Is this part: return view('contact', ['validation' => $this->validator]);
Instead of doing it like that I actually miss placing the file to call the view page properly so the code I only added my the folder name that is
page_templates
and if I include it in the code it should look like this:-
return view('page_template/contact', ['validation' => $this->validator]);
and it works after that haha.
I am trying to get form values and passing it in my model to store in the database. Whenever I end up submitting the form, I always get the values as NULL.
form.php
<form action="http://localhost/hbp/review/submit/" method="post">
<input type="hidden" name='<?php echo $this->security->get_csrf_token_name(); ?>' value='<?php echo $this->security->get_csrf_hash(); ?>'>
<div class="form-group">
<label for="exampleInputEmail1">Title</label>
<!-- <input type="text" name="title">-->
<?php echo form_input(['id' => 'title', 'name' => 'title', 'class' => 'form-control', 'placeholder' => 'Enter your review title']); ?>
<small id="emailHelp" class="form-text text-muted">We'll never share your email with anyone else.</small>
</div>
<div class="form-group">
<label for="exampleInputPassword1">Review</label>
<!-- <textarea rows="10" cols="100" name="message"></textarea>-->
<?php echo form_textarea(['id' => 'message', 'name' => 'message', 'class' => 'form-control', 'placeholder' => 'Enter your review title', 'rows' => '10', 'cols' => '100']); ?>
</div>
<button name="submit">Hello</button>
</form>
I have tried using both form_input() and simple HTML syntax for rendering form fields. None of them worked.
controller.php
if ($gClient->getAccessToken()) {
$userProfile = $google_oauthV2->userinfo->get();
$name = $userProfile['name'];
$email = $userProfile['email'];
$picture = $userProfile['picture'];
$this->load->library('form_validation');
$this->form_validation->set_rules('title', 'title', 'required');
$this->form_validation->set_rules('message', 'message', 'required');
if ($this->form_validation->run() == FALSE){
echo "error in your form ";
$this->session->set_flashdata('review_error', 'Please fill all the fields!');
$this->load->view('pages/review');
} else {
$this->session->set_flashdata('review_success', 'Thank you for you ');
$this->review_model->set_review($name, $email, $picture);
redirect(base_url() . 'review/');
}
echo "just dies";
model.php
class Review_model extends CI_Model
{
public function set_review($google_name, $google_email, $google_image)
{
$data = array('review_title' => $this->input->post('title'),
'review_content' => $this->input->post('message'),
'email' => $google_email,
'name' => $google_name,
'image_url' => $google_image);
return $this->db->insert('reviews', $data);
}
public function get_review(){
$query = $this->db->get('reviews');
return $query->result_array();
}
}
I keep getting the review_title can't be NULL.
I don't know where I got wrong but I couldn't find it out.
I have a form validation with a callback file check validation function
My Add_Post Function:
public function add_post()
{
$validation = array (
array(
'field' => 'post_title',
'label' => 'Post title',
'rules' => 'trim|required|alpha_numeric'
),
array(
'field' => 'headerimage',
'rules' => 'required|callback_file_check'
),
array(
'field' => 'post_desc',
'label' => 'Post Description',
'rules' => 'trim|required|alpha_numeric'
),
array(
'field' => 'post_content',
'label' => 'Post content',
'rules' => 'trim|required'
)
);
$this->form_validation->set_rules($validation);
if($this->form_validation->run()===FALSE)
{
$info['errors'] = validation_errors();
$info['success'] = false;
}
else
{
$config = array(
"upload_path" => "./uploads/blog_images",
"max_size" => "2048000",
"allowed_types"=> "gif|png|jpg|jpeg",
"file_name" => 'header_'.substr(md5(rand()),0,7),
"overwrite" => false
);
$this->load->library('upload', $config);
if($this->upload->do_upload('file'))
{
$uploadFile = $this->upload->upload_data();
$uploadFileName = $uploadFile['file_name'];
$data = array(
"post_title" => $this->input->post('post_title'),
"post_content" => $this->input->post('post_content'),
"post_image" => $uploadFileName,
"post_created" => $this->input->post('time')
);
$this->Blog_model->add_post($data);
}
$info['success'] = true;
$info['message'] = "Successfully added blog post";
}
$this->output->set_content_type('application/json')->set_output(json_encode($info));
}
Callback function:
public function file_check($str){
$allowed_mime_type_arr = array('application/pdf', 'image/gif', 'image/jpeg', 'image/pjpeg', 'image/png', 'image/x-png');
$mime = get_mime_by_extension($_FILES['headerimage']['name']);
if(isset($_FILES['headerimage']['name']) && $_FILES['headerimage']['name'] != "") {
if(in_array($mime, $allowed_mime_type_arr)) {
return true;
} else {
$this->form_validation->set_message('file_check', 'Please select only pdf/gif/jpg/png file.');
return false;
}
} else {
$this->form_validation->set_message('file_check', 'Please choose a file to upload.');
return false;
}
}
Here's for the view part:
<?php echo form_open_multipart('Blog/file_check',array("class"=>"form-horizontal","id"=>"blogform")); ?>
<div class="row">
<div class="col-md-6">
<input type="text" placeholder="Enter your post title" name="post_title" class="form-control">
</div>
<div class="col-md-6 form-group">
<label for="file" class="control-label col-md-4">Select header image:</label>
<div class="col-md-8">
<input type="file" name="headerimage" id="file" accept="image/*" />
</div>
</div>
</div>
<input type="text" placeholder="Enter your post description" name="post_desc" class="form-control">
<label class="control-label text-muted">Post Body:</label>
<div>
<textarea id="post_content" name="content"></textarea>
</div>
<button class="btn btn-default pull-right" type="button" id="save-post"><i class="fa fa-save"></i> Save Post</button>
<div class="clearfix"></div>
<?php echo form_close(); ?>
My Ajax code:
$(document).on('click','#save-post',function(){
$post_content = $('#post_content').summernote('code');
$time = $('#time').text();
$.ajax({
url:site_url('Blog/add_post'),
data: $('#blogform').serialize() + "&post_content=" + $post_content + "&time=" + $time,
type: "POST",
dataType: 'json',
encode: true,
success: function(data){
if(!data.success) {
if(data.errors) {
$('#blog-message').html(data.errors).addClass('alert alert-danger');
}
} else {
alert(data.message);
}
}
});
});
Input FileName Checked: I already checked the input name and it's the same.
Image Size: I checked for some related question of mine which is undefined index on file validation and they said image size must be big but I use a small size image sample.
I used Krajee's File Input Plugin.
user data has been lost if there is a validation error and error validation messages are also not showing on front end.
Here is my controller
public function add() {
$this->theme = 'Front';
if (!empty($this->logged_in)) {
return $this->redirect(Router::url('/', true) . $this->logged_in['Role']['alias']);
}
$this->set('title_for_layout', __('Create An Account'));
// hanlde post data
if ($this->request->is("post")) {
if (!empty($this->request->data)) {
$this->User->set($this->request->data);
if (!$this->User->validates()) {
$this->User->validationErrors;
$this->Session->setFlash(__('The Information could not be saved. Please, try again.'), 'message', array('class' => 'danger'));
$this->redirect(Router::url('/', true) . 'sign-up/');
}
}
// die('sdsddsaf');
// if (!empty($this->request->data['User']['role_id']) && $this->request->data['User']['role_id'] == 2) {
unset($this->request->data['User']['specialization_id']);
$randomSt = $this->Custom->randomString(28);
$this->request->data['User']['activation_key'] = $randomSt;
// }
if ($this->User->save($this->request->data)) {
$user = $this->request->data;
if (!empty($this->request->data['User']['role_id']) && $this->request->data['User']['role_id'] == 3) {
$this->Session->setFlash(__('Thank you for registering with us. Please check your email inbox/junk.'), 'message', array('class' => 'successs'));
// set mail variable
$to = $this->request->data['User']['email'];
$fname = $this->request->data['User']['first_name'];
$lname = $this->request->data['User']['last_name'];
//$activelink = SITEURL . 'activate?code=' . $randomSt;
$siteurl = Configure::read('Site.title');
$replace = array($fname, $lname, $siteurl);
// Send mail on Registration
$this->sendMail($to, 'RegisterDoctor', $replace);
} else {
$this->Session->setFlash(__('Thank you for registering with us. Please check your e-mail inbox/junk as your e-mail confirmation has just been sent.'), 'message', array('class' => 'successs'));
$activelink = Router::url('/', true) . 'activate/' . $this->User->id . '/' . $randomSt;
// set mail variable
$to = $this->request->data['User']['email'];
$fname = $this->request->data['User']['first_name'];
$lname = $this->request->data['User']['last_name'];
//$activelink = SITEURL . 'activate?code=' . $randomSt;
$siteurl = Configure::read('Site.title');
$replace = array($fname, $lname, $activelink, $siteurl);
// Send mail on Registration
$this->sendMail($to, 'Register', $replace);
}
$this->redirect(array('controller' => 'users', 'action' => 'login'));
}
}
$reponse = array();
$roles = $this->User->rolesSignup();
$genders = $this->User->genders();
$specializations = $this->User->specializations();
$this->set(compact('roles', 'genders', 'specializations'));
}
And below is my view
<?php
echo $this->Form->create('User', array(
'inputDefaults' => array('div' => false, 'label' => false, 'fieldset' => false),
'class' => 'ac p10',
// 'data-togglesd' => "validator",
'role' => 'form',
'type' => 'file',
'onSubmit' => 'return checksubmitPass()'
)
);
?>
<div class="ph10">
<div class="btn-group radio_group w100" data-toggle="buttons">
<label class="btn btn-primary col-md-6 <?php echo (empty($this->request->data['User']['role_id']) || #$this->request->data['User']['role_id'] == 2 ) ? 'active' : ""; ?> btn_roles">
<input type="radio" name="data[User][role_id]" value="2" class="role_id" <?php echo (empty($this->request->data['User']['role_id']) || #$this->request->data['User']['role_id'] == 2 ) ? 'checked="checked"' : ""; ?>> User
</label>
<label class="btn btn-primary col-md-6 <?php echo (!empty($this->request->data['User']['role_id']) && $this->request->data['User']['role_id'] == 3 ) ? 'active' : ""; ?> btn_roles">
<input type="radio" name="data[User][role_id]" value="3" class="role_id" <?php echo (!empty($this->request->data['User']['role_id']) && $this->request->data['User']['role_id'] == 3 ) ? 'checked="checked"' : ""; ?>> Doctor
</label>
</div>
</div>
<div class="form-group p10 cr">
<div class="cm upload_img round"><img src="<?php echo $this->webroot; ?>img/user_avtar(upload).png" class="user_pic_upload">
<?php echo $this->Form->file('image', array('class' => 'user_img', 'data-fv-file' => 'true', 'data-fv-notempty-message' => __('notEmpty'), 'data-fv-field' => 'data[User][image]')); ?>
</div>
<small style="display: none;" class="help-block" data-fv-validator="notEmpty" data-fv-for="data[User][image]" data-fv-result="VALID">This field cannot be left blank.</small>
</div>
<div class="form-group mt10 cr">
<div class="clearfix">
<div class="col-lg-6 first_name"><?php echo $this->Form->input('first_name', array('class' => 'form-control', 'placeholder' => 'First Name', 'data-stripe' => "alphabet", 'data-fv-notempty-message' => __('notEmpty'), 'data-fv-regexp' => 'true', 'data-fv-regexp-regexp' => "^[a-zA-Z\s]+$", 'data-fv-regexp-message' => "The first name can consist of alphabetical characters and spaces only")); ?></div>
<div class="col-lg-6 last_name"><?php echo $this->Form->input('last_name', array('class' => 'form-control', 'placeholder' => 'Last Name', 'data-fv-notempty-message' => __('notEmpty'), 'data-fv-regexp' => 'true', 'data-fv-regexp-regexp' => "^[a-zA-Z\s]+$", 'data-fv-regexp-message' => "The last name can consist of alphabetical characters and spaces only", 'required')); ?></div>
</div>
</div>
<div class="form-group ph10 mt10">
<?php echo $this->Form->input('email', array('class' => "form-control", 'placeholder' => 'Email Address', 'data-fv-notempty-message' => __('notEmpty'), 'data-fv-emailaddress-message' => __('validemail'))); ?>
</div>
<div class="form-group mt10 ph10 row_org">
<div id="dropdown-menu">
<?php echo $this->Form->input('specialization_id', array('empty' => 'Select Speciallization', 'class' => 'selectpicker form-control', 'data-fv-notempty-message' => __('notEmpty'), 'required')); ?>
</div>
</div>
<div class="form-group ph10 mt10">
<?php echo $this->Form->input('password', array('class' => "form-control", 'placeholder' => 'Password', 'type' => 'password', 'data-fv-notempty-message' => __('notEmpty'))); ?>
</div>
<span id="result"></span>
<div class="form-group ph10 mt10">
<?php
echo $this->Form->input('verify_password', array(
'class' => "form-control",
'type' => 'password',
'placeholder' => 'Confirm Password',
'data-fv-notempty-message' => __('notEmpty'),
'data-fv-identical' => "true",
'data-fv-identical-field' => "data[User][password]",
'data-fv-identical-message' => __('passwordNotMatch')
)
);
?>
</div>
<div class="form-group mt10">
<div class="clearfix">
<div class="col-lg-6 mobile-custom">
<?php echo $this->Form->input('mobile', array('class' => 'form-control phonenumber', 'placeholder' => 'Mobile number', 'maxlength' => '14', 'minlength' => '10', 'data-fv-stringlength-message' => 'The mobile number must be 10 to 14 characters long', 'data-fv-numeric-message' => __('Please enter valid mobile numbers'), 'data-fv-numeric' => "true")); ?>
</div>
<div class="col-lg-6" id="dropdown-menu">
<?php //echo $this->Form->input('gender', array('class' => 'form-control selectpicker', 'data-fv-notempty-message' => __('notEmpty'),'empty' => 'I Am','error' => false, 'required')); ?>
<select id="UserGender" title="I Am" required="required" data-fv-notempty-message="This field cannot be left blank." class="form-control" name="data[User][gender]" style="display: none;" data-fv-field="data[User][gender]">
<option value="Male">Male</option>
<option value="Female">Female</option>
<option value="Other">Other</option>
</select>
</div>
</div>
</div>
<div class="form-group ph10 mt10"><button type="submit" class="btn btn-info w100">Sign Up</button></div>
<p class="mt10"><small>By Signing up you are agree with <br>Terms & Conditions and Privacy Policy</small></p>
<p class="mt10 signup-text"><strong>Already on HealthDrop?</strong></p>
<div class="ph10">
<?php echo $this->Html->link('Sign In', Router::url('/', true) . 'login', array('class' => 'btn deep btn-primary w100')); ?>
</div>
<?php echo $this->Form->end(); ?>
it was working before bu suddenly stop to showing error and start loosing data.
I have check with this question but it is pointing out at field names in input and I have correct ones.
Any help appreciate.
You lost your data because there is redirect to sign-up url.
$this->redirect(Router::url('/', true) . 'sign-up/');
And after redirection
$this->request->data
is empty because you perform new request, the same with errors
According to your code there are two mistakes I found
you are using ! for validating the validations
Save method itself validate the data so no need to validate again.
So your code should be look like
if ($this->User->save($this->request->data)) {
//your code
}else{
$this->Session->setFlash(__('The Information could not be saved. Please, try again.'), 'message', array('class' => 'danger'));
$this->redirect(Router::url('/', true) . 'sign-up/');
}
and validation error messages are automatically assign to view, no need to worry about them