Add a checkbox in the admin product page (Prestashop) - prestashop-1.7

I have created a module to add different fields in the admin of the product sheet and I have a registration problem for the checkboxes my other input works very well. I don't see where the problem is coming from. Here is my product class:
<?php
class Product extends ProductCore
{
public $solde_display;
public $only_marketplace;
public $on_vp;
public $boost_product;
public $price_market;
public $tagmodele;
public function __construct($id_product = null, $full = false, $id_lang = null, $id_shop = null, Context $context = null)
{
parent::__construct($id_product, $full, $id_lang, $id_shop, $context);
// Boolean
self::$definition['fields']['solde_display'] = array('type' => self::TYPE_BOOL);
self::$definition['fields']['only_marketplace'] = array('type' => self::TYPE_BOOL);
self::$definition['fields']['on_vp'] = array('type' => self::TYPE_BOOL);
self::$definition['fields']['boost_product'] = array('type' => self::TYPE_BOOL);
// Text
self::$definition['fields']['price_market'] = array('type' => self::TYPE_FLOAT, 'validate' => 'isPrice');
self::$definition['fields']['tagmodele'] = array('type' => self::TYPE_STRING);
}
}
My template:
<div class="m-b-1 m-t-1">
<h2>{l s='Champs supplémentaires (Générale)' mod='overrideoptions'}</h2>
<div class="form-group">
<div class="col-lg-12 col-xl-5">
<div class="checkbox">
<label for="on_vp">
<input type="checkbox" name="on_vp" id="on_vp" value="1" {if $on_vp}checked="checked"{/if}>
Produit en Vente Privée
</label>
</div>
</div>
<div class="col-lg-12 col-xl-5">
<div class="checkbox">
<label for="solde_display">
<input type="checkbox" name="solde_display" id="solde_display" value="1" {if $solde_display}checked="checked"{/if}>
Solde display
</label>
</div>
</div>
<div class="col-lg-12 col-xl-5">
<div class="checkbox">
<label for="only_marketplace">
<input type="checkbox" name="only_marketplace" id="only_marketplace" value="1" {if $only_marketplace}checked="checked"{/if}>
Disponible uniquement en Place de marché !
</label>
</div>
</div>
<div class="col-lg-12 col-xl-5">
<div class="checkbox">
<label for="boost_product">
<input type="checkbox" name="boost_product" id="boost_product" value="1" {if $boost_product}checked="checked"{/if}>
Boost Product (Google Shopping)
</label>
</div>
</div>
</div>
<div class="form-group">
<label for="tagmodele">Tag modele</label>
<input type="text" class="form-control" name="tagmodele" id="tagmodele" placeholder="Tag modele" value="{$tagmodele}">
</div>
</div>
the Tag model registers very well except the checkbox.
Thanks for your help

Maybe too late but if it can help someone else...
You need to override the following file override/controllers/admin/AdminProductsController.php and add the logic to save your checkboxes such as
class AdminProductsController extends AdminProductsControllerCore
{
protected function copyFromPost(&$object, $table)
{
parent::copyFromPost($object, $table);
$object->solde_display = (int)Tools::getValue('solde_display');
$object->only_marketplace = (int)Tools::getValue('only_marketplace');
[...]
}
}

Related

Insert data from modal, Codeigniter

I'm trying to insert the input data from a modal but I don't know how to achieve this. I'm not really familiar with AJAX(I apologize for that). I did some readings and research but I'm getting confused. Here is my modal content reserve_form.php
<form action="" id="book-form">
<div class="row flex-lg-row-reverse align-items-center pt-1">
<h3>Reservation Details</h3>
<div class="col-10 col-sm-8 col-lg-6">
<input type="hidden" name="package_id" value="<?php ?>">
<div class="form-group">
<label for="date_start" class="control-label">Reserve Date:</label>
<input type="date" name="date_start" id="date_start" class="form-control form-conrtrol-sm rounded-0" min="<?php echo date("Y-m-d") ?>" value="<?php echo date("Y-m-d") ?>" required>
</div>
<div id="msg" class="text-danger"></div>
<div id="check-availability-loader" class="d-none">
<center>
<div class="d-flex align-items-center col-md-6">
<strong>Checking Availability...</strong>
<div class="spinner-border ml-auto" role="status" aria-hidden="true"></div>
</div>
</center>
</div>
<div class="form-group">
<label for="quantity" class="control-label">Number of Person <span><i>(Max. of 15 person)</i></span></label>
<input type="number" class="form-control form" required name="person" value="">
</div>
<div class="form-group">
<label for="amount" class="control-label">Additional Inclusions</label>
<div>
<input type="checkbox" id="inclusion" name="inclusion" value="">
<label for="inclusion"> Unlimited Samgyupsal & Al Fresco dining experience</label>
</div>
</div>
<div class="form-group">
<label for="amount" class="control-label">Total Amount</label>
<input type="number" name="cost" id="amount" class="form-control form-conrtrol-sm rounded-0 text-right" value="<?php echo isset($cost) ? number_format($cost, 2) : 0.00 ?>" required readonly>
</div>
</div>
<div class="col-lg-6">
<div class="form-group">
<label for="name" class="control-label">First Name</label>
<input type="text" class="form-control mb-3" name="firstname" placeholder="Enter First Name" value="">
</div>
<div class="form-group">
<label for="name" class="control-label">Last Name</label>
<input type="text" class="form-control mb-3" name="lastname" placeholder="Enter Last Name" value="">
</div>
<div class="form-group">
<label for="name" class="control-label">Contact</label>
<input type="text" class="form-control mb-3" name="contact" placeholder="09xx-xxx-xxxx" value="">
</div>
<div class="form-group">
<label for="name" class="control-label">Email</label>
<input type="text" class="form-control mb-3" name="email" placeholder="example#email.com" value="">
</div>
</div>
</div>
<div class="modal-footer py-2">
<button class="btn btn-warning" type="submit" name="details">Save</button>
<button class="btn btn-secondary "><span class="close-sm">Close</span></button>
</div>
</form>
Here's my modal in view.php
<!-- Modal content -->
<div class="modal-content">
<div class="modal-header py-1">
<h3><?php echo $packages->title; ?></h3>
</div>
<div class="modal-body py-2">
<?php $this->load->view('forms/reserve_form'); ?>
</div>
</div>
Here' my Controller(page.php)
public function reservation_details()
{
$details = array();
$details2 = array();
if ($this->input->post('details')) {
$this->form_validation->set_rules('firstname', 'First Name', 'required');
$this->form_validation->set_rules('lastname', 'Last Name', 'required');
$this->form_validation->set_rules('contact', 'Contact', 'required');
$this->form_validation->set_rules('email', 'Email', 'required');
$this->form_validation->set_rules('date_start', 'Reserve Date', 'required');
$this->form_validation->set_rules('person', 'Number of Person', 'required|max_length[15]');
if ($this->form_validation->run() == true) {
$details = array(
'firstname' => $this->input->post('firstname'),
'lastname' => $this->input->post('lastname'),
'contact' => $this->input->post('contact'),
'email' => $this->input->post('email'),
);
$this->UI_model->reserve_details($details);
$details2 = array(
'date_start' => $this->input->post('date_start'),
'person' => $this->input->post('person'),
'inclusion' => $this->input->post('inclusion'),
);
$this->UI_model->reserve_add($details2);
}
}
}
Here's the Model
public function reserve_details(){
if (!empty($data)) {
$this->db->insert('clients', $data);
return $this->db->insert_id();
}
return false;
}
public function reserve_add(){
if (!empty($data)) {
$this->db->insert('book_list', $data);
return $this->db->insert_id();
}
return false;
}
Also, I'm trying to insert the data for multiple tables. Any help will be much appreciated. Thanks! Is is also fine to place the submit button at modal footer? or it should be at reserve.php?
You're passing data array through these functions.
$this->UI_model->reserve_details($details);
$this->UI_model->reserve_add($details2);
But in the model, you're not catching those.
public function reserve_details(){
public function reserve_add(){
So it should be
public function reserve_details($data){
public function reserve_add($data){
Since you're checking if (!empty($data)) { its always retuns false, unless Undefixed Varibale error.

SQLSTATE[23000]: Integrity constraint violation in livewire

In Livewire component i have a form inside the modal to edit the information.
When I click on the button, the modal will open and display the item information inside the inputs.
The problem is that if one or all of the inputs do not change their value and the edit button is clicked, it gives the following error that says the values are empty!!. And the inputs must be changed so that there are no errors
SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'network' cannot be null (SQL: update `networks` set `network` = ?, `networkName` = ?, `address` = ?, `address_regex` = ?, `tag_memo` = ?, `tag_regex` = ?, `min_withdraw` = ?, `max_withdraw` = ?, `fee` = ?, `deposit` = inactive, `withdraw` = inactive, `networks`.`updated_at` = 2021-06-09 10:18:52 where `id` = 8)
component code:
<?php
namespace App\Http\Livewire\Backend\Currency;
use App\Models\Network;
use Livewire\Component;
class Networks extends Component
{
protected $listeners = ['refreshNetwork' => '$refresh'];
public $confirming;
public $editId;
public $networkEdit;
public $networkNameEdit;
public $address_networkEdit;
public $address_regexEdit;
public $tag_memo_networkEdit;
public $tag_regexEdit;
public $min_withdrawEdit;
public $max_withdrawEdit;
public $feeEdit;
public $depositEdit = false;
public $withdrawEdit = false;
public function editForm($id,$action)
{
if ($network = Network::where('id' , $id)->first()) {
$this->editId = $id;
$this->dispatchBrowserEvent('editNetworkModal', $networkData = [
'network' => $network->network,
'networkName' => $network->networkName,
'address_network' => $network->address,
'address_regex' => $network->address_regex,
'tag_memo_network' => $network->tag_memo_network,
'tag_memo_regex' => $network->tag_memo_regex,
'min_withdraw' => $network->min_withdraw,
'max_withdraw' => $network->max_withdraw,
'fee' => $network->fee ,
'deposit' => $network->deposit,
'withdraw' => $network->withdraw,
]);
}else{
$this->alert('warning', 'شبکه مورد نظر پیدا نشد !', [
'position' => 'center',
'timer' => 2000,
'toast' => false,
'text' => '',
'confirmButtonText' => 'خب',
'cancelButtonText' => 'خب',
'showCancelButton' => false,
'showConfirmButton' => false,
]);
}
}
public function Update($action)
{
if ($action == 'edit')
{
Network::where('id' , $this->editId)->update([
'network' => $this->networkEdit,
'networkName' => $this->networkNameEdit,
'address' => $this->address_networkEdit,
'address_regex' => $this->address_regexEdit,
'tag_memo' => $this->tag_memo_networkEdit,
'tag_regex' => $this->tag_regexEdit,
'min_withdraw' => $this->min_withdrawEdit,
'max_withdraw' => $this->max_withdrawEdit,
'fee' => $this->feeEdit,
'deposit' => $this->depositEdit == false ? 'inactive' : 'active',
'withdraw' => $this->withdrawEdit== false ? 'inactive' : 'active',
]);
$this->emit('refreshNetwork');
$this->dispatchBrowserEvent('hideEditNetworkModal');
$this->alert('success', 'شبکه با موفقیت ویرایش شد.', [
'position' => 'center',
'timer' => 2000,
'toast' => false,
'text' => '',
'confirmButtonText' => 'خب',
'cancelButtonText' => 'خب',
'showCancelButton' => false,
'showConfirmButton' => false,
]);
}
}
public function render()
{
return view('livewire.backend.currency.networks');
}
}
modal:
<div wire:key="B" class="modal fade" tabindex="-1" id="editNetworkModal">
<div class="modal-dialog modal-lg" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title">ویرایـش شبکـه انتقال</h5>
<a href="#" class="close" data-dismiss="modal" aria-label="Close">
<em class="icon ni ni-cross"></em>
</a>
</div>
<div class="modal-body">
<form action="#" class="form-validate is-alter">
<div class="row gy-3">
<div class="col-md-6">
<div class="form-group">
<label class="form-label" for="full-name">شبکه ارز</label>
<div class="form-control-wrap">
<input wire:model.defer="networkEdit" type="text" class="form-control" placeholder="مثال : BNB" id="networkEdit" required>
</div>
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<label class="form-label" for="email-address">نام شبکه</label>
<div class="form-control-wrap">
<input wire:model="networkNameEdit" id="networkNameEdit" type="text" class="form-control" placeholder="مثال: BEP20" required>
</div>
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<label class="form-label" for="phone-no">ادرس</label>
<div class="form-control-wrap">
<input wire:model="address_networkEdit" type="text" class="form-control" id="address_networkEdit">
</div>
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<label class="form-label" for="phone-no">اعتبار سنجی آدرس شبکه به وسیله عبارات منظم</label>
<div class="form-control-wrap">
<input wire:model="address_regexEdit" type="text" class="form-control" id="address_regexEdit">
</div>
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<label class="form-label" for="phone-no">آدرس Memo یا Tag</label>
<div class="form-control-wrap">
<input wire:model="tag_memo_networkEdit" type="text" class="form-control" id="tag_memo_networkEdit">
</div>
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<label class="form-label" for="phone-no">اعتبار سنجی Memo شبکه به وسیله عبارات منظم</label>
<div class="form-control-wrap">
<input wire:model="tag_regexEdit" type="text" class="form-control" id="tag_regexEdit">
</div>
</div>
</div>
<div class="col-md-4">
<div class="form-group">
<label class="form-label" for="phone-no">حداقل برداشت</label>
<div class="form-control-wrap">
<input wire:model="min_withdrawEdit" type="text" class="form-control" id="min_withdrawEdit">
</div>
</div>
</div>
<div class="col-md-4">
<div class="form-group">
<label class="form-label" for="phone-no">حداکثر برداشت</label>
<div class="form-control-wrap">
<input wire:model="max_withdrawEdit" type="text" class="form-control" id="max_withdrawEdit">
</div>
</div>
</div>
<div class="col-md-4">
<div class="form-group">
<label class="form-label" for="phone-no">کارمزد برداشت</label>
<div class="form-control-wrap">
<input wire:model="feeEdit" type="text" class="form-control" id="feeEdit">
</div>
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<div class="custom-control custom-switch">
<input wire:model="depositEdit" type="checkbox" class="custom-control-input" id="depositEdit">
<label class="custom-control-label" for="deposit">واریـز به این آدرس</label>
</div>
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<div class="custom-control custom-switch">
<input wire:model.defer="withdrawEdit" type="checkbox" class="custom-control-input" id="withdrawEdit">
<label class="custom-control-label" for="withdraw">برداشت به این آدرس</label>
</div>
</div>
</div>
</div>
</form>
</div>
<div class="modal-footer bg-light">
<button wire:click="Update('edit')" class="btn btn-round btn-outline-primary ">
<div wire:loading wire:target="Update">
<span class="spinner-border spinner-border-sm" role="status" aria-hidden="true"></span>
</div>
<span class="w-100px">ویرایـش شبکـه</span>
</button>
<button data-dismiss="modal" aria-label="Close" class="btn btn-round btn-outline-secondary w-90px"><span>بستن</span></button>
</div>
</div>
</div>
</div>
and js code to set value for inputs and open modal:
window.addEventListener('editNetworkModal', event => {
$("#editNetworkModal").modal('show');
$('#networkEdit').val(event.detail.network);
$('#networkNameEdit').val(event.detail.networkName);
$('#address_networkEdit').val(event.detail.address_network);
$('#address_regexEdit').val(event.detail.address_regex);
$('#tag_memo_networkEdit').val(event.detail.tag_memo_network);
$('#tag_regexEdit').val(event.detail.tag_regex);
$('#min_withdrawEdit').val(event.detail.min_withdraw);
$('#max_withdrawEdit').val(event.detail.max_withdraw);
$('#feeEdit').val(event.detail.fee);
$('#depositEdit').val(event.detail.deposit);
$('#withdraw').val(event.detail.withdraw);
console.log(event.detail)
});
$this->dispatchBrowserEvent('editNetworkModal', $networkData = [
'network' => $network->network,
One of the goals of Livewire, is forget about JS for this kind of things. Binding the property with wire:model you don't need at all use JS, even pass this db information through the event. With a simple method that retrieve the data from db and assign it to the public properties is enough for you get this in frontend
public function editForm($id,$action)
{
$this->getModelData($id);
$this->dispatchBrowserEvent('openEditModal');
}
public function getModelData($modelId)
{
$model = Model::find($modelId);
$this->property1 = $model->property1;
//......
}

Data retrieval in CodeIgniter Form

I have successfully created a registration and login system in Code Igniter.
After registration all the user data is saved in database.
I have used email and password in the login form and I want to display all the details related to that logged user.
I have tried a few things but not getting the exact one. How should I proceed?
//Controller file
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class User extends CI_Controller{
function __construct()
{
parent::__construct();
$this->load->helper(array('form', 'url'));
$this->load->library(array('session', 'form_validation', 'email', 'upload'));
$this->load->database();
$this->load->model('user_model');
}
public function index()
{
$this->load->view('registration');
}
public function registration()
{
//validate input value with form validation class of codeigniter
$this->form_validation->set_rules('fname', 'First Name', 'required|regex_match[/^[A-Za-z]{2,15}+$/]');
$this->form_validation->set_rules('lname', 'Last Name', 'required|regex_match[/^[A-Za-z]{2,15}+$/]');
$this->form_validation->set_rules('email', 'Email', 'required|valid_email|is_unique[user.email]');
$this->form_validation->set_rules('phone', 'Phone Number', 'required|regex_match[/^[789]\d{9}$/]');
$this->form_validation->set_rules('city', 'City', 'required|regex_match[/^[A-Za-z]{3,15}+$/]');
$this->form_validation->set_rules('zip', 'Zip Code', 'required|regex_match[/^\d{6}$/]');
$this->form_validation->set_rules('gender', 'Gender', 'required');
$this->form_validation->set_rules('password', 'Password', 'required|min_length[6]|max_length[15]');
$this->form_validation->set_rules('confirmpswd', 'Password Confirmation', 'required|matches[password]');
$this->form_validation->set_rules('image', 'Image', 'callback_do_upload','required');
//$this->form_validation->set_message('is_unique', 'This %s is already exits');
if ($this->form_validation->run() == FALSE)
{
$this->load->view('registration', array('error' => ' ' ));
}
else
{
$fname = $_POST['fname'];
$lname = $_POST['lname'];
$email = $_POST['email'];
$phone = $_POST['phone'];
$city = $_POST['city'];
$zip = $_POST['zip'];
$gender = $_POST['gender'];
$password = $_POST['password'];
$passhash = hash('md5', $password);
$image = $_FILES['image']['name'];
//call method for uploading image
$upload = $this->do_upload('image');
//md5 hashing algorithm to decode and encode input password
//$salt = uniqid(rand(10,10000000),true);
$saltid = md5($email);
$data = array('fname' => $fname,
'lname' => $lname,
'email' => $email,
'phone' => $phone,
'city' => $city,
'zip' => $zip,
'gender' => $gender,
'password' => $passhash,
'image' => $image);
if($this->user_model->insertuser($data))
{
$this->session->set_flashdata('msg','<div class="alert alert-danger text-center"> Registration Successful</div>');
redirect(base_url().'user/login');
}
else
{
$this->session->set_flashdata('msg','<div class="alert alert-danger text-center">
Something Wrong. Please try again ...</div>');
redirect(base_url());
}
}
}
public function do_upload($data)
{
$config['upload_path'] = './uploads/';
$config['allowed_types'] = 'gif|jpg|png';
$this->load->library('upload', $config);
/*$config['max_size'] = 1000000;
$config['max_width'] = 1024;
$config['max_height'] = 768;*/
//base_url('uploads/')
$this->upload->initialize($config);
if ( ! $this->upload->do_upload('image'))
{
$error = array('error' => $this->upload->display_errors());
}
else
{
$data = array('upload_data' => $this->upload->data());
}
return $data;
}
public function login()
{
$this->load->view('login');
}
public function check_login()
{
$email = $_POST['email'];
$pass = hash('md5', $_POST['password']);
$this->form_validation->set_rules('email', 'Email', 'required|valid_email');
$this->form_validation->set_rules('password', 'Password', 'required|min_length[6]|max_length[15]');
if($this->form_validation->run() == FALSE)
{
$this->load->view('login');
}
else
{
$res = $this->user_model->check_user($email , $pass);
if(!empty($res))
{
echo "you are registered";
echo "<br>";
echo "<br>";
echo "your details are as follows: ";
echo "<br>";
echo "<br>";
echo "email:".$email;
echo "<br>";
}
else
{
$this->session->set_flashdata('msg','<div class="alert alert-danger text-center">email/password not found</div>');
redirect(base_url().'user/login');
}
}
}
function setSession($userId,$userName) {
$userSession = array('userId'=>$userId,
'userName'=>$userName,
'loggedIn'=>TRUE );
$this->session->set_userdata($userSession);
}
public function logout()
{
$this->session->sess_destroy();
redirect(base_url().'user/login', 'refresh');
}
}
//View File
<!DOCTYPE html>
<html lang="en">
<head>
<title>Registration</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<style type="text/css">
.form-box {
max-width: 500px;
position: relative;
margin: 5% auto;
}
</style>
</head>
<body>
<div class="wrapper">
<div class="container">
<div class="row">
<div class="form-box">
<div class="panel panel-primary">
<div class="panel-heading text-center">
<h3>Register</h3>
</div>
<?php
echo $this->session->flashdata('msg');
?>
<div class="panel-body">
<div class="row">
<div class="col-sm-12">
</div>
</div>
<form action="<?php echo base_url('user/registration');?>" method="post" enctype="multipart/form-data">
<div class="row">
<div class="col-sm-6">
<div class="form-group">
<label class="control-label" for="fname">First Name</label>
<div>
<input type="text" class="form-control" id="fname" name="fname" placeholder="First Name" required="">
<span class="text-danger"><?php echo form_error('fname'); ?></span>
</div>
</div>
</div>
<div class="col-sm-6">
<div class="form-group">
<label class="control-label" for="fname">Last Name</label>
<div>
<input type="text" class="form-control" id="lname" name="lname" placeholder="Last Name" required="">
<span class="text-danger"><?php echo form_error('lname'); ?></span>
</div>
</div>
</div>
<div class="col-sm-12">
<div class="form-group">
<label class="control-label" for="email"> Email</label>
<div>
<input type="email" class="form-control" id="email" name="email" placeholder="Email" required="">
<span class="text-danger"><?php echo form_error('email'); ?></span>
</div>
</div>
</div>
<div class="col-sm-6">
<div class="form-group">
<label class="control-label" for="phone">Phone Number</label>
<div>
<input type="text" class="form-control" id="phone" name="phone" maxlength="10" placeholder="Phone Number" required="">
<span class="text-danger"><?php echo form_error('phone'); ?></span>
</div>
</div>
</div>
<div class="col-sm-6">
<div class="form-group">
<label class="control-label" for="city">City</label>
<div>
<input type="text" class="form-control" id="city" name="city" placeholder="City" required="">
<span class="text-danger"><?php echo form_error('city'); ?></span>
</div>
</div>
</div>
<div class="col-sm-6">
<div class="form-group">
<label class="control-label" for="zip">Zip Code</label>
<div>
<input type="text" class="form-control" id="zip" name="zip" placeholder="Zip Code" required="">
<span class="text-danger"><?php echo form_error('zip'); ?></span>
</div>
</div>
</div>
<div class="col-sm-6">
<div class="form-group">
<label class="control-label" for="gender">Gender</label>
<div>
<input type="radio" name="gender" value="male" id="gender" checked="true"> Male
<input type="radio" name="gender" value="female" id="gender"> Female
<input type="radio" name="gender" value="transgender" id="gender"> Transgender
<span class="text-danger"><?php echo form_error('gender'); ?></span>
</div>
</div>
</div>
<br>
<div class="col-sm-12">
<div class="form-group">
<label class="control-label" for="pswd">Password</label>
<div>
<input type="password" class="form-control" id="pswd" name="password" placeholder="Password" required="">
<span class="text-danger"><?php echo form_error('password'); ?></span>
</div>
</div>
</div>
<div class="col-sm-12">
<div class="form-group">
<label class="control-label" for="cn-pswd">Confirm Password</label>
<div>
<input type="password" class="form-control" id="cn-pswd" name="confirmpswd" placeholder="Confirm Password" required="">
<span class="text-danger"><?php echo form_error('confirmpswd'); ?></span>
</div>
</div>
</div>
<div class="form-group">
<div class="row">
<div class="col-sm-offset-5 col-sm-3 btn-submit">
<button type="submit" class="btn btn-success">Register</button>
</div>
</div>
</div>
<div class="col-sm-12">
<div class="form-group">
Select image to upload:<br>
<input type="file" name="image" id="image">
<br/><br/>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
</div>
<!-- jQuery (necessary for Bootstrap's JavaScript plugins) -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</body>
</html>
// Model file
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class User_model extends CI_Model
{
public function insertuser($data)
{
return $this->db->insert('candidates', $data);
}
public function verifyemail($key)
{
$this->db->where('md5(email)', $key);
return $this->db->update('candidates', $data);
}
public function check_user($email,$pass)
{
$sql = "SELECT id , fname FROM candidates where email = ? and password = ?";
$data = $this->db->query($sql, array($email,$pass));
return ($data->result_array()) ;
}
// Function To Fetch Selected Record
public function show_user_id($data){
$this->db->select('*');
$this->db->from('candidates');
$this->db->where('email', $data);
$q=$this->db->get('candidates');
return $q->row_array();
}
// Update Query For Selected Student
public function update_user_id1($id,$data){
$this->db->where('email', $id);
$this->db->update('candidates', $data);
}
}
?>
// While registering time your are using md5 encryption for password but while
// retrieving time you are passing password without encryption formate
$data = $this->db->query($sql, array($email,$pass));
// Use this in your model
$data = $this->db->query($sql, array($email,hash('md5', $pass)));

how to compare current and old password both are same or not before updation in DB using Codeigniter

I used this HTML for developing Form
<form method="post" action="<?php echo site_url('patients/change_patient_password'); ?>/<?php echo $this->session->userdata('patientDiseasesId'); ?>" class="form-horizontal">
<div class="form-body">
<div class="form-group">
<label class="col-md-3 control-label">Current Password</label>
<div class="col-md-4">
<input type="text" required class="form-control" name="password" placeholder="Current Password">
<?php $pass = form_error('password'); if(isset($pass)): ?><span class="help-block"><?php echo form_error('password'); ?></span><?php endif; ?>
</div>
</div>
<div class="form-group">
<label class="col-md-3 control-label">New Password </label>
<div class="col-md-4">
<input type="text" required class="form-control" name="password_confirm" placeholder="New Password">
<?php $pass_confirm = form_error('password_confirm'); if(isset($pass_confirm)): ?><span class="help-block"><?php echo form_error('password_confirm'); ?></span><?php endif; ?>
</div>
</div>
<div class="form-group">
<label class="col-md-3 control-label">ReType New Password</label>
<div class="col-md-4">
<input type="text" required class="form-control" name="password_confirm2" placeholder="ReType New Password">
<?php $pass_confirm2 = form_error('password_confirm2'); if(isset($pass_confirm2)): ?><span class="help-block"><?php echo form_error('password_confirm2'); ?></span><?php endif; ?>
</div>
</div>
</div>
<div class="form-actions">
<div class="row">
<div class="col-md-offset-3 col-md-9">
<button type="submit" class="btn green">Update Password</button>
<button type="button" class="btn default">Cancel</button>
</div>
</div>
</div>
</form>
also please have a look my code controller.
public function change_patient_password($patientId){
$this->load->library('form_validation');
$this->form_validation->set_error_delimiters('<div class="error">', '</div>');
$this->form_validation->set_rules('password', 'Password', 'required|is_unique[patients.password]');
$this->form_validation->set_rules('password_confirm', 'New Password', 'required|matches[password_confirm2]');
$this->form_validation->set_rules('password_confirm2', 'ReType New Password', 'required');
if ($this->form_validation->run() == FALSE)
{
$this->change_patient_password_form();
}
else
{
$this->load->model('patients_model');
$data['password_updated'] = $this->patients_model->change_patient_password_model($patientId);
if($data['password_updated']==true){
$data['success']=true;
$data['main_content']= 'change_patient_password_form';
$this->load->view('includes/patient_template',$data);
}else{
$data['error']=true;
$data['main_content']= 'change_patient_password_form';
$this->load->view('includes/patient_template',$data);
}
}
here is the final model code
public function change_patient_password_model($patientId){
$data = array(
'password' => md5($this->input->post('password_confirm'))
);
$this->db->where('patientDiseasesId', $patientId);
return $this->db->update('patients', $data);
}
I see you're using "is_unique" in your form validation. Will each password be unique?
How I would do this, is to query the DB before we update it, and check if the passwords match. Like so.
public function change_patient_password_model($patientId)
{
// Get this users info
$query = $this->db->get_where('patients', array('patientDiseasesId' => $patientId));
if($query->num_rows() > 0)
{
// We have the patient, so check if the passwords match
$current_password = $query->row('password');
$inputted_password = md5($this->input->post('password_confirm'));
if( $current_password != $inputted_password)
{
// They are not the same, so update it...
$data['password'] = $inputted_password;
$this->db->where('patientDiseasesId', $patientId);
return $this->db->update('patients', $data);
}
else
{
// They are the same...
return false;
}
}
else
{
// No patients with this ID
return false;
}
}
I hope this helps.

Image uploading using codeigniter file uploading class

This is not a how to upload image question . I have almost successfully managed to add a image upload function into my add client function . It works well when i try to upload a valid file .. but when i select a invalid file or larger file then it shows undefined variable upload_data and codeigniter database error where img_path is NULL it says Column 'img_path' cannot be null. why this function isn't working $this->upload->display_errors(); . The validation errors are showing nicely but no file validation error showing up.
I am using Codeigniter and hmvc
here is my controller
<?php
class Clients extends MX_Controller{
function __construct(){
parent::__construct();
$this->load->model('mdl_clients');
}
function add(){
$data['success'] = null;
$data['errors']= null;
if($_POST){
$config_arr = array(
'upload_path' => './uploads/',
'allowed_types' => 'gif|jpg|png',
'max_size' => '2048',
'max_width' => '1024',
'max_height' => '768',
'encrypt_name' => true,
);
$this->load->library('upload', $config_arr);
if (!$this->upload->do_upload()) {
$data['errors'] = $this->upload->display_errors(); // this isn't working
} else {
$upload_data = $this->upload->data();
}
$config=array(
array(
'field'=>'firstName',
'label'=>'First Name',
'rules'=>'required|max_length[15]|min_length[3]'
),
array(
'field'=>'city',
'label'=>'City',
'rules'=>'required'
),
array(
'field'=>'mobile_phone',
'label'=>'Mobile Number',
'rules'=>'required'
),
array(
'field'=>'email',
'label'=>'Email',
'rules'=>'required|is_unique[clients.email]|valid_email'
),
);
$this->load->library('form_validation');
$this->form_validation->set_rules($config);
if($this->form_validation->run() == FALSE){
$data['errors'] = validation_errors();
}else{
$data=array(
'img_path'=>$upload_data['file_name'],
'firstName'=>$_POST['firstName'],
'email'=>$_POST['email'],
'city'=>$_POST['city'],
'mobile_phone'=>$_POST['mobile_phone'],
);
$this->mdl_clients->add($data);
$data['success'] = 1;
$data['errors']= 0;
}
}
$data['title'] = 'Add Client Database';
$data['main_content'] = 'clients/add';
echo Modules::run('templates/admin', $data);
}
and my view file .. add.php
<? if($success==1) {?>
<div class="alert alert-success">
<a class="close" data-dismiss="alert" href="#">×</a>
Data Has been Updated !
</div>
<? } ?>
<?php if($errors) { ?>
<div class="alert alert-error" >
<a class="close" data-dismiss="alert" href="#">×</a>
<?=$errors?>
</div>
<? } ?>
<?php $attributes = array('class' => 'form-horizontal');
echo form_open_multipart('clients/add', $attributes); ?>
<fieldset>
<!-- Address form -->
<h2>Client Information</h2>
<hr />
All Fields Marked with <span style="color: red;">*</span> is necessary .
<hr />
<!-- Upload input-->
<div class="control-group">
<label class="control-label">Upload<span style="color: red;">*</span></label>
<div class="controls">
<input name="userfile" name="userfile" type="file"
class="input-xlarge">
<p class="help-block"></p>
</div>
</div>
<!-- firstName input-->
<div class="control-group">
<label class="control-label">First Name<span style="color: red;">*</span></label>
<div class="controls">
<input id="firstName" name="firstName" type="text" placeholder="First Name"
class="input-xlarge" required>
<p class="help-block"></p>
</div>
</div>
<!-- Email input-->
<div class="control-group">
<label class="control-label">E-Mail<span style="color: red;">*</span></label>
<div class="controls">
<input id="email" name="email" type="text" placeholder="A Valid Email Address"
class="input-xlarge" required>
<p class="help-block"></p>
</div>
</div>
<!-- City input-->
<div class="control-group">
<label class="control-label">City<span style="color: red;">*</span></label>
<div class="controls">
<input id="city" name="city" type="text" placeholder="City Name"
class="input-xlarge" required>
<p class="help-block"></p>
</div>
<!-- Mobile input-->
<div class="control-group">
<label class="control-label">Mobile Number<span style="color: red;">*</span></label>
<div class="controls">
<input id="mobile_phone" name="mobile_phone" type="text" placeholder="Current Mobile Phone Number"
class="input-xlarge" required>
<p class="help-block"></p>
</div>
</div>
<!-- Button -->
<div class="control-group">
<div class="controls">
<button class="btn btn-success">Add to Database</button>
</div>
</div>
</fieldset>
</form>
Assuming an input element of:
<input type="file" name="image" id="image">
Change the following line:
!$this->upload->do_upload()
to:
!$this->upload->do_upload('image')
Please let me know if you face any problem.
UPDATE
If you want to send it to the template then do something like this:
if (!$this->upload->do_upload()) {
$error = array('error' => $this->upload->display_errors());
$this->session->set_flashdata('msg',$error['error']);
redirect('controller_name/function_name','refresh');
}
Let me know if this works for you.
While doing the form validation you are not taking into consideration if there were upload errors or not. You should check if there were upload errors or not than proceed with the form validation
if($data['errors'] != '')
{
//do something, probably redirect back to the view and show the errors
}
else
{
if($this->form_validation->run() == FALSE)
{
$data['errors'] = validation_errors();
}
else
{
$data=array(
'img_path'=>$upload_data['file_name'],
'firstName'=>$_POST['firstName'],
'email'=>$_POST['email'],
'city'=>$_POST['city'],
'mobile_phone'=>$_POST['mobile_phone'],
);
$this->mdl_clients->add($data);
$data['success'] = 1;
$data['errors']= 0;
}
}

Resources