Keep select value on change with laravel - forms

I am having a paginated backend table with db-data. The admin person can filter that table for data status. This happens via ajax. Everything works fine but I do not get the selected filter value to remain selected when I click on the second pagination link.
E.g. I choose select option: '1' => 'Active' so that only db-rows show up that have a status of 1. But when I then click on the second pagination link to see the next 20 rows then again it also displays the inactive db-rows. How would I get the selected option to remain selected in this situation? I tried Input::old('status') and passing $selected to view as below but no success. Thank you for any hint!
View:
<form id="filter_form" onsubmit="" action="<?php echo URL::action('countries#anyIndex'); ?>">
<?php echo Form::select('filter_status', funcs::get_status_options(), $selected, array('id' => 'filter_status')); ?>
</form>
Ajax:
$(function(){
$("#filter_status").on('change', function(){
frm = $("#filter_form");
frm.serialize();
status = $('#filter_status').val();
$.ajax({
type: "POST",
url: $(frm).attr('action'),
data: {status: status},
success: function(data){
$("#list").html(data.list);
},
dataType: "json"
});
});
});
Controller:
class countries extends BaseController {
public $filter = array(0,1,2);
function anyIndex()
{
$data['title'] = "Countries list";
if(Input::has('status')){
$status = Input::get('status');
if($status != 2){
$this->filter = array($status);
}
}
$d['items'] = $this->_getItems(20);
if(Request::ajax()){
$data['list'] = View::make('admin/countries/countries_list', $d)->withInput($status)->render();
return Response::json($data);
}
$data['selected'] = $this->filter;
$data['list'] = View::make('admin/countries/countries_list', $d);
return View::make('admin/admin_layout')->nest('view', 'admin/countries/countries_view', $data);
}
private function _getItems($paginate)
{
$items = Country::whereIn('status', $this->filter)->paginate($paginate);
return $items;
}
}

Related

advcheckbox in moodle form is storing only 0 in database

I am new Moodle and working on form data saving. I have created a group of checkbox which will take some input from the users and store it to the database, but unfortunately it is storing only 0/1 in the database. I have no clue where I made the mistake.
This my php file where I added the form field-
class custom_signup_form extends moodleform {
//Add elements to form
public function definition() {
global $CFG;
global $DB;
$mform = $this->_form; // Don't forget the underscore!
//$mform->addElement('text', 'email', get_string('email')); // Add elements to your form.
//$mform->setType('email', PARAM_NOTAGS); // Set type of element.
//$mform->setDefault('email', 'Please enter email'); // Default value.
if($this->content !== Null){
return $this->content;
}
$courses = $DB->get_records('course');
$categories = $DB->get_records('course_categories');
$interestedcourse=array();
foreach($courses as $course){
$coursestring = $course->fullname;
$interestedcourse[] = $mform->createElement('advcheckbox', 'interestedcourse[]','', $coursestring, array('group' => 1), array('',$coursestring));
}
$mform->addGroup($interestedcourse, 'interestedcoursegroup', get_string('interestedcourse', 'assignsubmission_metadata'),array('<br>'), false);
$interestedcategory=array();
foreach($categories as $category){
$categorystring = $category->name;
$interestedcategory[] = $mform->createElement('advcheckbox', 'interestedcategory[]','', $categorystring, array('group' => 1), array('',$categorystring));
}
$mform->addGroup($interestedcategory, 'interestedcategorygroup', get_string('interestedcategory', 'assignsubmission_metadata'),array('<br>'), false);
$this->add_action_buttons();
This is the php file for saving form data-
require_once(__DIR__ . '/../../config.php');
require_once($CFG->dirroot . '/local/custom_signup/classes/form/edit.php');
global $DB;
$PAGE->set_url(new moodle_url('/local/custom_signup/signupform.php'));
$PAGE->set_title(get_string('custom_signup', 'local_custom_signup'));
#custom form for signup
$mform = new custom_signup_form();
if ($mform->is_cancelled()) {
// Go back to manage.php page
redirect($CFG->wwwroot . '/local/custom_signup/manage.php', get_string('cancelled_form', 'local_message'));
}
else if ($fromform = $mform->get_data()) {
var_dump($fromform);
die;
}
echo $OUTPUT->header();
$mform->display();
echo $OUTPUT->render_from_template('local_custom_signup/signupform', $templatecontext);
echo $OUTPUT->footer();
object returned from the form submission-
object(stdClass)#288 (3) { ["interestedcourse"]=> array(1) { [""]=> string(0) "" } ["interestedcategory"]=> array(1) { [""]=> string(0) "" } ["submitbutton"]=> string(12) "Save changes" }

ZF3 redirect()->toUrl() not redirecting

I'm having a weird issue with ZF3.
I have a vanilla form in the view and a jquery ajax to send it to the controller, something like this:
<form>some form</form>
<script>
$("#form").submit(function (e) {
e.preventDefault();
$.ajax({
method: "POST",
url: "stats",
data: {name: 'TEST'} // name selected in the form
});
});
</script>
The controller for action stats looks like this:
$stat = new Stat();
$route_name = $this->params()->fromRoute('name', 'none');
$post_name = $this->params()->fromPost('name', 'none');
if(!strcmp($route_name, 'none')) // if no redirection yet
{
if(!strcmp($post_name, 'none')) // if no form was sent
{
// display the form to choose the customer
return new ViewModel([
'customer_list' => $stat->get_customer_list(),
]);
}
else // if the form was sent, get name and direct to /stats/someName
{
return $this->redirect()->toRoute('stats', ['name' => 'someName']);
}
}
else // after redirection, get the name in the URL and show some data about this customer
{
return new ViewModel([
'avg_time' => $stat->get_avg_time(rawurldecode($route_name)),
]);
}
The problem is that the redirection does not occure on the screen but I still get the route parameter if I print $route_name after submitting the form.
Anyway, the goal is to have a form with a select to choose the customer name and load the customer data into /stats/[name]. Am I going in the wrong direction ? And is the redirection issue a bug or my code is wrong ?
So there I solved it thx to rkeet, this is the form & jquery:
<form id="customer_choice" method="POST" action=""> some form </form>
<script>
$("#customer_choice").submit(function () {
$("#customer_choice").attr('action', 'stats/' + $("#customer_select").val())
});
</script>
And this is the controller (hope no customer is named 'none'):
$stat = new Stat();
$name = $this->params()->fromRoute('name', 'none');
if(!strcmp($name, 'none'))
{
return new ViewModel([
'customer_list' => $stat->get_customer_list(),
]);
}
else
{
return new ViewModel([
'avg_time' => $stat->get_avg_time($name),
]);
}
The result is basepath/stats/[customer name] and changing the url manually works as well.
(if you don't want changing the url manually to change the result, use fromPost instead of fromRoute)

Laravel 5.4 how to exclude empty field in url when GET form?

I built form with GET method but when i submit form empty field also pass to url, can i exclude empty field from passing to url ?
For example > when i submit my form url changed to :
?jobTitle=Title&jobCompany=CompanyName&jobGovernorate=&jobLocation=&postingDate=ad
Here in this example jobGovernorate and jobLocation is empty so i want form skip those when i submit the form.
If there's a way to get url like this
?jobTitle=Title&jobCompany=CompanyName&postingDate=ad
Because jobGovernorate and jobLocation is empty
Sorry for poor english, Thank you.
You can use middleware for your problem
class StripEmptyParams
{
public function handle($request, Closure $next)
{
$query = request()->query();
$querycount = count($query);
foreach ($query as $key => $value) {
if ($value == '') {
unset($query[$key]);
}
}
if ($querycount > count($query)) {
$path = url()->current() . (!empty($query) ? '/?' . http_build_query($query) : '');
return redirect()->to($path);
}
return $next($request);
}
}
then call for specific route like code below
Route::get('/search','YourController#search')->middleware(StripEmptyParams::class);
Assuming you have a form as below
<form>
<input type="text" class="url_params" name="jobTitle" value="">
<input type="text" class="url_params" name="jobCompany" value="">
<input type="text" class="url_params" name="jobGovernorate" value="">
<input type="text" class="url_params" name="jobLocation" value="">
<input type="text" class="url_params" name="postingDate" value="">
<input type="submit" name="submit" id="submit">
</form>
<script type="text/javascript">
$(document).ready(function () {
$("#submit").on("click", function(e) {
e.preventDefault();
var url = '{{ url('/') }}?';
var total = $(".url_params").length;
$(".url_params").each(function (index) {
if ($(this).val().trim().length) {
if (index === total - 1) {
url += $(this).attr('name') + '=' + $(this).val();
} else {
url += $(this).attr('name') + '=' + $(this).val() + "&";
}
}
});
window.location.href = url;
});
});
</script>
The above code will generate an URL based on the field value and redirect to the url. So it won't generate a url with the empty field value key.
And having an empty field value shouldn't make a difference as you could check for the url values in the controller using $request->input('key')
Hope this helps!
Go through array like this, you will just check if your array has empty, will not add the key.
$data = array('foo'=>'bar',
'baz'=>'boom',
'cow'=>'milk',
'php'=>'hypertext processor');
echo http_build_query($data) . "\n";
//echo http_build_query($data, '', '&'); // only for use &amp instead & if needed
I have applied the next middleware on a Laravel 8.x project to solve a related problem. This may be helpful to other ones...
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Http\Request;
class StripEmptyParamsFromQueryString
{
/**
* Remove parameters with empty value from a query string.
*
* #param \Illuminate\Http\Request $request
* #param \Closure(\Illuminate\Http\Request): (\Illuminate\Http\Response|\Illuminate\Http\RedirectResponse) $next
* #return \Illuminate\Http\Response|\Illuminate\Http\RedirectResponse
*/
public function handle(Request $request, Closure $next)
{
// Get the current query and the number of query parameters.
$query = request()->query();
$queryCount = count($query);
// Strip empty query parameters.
foreach ($query as $param => $value) {
if (! isset($value) || $value == '') {
unset($query[$param]);
}
}
// If there were empty query parameters, redirect to a new url with the
// non empty query parameters. Otherwise keep going with the current
// request.
if ($queryCount > count($query)) {
return redirect()->route($request->route()->getName(), $query);
}
return $next($request);
}
}
Note the middleware should only be applied to specific routes, not to all request. In my particular case I have a resource controller and to apply the middleware only to the index route I have used the next approach inside the resource controller:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Middleware\StripEmptyParamsFromQueryString;
class MyController extends Controller
{
/**
* Instantiate a new controller instance.
*
* #return void
*/
public function __construct()
{
$this->middleware(StripEmptyParamsFromQueryString::class)
->only('index');
}
...
}

how multiple row delete using checkbox in yii2

How can I use in GridView delete selected object,in Yii 2 Framework such as following image:
[enter image description here][2]
Try this
<?=Html::beginForm(['controller/bulk'],'post');?>
<?=Html::dropDownList('action','',[''=>'Mark selected as: ','c'=>'Confirmed','nc'=>'No Confirmed'],['class'=>'dropdown',])?>
<?=Html::submitButton('Send', ['class' => 'btn btn-info',]);?>
<?=GridView::widget([
'dataProvider' => $dataProvider,
'columns' => [
['class' => 'yii\grid\CheckboxColumn'],
'id',
],
]); ?>
<?= Html::endForm();?>
This is the controller:
public function actionBulk(){
$action=Yii::$app->request->post('action');
$selection=(array)Yii::$app->request->post('selection');//typecasting
foreach($selection as $id){
$e=Evento::findOne((int)$id);//make a typecasting
//do your stuff
$e->save();
}
}
Or Else
Follow all the steps given in this Link, You will Surely achive your goal.
Yii 2 : how to bulk delete data in kartik grid view?
https://stackoverflow.com/questions/27397588/yii-2-how-to-bulk-delete-data-in-kartik-grid-view/
You can use a column with checkboxes and bulk actions for each row selected.
Here is a related question:
Yii2 How to properly create checkbox column in gridview for bulk actions?
<?php
$url = Url::to(['user/delete']);
$this->registerJs('
$(document).on("click", "#delete_btn",function(event){
event.preventDefault();
var grid = $(this).data(\'grid\');
var Ids = $(\'#\'+grid).yiiGridView(\'getSelectedRows\');
var status = $(this).data(\'status\');
if(Ids.length > 0){
if(confirm("Are You Sure To Delete Selected Record !")){
$.ajax({
type: \'POST\',
url : \''.$url.'\' ,
data : {ids: Ids},
dataType : \'JSON\',
success : function($resp) {
if($resp.success){
alert(resp.msg);
}
}
});
}
}else{
alert(\'Please Select Record \');
}
});
', \yii\web\View::POS_READY);
?>
[1]: http://i.stack.imgur.com/iFjT1.png
I have succeeded in deleting multiple rows in gridview Yii2 by doing the following:
Create button in index.php
<p>
<button type="button" onclick="getRows()" class="btn btn-success">Delete Bulk</button>
</p>
Add javascript code in index.php to perform the event of getting the checked rows from the GridView widget.
<script>
function getRows()
{
//var user_id as row_id from the gridview column
// var list = [] is an array for storing the values selected from the //gridview
// so as to post to the controller.
var user_id;
var list = [];
//input[name="selection[]"] this can be seen by inspecting the checkbox from your //gridview
$('input[name="selection[]"]:checked').each(function(){
user_id = this.value;
list.push(user_id);
});
$.ajax({
type: 'post',
url:'index.php?r=student-detail-update/bulk',
data: {selection: list},
});
}
</script>
Put this code in your contoller
if ($selection=(array)Yii::$app->request->post('selection')) {
foreach($selection as $id){
$StudentDetailUpdates = StudentDetailUpdate::find()
->where(['user_id' => $id])
->all(); //....put your staff here
}

Moodle multi-select: linking over items

I'm trying to use the multi-select form element in a Moodle database to generate a list of tags. I would like these tags to link to the relevant search page displaying the filtered results.
The following template code works for singly tagged items, but fails for items with multiple tags:
<a href='/view.php?mode=list&filter=[[Tags]]'>[[Tags]]</a>
Is there a way to loop over items in a multi-select? Something like:
[[for Tag in Tags]] <a href='/view.php?mode=list&filter=[[Tag]]'>[[Tag]]</a> [[/for]]
I'm not certain there is an easy way to do this using the method above. Though, I've hacked together some javascript to accomplish the same thing:
function init() {
var tags = document.getElementsByClassName('tags');
for (var i=0; i<tags.length; i++) {
tags[i].innerHTML = tags[i].innerHTML.replace(/\w[\w\s]+?(?=<br>)/g, function(n) {
return "<a href='view.php?d=16&mode=list&perpage=10&filter=1&f_81%5B%5D="+ escape(n) + "'>" + n + "</a>";
});
}
};
window.onload = init;
Assuming you have an edit_form.php with something like this
defined('MOODLE_INTERNAL') || die;
require_once($CFG->libdir . '/formslib.php');
class edit_form extends moodleform {
public function definition() {
$mform =& $this->_form;
$options = array('red' => 'red', 'blue' => 'blue', 'green' => 'green');
$select = $mform->addElement('select', 'tags', get_string('tags'), $options);
$select->setMultiple(true);
$this->add_action_buttons(false, get_string('submit'));
}
}
Then use this in your edit.php file
require_once(dirname(__FILE__) . '/edit_form.php');
...
$mform = new edit_form();
$mform->display();
if ($formdata = $mform->get_data()) {
foreach ($formdata->tags as $tag) {
$url = new moodle_url('/view.php', array('mode' => 'list', 'tag' => $tag));
echo html_writer::link($url, $tag);
}
}