I try to learn php/twig from a tutorial video and I tried to recreate the exercise but can't get back data from a simple form. The name variable in the action is always null. Everything else works. I looked through it multiple times but did everything like in the video. Some help would be really appreciated, thank you!
The action:
public function AddAction(Request $request) : Response{
$name = $request->request->get("name"); //always null
if ($name){
file_put_contents($this->fname, $name,FILE_APPEND);
$this->addFlash("notice","ITEM ADDED");
}
else{
$this->addFlash("notice","DATA ERROR");
}
return $this->redirectToRoute("list");
}
The form:
{% block body %}
<form action="{{ path('add') }}" mehod="POST">
<table>
<tr><td>Name of new item:</td>
<td><input type="text" name="name"/></td></tr>
<tr><td></td>
<td colspan="2"><input type="submit" value="SEND"/></td></tr>
</table>
</form>
{% endblock %}
Related
I created a form and want to save submitted data in back-end
//front-end
{% extends 'partials/base.html.twig' %}
{% block content %}
<form method="post" action="savedata">
<input type=text name="data">
<input type="submit">
</form>
{% endblock %}
//back-end
function savedata()
{
echo 'saved data:'.$_POST['data'];
exit;
}
I expect the code like this
$grav->post('/savedata', DataController->savedata);
But I cannot found any tutorial about custom Controller in documentation
How can I achieve this purpose?
I'm using codeiniter ,with Twig as template engine,and I have this select multiple on the template
<form action="{{ base_url }}mydirection/encuestas/perfil_interna" method="post" >
<select multiple="multiple" name="profile_questions">
{% for question in questions %}
<option id="qid_{{question.id}}">{{ question.text}}</option>
{% endfor %}
</select>
<input type="submit" value="Enviar">
</form>
this is the function on the controller
public function set_profile_internal_question(){
var_dump($_REQUEST);
}
But I get and empty array
and the route only work without the method
$route['mydirection/encuestas/perfil_interna']= 'Backend/Questions/set_profile_internal_question';
this way doesn't work
$route['mydirection/encuestas/perfil_interna']['POST']= 'Backend/Questions/set_profile_internal_question';
But its a form,post should work.
im new to laravel. So im trying to delete a record from database from my index page. But it only delete the record with the lowest primary key value, my id field.
Here's my controller code for destroy function:
public function destroy(Province $province)
{
//
$findProvince = DB::table('provinces')->where('id', $province->id)->delete();
if($findProvince){
return redirect()->route('provinces.index')->with('success', 'Province deleted successfully');
}
return back()->with('error', 'Province could not be deleted');
//var_dump($province->id);
}
Here's my view code:
#extends('layouts.app')
#section('content')
<div class="col-md-8 offset-md-2">
<br/>
<div>
Add New Province
</div>
<br/>
<table class="table">
<thead>
<tr>
<th scope="col">#</th>
<th scope="col">Name</th>
<th scope="col">Image</th>
<th scope="col">Operations</th>
</tr>
</thead>
<tbody>
#foreach($provinces as $province)
<tr>
<th scope="row">{{ $province->id }}</th>
<td>{{ $province->name }}</td>
<td><img src="../{{ $province->imgPath }}" width="200px"/></td>
<td>
Edit |
<a
class="btn btn-danger"
href="#"
onclick="
var result = confirm('Are you sure you wish to delete this province?');
if( result ){
event.preventDefault();
document.getElementById('delete-form').submit();
}
">Delete
</a>
<form id="delete-form" action="{{route('provinces.destroy', $province->id)}}" method="POST" style="display: none;">
<input type="hidden" name="_method" value="delete">
{{ csrf_field() }}
</form>
</td>
</tr>
#endforeach
</tbody>
</table>
</div>
#endsection
I tried using var_dump on the $province->id but it only output the lowest 'id' value.
id's are unique. You will get this unexpected behavior if you use the same id in a loop. Either use unique id's or put your buttons inside the form (I suggest this).
<td>
<form class="delete-form" action="{{ route('provinces.destroy', $province->id) }}" method="POST">
<input type="hidden" name="_method" value="delete">
{{ csrf_field() }}
Edit |
<a class="btn btn-danger">Delete</a>
</form>
</td>
And then use this Javascript in a seperate file for confirmation:
(function(){
let forms = document.querySelectorAll('form.delete-form');
[].forEach.call(forms, function(form){
form.onsubmit = function(e) {
if ( ! confirm('Are you sure you wish to delete this province?'))
return e.preventDefault();
}
});
})();
If you still want to use your approach, add the id of $province to the id attribute of your form. This will make your form unique so you get access it with an id.
<form id="delete-form-{{ $province->id }}" ...>
And then your Javascript:
if( result ){
event.preventDefault();
document.getElementById('delete-form-{{ $province->id }}').submit();
}
Thanks everyone for your help. And sorry that it took me long to reply. I've been really busy with other schools. So i managed to track down the problem with my code. It's with my view. All the created delete form has the same id. So if i just added the record id to the form. It works just fine.
I need some help in my laravel application with passing the values from a form though to another page. I have a table with data on area objects, and I want to be able to select two (or more) area objects, and then view those in a new page.
In my index.blade.php I have the hollowing form:
<form method = "POST" action="/areas/comparison" id="preferencesForm" class="form-group">
!{csrf_field()}!
<table id='areas_table' class="table table-striped">
<thead class="thead-default">
<tr>
<th>Select</th>
<th>Area</th>
<th>Overall Score</th>
<th>Housing Affordability Ratio</th>
<th>Mean House Price</th>
<th>Crime Level</th>
<th>Green Space</th>
<th>Good GCSE's</th>
<th>Number of Pubs & Restaraunts:</th>
<th>Superfast Broadband</th>
</tr>
</thead>
<tbody>
#foreach ($areas as $area)
<tr>
<td scrope="row"><input type="checkbox" name="area[]" value="!{$area->id}!"></td>
<th>!{$area->name}!</th>
<td>!{Helpers::calculateOverallScore($area)}!</td>
<td>!{$area->housing_affordability_ratio}!</td>
<td>£!{$area->mean_house_price_2015}!</td>
<td>!{$area->crime}!</td>
<td>!{$area->greenspace*100}!%</td>
<td>!{$area->five_good_gcses*100}!%</td>
<td>!{$area->restaurants}!/km<sup>2</sup></td>
<td>!{$area->superfast_broadband*100}!%</td>
</tr>
#endforeach
#endif
</tbody>
</table>
<input type="hidden" name="_token" value="{{ csrf_token() }}">
<input type="submit" id="compare_button" class="btn btn-primary" value="Compare"/>
</form>
And I would like to then go to show_comparison.blade.php and be able to display the data on the two (or more) areas that I selected.
In routes.php I have:
Route::post('/areas/comparison', 'AreasController#show_comparison');
And then in AreasController:
public function show_comparison(Area $area)
{
$formData = Request::all(); //Get the form data with the facade
return view('areas.show_comparison', compact('formData'));
}
However when I click submit and it tries taking me to show_comparison.blade.php it returns the error message "Trying to get property of non-object".
Here is show_comparison.blade.php:
#extends('layout')
#section('content')
<div class="container">
Back
<h1>Comparison</h1>
<p>Hello, this is the comparison page. !{$formData}!</p>
</div>
#stop
Ideally I would like to be able to print the data in the form of !{ area1->name}! and !{area2->name}! according to my selection.
If anyone can show my how I should be passing form selected data through to another page that would be amazing. (Thank you for taking the time to read this.)
I was given an answer on another forum. This solution will take the id that the form passes it, then will fetch the corresponding area objects and pass these in an array to the show_comparisons.blade.php view.
public function show_comparison(Request $request)
{
$areas= Area::whereIn('id',$request->area)->get();
return view('areas.show_comparison', compact('areas'));
}
It is my first attempt to store product's information into mysql. I apologize in advance if the code is not in the best form, Im still learning. This is my registration.html.twig
{% extends 'base.html.twig' %}
{% block stylesheets %}
<link href="{{ asset('bundles/framework/css/myStyle.css') }}" rel="stylesheet" />
{% endblock %}
{% block title %}Create your product {% endblock %}
{% block body %}
<div id="container">
<h1 id="header">Create your product and store it in the database!</h1>
</div>
<form method="POST" id="registrationForm">
<input type="text" id="pName" placeholder="Product name">
<input type="text" id="pPrice" placeholder="Product price"> <br>
<textarea id="pDescription" placeholder="Product description"></textarea>
</form>
<input type="submit" value="Submit" >
{% endblock %}
I also have Product entity class with setters&getters, not going to include it here because of amount of code.
This is my ProductForm :
class ProductForm extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('pName')
->add('pPrice')
->add('pDescription')
;
}
}
and here is part of my controller for the /insert page:
public function createAction()
{
$product = 'AppBundle\Entity\Product';
$form = $this->createForm(ProductForm::class, $product);
if($form->isValid())
{
$em= $this->getDoctrine()->getManager();
//Save into database code should go here...
}
}
For starters, it complains that it Expected argument of type "object, array or empty", "string" given which I guess comes from the controller where I try to pass $product variable with specified path to the entity class. In the documentation this part is very confusing. It says $product = ... leaving me without anything, I managed to understand that this is a path to entity class which should be passed to createForm method, but as mentioned before it complains that it is string, not array. Could someone review my code and give a feedback on what is wrong? Im really lost at the moment and not sure what to do next or how to solve this. Thank you in advance.
Your form fields don't have name attributes set, which means that no data will be posted from it.
In the controller, $product should be an instance of AppBundle\Entity\Product, not just a class name:
$product = new \AppBundle\Entity\Product();
The form will not automatically retrieve the data from HTTP request (which are not there because of point 1), you must handle the request manually:
// inject the request here
public function createAction(\Symfony\Component\HttpFoundation\Request $request) {
// ...
$form->handleRequest($request);
if ($form->isValid()) {
// ...
}
}