No route found when I set a parameter - php

I'm developing an app with Symfony 4 but I'm having a little problem here.
I made a controller with a required parameter but when I to follow the route I get this message:
Here's the code of is my html file:
{% extends 'base.html.twig' %}
{% block title %}Registro Madre{% endblock %}
{% block body %}
<div class="container">
<h1>Ingrese los datos de la madre</h1>
<form action="/insertMadre" method="POST">
<div class="row">
<div class="col-sm-6">
<div class="form-group">
<label for="nombre">Nombres:</label>
<input type="text" name="nombre" class="form-control" id="nombre" required>
</div>
</div>
<div class="col-sm-6">
<div class="form-group">
<label for="apellido">Apellidos:</label>
<input type="text" name="apellido" class="form-control" id="apellido" required>
</div>
</div>
</div>
<div class="row">
<div class="col-sm-2">
<div class="form-group">
<label for="nacimiento">Fecha de nacimiento</label>
<input type="date" name="nacimiento" id="nacimiento" class="form-control" required>
</div>
</div>
<div class="col-sm-4">
<div class="form-group">
<label for="nacionalidad">Nacionalidad</label>
<input type="text" name="nacionalidad" id="nacionalidad" class="form-control" required>
</div>
</div>
<div class="col-sm-3">
<div class="form-group">
<label for="contacto">Teléfono de Contacto</label>
<input type="tel" name="contacto" id="contacto" class="form-control" required>
</div>
</div>
<div class="col-sm-3">
<div class="form-group">
<label for="dui">DUI (sin guiones)/No. Pasaporte</label>
<input type="text" name="dui" id="dui" class="form-control">
</div>
</div>
</div>
<div class="row">
<div class="col-sm-6">
<div class="form-group">
<label for="direccion">Dirección:</label>
<input type="text" name="direccion" id="direccion" class="form-control" required>
</div>
</div>
<div class="col-sm-3">
<div class="form-group">
<label for="departamento">Departamento:</label>
<select name="departamento" id="departamento" class="form-control" required>
<option value="">Seleccione una opción..</option>
{% for departamento in departamentos %}
<option value="{{ departamento.id }}">{{ departamento.depname }}</option>
{% endfor %}
</select>
</div>
</div>
<div class="col-sm-3">
<div class="form-group">
<label for="municipio">Municipio:</label>
<select name="municipio" id="municipio" class="form-control" required>
<option value="">Seleccione una opción..</option>
</select>
</div>
</div>
</div>
<legend>Datos Clínicos</legend>
<div id="datos-clinicos">
<div class="row">
<div class="col-sm-2">
<span class="datos-clinicos-text">Fórmula Obstétrica</span>
</div>
<div class="col-sm-1">
<span class="datos-clinicos-text">G</span>
</div>
<div class="col-sm-1">
<input type="number" class="form-control" min="0" step="1" value="0" name="formG" id="formG">
</div>
<div class="col-sm-1">
<span class="datos-clinicos-text">P</span>
</div>
<div class="col-sm-1">
<input type="number" class="form-control" min="0" step="1" value="0" name="formP" id="formP">
</div>
<div class="col-sm-1">
<span class="datos-clinicos-text">P</span>
</div>
<div class="col-sm-1">
<input type="number" class="form-control" min="0" step="1" value="0" name="formP1" id="formP1">
</div>
<div class="col-sm-1">
<span class="datos-clinicos-text">A</span>
</div>
<div class="col-sm-1">
<input type="number" class="form-control" min="0" step="1" value="0" name="formA" id="formA">
</div>
<div class="col-sm-1">
<span class="datos-clinicos-text">V</span>
</div>
<div class="col-sm-1">
<input type="number" class="form-control" min="0" step="1" value="0" name="formV" id="formV">
</div>
</div>
</div>
<div class="row">
<div class="col-sm-6">
<div class="form-group">
<label for="enfermedadMedica">Enfermedades médicas que afecten el desarrollo del embarazo</label>
<select name="enfermedadMedica" id="enfermedadMedica" class="form-control">
<option value="0">Elija una opción</option>
</select>
</div>
</div>
<div class="col-sm-6">
<div class="form-group">
<label for="enfermedadExantematica">Enfermedad exantemática durante el embarazo</label>
<select name="enfermedadExantematica" id="enfermedadExantematica" class="form-control">
<option value="0">Elija una opción</option>
</select>
</div>
</div>
</div>
<div class="row">
<div class="col-sm-12">
<div class="form-group">
<label for="informacionExtra">Otra Información</label>
<textarea name="informacionExtra" id="informacionExtra" class="form-control" rows="5" style="resize:none"></textarea>
</div>
</div>
</div>
<div class="row">
<div class="col-sm-12 text-right">
<input type="submit" value="Registrar" class="btn-site">
</div>
</div>
</form>
</div>
{% endblock %}
Here's my controller:
namespace App\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\Routing\Annotation\Route;
use App\Entity\Madre;
use App\Entity\DatosClinicosMadre;
use App\Entity\ProductoObstetrico;
use App\Entity\CondicionProducto;
class ProductoController extends AbstractController
{
public function registro($id)
{
$madre = $this->getDoctrine()->getRepository(Madre::class)->find($id);
return $this->render('producto/register.html.twig');
}
}
And here's my route:
registro-producto:
path: /ingresar-producto/{id}
name_prefix: nuevoProducto
controller: App\Controller\ProductoController::registro
If I don't send a parameter I don't have any problems but when I want to send an ID it comes the issue, and if I set the route with a parameter and I don't send a parameter I get an error telling me that I must have to send a parameter. I don't know what's going on...
UPDATE
This is what I get when I run php bin/console debug:router
Thank you all!

This is because you haven't declared the param type.
Try amending your routes file to this:
registro-producto:
path: /ingresar-producto/{id}
name_prefix: nuevoProducto
controller: App\Controller\ProductoController::registro
requirements:
id: \d+
Doing this will set the {id} type to digit, allowing the /3 param.
See here:
Taken from Symfony Docs:
Adding {wildcard} Requirements
Imagine the blog_list route will contain a paginated list of blog posts, with URLs like /blog/2 and /blog/3 for pages 2 and 3. If you change the route's path to /blog/{page}, you'll have a problem:
blog_list: /blog/{page} will match /blog/*;
blog_show: /blog/{slug} will also match /blog/*.
When two routes match the same URL, the first route that's loaded wins. Unfortunately, that means that /blog/yay-routing will match the blog_list. No good!
To fix this, add a requirement that the {page} wildcard can only match numbers (digits)
ref: https://symfony.com/doc/current/routing.html

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',

Can't get input values with enctype="multipart/form-data"

I'm working with Forms on Laravel, and I'm still learning. I thought I had it all figured out already, but I've been alted by an issue:
When I have enctype="multipart/form-data", I can't get the input values. The file I upload still gets uploaded to the disk, but the rest of the values are not printed. If I remove enctype="multipart/form-data", I do get the values.
Form:
<form id="forms" method="POST" action="alteracaocomissao" enctype="multipart/form-data">
{{ csrf_field() }}
<div class="form-row">
<div class="form-group col-md-6">
<label for="nomeentidade">Nome:</label>
<input type="text" class="form-control" id="nome1" name="nome1" placeholder="Nome entidade" required>
</div>
<div class="form-group col-md-6">
<label for="numentidade">Nº:</label>
<input type="text" class="form-control" id="num1" name="num1" placeholder="Número" required>
</div>
</div>
<div class="form-row">
<div class="form-group col-md-6 mb-3">
<label for="conta">Conta:</label>
<input type="text" class="form-control" id="conta" name="conta" placeholder="Conta" required>
</div>
<div class="form-group col-md-3 mb-3">
<label for="balcao">Local:</label>
<select class="form-control" id="local1" name="local1" required>
<option value="">Escolher...</option>
<option value="1">Local</option>
<option value="2">Local1</option>
</select>
</div>
<div class="form-group col-md-3 mb-3">
<label for="atleracao">Tipo de alteração:</label>
<select class="form-control" id="alteracao" name="alteracao" required>
<option value="">Escolher...</option>
<option value="1">Alterar1</option>
<option value="2">Alterar2</option>
</select>
</div>
</div>
<hr>
<div class="form-row" id="buildyourform">
<div class="form-group col-md-4">
<label for="comissao">TEST:</label>
<select class="form-control" id="TEST1" name="TEST1" required>
<option value="">Escolher...</option>
<option value="1">TEST</option>
<option value="2">TEST1</option>
</select>
</div>
<div class="form-group col-md-2">
<label for="desconto">Desconto solicitado:</label>
<div class="input-group">
<input type="text" class="form-control" id="desconto" name="desconto" placeholder="Número" required>
<span class=input-group-addon>%</span>
</div>
</div>
<div class="form-group col-md-2">
<label for="add"> &nbsp </label>
<input type="button" value="Adicionar campos" class="form-control btn btn-light" id="add" />
</div>
<div class="form-group col-md-1" id="2field">
<label for="remove"> &nbsp </label>
<input type="button" value="Remover" class="form-control btn btn-light" id="remove" />
</div>
<div class="form-group col-md-2">
</div>
</div>
<hr>
<div class="form-row">
<div class="form-group col-md-12">
<label for="fundamentacao">Fundamentação:</label>
<textarea type="text" class="form-control" id="fundamentacao" name="fundamentacao" placeholder="Fundamentação do pedido" required></textarea>
</div>
</div>
<div class="form-row">
<div class="form-group col-md-2">
<label for="file2">Anexo:</label>
<input type="file" name="file2" id="file2" required>
</div>
</div>
<hr>
<button type="submit" class="btn btn-primary">Enviar</button>
</form>
Controller:
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class PostController extends Controller
{
public function AltComiss(Request $request)
{
session_start();
$array1 = $request -> all();
$path = $request->file('file2')->store('altComiss');
$arrayRm1 = array_shift($array1);
$_SESSION["testPostSection1"] = $array1;
return redirect('alteracaocomissao');
}
}
Route:
Route::post('alteracaocomissao', 'PostController#AltComiss');
Testing code:
#php
session_start();
if (isset($_SESSION["testPostSection1"])) {
echo '<pre>'; print_r($_SESSION["testPostSection1"]); echo '</pre>';
}
#endphp
I do have SESSION there to test if the values are getting saved, because I still havn't set up the database, and until I do I'm using SESSION to test. Obviously once I set the database up I will switch from SESSION to inserting the values into the database.
Thanks in advance!
I think it's will help you
use Illuminate\Http\Request;
//use these For Start your session and Store file
use Illuminate\Support\Facades\Session;
use Illuminate\Support\Facades\Storage;
class PostController extends Controller{
public function AltComiss(Request $request){
$array1 = $request->all();
if ($request->hasFile('file2')) {
$file = $request->file('file2');
$destinationPath = 'altComiss';
$file->move($destinationPath,$file->getClientOriginalName());
}
$arrayRm1 = array_shift($array1);
Session::flash('allInput',$arrayRm1);
return redirect('alteracaocomissao');
}
}
On your view file for get the session data just use
#if (Session::has('allInput'))
<?php
echo '<pre>';
print_r(Session::get('allInput'));
echo '</pre>';
?>
#endif

create a shortcode of html form

I am trying to create a short code for html form. because I want to use this multiple time in my word-press page.
I have no idea how to do this . if any help please let help me
<form action="<?php echo get_page_link(2599) ?>" method="POST" >
<input type='hidden' name='page_id' value='2599'>
<div class="row">
<div class="form-group col-sm-3 col-md-2" id="bgform_text2">
<h4>SEARCH</h4>
<p>For Your Favourite Place</p>
</div>
<div class="form-group col-sm-5 col-md-2">
<label>Where to ? </label>
<input type="text" name="names" class="input-text full-width" placeholder="start typing here....">
</div>
<div class="form-group col-sm-5 col-md-4">
<div class="row">
<div class="col-xs-6">
<label>Arrive </label>
<div class="controls">
<input type="text" name="arive_time" id="departing">
</div>
</div>
<div class="col-xs-6">
<label>Departs </label>
<div class="controls">
<input type="text" name="depart_time" id="returning">
</div>
</div>
</div>
</div>
<div class="form-group col-sm-9 col-md-2">
<label>Sleeps </label>
<div class="controls">
<i class="fa fa-sort"></i>
<select name="sleeps">
<option value="" disabled="" selected=""></option>
<option value="1">1</option><option value="2">2</option><option value="3">3</option><option value="4">4</option><option value="5">5</option></option>
</select>
</div>
</div>
<div class="form-group col-sm-3 col-md-2">
<input type="submit" value="submit" name="submit_btn" class="button">
</div>
</div>
</form>
Try this.
<?php
function my_shortcode(){
$pagelink = get_page_link(2599);
return '<form action="'.$pagelink.'" method="POST" >
<input type="hidden" name="page_id" value="2599">
<div class="row">
<div class="form-group col-sm-3 col-md-2" id="bgform_text2">
<h4>SEARCH</h4>
<p>For Your Favourite Place</p>
</div>
<div class="form-group col-sm-5 col-md-2">
<label>Where to ? </label>
<input type="text" name="names" class="input-text full-width" placeholder="start typing here....">
</div>
<div class="form-group col-sm-5 col-md-4">
<div class="row">
<div class="col-xs-6">
<label>Arrive </label>
<div class="controls">
<input type="text" name="arive_time" id="departing">
</div>
</div>
<div class="col-xs-6">
<label>Departs </label>
<div class="controls">
<input type="text" name="depart_time" id="returning">
</div>
</div>
</div>
</div>
<div class="form-group col-sm-9 col-md-2">
<label>Sleeps </label>
<div class="controls">
<i class="fa fa-sort"></i>
<select name="sleeps">
<option value="" disabled="" selected=""></option>
<option value="1">1</option><option value="2">2</option><option value="3">3</option><option value="4">4</option><option value="5">5</option></option>
</select>
</div>
</div>
<div class="form-group col-sm-3 col-md-2">
<input type="submit" value="submit" name="submit_btn" class="button">
</div>
</div>
</form>';
}
add_shortcode('my_shortcode_name','my_shortcode');
?>
you can use this shortcode in your page
<?php echo do_shortcode('[my_shortcode_name]');?>
I think you are saying that you do not want to copy-paste the exact same code on multiple places inside your project, PHP has an include control structure method to take any file and use the contents on run-time.
Your code could eventually look something like this:
# form definition inside the main page that needs the form
<form action="<?php echo get_page_link(2599) ?>" method="POST" >
# include the template
<?php include('template.php') ?>
</form>
# template.php contains the html form
<input type='hidden' name='page_id' value='2599'>

Laravel submitting form gets page expired

So i have a very basic controller located at : app/Http/Controllers/RentalRequestController
namespace App\Http\Controllers;
use Illuminate\Routing\Controller as BaseController;
class RentalRequestController extends BaseController
{
public function store(Request $request, $obj)
{
$g = 0;
return view("success");
}
}
Then in my web.php i have the following:
Route::Post('/', 'RentalRequestController#store');
And then i have the following form in my view:
<form id="rentalForm" name="rentalForm" role="form" action="/" method="post">
<!-- Row -->
<div class="f-row">
<div class="form-group one-fourth">
<label for="address">Gade</label>
<input type="text" name="address" id="address"
data-parsley-required-message="Indtast venligst din gade" required
data-parsley-errors-container="#errAddress"/>
<div class="full-width">
<label id="errAddress"></label>
</div>
</div>
<div class="form-group one-fourth">
<label for="number">Husnummer</label>
<input type="number" name="number" id="number"
data-parsley-required-message="Indtast venligst dit husnummer" required=""
data-parsley-errors-container="#errNumber">
<div class="full-width" style="">
<label id="errNumber"></label>
</div>
</div>
<div class="form-group one-fourth">
<label for="zip">Postnr</label>
<input type="text" name="zip" id="zip" required=""
data-parsley-required-message="Indtast venligst dit postnr"
data-parsley-length-message="Indtast et dansk postnr"
data-parsley-length="[4,4]" data-parsley-zip="dk"
data-parsley-errors-container="#errZip">
<div class="full-width" style="">
<label id="errZip"></label>
</div>
</div>
<div class="form-group one-fourth">
<label for="city">By</label>
<input type="text" name="city" id="city" required=""
data-parsley-required-message="Indtast venligst din by"
data-parsley-errors-container="#errCity">
<div class="full-width" style="">
<label id="errCity"></label>
</div>
</div>
</div>
<!-- //Row -->
<!-- Row -->
<div class="f-row">
</div>
<!-- //Row -->
<div class="f-row">
<div class="form-group one-fourth">
<label for="kvm">kvadratmeter</label>
<input type="number" id="kvm" min="1" class="uniform-input number" name="kvm" required=""
data-parsley-required-message="Indtast venligst arealet på din bolig"
data-parsley-errors-container="#errKvm">
<div class="full-width" style="">
<label id="errKvm"></label>
</div>
</div>
<div class="form-group one-fourth">
<label for="price">Nuværende husleje</label>
<input type="number" id="price" name="price" step="0.01" required=""
data-parsley-required-message="Indtast venligst din nuværende husleje"
data-parsley-errors-container="#errPrice">
<div class="full-width" style="">
<label id="errPrice"></label>
</div>
</div>
<div class="form-group select one-fourth">
<label for="concatSelector">Vælg kontakt form</label>
<div class="selector">
<select id="concatSelector" required="" data-parsley-required-message="Indtast venligst din nuværende husleje">
<option selected="">Vælg kontakt form</option>
<option value="cell">Telefon</option>
<option value="mail">E-mail</option>
</select>
</div>
</div>
<div class="form-group one-fourth fadeIn" id="selectEmail">
<label for="email">Kontakt information</label>
<input type="email" id="email" name="email" placeholder="E-mail" required=""
data-parsley-type="email"
data-parsley-type-message="Indtast venligst en gyldig e-mail"
data-parsley-required-message="Indtast venligst en gyldig e-mail"
data-parsley-errors-container="#errEmail"
>
<div class="full-width" style="">
<label id="errEmail"></label>
</div>
</div>
<div class="form-group one-fourth fadeIn" id="selectCell">
<label for="mobile">Kontakt information</label>
<input type="number" id="mobile" name="phone" placeholder="Telefon" required=""
data-parsley-required-message="Indtast venligst et gyldig telefon nr."
data-parsley-errors-container="#errCell"
>
<div class="full-width" style="">
<label id="errCell"></label>
</div>
</div>
</div>
<div class="f-row">
<div class="form-group right one-fourth" style="margin-top: 35px">
<button type="button" onclick="sendInformation()" class="btn large black">Kan jeg spare penge?
</button>
</div>
</div>
Now when i submit the form it redirects me to a page saying:
The page has expired due to inactivity.
Please refresh and try again.
Can anyone tell me what ive done wrong?
You should add:
{{ csrf_field() }}
inside <form> element for example like this:
<form id="rentalForm" name="rentalForm" role="form" action="/" method="post">
{{ csrf_field() }}
This is called CSRF protection
<form id="rentalForm" name="rentalForm" role="form" action="/" method="post">
#csrf
<!-- do you awesome code here -->
</form>
if you do not use javascript to submit form just add #csrf below form tag

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