How to use post method via MVC - php

This is my view file called application.html.
I just started learning the Zend framework.
I have existing database table (mytable.sql), with three columns:
ID
APP_ID
APP_NAME
So now my goal is, I need create new app using post method and that new app name must be save in to database.
<form method="post" action="/admin/appmgt/createAction">
<p>
<label class="field" for="APP_ID"><span>*</span>APP_ID</label>
<input type="text" name="APP_ID" class="textbox-300" />
</p>
<p>
<label class="field" for="APP_NAME"><span>*</span>APP_NAME</label>
<input type="text" name="APP_NAME" class="textbox-300" />
</p>
<input type='submit' name='submit' value='Submit Form' />
</form>
This my controller file:
public function createAction() {
$this->view->form = $this->getForm();
if ($this->getRequest()->isPost()) {
if (!$this->view->form->isValid($_POST)) {
return $this->render('form');
}
}
}
This is my Model file:
public function createApp($APP_ID, $APP_NAME) {
$data = array(
'APP_ID' => $APP_ID,
'APP_NAME' => $$APP_NAME
);
$this->insert($data);
}
Could you please help me ?

Related

How to add correctly 2 items in this JSON? - Laravel

I must save x2 the same data fields (nif and name) at the same time in the DB.
With 1 field (nif) it works perfectly and save x2 rows in the DB with different info, so the JSON works, but adding the 2th field (name) it just save the nif value in all the fields.
I don't understand so much the JSON and his syntax logic, but I think the problem is how I wrote it in the controller.
P.D. No, I can't put EnviarCurriculumPreguntas::create x2 in a row because that's not the purpose of this code, so I'm using a JSON instead.
EnviarCurriculum.php
namespace App;
use Illuminate\Database\Eloquent\Model;
class EnviarCurriculum extends Model
{
protected $table = 'table';
protected $primaryKey = 'ID_table';
protected $fillable = [
'nif',
'name'
];
public function getRepeatedFields()
{
return json_decode($this->nif);
return json_decode($this->name);
}
}
EnviarCurriculumController.php
namespace App\Http\Controllers\enviarCurriculum;
use App\EnviarCurriculum;
use App\Configuracion;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
class EnviarCurriculumController extends Controller
{
public function index()
{
return view('enviar_curriculum', ['EnviarCurriculum' => new EnviarCurriculum()]);
}
public function create()
{
return view('enviar_curriculum', ['EnviarCurriculum' => new EnviarCurriculum()]);
}
public function store(Request $request)
{
foreach (request('nif', 'name') as $val) {
EnviarCurriculum::create(['nif' => $val, 'name' => $val]);
}
}
}
enviar_curriculum.blade.php
<!DOCTYPE html>
<html lang="es">
<head>
...
</head>
<body>
<form action="{{ route("store") }}" method="POST">
#csrf
<div>
<input type="text" name="nif[]" id="nif">
<input type="text" name="name[]" id="name">
</div>
<br>
<div>
<input type="text" name="nif[]" id="nif">
<input type="text" name="name[]" id="name">
</div>
<input type="submit" class="btn btn-primary" value="Enviar">
</form>
</body>
</html>
you can't have input having the same name without being an array
<!DOCTYPE html>
<html lang="es">
<head>
...
</head>
<body>
<form action="{{ route("store") }}" method="POST">
#csrf
<div>
<input type="text" name="nif[]" id="nif">
<input type="text" name="name[]" id="name">
</div>
<br>
<div>
<input type="text" name="nif[]" id="nif">
<input type="text" name="name[]" id="name">
</div>
<input type="submit" class="btn btn-primary" value="Enviar">
</form>
</body>
</html>
Then in your store method loop the array inputs
public function store(Request $request)
{
$nifs = $request->input('nif', []);
$names = $request->input('name', []);
foreach ($nifs as $key => $nif) {
EnviarCurriculum::create(['nif' => $nif, 'name' => $names[$key]??'']);
}
}
Then fix your getRepeatedFields() method to return both decoded fields.
public function getRepeatedFields()
{
return [
'nifs' => json_decode($this->nif),
'names' => json_decode($this->name),
];
}
<input type="text" name="nif[]" id="nif">
<input type="text" name="name[]" id="name">
in name , nif only store the last inserted item please change it as array

Unable to save data on Form POST Laravel app?

I am using PHP Laravel framework. I am trying to save a form after submission. Strangely first time it is not saving, but subsequently, it is saving. On the first post request, the flow isn't even entering function save_application
Code below.
My controller:
class ApplicationController extends Controller
{
/**
* Create a new controller instance.
*
* #return void
*/
public function __construct()
{
$this->middleware('auth',['except' => ['store_application']]);
}
/**
* Show the application dashboard.
*
* #return \Illuminate\Http\Response
*/
public function save_application(Request $request){
$user = Auth::user();
if(isset($request->application)){
$application = Application::where("user_id",$user->id)->first();
if($application){
$application->update($request->application);
}else{
$application = new Application;
$application = Application::create($request->application);
$application->user_id = $user->id;
$application->save();
}
}
return $this->store_application($request);
}
public function store_application(Request $request){
if(isset($request->application)){
if($request->session()->has('application')){
$request->session()->forget('application');
}
$application_data = [];
$application = new Application;
$application->attributes = $request->application;
$application_data["application"] = $application;
$request->session()->put("application" , $application_data);
}
//
return Redirect::to("/application")->withErrors(array("success"=>"Thank you for submitting the application"));
}
}
My routers
Route::post('/application', 'ApplicationController#save_application')->name('application');
Route::post('/application_store', 'ApplicationController#store_application')->name('application');
My html
<form method="POST" action="/application" enctype="multipart/form-data" id='application_form'>
<input type="hidden" name="_token" value="xtQapusSjgf5XVUxjCOudedeH93a8hEqyfaNh8ChEaKt">
<input type='checkbox'>
<label>I've read and accept the terms and conditions</label>
<p class='font-size-16 font-bold text-uppercase text-black'>
Your information
</p>
<hr class='hr1'>
<div class='row form-group'>
<div class='col-lg-6'>
<label class='control-label'>First name*</label>
<input type='text' class='form-control' name='application[first_name]' value="">
</div>
<div class='col-lg-6'>
<label class='control-label' >Last name*</label>
<input type='text' class='form-control' name='application[last_name]' value="">
</div>
</div>
<div class='form-group'>
<label class='control-label' >Middle name</label>
<input type='text' class='form-control' name='application[middle_name]' value="">
</div>
<div class='form-group'>
<label class='control-label'>ID*</label>
<input type='text' class='form-control' name='application[]' value="">
</div>
<button class="btn btn-primary text-uppercase">Submit <i class='fa fa-check text-white'></i></button>
</form>
your routes have the same name, give them differents.
Route::post('/application', 'ApplicationController#save_application')->name('application');
Route::post('/application_store', 'ApplicationController#store_application')->name('other');
and in your form, you can:
<form method="POST" action="{{ route('application') }}" enctype="multipart/form-data" id='application_form'>
and as senty say:
<button type="submit">
</form>
I think you overcomplicate things, you can simply use updateOrCreate() to make it cleaner.
First of all, make sure $fillable or $guarded is utilized in your Application model. (Application.php)
protected $fillable = ['each', 'field', 'as', 'string'];
// or
protected $guarded = [];
Some improvements for your method:
public function save_application(Request $request){
// 1. Do a proper check
$request->validate([
'application.first_name' => 'required',
'application.middle_name' => 'required',
'application.last_name' => 'required'
]);
// 2. Update or Create
$application->updateOrCreate(
[ 'user_id' => $user->id ],
$request->application // I suppose this is an array that you want
);
// 3. Handle the redirect the right way so you can eliminate the other `store_applcation()` method entirely
return redirect()->back()->with([
'application' => $application
'success' => "Your Message"
]);
}
Also you don't need store_application() method in your controller or its route because your html form is POST'ing to /application route.
This is what you want, right?

Laravel form post to controller

I am new to Laravel and I'm having trouble with posting data to a controller. I couldn't find the corresponding documentation. I want to something similar in Laravel that I do in C# MVC.
<form action="/someurl" method="post">
<input type="text" name="someName" />
<input type="submit">
</form>
Controller
[HttpPost]
public ActionResult SomeUrl(string someName)
{
...
}
You should use route.
your .html
<form action="{{url('someurl')}}" method="post">
<input type="text" name="someName" />
<input type="submit">
</form>
in routes.php
Route::post('someurl', 'YourController#someMethod');
and finally in YourController.php
public function someMethod(Request $request)
{
dd($request->all()); //to check all the datas dumped from the form
//if your want to get single element,someName in this case
$someName = $request->someName;
}
This works best
<form action="{{url('someurl')}}" method="post">
#csrf
<input type="text" name="someName" />
<input type="submit">
</form>
in web.php
Route::post('someurl', 'YourController#someMethod');
and in your Controller
public function someMethod(Request $request)
{
dd($request->all()); //to check all the datas dumped from the form
//if your want to get single element,someName in this case
$someName = $request->someName;
}

Rendering a template without changing the route in Symfony2

I've made a login function in which I render a template after checking the login and password. This's the form that i've made inside a template.
<form action="{{ path("login") }}" method="post" id="formulaire_connexion">
<label class="control-label">Email
<input type="text" name="email" id="email" placeholder="your#email.com" onclick="this.select()"/>
</label>
<label class="control-label">Password</br>
<input type="password" name="password" id="password" placeholder="*********" onclick="this.select()"/>
</label>
<input type="checkbox" id="remember_me" name="remember_me"><label for="remember_me">Remember me </label></br>
<button type="submit" id="connexion" name="connexion">Connexion</button>
</form>
And this's the logging check method :
public function loginAction(Request $request)
{
$mail = $request->get('email');
$pass = $request->get('password');
$oauth = new OAuth($mail, $pass);
$baseUrl = "http://api.localhost/v1/";
$connexion = "{$baseUrl}login/".$mail."/".$pass;
$oauth->fetch($connexion, $_REQUEST, OAUTH_HTTP_METHOD_GET);
$reponseInformations = json_decode($oauth->getLastResponse(), true);
if (!$reponseInformations) {
$data['erreur'] = "Bad credentials";
return $this->render('EspacePointDeVenteBundle:Authentication:authentication.html.twig', array(
'erreur' => $data,
));
}else{
return $this->render('EspacePointDeVenteBundle:Home:index.html.twig', array(
'reseau' => $reseau,
'identifiant' => $key,
'key' => $identifiant,
));
}
}
After a wrong login connexion I render the same login template, but the routing is changed to /login instead of havig /index per example. What I need to know how to keep the same routing even if we called a foreign method.

codeigniter setting up a password!

I try to set up a password in a codeigniter form...
Everything seems ok to my eyes but no matter which password I use the form is still submitted...
here is the code in the controler:
class MyBlog extends Controller{
function MyBlog(){
parent::Controller();
$this->load->helper(array('url','form','html')); //here we load some classes that we use
$this->load->scaffolding('entries'); //scaffolfing is a feature that lets you add or remove elements from the database
$this->load->scaffolding('comments');
$this->load->library('form_validation');//load validation class used to validate our forms...
}
function index(){
$data['title'] = "My Blog Title"; //the title of my blog
$data['query'] = $this->db->get('entries'); //here we make a small query to entries table
$this->load->view('myBlog_view', $data); ///load all data variables on myBlog_view.php
//this is also for the form validation
$this->form_validation->set_rules('title', 'Title', 'required');
$this->form_validation->set_rules('body', 'Body', 'required');
$this->form_validation->set_rules('author', 'Author', 'required');
$this->form_validation->set_rules('pass', 'Pass', 'callback_pass_check');
function pass_check($str) {
if ($str == 'baywatch'){
return TRUE;
}
else{
return FALSE;
}
}
if ($this->form_validation->run() == TRUE)
{
$this->myBlog_insert();
//$this->load->view('formSuccess_view');
}
}
function myBlog_insert(){
$insert = array( 'title' => $_POST['title'],
'body' => $_POST['body'],
'author' => $_POST['author']
);
$this->db->insert('entries',$insert);
redirect('myBlog/');
}
}
and this is my form:
<div class="theForm">
<?php echo $this->form_validation->error_string; ?>
<?php echo validation_errors(); ?>
<?php echo form_open('myBlog'); ?>
<label for="title">Title:</label>
<input type='text' name="title" size="40" id="title" />
<p>
<label for="body">Body:</label>
<textarea name="body" rows = "10" cols="60" id="body"></textarea>
</p>
<p>
<label for="author">Author:</label>
<input type="text" name="author" size="40" id="author"/>
</p>
<p>
<label for="pass">Password:</label>
<input type="password" name="pass" size="38" id="pass"/>
</p>
<p><input type="submit" value="Submit New Post"/></p>
</form>
</div>
</body>
</html>
any ideas?
thanks in advance
<label for="pass">Password:</label>
<input type="text" name="pass" size="38" id="author"/>
The input type is text no password, the id='pass'.
Ok, a couple of things first:
1) id's should be unique. ie your author field and your password field shouldn't have the same id.
2) password fileds should use the type "password" not "text".
I think the reason you're having problems is with your callback function pass_check(). Try changing your function to:
function pass_check($pass)
{
if($pass !== 'baywatch')
{
return FALSE;
}
By the way, scaffolding has now been deprecated. Can I suggest you look into using models and the active record class as a way of interacting with your db? Also, this really isn't a very secure way of handling passwords. Have a look at some of the CI authentication libraries and see if you can implement one of them.
Ok guys...I found what the problem was...function pass_check was declared inside index()...and for some reason it needs to be outside as a method of the class...Hope this will help others... I give some ups for all the suggestions...

Categories