Not being able to select the same name into a form - php

So I have this form where i can fill in companies but right now I am being able to insert multiple companies with the same name but I don't want that.. I want the name of the company to be unique or else if I put in the same name thats already in the database it should give me an error.
How can I do that?
This is my form in my view html:
<br>
<center> <h3> Instituut toevoegen </h3> </center>
<br>
<?php echo form_open('index.php/Instituut/Add_instituut'); ?>
<div class="form-group">
<label>Instituut:</label>
<input class="form-control" name="instituut" id="instituut" type="text">
</div>
<div class="form-group">
<label>Telefoonnummer van instituut:</label>
<input class="form-control" name="instituuttelefoon" id="instituuttelefoon" type="text">
</div>
<div>
<button class="btn btn-primary" name="Add_instituut" >Toevoegen</button>
</div>
</form>
</div>
This is the controller function:
public function Add_instituut()
{
if (isset($_POST['Add_instituut'])) {
$this->form_validation->set_rules('instituut', 'Instituut', 'required');
$this->form_validation->set_rules('instituuttelefoon', 'instituuttelefoon', 'required');
//If form validation true
if ($this->form_validation->run() == TRUE) {
//voeg werknemer toe in database
$data = array (
'instituut'=>$_POST['instituut'],
'instituuttelefoon'=>$_POST['instituuttelefoon'],
);
$this->db->insert('instituut',$data);
$this->session->set_flashdata("success", "u heeft een nieuw instituut toegevoegd");
redirect("index.php/Instituut", "refresh");
}
}
}
I probably should add something in the form validation rules?
instituut means company name
Thanks
any kind of help is appreciated

You can add is_unique in form validation rules
$this->form_validation->set_rules('instituut', 'Instituut', 'required|is_unique[your_table_name.instituut]');
check tutorial. for unique value:
https://www.codeigniter.com/userguide3/libraries/form_validation.html#rule-reference

Related

Use of undefined constant contacts - assumed 'contacts' error

Recently I have been working to insert data into a database with laravel. Everything went fine. But know I am stuck with the error: "Use of undefined constant contacts - assumed 'contacts'". I do not know how to fix this.
I have already on the Laracast website to see if I could find an explanation on how to solve this, but I couldn't since the answers were not the once I was looking for. I have also looked in StackOverflow. But there were (again) no answers that could help me fix this the problem. I also have asked a classmate of mine but he also couldn't fix it.
My controller:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\contacts;
class ContactsController extends Controller
{
/*Haal alle data op uit de contact tabel return een view file*/
public function index($contact = contacts){
$Contact = contacts::all();
return view('contact',compact('contacts'));
}
/*Return een view file*/
public function create(){
return view('contacts');
}
public function storeContact(){
/*Maakt nieuwe variabele, wanneer er op de knop wordt geklikt worden er 2 waardes opgehaald.*/
$contacts = new contacts();
$contacts->name = request('voornaam');
$contacts->description = request('bericht');
$contacts->save();
return redirect('/contacts');
}
}
My view:
#extends ('Layout')
#section('title')
Contact
#endsection
#section('content')
<br>
<h2>Contact</h2>
<p>Voor verdere informatie (die u niet op onze website kunt vinden) kunt u ons bereiken op onze email of telefoonnummer:</p>
<p>Email: Cronensteynfake#gmail.com</p>
<p>telefoonnummer: 06-11122234</p>
<br>
U kunt ook ons contactformulier invullen.
<br><br>
<h2>Cronenstyn Contactformulier</h2>
<form action="" method="post">
#csrf
<div class="form-group">
<label for="exampleInputPassword1">Voornaam</label>
<input type="text" class="form-control" id="Vnaam" placeholder="Voornaam">
</div>
<div class="form-group">
<label for="exampleInputPassword1">Achternaam</label>
<input type="text" class="form-control" id="Anaam" placeholder="Achternaam">
</div>
<div class="form-group">
<label for="exampleInputEmail1">Email</label>
<input type="email" class="form-control" id="Email" aria-describedby="emailHelp" placeholder="Uw email">
<small id="emailHelp" class="form-text text-muted">Wij delen uw email met niemand</small>
</div>
<label for="exampleInputEmail1">Bericht</label>
<div class="form-group shadow-textarea">
<textarea class="form-control z-depth-1" id="bericht" rows="3" placeholder="Uw bericht"></textarea>
</div>
<button onclick="Message()" type="submit" class="btn btn-primary">Verzenden</button>
<script>
function Message() {
alert("Uw bericht is met succes verstuurd.");
}
</script>
</form>
#endsection
My route:
<?php
Route::get('/', function () {
return view('welcome');
});
Route::GET('/home',('CronensteynController#home'));
Route::GET('/nieuws',('CronensteynController#nieuws'));
Route::GET('/galerij',('CronensteynController#gallerij'));
Route::GET('/activiteit',('CronensteynController#activiteit'));
Route::GET('/contact',('CronensteynController#contact'));
Route::GET('/about',('CronensteynController#about'));
Route::get('/beheer', 'PageController#beheer');
Route::get('/create_beheer', 'PageController#Create_beheer');
Route::get('/update_beheer', 'PageController#Update_beheer');
Route::get('/delete_beheer', 'PageController#delete_beheer');
Route::post('/create_beheer', 'CreateBeheerController#store');
Route::post('/contact', 'contactsController#index');
Hopefully I have given you enough info and code about the problem.
Greetings,
Parsa_237
Follow a convention to avoid errors regarding cases.
Generally models start with a capital letter.
Always make your model name singular. For model Contact laravel will look the table contacts.
For more information on naming convention you can follow this link
Here you are passing $contact to index method you don't have to do that.
public function index(){
$Contacts = contacts::all();
return view('contact',compact('Contacts'));
}

how to redirect and show error validateion in laravel

good day,
I new in laravel Framework and I face this two problems : -
first one
I want to redirect to my page after 2 seconds automatically.
the second one
I make custom function call (is exist )
if this function returns true data I want to print "name exist before " but the problem here is form was rested when this function returns true and print message.
how to prevent form resetting from inputs value?
here is my code
controller code
enter code here
public function add(Request $request)
{
// start add
if($request->isMethod('post'))
{
if(isset($_POST['add']))
{
// start validatio array
$validationarray=$this->validate($request,[
//'name' =>'required|max:25|min:1|unique:mysql2.products,name|alpha',
'name' =>'required|alpha',
'price' =>'required|numeric',
]);
// check name is exist
if(true !=dBHelper::isExist('mysql2','products','`status`=? AND `deleted` =? AND `name`=?',array(1,1,$validationarray['name'])))
{
$product=new productModel();
// start add
$product->name=$request->input('name');
$product->save();
$add=$product->id;
$poducten=new productEnModel();
$poducten->id_product=$add;
$poducten->name=$request->input('name');
$poducten->price=$request->input('price');
$poducten->save();
$dataview['message']='data addes';
}else{
$dataview['message']='name is exist before';
}
}
}
$dataview['pagetitle']="add product geka";
return view('productss.add',$dataview);
}
this is my routes
Route::get('/products/add',"produtController#add");
Route::post('/products/add',"produtController#add");
this is my view
#extends('layout.header')
#section('content')
#if(isset($message))
{{$message}}
#endif
#if(count($errors)>0)
<div class="alert alert-danger">
<ul>
#foreach($errors->all() as $error)
<li>{{$error}}</li>
#endforeach
</ul>
</div>
#endif
<form role="form" action="add" method="post" enctype="multipart/form-data">
{{csrf_field()}}
<div class="box-body">
<div class="form-group{{$errors->has('name')?'has-error':''}}">
<label for="exampleInputEmail1">Employee Name</label>
<input type="text" name="name" value="{{Request::old('name')}}" class="form-control" id="" placeholder="Enter Employee Name">
</div>
<div class="form-group">
<label for="exampleInputEmail1">Email Address</label>
<input type="text" name="price" value="{{Request::old('price')}}" class="form-control" id="" placeholder="Enter Employee Email Address">
</div>
</div>
<!-- /.box-body -->
<div class="box-footer">
<button type="submit" name="add" class="btn btn-primary">Add</button>
</div>
</form>
#endsection
I hope that I understood your question.
Instead of using {{ Request::old('price') }} use {{ old('price') }}
This should retrieve the form data after page was reloaded.
Try the below the code for error display in view page
$validator = Validator::make($params, $req_params);
if ($validator->fails()) {
$errors = $validator->errors()->toArray();
return Redirect::to($web_view_path)->with('errors', $errors);
}
You want to automatically redirect to another page submit the form using ajax and use below the settimeout menthod.
setTimeout(function(){ // Here mentioned the redirect query }, 3000);
//use $request instead of $_POST
if($request->isMethod('post'))
{
if(isset($request['add']))
{
// start validatio array
$validationarray=$this->validate($request,[
//'name' =>'required|max:25|min:1|unique:mysql2.products,name|alpha',
'name' =>'required|alpha',
'price' =>'required|numeric',
]);
// check name is exist

form date check in codeigniter framework

So I have made a form where staff members can post activities like soccer or tennis with a form. So I have 2 dates which they can select. The first date is the start date of the activity and the second date is the end date of the activity. I don't want it to be able to select an end date earlier than a selected startdate. So for example I want to fill in an activity like bowling and it in the form I put at the start date 03-04-2018 and the end date 02-02-2018, I don't want that to be possible.
This is how my form looks:
<?php echo form_open('index.php/Jongeren_activiteiten/Add_activiteit'); ?>
<br>
<center>Naam van activiteit:</center>
<div class="form-group">
<input class="form-control" name="activiteit" id="activiteit" type="text">
</div>
<center>Begindatum:</center>
<div class="form-group">
<input class="form-control" name="begindatum" id="begindatum" placeholder="Startdatum cursus" type="date">
</div>
<center>Einddatum:</center>
<div class="form-group">
<input class="form-control" name="einddatum" id="einddatum" placeholder="einddatum cursus" type="date">
</div>
<div>
<button class="btn btn-primary" name="Add_activiteit" >Toevoegen</button>
</div>
</form>
And this is the controller function of the form:
public function Add_activiteit()
{
if (isset($_POST['Add_activiteit'])) {
$this->form_validation->set_rules('activiteit', 'Activiteit', 'required');
$this->form_validation->set_rules('begindatum', 'Begindatum', 'required');
$this->form_validation->set_rules('einddatum', 'Einddatum', 'required');
//If form validation true
if ($this->form_validation->run() == TRUE) {
// echo 'form validated';
$data = array (
'activiteit'=>$_POST['activiteit'],
'begindatum'=>$_POST['begindatum'],
'einddatum'=>$_POST['einddatum'],
);
$this->db->insert('activiteit',$data);
$this->session->set_flashdata("success", "u heeft een nieuwe activiteit toegevoegd");
redirect("index.php/Jongeren_activiteiten", "refresh");
}
}
}
begindatum means start date and einddatum means end date. So how do I fix it so you can only select an end date later than a startdate?
I also don't want people to being able select a day in the past.
Any kind of help is appreciated
You should use a callback function..
The way you would do this is by creating a function like this:
function checkDate($start, $end){
if($start > $end){
$this->form_validation->set_message('checkDate', 'The end date must be later than the start date.');
return FALSE;
}else{
return TRUE;
}
}
Then you would add it to your form validation rules(I would do it for the end date), but prefix it with 'callback_'
So it would look like this:
$this->form_validation->set_rules('einddatum', 'Einddatum', 'required|callback_checkDate');
A further explanation provided by CodeIgniter can be found here: https://www.codeigniter.com/user_guide/libraries/form_validation.html

How to insert zero rows in codeigniter

I'm click my submit button freely without enter values in the form..then in my database a row inserted that columns contain zeros
controller
function submit_expense()
{
$exp_date=$this->input->post('expense_date');
$expense_ids= $this->input->post('expense');
$expense_ids=substr($expense_ids,0,strlen($expense_ids)-1);
$expense_id_array = explode(',',$expense_ids);
$id=$this->session->userdata('userid');
for($i=0;$i<count($expense_id_array);$i++)
{
$required_id = TRIM($expense_id_array[$i]);
$this->form_validation->set_error_delimiters('<div style="color:#B94A48">', '</div>');
$this->form_validation->set_rules('exp_amount_'.$required_id, 'Expense Amount', 'required|numeric');
$this->form_validation->set_rules('comment_'.$required_id, 'Comments', 'required|alpha');
if ( $this -> form_validation -> run() === FALSE )
{
$this->index();
}
else
{
$amount= $this->input->post('exp_amount_'.$required_id);
$comment=$this->input->post('comment_'.$required_id);
$expense_data=array(
'expense_id'=>$required_id,
'expense_amount'=>$amount,
'user_id'=>$id,
'date'=>$exp_date,
'comments'=>$comment,
);
$this->home_model->insert_expense($expense_data);
$this->session->set_flashdata('message', 'Successfully submitted.');
redirect(base_url().'home/index');
}
}
}
And also my validation is not working
footer_view
var new_String ='<div class="form-group" id="ex_'+unqid1+'">'
+'<label for="exampleInputPassword1">'+name+'</label> </br>'
+'<input name="exp_amount_'+unqid1+'" id="id_'+unqid1+'" type="text" '+
'class="form-control" placeholder="Enter '+name+' expense amount" style="margin-right:20px;" required>'
+'<input name="comment_'+unqid1+'" type="text" id="comment" class="form-con" placeholder="Comments" style="margin-right:20px;" required ></div >' ;
$("#create_exp").append(new_String);
view
this is my view use the id create_exp in my footer
<form role="form" action="<?echo base_url()?>home/submit_expense" method="post">
<?$todays_date=date('Y-m-d');?>
<input id="expense_date" name="expense_date" value="<?echo $todays_date;?>" type="hidden" />
<div class="red">
<? echo $this->session->flashdata('message'); ?>
</div>
<div class="box-body" id="create_exp">
<?php echo validation_errors(); ?>
<span>Choose from the right which all you need to enter for today</span>
<!--here goes the input boxes-->
<!-- /.input boxes -->
</div><!-- /.box-body -->
<span id="errmsg1"></span>
<input id="expenseVal" name="expense" type="hidden" class="form-control">
<div class="box-footer" id="button_id">
<button type="submit" class="btn btn-primary" >Submit</button>
</div>
</form>
As the OP Wants to show the all the Errors inside a div
<div id="error">
<?php echo validation_errors(); ?>
</div>
As the OP Wants some additional info,
To include a view or common page
$this->load->view('yourownpage');
Then you should have yourownpage.php inside your views folder
To have pagination, Have this in your controller's function
$this->load->library('pagination');
$config['base_url'] = 'yourownpage';
$config['total_rows'] = 200;
$config['per_page'] = 20;
$this->pagination->initialize($config);
echo $this->pagination->create_links();
Note :
Make sure to place the error div in the place that didn't hurt your textbox

Codeigniter multi forms on one page validation errors

I have two forms in my page. when I submit either of the form, both of them show the same validation error message. I used
if (isset ($_POST['click_cus_button']))
to check what button is licked in the from seems it does not work for me.
Can anyone tell me why this bit of code isn't working?
this is my controller (admin.php)
function add_users_data()
{
if (isset ($_POST['click_cus_button']))// click_cus_button is set load this validation errors
{
$this->form_validation->set_rules('cus_name', 'Name', 'trim|required|min_length[5]');
// validate name
$this->form_validation->set_rules('cus_email', 'Email', 'trim|required|valid_email');
// validate email
$this->form_validation->set_rules('cus_phone', 'Phone Number', 'trim|required|min_length[10]|max_length[10]');
// validate phone number
$this->form_validation->set_rules('cus_password', 'Password', 'required|matches[cus_passconf]');
// validate password
$this->form_validation->set_rules('cus_passconf', 'Retype Password', 'required');
// validate password
if ($this->form_validation->run() == FALSE)// if from validation failed load following pages from views
{
$this->load->view('admin/admin_add_users.php');
}
else // if from validation success load following pages from views
{
$data = array(
'cus_name' => $this->input->post('cus_name'),
'cus_email' => $this->input->post('cus_email'),
'cus_mobile' => $this->input->post('cus_mobile'),
'cus_phone' => $this->input->post('cus_phone'),
'cus_status' => $this->input->post('cus_status')
//'database_field' => $this->input->post('text_box_name')
);
$this->mod_users->add_record($data);//add a comment
$data['result']="Customer Added Successfully ";
$this->load->view('admin/admin_add_users.php',$data);
}
}
else if (isset ($_POST['click_oper_button']))// click_oper_button is set load this validation errors
{
$this->form_validation->set_rules('oper_firstname', 'Name', 'trim|required|min_length[5]');
// validate name
$this->form_validation->set_rules('oper_lastname', 'Name', 'trim|required|min_length[5]');
// validate name
if ($this->form_validation->run() == FALSE)// if from validation failed load following pages from views
{
$this->load->view('admin/admin_add_users.php');
}
else // if from validation success load following pages from views
{
$data['result']="Customer Added Successfully ";
$this->load->view('admin/admin_add_users.php',$data);
}
}
}
this is my View (admin_add_users.php)
I removed some fields to make the code shorter in the view
<?php echo form_open('admin/add_users_data') ?><!-- start of the form -->
<div class="span8">
<div style="padding-bottom:11px;">
<div class="div add_cus box"><!-- start of the add customer add form -->
<?php echo validation_errors('<div class="notice marker-on-bottom bg-darkRed fg-white" id="bottom_form_error">', '</div>'); ?>
<?php
if(isset($result))
{
echo '<div class="notice marker-on-bottom bg-green fg-white">'.$result.'</div>';
}
?>
<!-- Display Validation error massages -->
<feildset>
<legend><i class="icon-user-2 on-right on-left"></i><strong>Add Customer</strong></legend>
<input name='cus_status' type='hidden' value='disabled'/>
<input type="submit" value="Add Customer" class="info" name="click_cus_button">
</feildset>
</div><!-- END of the add customer add form -->
</div>
<div class="div add_oper box"><!-- start of the add Operator add form -->
<?php echo validation_errors('<div class="notice marker-on-bottom bg-darkRed fg-white" id="bottom_form_error">', '</div>'); ?>
<?php
if(isset($result))
{
echo '<div class="notice marker-on-bottom bg-green fg-white">'.$result.'</div>';
}
?>
<feildset>
<legend><i class="icon-user on-right on-left"></i><strong>Add Operator</strong></legend>
<h6>*All fields marked are required</h6>
<lable>Name*</lable><br>
<div class="input-control text size6" data-role="input-control">
<input type="text" name="oper_firstname" placeholder="First Name">
</div>
<div class="input-control text size6" data-role="input-control">
<input type="text" name="oper_lastname" placeholder="Last Name">
</div>
<br>
<div class="input-control radio default-style" data-role="input-control">
<label>
Gender*<br>
<input type="radio" checked="" name="oper_gender">
<span class="check"></span>
Male
</label>
</div>
<div class="input-control radio default-style" data-role="input-control">
<label>
<input type="radio" name="oper_gender">
<span class="check"></span>
Female
</label>
</div>
<br>
<lable>Date of Birth*</lable>
<div class="input-control text" data-role="input-control">
<input id="datepicker" name="oper_dob" type="text">
</div>
<lable>Address*</lable><br>
<div class="input-control text size1" data-role="input-control">
<input type="text" name="oper_add_no" placeholder="No">
</div>
<input type="submit" value="Add Operator" class="info" name="click_oper_button">
</feildset>
</div><!-- END of the add Operator add form -->
<div class="div add_admin">
RadioButton 3 Selected
</div>
</div>
<?php echo form_close(); ?><!-- END of the form -->

Categories