302 found in Laravel project - php

Route
Route::get('/addproduct', [UserController::class, 'addproduct'])->name('addproduct');
Route::post('/addnewproduct', [UserController::class, 'addnewproduct'])->name('addnewproduct');
Route::get('/showproducts', [UserController::class, 'showproducts'])->name('showproducts');
Controller
public function addproduct()
{
return view('addProduct');
}
public function addnewproduct(Request $request)
{
$user_id = Auth::user()->id;
$request->validate([
'file' => 'required|mimes:jpg,png,gif,svg',
'name' => 'required|string|min:3|max:30',
'description' => 'required|string|min:1|max:255',
'category' => 'required|string|max:255',
]);
$productModel = new Product();
$filename =time().'_' .$request->name;
$filePath = $request->file('file')->move('upload', $filename);
$productModel->name = $request->name;
$productModel->description = $request->description;
$productModel->category = $request->category;
$productModel->image = $filePath;
$productModel->save();
return redirect()->route('showproducts');
}
public function showproducts()
{
$user_id = Auth::user()->id;
$results=DB::select('SELECT * FROM products');
$data = [
'results' =>$results
];
return view('showProduct')->with($data);
}
View
<div class="card-body">
<form method="POST" action="{{ route('addnewproduct') }}" class="needs-validation form" enctype="multipart/form-data" novalidate>
#csrf
<div class="row">
<div class="col-sm-6">
<input type="file" id="input-file-now" class="form-control dropify" name="file" required/>
</div>
<div class="col-sm-6">
<div class="row mb-3">
<label for="validationName" class="form-label">Product name</label>
<div class="input-group has-validation">
<input type="text" class="form-control" name="name" id="validationName" aria-describedby="inputGroupPrepend" required>
<div class="invalid-feedback">
You have to enter Product name!
</div>
</div>
</div>
<div class="row mb-3">
<label for="validationCategory" class="form-label">Category</label>
<div class="input-group has-validation">
<select class="form-select" name="category" id="validationCategory" required>
<option selected disabled value="">Select...</option>
<option value="c1">c1</option>
<option value="c2">c2</option>
</select>
</div>
<div class="invalid-feedback">
Please select Category
</div>
</div>
<div class="row mb-3">
<label for="validationDes" class="form-label">Description</label>
<div class="input-group has-validation">
<textarea type="text" class="form-control text-des" name="address" id="validationDes" aria-describedby="inputGroupPrepend" required></textarea>
<div class="invalid-feedback">
Please enter product descriiption in here.
</div>
</div>
</div>
</div>
</div>
<div class="row">
<div class="form-check">
<input class="form-check-input" type="checkbox" value="" id="invalidCheck" required>
<label class="form-check-label" for="invalidCheck">
Check it.
</label>
<div class="invalid-feedback">
You have to checkbox!
</div>
</div>
</div>
<div class="row">
<div class="float-end">
<button class="btn btn-primary sumbtn float-end" type="submit"><i class="bi bi-person-plus-fill"></i> ADD</button>
</div>
</div>
</form>
</div>
after enter all fields and file select and then click checkbox, but when I click button don't go to showproducts page, and don't save enterd data and file.
view screenshot
after click button get 302 and not redirect to "showproducts"
Please help me, I'm very very stress with that problem

Related

Can't insert data on my database from laravel

When I try to insert data into my database, Laravel does not insert the records, but it is strange because when I migrate the tables to be able to perform the database, Laravel creates them without any problem, I do not know what I can be doing wrong if the migration run but stored no
Route:
Route::post('/proyecto', [ctrlCars::class,'store'])->name('cars');
Controler:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\cars;
class ctrlCars extends Controller
{
public function store(Request $request){
$request->validate([
'carRegistration'=> ['required','min:6'],
'name'=> ['required','min:6'],
'fromProduction' => ['required','min:6'],
'stateStored'=> ['required'],
'model'=> ['required','min:4'],
'dateAssembled' => ['required'],
]);
$car = new cars;
$car->carRegistration = $request->carRegistration;
$car->name = $request->name;
$car->fromProduction = $request->fromProduction;
$car->stateStored = $request->stateStored;
$car->model = $request->model;
$car->dateAssembled = $request->dateAssembled;
$car-> save();
return redirect()->route('cars')->with('success','Registro guardado satisfactoriamente');
}}
Template:
#extends('header')
#section('content')
<div class="container w-10 mt-5 border p-4">
<form action="{{ route('cars') }}" method="POST">
#csrf
#if (session('success'))
<h6 class="alert alert-success">{{ session('success') }}</h6>
#endif
#error('carRegistration')
<h6 class="alert alert-danger">{{ $message }}</h6>
#enderror
<p class="h2">Registro vehiculos</p>
<br>
<div class="row">
<section class="col-md-12">
<div class="form-group">
<section class="row">
<div class="col-md-4">
<label for="carRegistration" class="form-label">Placa</label>
<input type="text" class="form-control" name="carRegistration" placeholder="CDE001" maxlength="6">
</div>
<div class="col-md-4">
<label for="name" class="form-label">Nombre</label>
<input type="text" class="form-control" name="name" placeholder="Ferrari Enzo">
</div>
<div class="col-md-4">
<label for="fromProduction" class="form-label">Planta Produccion</label>
<input type="text" class="form-control" name="fromProduction" placeholder="Bmw sede1">
</div>
</section>
<section class="row mt-4">
<div class="col-md-4">
<label for="placa" class="form-label">Fecha Ensamble</label>
<input type="date" class="form-control" name="dateAssembled" placeholder="CDE001">
</div>
<div class="col-md-4">
<label for="model" class="form-label">Módelo Matricula</label>
<input type="text" class="form-control" name="model" maxlength="4" placeholder="2013">
</div>
<div class="col-md-4">
<label for="stateStored" class="form-label">Ciudad Almacenamiento</label>
<Select type="text" class="form-control" id="stateStored" placeholder="Medellin">
<option value=''>Elija una opción</option>
<option value='Medellin'>Medellín</option>
<option value="Bucaramanga">Bucaramanga</option>
<option value="Cali">Cali</option>
<option value="Bogota">Bogotá</option>
</Select>
</div>
</section>
</div>
</section>
</div>
<button type="submit" class="btn btn-success mt-4">Guardar</button>
</form>
</div>
The problem is from your template. The select tag should have a name attribute.
Change your template to this
$car->dateAssembled = $request->dateAssembled;
$car-> save();
return redirect()->route('cars')->with('success','Registro guardado satisfactoriamente');
}}
Template:
#extends('header')
#section('content')
<div class="container w-10 mt-5 border p-4">
<form action="{{ route('cars') }}" method="POST">
#csrf
#if (session('success'))
<h6 class="alert alert-success">{{ session('success') }}</h6>
#endif
#error('carRegistration')
<h6 class="alert alert-danger">{{ $message }}</h6>
#enderror
<p class="h2">Registro vehiculos</p>
<br>
<div class="row">
<section class="col-md-12">
<div class="form-group">
<section class="row">
<div class="col-md-4">
<label for="carRegistration" class="form-label">Placa</label>
<input type="text" class="form-control" name="carRegistration" placeholder="CDE001" maxlength="6">
</div>
<div class="col-md-4">
<label for="name" class="form-label">Nombre</label>
<input type="text" class="form-control" name="name" placeholder="Ferrari Enzo">
</div>
<div class="col-md-4">
<label for="fromProduction" class="form-label">Planta Produccion</label>
<input type="text" class="form-control" name="fromProduction" placeholder="Bmw sede1">
</div>
</section>
<section class="row mt-4">
<div class="col-md-4">
<label for="placa" class="form-label">Fecha Ensamble</label>
<input type="date" class="form-control" name="dateAssembled" placeholder="CDE001">
</div>
<div class="col-md-4">
<label for="model" class="form-label">Módelo Matricula</label>
<input type="text" class="form-control" name="model" maxlength="4" placeholder="2013">
</div>
<div class="col-md-4">
<label for="stateStored" class="form-label">Ciudad Almacenamiento</label>
<Select type="text" name="stateStored" class="form-control" id="stateStored" placeholder="Medellin">
<option value=''>Elija una opción</option>
<option value='Medellin'>Medellín</option>
<option value="Bucaramanga">Bucaramanga</option>
<option value="Cali">Cali</option>
<option value="Bogota">Bogotá</option>
</Select>
</div>
</section>
</div>
</section>
</div>
<button type="submit" class="btn btn-success mt-4">Guardar</button>
</form>
</div>
Thanks for help, the error come from because I call from name on the controller and in this input only have ID, and in the validation for this field have 'required';
I don't know how reply comments, but thanks aynber and Daniel L, you were nice help
First time Comment your validation section and try again. If your data successfully inserted. Then Your need to modify your required field like below.
Replace
['required','min:6']
Like this:
'required|min:6',

Form with enctype return null file in request

I tried to edit the products in my store. On request, missing $request->file('image');
I'm attaching the source code below, I really don't know why I don't receive the image in the request, because I think it's correct what I did
My form :
<form method="POST" action="{{ route('products.update', $product->id)}}" enctype="multipart/form-data">
#csrf
#method('PATCH')
<div class="row">
<div class="col">
<div class="form-group">
<label for="exampleFormControlInput1">Product slug</label>
<input type="text" name="product_slug" value="{{$product->product_slug}}" class="form-control" id="exampleFormControlInput1" placeholder="Enter slug">
</div>
</div>
<div class="col">
<div class="form-group">
<label for="exampleFormControlInput111">Product title</label>
<input type="text" name="product_title" value="{{$product->product_title}}" class="form-control" id="exampleFormControlInput111" placeholder="Enter slug">
</div>
</div>
</div>
<div class="row">
<div class="col">
<div class="form-group">
<label for="exampleFormControlInput2">Product category</label>
<input type="text" name="product_category" value="{{$product->product_category}}" class="form-control" id="exampleFormControlInput2" placeholder="name#example.com">
</div>
</div>
<div class="col">
<div class="form-group">
<label for="exampleFormControlInput3">Product brand</label>
<input type="text" name="product_brand" value="{{$product->product_brand}}" class="form-control" id="exampleFormControlInput3" placeholder="name#example.com">
</div>
</div>
</div>
<div class="row">
<div class="col">
<div class="form-group">
<label for="exampleFormControlInput22">Product display</label>
<input type="text" name="product_display" value="{{$product->product_display}}" class="form-control" id="exampleFormControlInput22" placeholder="name#example.com">
</div>
</div>
<div class="col">
<div class="form-group">
<label for="exampleFormControlInput34">Product ram</label>
<input type="text" name="product_ram" value="{{$product->product_ram}}" class="form-control" id="exampleFormControlInput34" placeholder="name#example.com">
</div>
</div>
</div>
<div class="row">
<div class="col">
<div class="form-group">
<label for="exampleFormControlInput33">Product os</label>
<input type="text" name="product_os" value="{{$product->product_os}}" class="form-control" id="exampleFormControlInput33" placeholder="name#example.com">
</div>
</div>
<div class="col">
<div class="form-group">
<label for="exampleFormControlInput333">Product camera</label>
<input type="text" name="product_camera" value="{{$product->product_camera}}" class="form-control" id="exampleFormControlInput333" placeholder="name#example.com">
</div>
</div>
</div>
<div class="row">
<div class="col">
<div class="form-group">
<label for="exampleFormControlInput8">Product price</label>
<input type="text" name="product_price" value="{{$product->product_price}}" class="form-control" id="exampleFormControlInput8" placeholder="name#example.com">
</div>
</div>
<div class="col">
<div class="form-group">
<label for="exampleFormControlFile1">Change product photo</label>
<input type="file" name="image" value="{{$product->product_image}}" class="form-control-file" id="exampleFormControlFile1">
<img src="/storage/img/tech/{{$product->product_image}}" style="width:300px" alt="product_image">
</div>
</div>
</div>
<div class="form-group">
<label for="short_description">Short description</label>
<textarea class="form-control" name="about_product" id="short_description" rows="10">{{$product->about_product}}</textarea>
</div>
<div class="form-group">
<label for="long_description">Long description</label>
<textarea class="form-control" name="product_description" id="long_description" rows="10">{{$product->product_description}}</textarea>
</div>
<input type="submit" value="Edit" class="btn btn-success" name="submit">
Go back
</form>
If I remove the part with the image, the code is perfectly functional
My function in controller(type resource)
public function update(Request $request, $id)
{
dd($request->all());
$request->validate([
'product_slug' => 'required|max:100',
'product_title' => 'required|max:100',
'product_category' => 'required|max:100',
'product_brand' => 'required|max:100',
'product_image' => 'image|mimes:jpeg,png,jpg,gif,svg|max:2048',
'product_display' => 'required',
'product_camera' => 'required',
'product_ram' => 'required',
'product_os' => 'required',
'product_price' => 'required|max:100',
'about_product' => 'required',
'product_description' => 'required'
]);
$input = $request->all();
if ($image = $request->file('image')) {
$destinationPath = 'storage/img/tech/';
$profileImage = $image->getClientOriginalName();
$image->move($destinationPath, $profileImage);
$input['image'] = $profileImage;
} else {
unset($input['image']);
}
$product = Product::find($id);
$product->product_slug = $request->get('product_slug');
$product->product_title = $request->get('product_title');
$product->product_category = $request->get('product_category');
$product->product_brand = $request->get('product_brand');
$product->product_display = $request->get('product_display');
$product->product_ram = $request->get('product_ram');
$product->product_camera = $request->get('product_camera');
$product->product_os = $request->get('product_os');
$product->product_price = $request->get('product_price');
$product->product_image = $profileImage;
$product->about_product = $request->get('about_product');
$product->product_description = $request->get('product_description');
$product->update();
return redirect('/admin/products')->with('success', "product updated!");
}
The core issue here is that value="{{ $product-> product_image }}" is not valid. <input type="file"> doesn't support that, as the image needs to be directly uploaded from the User's machine, and unless a file is selected and uploaded, $request->file('image') will be null.
To handle this cleaner, use some conditional logic in the Controller:
First, upload the image and set a reference to the file:
$profileImage = null;
if ($image = $request->file('image')) {
$destinationPath = 'storage/img/tech/';
$profileImage = $image->getClientOriginalName();
$image->move($destinationPath, $profileImage);
}
Next, set the $product->product_image based on the value of $profileImage:
$product = Product::find($id);
...
if ($profileImage)
$product->product_image = $profileImage;
}
A ternary or null-coalesce statement can be used, but it'll look a bit weird:
$product->product_image = $profileImage ? $profileImage : $product->product_image;
// OR
$product->product_image = $profileImage ?? $product->product_image;
Both of these cases will set $product->product_image to $profileImage, or the existing value of $product->profile_image if nothing is provided (that will be an existing image or null)

Show duplicate entry warning in laravel

how to display duplicate entry warning error to my view in laravel blade. so when they key in same name the warning will appear when they saved it.
Note: i have already make my Schema $table->string('studentname')->unique();;
Controller
public function store(Request $request)
{
$this->validate($request, [
'studentname'=>'required|max:50',
]);
$students = new Student();
$students->studentname = $request->studentname;
$students->address = $request->address;
$students->religion = $request->religion;
$students->save();
return redirect()->route('students.index')
->with('flash_message', 'Success.');
}
View-Blade
<div class="container">
<h1 class="well">Registration Form</h1>
<div class="col-lg-12 well">
<div class="row">
<form action="{{route('students.store')}}" method="POST">
{{csrf_field()}}
<div class="col-sm-12">
<h3>CHILD'S INFORMATION</h3>
<hr>
<div class="row">
<div class="col-sm-4 form-group">
<label>FULLNAME</label>
<input type="text" name="studentname" value="" placeholder="Enter FULLNAME.." class="form-control" required>
</div>
<div class="col-sm-4 form-group">
<label>RELIGION</label>
<input type="text" name="religion" value="" placeholder="Enter RELIGION.." class="form-control">
</div>
<div class="col-sm-4 form-group">
<label>ADDRESS</label>
<input type="text" name="address" value="" placeholder="Enter ADDRESS.." class="form-control">
</div>
<div>
<button type="submit" class="btn btn-default">SUBMIT</button>
</div>
</div>
</div>
</div>
Add the unique validation which returns a message if it fails.
$this->validate($request, [
'studentname'=>'required|max:50|unique:table_name,studentname',
]);
And then, in your blade template, do this.
<div class="col-sm-4 form-group {{ $errors->get('studentname') ? 'has-error' : '' }}">
<label>FULLNAME</label>
<input type="text" name="studentname" value="" placeholder="Enter FULLNAME.." class="form-control" required>
#foreach($errors->get('studentname') as $error)
<span class="help-block">{{ $error }}</span>
#endforeach
</div>

Upload photo in project and db - Laravel

I need some help with upload. I want to insert a product into the db. The product has 3 pictures. I want the picture to be uploaded into a specific folder in the project, and the path to be entered into the db.
The folder where I want to upload the photos is: /public/css/img
My Db looks like this: I will put an example added manually in db.
id | title |price|category_id| images1 | images2| | images3| etc.
1 |Sofa |324.0 5 |/css/img/1.jpg |/css/img/2.jpg |/css/img/3.jpg
This is my view addProductModal.blade.php -> Is a modal with form.
<div class="modal fade" id="modalFormaddproduct" role="dialog">
<div class="modal-dialog" id="route">
<div class="modal-content">
<!-- Modal Header -->
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">
<span aria-hidden="true">×</span>
<span class="sr-only">Inchide</span>
</button>
<h4 class="modal-title" id="myModalLabel">Adauga Subcategorie</h4>
</div>
<!-- Modal Body -->
<div class="modal-body" style="text-align: center;">
<p class="statusMsg"></p>
<form role="form" action="{{route('addproduct')}}" method="post">
{{csrf_field()}}
<div class="row">
<div class="col-sm-6">
<div class="form-group">
<label>Nume</label>
<input type="text" class="form-control text-center" name="name" placeholder="">
</div>
</div>
<div class="col-sm-6">
<div class="form-group">
<label>Pret</label>
<input type="text" class="form-control text-center" name="price" placeholder="">
</div>
</div>
</div>
<!-- /.row -->
<div class="col-sm-6">
<div class="form-group">
<label>Subcategoria:</label>
<select style="text-align-last:center" class="form-control text-center" name="category_id">
#foreach($categories as $category)
#foreach($category->subcategories as $subcategory)
<option value="{{$subcategory->id}}">{{$subcategory->category}}</option>
#endforeach
#endforeach
</select>
</div>
</div>
<div class="row">
<div class="col-sm-6">
<div class="form-group">
<label>Descriere</label>
<input type="text" class="form-control text-center" name="description" placeholder="">
</div>
</div>
<div class="col-sm-6">
<div class="form-group">
<label>Marime</label>
<input type="text" class="form-control text-center" name="size" placeholder="">
</div>
</div>
<div class="col-sm-6">
<div class="form-group">
<label>Material</label>
<input type="text" class="form-control text-center" name="material" placeholder="">
</div>
</div>
<div class="col-sm-6">
<div class="form-group">
<label>Cantitate</label>
<input type="text" class="form-control text-center" name="quantity" placeholder="">
</div>
</div>
<div class="col-sm-6">
<div class="form-group">
<label>Recomandat:</label>
<select style="text-align-last:center" class="form-control text-center" name="hot">
<option value="0">Nerecomandat</option>
<option value="1">Recomandat</option>
</select>
</div>
</div>
<div class="row">
<div class="col-sm-4">
<div class="form-group">
<label>Imagine 1:</label>
<input type="file" name="file1" id="file1">
<input type="submit" value="Upload1" name="submit1">
<input type="hidden" value="{{ csrf_token() }}" name="_token">
</div>
</div>
<div class="col-sm-4">
<div class="form-group">
<label>Imagine 2:</label>
<input type="file" name="file2" id="file2">
<input type="submit" value="Upload2" name="submit2">
<input type="hidden" value="{{ csrf_token() }}" name="_token">
</div>
</div>
<div class="col-sm-4">
<div class="form-group">
<label>Imagine 3:</label>
<input type="file" name="file3" id="file3">
<input type="submit" value="Upload3" name="submit3">
<input type="hidden" value="{{ csrf_token() }}" name="_token">
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" style="background: gainsboro; border-radius: 8px" class="btn btn-default" data-dismiss="modal">Inchide</button>
<button type="submit" style="background: #10D47D; border-radius: 8px" class="btn btn-primary">Adauga</button>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
Route is Route::post('/products/add', 'AdminController#addproduct')->name('addproduct');
Controller: AdminController.php
public function addproduct(Request $request)
{
$product = new Product();
$product->title = $request->name;
$product->price = $request->price;
$product->category_id = $request->category_id;
$product->description = $request->description;
$product->size = $request->size;
$product->material = $request->material;
$product->quantity = $request->quantity;
$product->hot = $request->hot;
$product->images1 = $request->file1;
$product->images2 = $request->file2;
$product->images3 = $request->file3;
if (Input::hasFile('file1','file2','file3')) {
echo 'Uploaded';
$file = Input::file('file1','file2','file3');
$file->move('uploads', $file->getClientOriginalName());
echo '';
}
$product->save();
return redirect(route('adminproducts'))->with('success', 'The Product was added');
}
You should add into your form:
enctype="multipart/form-data"
to make sure you can upload a file like so:
<form role="form" action="{{route('addproduct')}}" method="post" enctype="multipart/form-data">
I do not think there is any reason not to use some maintained library but write all the functionality yourself. I would recommend you to take a look on: https://github.com/spatie/laravel-medialibrary
I found the solution.
public function addproduct(Request $request)
{
$product = new Product();
$product->title = $request->name;
$product->price = $request->price;
$product->category_id = $request->category_id;
$product->description = $request->description;
$product->size = $request->size;
$product->material = $request->material;
$product->quantity = $request->quantity;
$product->hot = $request->hot;
$file1 = Input::file('file1');
$file2 = Input::file('file2');
$file3 = Input::file('file3');
$filename1 = $file1->getClientOriginalName();
$filename2 = $file2->getClientOriginalName();
$filename3 = $file3->getClientOriginalName();
$file1 = $file1->move(public_path().'/img', $filename1);
$file2 = $file2->move(public_path().'/img', $filename2);
$file3 = $file3->move(public_path().'/img', $filename3);
$product->images1 = '/img/'.$filename1;
$product->images2 = '/img/'.$filename2;
$product->images3 = '/img/'.$filename3;
$product->save();
return redirect(route('adminproducts'))->with('success', 'Produsul a fost creat');
}

Populate ng-model - Value not working AngularJS

I have an AngularJS front end for a new internal web portal I am building. Using value={{data.Param}} I have successfully gotten my get and create requests to work via Slim PHP. Now however I am trying to create a PUT request and I am running into an issue.
This is the current code for my "Update /PUT" page.
request-edit.html
<div class="jumbotron text-center">
<form class="form-horizontal" role="form">
<div class="form-group">
<div class="text-center">
<h1>{{ header }}</h1>
<br/>
<h3>{{ request.Header }}</h3>
<br/>
</div>
</div>
<div class="form-group">
<label class="col-sm-3 control-label">Id:</label>
<div class="col-sm-3">
<input name="id" class="form-control" type="text" value="{{request.ID}}" disabled />
</div>
<label class="col-sm-3 control-label">Date:</label>
<div class="col-sm-3">
<input type="text" class="form-control" value="{{ request.Date_Submitted }}" disabled/>
</div>
</div>
<div class="form-group">
<label class="col-sm-3 control-label">Change Initiator:</label>
<div class="col-sm-3">
<input type="text" class="form-control" placeholder="{{request.Change_Initiator}}" ng-model="request.changeInitiator"/>
</div>
<label class="col-sm-3 control-label">Risk Level:</label>
<div class="col-sm-3">
<input type="text" class="form-control" placeholder="{{ request.Risk_Level }}" ng-model="request.riskLevel" />
</div>
</div>
<div class="form-group">
<label class="col-sm-3 control-label">CI Details:</label>
<div class="col-sm-3">
<input type="text" class="form-control" placeholder="{{ request.Change_Initiator_id }}" ng-model="request.changeInitiatorId" />
</div>
</div>
<div class="form-group">
<label class="col-sm-3 control-label">Requestor:</label>
<div class="col-sm-3">
<input type="text" class="form-control" placeholder="{{ request.Requestor }}" ng-model="request.requestor" />
</div>
<label class="col-sm-3 control-label">Systems Affected:</label>
<div class="col-sm-3">
<input type="text" class="form-control" placeholder="{{ request.Systems_Affected }}" ng-model="request.systemsAffected" />
</div>
</div>
<div class="form-group">
<label class="col-sm-3 control-label">Implemented By:</label>
<div class="col-sm-3">
<input type="text" class="form-control" placeholder="{{ request.Implemented_By }}" ng-model="request.implementationBy" />
</div>
<label class="col-sm-3 control-label">Implementation Date:</label>
<div class="col-sm-3">
<input type="text" class="form-control" placeholder="{{ request.Implementation_Date }}" ng-model="request.implementationDate" bs-datepicker/>
</div>
</div>
<div class="form-group">
<label class="col-sm-3 control-label">Close Date:</label>
<div class="col-sm-3">
<input type="text" class="form-control" placeholder="{{ request.Close_Date }}" ng-model="request.closeDate" />
</div>
</div>
<div class="form-group">
<label class="col-sm-3 control-label">Work to be Performed:</label>
<div class="col-sm-3">
<textarea name="request.description" ng-model="request.workToBePerformed" placeholder="{{ request.Work_to_be_performed }}" ></textarea>
</div>
<label class="col-sm-3 control-label">Backout Plan:</label>
<div class="col-sm-3">
<textarea name="request.description" ng-model="request.backoutPlan" placeholder="{{ request.Backout_Plan }}" ></textarea>
</div>
</div>
<div class="form-group">
<button class="update" ng:click="updateRequest()">Save Edits</button>
<button class="approve" ng:click="approveRequest()">Approve</button>
</div>
</form>
<div class="form-group">
<a href="#/requests" class="btn btn-default pull-right">
<span class="glyphicon glyphicon-arrow-left"></span> Back
</a>
</div>
</div>
My confusion in with ng-model, value and placeholders. Currently all my data populates in the form, but when the user goes to update the page they have to re-fill out every box or else blank data will be pushed. I understand the Placeholder does not actually fill in the data - however I have been un-able to use both ng-model and value on the same input field.
My top two fields populate using value just fine, but I do not want people to edit the date or ID. My other fields show the correct data in a temp form using placeholder but do not populate using ng-model. Additionally when my user goes to make the update the ng-model DOES function.
So in short my current issue is that ng-model does not display the original data- but does push it correctly. This causes my users to have to re-type all the data everytime or else the record will be updated with null values.
Below is the rest of my logic for review.
app.js
var app = angular.module('changeControlApp', [
'ngRoute',
'ngResource'
]);
//This configures the routes and associates each route with a view and a controller
app.config(function($routeProvider, $locationProvider) {
//$locationProvider.html5Mode(true);
$routeProvider
.when('/', {templateUrl: 'app/partials/request-list.html', controller: 'viewController' })
.when('/requests', {templateUrl: 'app/partials/request-list.html', controller: 'viewController' })
.when('/requests/create', {templateUrl: 'app/partials/request-create.html', controller: 'createRequestController' })
.when('/settings', {templateUrl: 'app/partials/settings.html', controller: 'settingsController'})
.when('/requests/:id', {templateUrl: 'app/partials/request-view.html', controller: 'viewRequestController' })
.when('/requests/edit/:id', {templateUrl: 'app/partials/request-edit.html', controller: 'editRequestController' })
.otherwise({ redirectTo: '/' });
});
app.controller('editRequestController', function($scope, $location, $route, $routeParams, $resource) {
$scope.header = 'Edit Change Request';
// Update User details
var request_Id = $routeParams.id;
if (request_Id) {
var Request = $resource(('http://pdgrosit02v/changeRequest/app/api/requests/'+ request_Id));
$scope.request = Request.get();
}
$scope.updateRequest = function() {
var RequestPut = $resource(('http://pdgrosit02v/changeRequest/app/api/requests/'+ request_Id), {}, { update: { method: 'PUT'}} );
RequestPut.update($scope.request, function() {
// success
$location.path('/requests');
}, function() {
// error
console.log(error);
});
}
});
And the Slim file
index.php
<?php
require 'Slim/Slim.php';
\Slim\Slim::registerAutoloader();
use Slim\Slim;
$app = new Slim();
//$paramValue = $app->request->params('paramName');
$app->get('/requests', 'getRequests');
$app->get('/requests/:id', 'getRequest');
$app->post('/requests/create', 'addRequest');
$app->put('/requests/:id', 'updateRequest');
$app->run();
function updateRequest($id) {
$request = Slim::getInstance()->request()->getBody();
$data = json_decode($request, true);
$sql = "UPDATE change_request SET Change_Initiator=:changeInitiator, Change_Initiator_id=:changeInitiatorId, Risk_Level=:riskLevel, Requestor=:requestor, Work_to_be_performed=:workToBePerformed, Backout_Plan=:backoutPlan, Backout_Time=:backoutTime, Implementation_Date=:implementationDate, Header=:title, Systems_Affected=:systemsAffected, Implemented_By=:implementationBy WHERE ID=$id";
//$sql = "UPDATE change_request SET Change_Initiator=:changeInitiator WHERE ID=$id";
try {
$db = getConnection();
$stmt = $db->prepare($sql);
$stmt->bindValue(":changeInitiator", $data['changeInitiator']);
$stmt->bindParam(":changeInitiatorId", $data['changeInitiatorId']);
$stmt->bindParam(":riskLevel", $data['riskLevel']);
$stmt->bindParam(":requestor", $data['requestor']);
$stmt->bindParam(":workToBePerformed", $data['workToBePerformed']);
$stmt->bindParam(":backoutPlan", $data['backoutPlan']);
$stmt->bindParam(":backoutTime", $data['backoutTime']);
$stmt->bindParam(":implementationDate", $data['implementationDate']);
$stmt->bindParam(":title", $data['title']);
$stmt->bindParam(":systemsAffected", $data['systemsAffected']);
$stmt->bindParam(":implementationBy", $data['implementationBy']);
$stmt->execute();
$db = null;
echo json_encode($data);
} catch(PDOException $e) {
echo '{"error":{"text":'. $e->getMessage() .'}}';
}
}
I figured out the issue, turns out Value and ng-model conflict and I had to modify my form to get the data correctly.
I removed all value commands and replaced them with ng-model="data.keyvalue". I was confused before as I thought you needed to use {{}} when referencing things off the scope.
I also added form validation for updating - new code below
request-edit.html
<div class="jumbotron text-center">
<form class="form-horizontal" role="form" name="requestEditForm" ng-submit="updateRequest()">
<div class="form-group">
<div class="text-center">
<h1>{{ header }}</h1>
<br/>
<h3>Title of request:</h3>
<input name="title" id="title" class="form-control" type="text" ng-model="request.Header" />
<br/>
</div>
</div>
<div class="form-group">
<label class="col-sm-3 control-label">Id:</label>
<div class="col-sm-3">
<input name="id" class="form-control" type="text" value="{{request.ID}}" disabled />
</div>
<label class="col-sm-3 control-label">Date Submitted:</label>
<div class="col-sm-3">
<input type="text" class="form-control" value="{{ request.Date_Submitted }}" disabled/>
</div>
</div>
<div class="form-group">
<label class="col-sm-3 control-label">Change Initiator:</label>
<div class="col-sm-3">
<input type="text" class="form-control" ng-model="request.Change_Initiator" name="changeInitiator" id="changeInitiator" />
<span class="error" ng-show="requestEditForm.changeInitiator.$error.required && requestEditForm.changeInitiator.$dirty">Title is required</span>
</div>
<label class="col-sm-3 control-label">Risk Level:</label>
<div class="col-sm-3">
<input type="text" class="form-control" ng-model="request.Risk_Level" name="riskLevel" id="riskLevel" required/>
<span class="error" ng-show="requestEditForm.riskLevel.$error.required && requestEditForm.riskLevel.$dirty">Risk Level is required</span>
</div>
</div>
<div class="form-group">
<label class="col-sm-3 control-label">CI Details:</label>
<div class="col-sm-3">
<input type="text" class="form-control" ng-model="request.Change_Initiator_id" />
</div>
</div>
<div class="form-group">
<label class="col-sm-3 control-label">Requestor:</label>
<div class="col-sm-3">
<input type="text" class="form-control" ng-model="request.Requestor" />
</div>
<label class="col-sm-3 control-label">Systems Affected:</label>
<div class="col-sm-3">
<input type="text" class="form-control" ng-model="request.Systems_Affected" />
</div>
</div>
<div class="form-group">
<label class="col-sm-3 control-label">Implemented By:</label>
<div class="col-sm-3">
<input type="text" class="form-control" ng-model="request.Implemented_By" />
</div>
<label class="col-sm-3 control-label">Implementation Date:</label>
<div class="col-sm-3">
<input type="text" class="form-control" ng-model="request.Implementation_Date" bs-datepicker/>
</div>
</div>
<div class="form-group">
<label class="col-sm-3 control-label">Close Date:</label>
<div class="col-sm-3">
<input type="text" class="form-control" ng-model="request.Close_Date" />
</div>
</div>
<div class="form-group">
<label class="col-sm-3 control-label">Work to be Performed:</label>
<div class="col-sm-3">
<textarea name="request.description" ng-model="request.Work_to_be_performed"></textarea>
</div>
<label class="col-sm-3 control-label">Backout Plan:</label>
<div class="col-sm-3">
<textarea name="request.description" ng-model="request.Backout_Plan"></textarea>
</div>
</div>
<div class="form-group">
<button class="submit">Save Edits</button>
<button class="approve" ng:click="approveRequest()">Approve</button>
</div>
</form>
<div class="form-group">
<a href="#/requests" class="btn btn-default pull-right">
<span class="glyphicon glyphicon-arrow-left"></span> Back
</a>
</div>
</div>

Categories