Problem of recovery of an element selected in a select - php

I am a beginner in Laravel. I want to implement a feature that:
I want to use Laravel 8 and PHP:
Select a part of the data in a table (via a select)
how to get the id selected in the select :
-> get the identifier selected in the option tag in order to use it in an sql query that combines selection and insertion
Copy the data and insert it in another table (via an add button)
how to recover the id present in the url of the page
Display the data inserted in a table
no problem
<select name="id_segment" class="form-control">
<?php
$req1 = DB::select("SELECT id_segment, nom_segment FROM `segements` ");
foreach ($req1 as $re1 => $r1) {
?>
<option name="id_segment" value="{{ $r1->id_segment }}"> {{ $r1->id_segment }}
{{ $r1->nom_segment }}</option>
<?php
} ?>
</select>
</div>
</div>
<div class="col-xs-12 col-sm-12 col-md-12 text-center">
<button type="submit" class="btn btn-primary" id="AjoutSegment">Ajouter</button>
<a class="btn btn-primary" href="{{ route('groupecampagnes.index') }}"> Back</a>
</div>
I have already tried with $_POST and $_GET while making a var_dump, but I have seen that some people say that it does not work, me it gave me the display of an error with the id that I seek to recover precisely, whereas it should just display it to me on the page to see if I recover it well and truly. The var_dump is not present in the code because I removed it in the meantime. After I tried various solutions found on the net, which have me display as error for some of them that I had to do with a std class object.

Assuming your code is in a file called page and stored in the views directory (resources/views/page.blade.php), you could go to your controller and pass the needed data to your view like this:
$segments = DB::select("SELECT id_segment, nom_segment FROM `segements` ")->get();
return view('page', compact('segments'))
Then you can use it in your view:
<select name="id_segment" class="form-control">
#foreach ($segments as $r1)
<option name="id_segment" value="{{ $r1->id_segment }}"> {{ $r1->id_segment }} {{ $r1->nom_segment }}</option>
#endforeach
</select>

Related

Symfony 4.4 functional test delete form not working

I have an multi-delete functionality (kind of like PHPMyAdmin, checkboxes you can check to delete multiple items). The functionality itself works, but I'm implementing it in my functional test. However, somehow it doesn't work.
This is the code of my service (where multi-delete is handled, this is in a function that's called within controllers)
$form = $this->formFactory->createBuilder()->setMethod('DELETE')->getForm();
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$this->deleteKeys($request);
return new RedirectResponse($this->session->get('referer'));
}
The function renders a template with the form, a button and a list of all items being deleted. This is the template:
{{ form_start(form) }}
<div class="row">
<div class="col-md-12">
<div class="box">
<div class="box-body">
{{ form_widget(form) }}
<p>{{ 'standard.Are you sure you want to delete the following items'|trans }}?</p>
<p>
{% for item in items %}
<strong class="d-block">{{ item.displayProp }}</strong>
<input type="hidden" name="items[]" value="{{ item.id }}">
{% endfor %}
</p>
</div>
<div class="box-footer">
<input class="btn btn-danger" type="submit" name="delete_items" value="{{ 'standard.Delete'|trans }}">
<a class="btn btn-default" href="{{ app.session.get('referer') }}">{{ 'standard.Cancel'|trans }}</a>
</div>
</div>
</div>
</div>
{{ form_end(form) }}
So, testing it via my browser, it works completely fine. Then, lets look at the code in my test. The code to get to the confirm page works, it shows the right items selected to delete. But it contains a form:
$form = $crawler->selectButton('delete_items')->form(null, 'DELETE');
$crawler = $this->client->submit($form);
So, it selects the form based on the delete_items button name (which exists), it doesn't throw an error or something, it submits the form, but after it, getting the HTML of $crawler still displays the "deleted" items. Again, if I test the functionality in the browser in the module itself, it works, but in the functional test it somehow doesn't.
Also I tried using $this->client->followRedirect() which says the request isn't redirected. But it's just a normal delete form without validation so I don't see why it shouldn't work.
EDIT:
Apparently somehow the form isn't submitted, var_dump($form->isSubmitted()); says false. I'm not sure why it isn't submitted though since it does get submitted if I test it in the browser though.

Laravel - How to get the value of input in a view

I'm building a page with 2 forms like this:
index.blade.php:
<form action="/" method="post">
<input type="text" list="cats" name="catipt" id="catipt" />
<datalist id="cats">
#foreach($categories as $category)
<option>{{ $category->name }}</option>
#endforeach
</datalist>
<button type="submit">Add</button>
</form>
#include("catForms")
catForms.blade.php contains a form aside from the first one, with a send button to send the form input via email. The second form in which there are many div that each has input for the user to fill in. The first form allows user to add items to the dropdown list, so it's a post method. Based on the input in the first form, a corresponding div in second form will show, others will hide, using Jquery. Now, I want to send the data from the user via email, but how do I get the value of the input in the first form in the email view so that I can filter out the irrelevant div? Otherwise, I'll have to list out all div even they are empty.
The problem is that, there are two forms, so there are two Request $request, I can't get the input value from the first form in email view. I tried this in email view, but this doesn't work:
#php
use Symfony\Component\Console\Input\Input;
#endphp
Cat: {{ Input::get('catipt') }}
<form action="/" method="post">
<input type="text" list="cats" name="catipt" id="catipt" />
<datalist id="cats" name="cat-name">
#foreach($categories as $category)
<option value="{{ $category->name }}">{{ $category->name }}</option>
#endforeach
</datalist>
<button type="submit">Add</button>
</form>

Display the dropdown text using laravel

I'm working on a reporting page using php Laravel framework. I select the options from the comboboxes, these values are sent to the controller to replace them in some queries used to display the reports.
When I click the submit button, the page refreshes and the name shown is the last element of the dropdown.
My Controller:
$negocioDive = DB::table('ma_leads_reporte')
->selectRaw('NEGOCIO, year(FEC_CREACION) as AÑO')
->groupBy('NEGOCIO', 'AÑO')
->get()->toArray();
$selectFecha = DB::table('param_fecha')
->selectRaw('mesNum, mesNom')
->groupBy('mesNum', 'mesNom')
->get()->toArray();
$año = $request ->input('año');
$mes = $request -> input('mes');
$negocio = $request -> input('negocio');
//Solicitud de Cotización versus mes anterior
$mesAnt = DB::table('ma_leads_reporte')
->selectRaw('count(*) as C, day(FEC_CREACION) AS DIA, monthname(FEC_CREACION) AS MES')
->whereMonth('date_identified', '=', $mes-1)
->whereYear('date_identified', '=', $año)
->groupBy('MES', 'DIA')
->get()->toArray();
$vscont = array_column($mesAnt, 'C');
$antMes = array_column($mesAnt, 'MES');
$dia = array_column($mesAnt, 'DIA');
My View:
<div class="container">
<div class="row justify-content-center">
<div class="content mt-3">
<div class="animated fadeIn">
<div class="col-lg-8">
<div class="card">
<div class="card-header">
<form action="{{route('reportes')}}" method="GET" id="fecha">
{{Form::label('', 'Año')}}
<select id="año" name="año">
#foreach($negocioDive as
$negocioD)
<option value="{{$negocioD->AÑO}}"
selected="selected">{{$negocioD->AÑO}}</option>
#endforeach
</select>
{{Form::label('', 'Mes')}}
<select id="mes" name="mes">
#foreach($selectFecha as $fecha)
<option value="{{$fecha->mesNum}}" name="{{$fecha->mesNom}}">{{$fecha->mesNom}}</option>
#endforeach
</select>
{{Form::label('', 'Negocio')}}
<select id="negocio" name="negocio" >
#foreach($negocioDive as $negocioD)
<option value="{{$negocioD->NEGOCIO}}" selected="selected">{{$negocioD->NEGOCIO}}</option>
#endforeach
</select>
<button type="submit"class="btn btn-default" id="filter">Filtrar
<i class="fa fa-filter"></i>
</button>
</form>
<?php if(isset($_GET['año']) && isset($_GET['mes']) && isset($_GET['negocio'])){
echo "<h4> Año: $año | Mes: {$fecha->mesNom} | Negocio: $negocio </h4>";
}?><!--
<p id="mesJS"></p> -->
</div>
</div>
</div>
After receiving the request variables, it should show the correct values instead of the last index of the dropdown.
What can I do?
dropdown options:
After submit:
The reason it is showing the last index of the dropdown is that you are looping on your various items and creating your options within each select box with 'selected' overwritten every time all the way to the last one in the loop.
To fix this, you'll need to add some type of conditional on the option box to tell it if the loop item is the correct selected one. If the new model has the key within this loop, then, and only then, make it selected. Something like this (You'll need to make this code your own):
#foreach($negocioDive as $id=>name)
<option value="{{$id}}" {{$theThingYouAreSelecting->id === $id?"selected":''}}>$name</option>
#endforeach
NOTE - I'm assuming you are sending a key->value array to the foreach as this is what the option expects - the key would be the id and the value would be the name for the item.
Once you get this working, I strongly recommend looking at LaravelCollective HTML - it binds the model to the form and automates a huge chunk of the conditionals.

Laravel: Two Actions in a Form - one with "on-change" one with a button?

in my Laravel App I have a Blade "Insert Project" where I want to dynamic load html data from Database when a DropDown changes. To be more concrete: I have several Project Categories in the Table "Cats" (id, name, code) - Each Category needs different fields to be added, therefore I have put the html code in the Table "Cats". I want to achieve the following:
If a user selects a Project Category the html code which is attached to the category should be shown.
My Code so far:
<form method="POST" action="{{ route('project-insert') }}">
#csrf
<form action="{{ route('filter') }}" method="post">
<label for="Cat">Kategorie</label>
<select class="form-control" name="cat_id" id="cat_id" data-parsley-required="true" onchange='this.form.submit()'>
#foreach ($cats as $sn)
{
<option value="{{ $sn->id }}">{{ $sn->name }}</option>
}
#endforeach
</select>
</form>
<div class="form-group row mb-0">
<div class="col-md-6 offset-md-4">
<button type="submit" class="btn btn-primary">
{{ __('Add Project') }}
</button>
</div>
</div>
</form>
In my Controller I have add:
public function insertProject(Request $data) {
return $data['cat_id'];
}
public function filter(Request $request)
{
$cat_id = $request->input("cat_id");
return $cat_id;
$code = DB::table('cats')->where('id', '=', $cat_id);
var_dump($code->code);
}
When I change the DropDown, then the function "insertProject" will be called and not the desired function "filter".
How can I achieve it to call the correct function, or how can I achieve it to call "insertProject" only when the button has been pressed?
Thank you for your advice and help.
Stefan

Laravel - Method Not Allowed HTTP Exception (RouteCollection.php line 218)

I'm currently new on Laravel and trying to develop my first project. I have this MethodNotAllowedHttpException in RouteCollection.php line 218 error during my development for inserting data into database. I have searched both Google & Stackoverflow for solutions but non are related to my current problem and some of them way too complex for this simple problem (I think so...).
I have my form in my checklist page:-
<form action="{{url('addchecklist')}}" method="POST">
{{ csrf_field() }}
<div class="row">
<div class="col-sm-12">
<div class="text-left">
<input type="hidden" name="schmFK" value="{{$id}}">
<div class="col-sm-6">
<h4>
<label>Section</label>
<select class="selectpicker form-control" data-live-search="true" name="sctionPK">
<option selected>Select the Section</option>
#foreach ($sction as $key=>$slct1)
<option value="{{$slct1->ssctionPK}}">{{strtoupper($slct1->ssctionName)}}</option>
#endforeach
</select>
</h4>
</div>
<div class="col-sm-2">
<button type="button" data-toggle="modal" data-target=".bs-example-modal-lg" class="btn btn-primary btn-sm" style="margin-top:33px; padding-top:7px; padding-bottom:7px;">Add Section</button>
</div>
<div class="col-sm-4">
<h4>
<label>Severity</label>
<select class="selectpicker form-control" name="svrityPK">
<option selected>Select the Severity</option>
#foreach ($svrity as $key=>$slct2)
<option value="{{$slct2->severityPK}}">{{strtoupper($slct2->severityName)}}</option>
#endforeach
</select>
</h4>
</div>
<div class="col-sm-12">
<h4>
<label>Question</label>
<input class="form-control" type="text" placeholder="Question" name="question">
</h4>
</div>
<div class="col-sm-6">
#include('widgets.button', array('class'=>'primary btnaddstd', 'size'=>'lg', 'type'=>'submit', 'value'=>'Add Checklist'))
</div>
</div>
</div>
</div>
</form>
Then I have this route for inserting data from the form into database:-
Route::post('/addchecklist', function (Request $request){
// Create instance to store record
$scheme = new App\checklists;
$scheme->schmFK = $request->schmFK;
$scheme->schSectionFK = $request->sctionPK;
$scheme->severityFK = $request->svrityPK;
$scheme->clQuestion = $request->question;
$scheme->save(); // save the input
// Sort all records descending to retrieve the newest added record
$input = App\checklists::orderBy('cklistPK','desc')->first();
// Set search field variable default value of null
$src = isset($src) ? $src : null;
// Get Checklist reference from cklists_stddetails with the designated ID
$chkstd = App\Cklists_stddetail::where('cklistFK', $input->cklistPK)
->join('stddetails', 'stdDtlFK', '=', 'stddetails.sdtlPK')
->get();
// Get the newest stored record
$chcklst = App\checklists::where('cklistPK', $input->cklistPK)->firstOrFail();
// Get all data from table 'stddetails'
$stddetail = App\stddetails::all();
// Get all data from table 'standards'
$stndrd = App\standard::all();
// Get all data from table 'sections'
$sction = App\Section::all();
// Redirect to 'addref.blade' page with the newest added record
return redirect('addref/'.$input->cklistPK)
->with('src', $src)
->with('chkstd', $chkstd)
->with('id',$input->cklistPK)
->with('schmid', $request->schmFK)
->with('chcklst', $chcklst)
->with('stddetail', $stddetail)
->with('stndrd', $stndrd)
->with('sction', $sction);
});
My scenario is this, I have a form for user to input data in it. Then when the data is saved, they will be redirected to the page of that data to do something there. The data is successfully saved in the database but the redirection to the designated page (addref.blade) with the newest record ID return error:-
But the URL goes where I wanted it to go (means the URL is right):-
As you can see, the usual solution from the net that I found are:-
Make sure both method from routes and the form is the same, and mine it is:-
method="POST"
Route::post
Make sure the URL routes can recognize the form's action URL, and mine it is:-
<form action="{{url('addchecklist')}}" method="POST">
Route::post('/addchecklist', function (Request $request)
Include CSRF token field in the form, and mine it have been included:-
<form action="{{url('addchecklist')}}" method="POST">
{{ csrf_field() }}
I have tried those simple solution provided on the net and nothing is helpful enough. I'm still wondering what else I have missed and hoped that anyone here can assist on solving my issue.
I think the error is that you have a redirect which you have not registered in your routes or web.php file.
Sample redirect:
Route::post('/addchecklist', function (Request $request){
//some post process here...
return redirect('addref/'.$input->cklistPK)
->with('src', $src)
->with('chkstd', $chkstd)
->with('id',$input->cklistPK)
->with('schmid', $request->schmFK)
->with('chcklst', $chcklst)
->with('stddetail', $stddetail)
->with('stndrd', $stndrd)
->with('sction', $sction);
});
Route::get('addref/{id}', function(Request $request){
//show the blade.php with data
});
Can you please write :
url('/addchecklist')
instead of :
url('addchecklist')
and then print_r('in');
and die; and check what you get.
Route::post('/addchecklist', function (Request $request){
print_r('in');
die;
});

Categories