How get id off button in laravel controller laravel 5.3 - php

Here i have buttons like this
<button type="submit" name="submit_1" class="btn green" value="submit_1">Save & Add Another</button>
<button type="submit" name="submit_1" class="btn green" value="submit_2">Save & Exit</button>
in my controller i redirect pages on button click i cannot change name of buttons because i am using in update function to redirect with submit_1
now what should do i also can use id maybe for this but dont know how to use it
if(Input::get('submit_1')) {
return redirect()->route('data.create');
} elseif(Input::get('')) {
return redirect()->route('data.index');
}
Its always redirect to create page but i want if i click button2 which is Save & Exit it should be redirect to index page.
what should i do to to differentiate between buttons except changing name of buttons.. if any method with id please help me and guide to best

You need to compare the input with a value.
At the minute your basically just saying if('submit_1') (or 'submit_2') either will evaluate to being true, you're not actually checking the the value for submit_1 is actually 'submit_1'.
(I think the confusion comes from having the value of one of your buttons being the same as the name of your buttons )
Change your if condition to be:
if(Input::get('submit_1') == 'submit_1')
Hope this helps!

You should look for the value of the submit_1 button.
if(Input::get('submit_1') == "submit_1") {
return redirect()->route('data.create');
} else if(Input::get('submit_1') == "submit_2") {
return redirect()->route('data.index');
}
However giving same name to 2 different buttons is not a good approach.

first set id in your button.
lets say id 1 and id 2
In this case route call in your button should be like..
<a href="[your route]" id=1 class="btn green">
And in your routs it should be like
Route::get('[your link to be displayed]{id?}', 'Controller#action')
In th function call it should be like
public function action($id = null) {
if($id=1) {
return redirect()->route('data.create');
}
elseif($id=2) {
return redirect()->route('data.index');
}
}
Hope this would be usefull

Related

Show data from another table with modal - Codeigniter

i have 2 tables
Now when i click detail , i want to show data from table 2 which have reportcode as i click on table 1 (image 1)
And now i want to show it on modal , so here is the example
1) click detail button -> get reportcode -> show reimbursename,etc to modal
Can you explain to me what should i do first ? and can you suggest me a plan please ,any answers will be appreciated. Thanks
My suggestion is:
1 - Add one class to detail button, i.e: detailButton and a data attribute or href with the especific reportCode.
<table>
<tr>
<td> ... </td>
<td> <button class='detailButton' href='<?php echo $reportCode; ?>' ... </button> </td>
2 - Add jquery to the bottom of the page:
$('.detailButton').click(function(e){
e.preventDefault();
var reportCode = $(this).attr('href');
var url = "yourUrl/controller/function";
$.post(url,{ code:reportCode },function(data){
//do stuff
//i.e: $('.modal').html(data).show();
});
});
Now you have a function that gets the reportCode, sends it to your controller by POST, you return something and the function gets the response and attach to a html.
Note, this way you must return a table from your controller. You could build dinamically too.
Hope it helps!
UPDATE:
You could check the values to your model and then use a exisitin template (for example one that generates the detail table), and return to your view as data to be attached at the correct position (method 1):
function detail(){
$getcode= $this->input->post('reportCode');
$data['showdetail'] = $this->model_expreport->showdetail($getcode);
$ret = $this->load->view('detail_template',$data,true); //return as data
print_r($ret);
}
Or you could use the Method 2:
function detail(){
$getcode= $this->input->post('reportCode');
$data['showdetail'] = $this->model_expreport->showdetail($getcode);
$this->output->set_content_type('application/json');
$this->output->set_output(json_encode($data));
}
This way, the view will recive a JSON that you could iterate and build your own page. Or you could create the full view and return it as data (in order to only append to your view).
You could use both.
In the view, you will recive either a full view:
$.post(url,{ code:reportCode },function(data){
$('#modal').html(data); //put the 'detail' response to the modal
}
Or with JSON you must iterate and build your own div dinamically, there are a lot of tutorials for this: https://uno-de-piera.com/cargar-json-con-jquery-y-codeigniter/

Codeigniter | Get previous URL and used as back button to previous page

I really wonder how can I do this, I have 3 pages that has the same link going to 1 page, now what I want to do is to have 1 button that is intelligently enough to get which of the 3 pages was used to go to that page and used it as it's link going back to that previous page.
Please if anyone who knows how to do this, help me to get out to this chaos. post some code how to do it in codeigniter. Thank you in advance.
By using a simple javascript to achieve previous button like,
Previous
With the url helper loaded, set the current_url in a hidden field say 'refer_from'.
<input type="hidden" name="refer_from" value="<?php echo current_url(); ?>" />
Get this using Input Class and set this on the anchor link
Previous
NOTE: using window.history.go(-1) will fail and throw a js error, if the user some how lands
directly on the "1" last page. window.history will be empty in that case.
In my case jquery back methods means window.history etc,were not working so,I tried this hope this helps you guys.call this method on click. cheers
function redirection()
{
<?php $send=$_SERVER['HTTP_REFERER'];?>
var redirect_to="<?php echo $send;?>";
window.location = redirect_to;
}
In controller add:
$data['back'] = $_SERVER['HTTP_REFERER'];
In view add a button and link to $back.
//to get previous url $_SERVER['HTTP_REFERER'];
<?php $send = $_SERVER['HTTP_REFERER'];?>
var redirect_to="<?php echo $send;?>";
//to redirected to this link
location.assign(redirect_to);
//you can pass static link also to redirected to this link
location.assign('facebook.com');
I don't know the older version, I guess there was such funcionallity but know there is and you should avoid use the accepted answer it may break in many ways.
Know you can use method previous_url.
Just add it where you need and is all done
<div class="container">
<a href="<?= previous_url();?>" class="btn btn-info">
<i class="bi bi-arrow-return-left"></i>
</a>
</div>
Returns the full URL (including segments) of the page the user was previously on.
Due to security issues of blindly trusting the HTTP_REFERER system variable, CodeIgniter will store previously visited pages in the session if it’s available. This ensures that we always use a known and trusted source. If the session hasn’t been loaded, or is otherwise unavailable, then a sanitized version of HTTP_REFERER will be used.
EDIT
Improvements Issue fix
I noticed that the previous_url alone may suit for all scenarios, especially if we have a form which redirects back to the same page; that's because the previous page would be the one that the user was currently, hence will not come back in the desire place (and others solutions would have same issue anyway), a simple solution, and by all means improvable, is the following:
In /app/Controllers/BaseController.php
/// Use this as base redirect
public static $baseRedirect = '/index';
/** #public
* Will check the User position and avoid and URL which aren't desired
* - #example
* Current Page: /news
* Previus : /index
*
* if the user update a form in the current page, which is a POST or GET and the user is
* /news/update and then will go back to the current page now previous_url() will be /news and
* NOT /index , if the user presses back will go to /news again and not /index.
*
* #var array $skip An array with url slugs to check the previous url, if the previous url containts any then skip to fallback
* #var string $baseRedirect : base redirec if fallback is not provided
* #param string|null $fallback use a target url as the desired 'Go Back' URL
*/
public function getPreviousURL(?string $fallback=null)
{
// NOTE: We need the current_url also inside, to check that we don't go back in the same page ;)
$skip = [current_url(), "create", "udate", "delete", "post"];
$prev = previous_url();
foreach($skip as $s) {
if (str_contains($prev, $s)) {
return site_url($fallback ? $fallback : self::$baseRedirect);
}
}
return $prev;
}
Now , in any controller which extends BaseController
class MyController extends BaseController
// ... code
public function view($slug=null)
{
// code
$data = [
// data
'prev' => $this->getPreviousURL(), // this will be available in any Controller
];
echo view('templates/header', $data);
echo view('news/view', $data);
echo view('templates/footer', $data);
}
Additionally you can pass any fallback into the url ;)
$data = [
// data
'prev' => $this->getPreviousURL(fallback: '/home'), // this will be available in any Controller
];
In a view news/view.php
<?php $prev = $prev ??= site_url('/index'); ?>
<div class="container">
<a href="<?= $prev ?>" class="btn btn-info">
G Back <i class="bi bi-arrow-return-left"></i>
</a>
</div>
/*Back button in codeigniter project using jquery */
<button type="button" class="btn btn-primary btn-sm" id= "back">Back</button>
//JQuery of back button
<script type="text/javascript">
$(document).ready(function(){
$('#back').on('click', function(){
<?php $send = $_SERVER['HTTP_REFERER'];?>
var redirect_to="<?php echo $send;?>";
window.location.href = redirect_to;
});
});
</script>

dropdown menu with links to the functions

I currently have two buttons. 1 to change a mysql variable to 1 and one to change it to 0
This works fine but i would like to have them in a dropdown. So i dont have 2 buttons showing.
<td>
<i class="fa fa-check"></i>
<i class="fa fa-check"></i>
</td>
the first one sets "complete" to 1 and the second one sets "complete" to 0.
Prepare options array as below
$opts=array(
'' =>'--Select--',
'0'=>'Option 1',
'1'=>'Option 2'
);
Generate dropdown with below CI Code:
<?php echo form_dropdown('dropdown_name',$opts,'','onchange="gotopage(this.value)"');?>
In js:
function gotopage(val)
{
if(val!="")
{
window.location = "<?php echo site_url("PATH_TO_GO");?>/"+val; // pass parameter in url
}
}
Without seeing the code only we can tell you in general what to do to make a drop down in codeignitor. In your view page, you should put this to generate a select combination box. The value can be received only if, its in a form. if you don't want a form, then you may need to incorporate Ajax with this.
<?php echo form_dropdown('cmb',$select_options,'0');?>
The first variable will become the name of the variable and the third variable is the default option that that has to be select (in this case Option 1 will be selected). The third variable is the data array which contains the options of the dropdown.
The data array, have to be like this, which have to be passed from controller into the view.
$select_options=array(
'0'=>'Option 1';
'1'=>'Option 2'
);

Hiding in foreach loop

I am getting json in "data" and passing it in for loop. Onclick of buy button, it goes to the App function. On success I need to hide the buy button and display the download label.
My problem is onclick of 1st buy button, download link for both the buttons appear.
Ideally oneclick of first buy button, buy button should be hidden and download label should appear. similarly oneclick of second buy button, buy button should be hidden and download label should appear.
How do I get particular id of each button so that I can hide one at a time?
Please help me out
function (data)
{
var Class ='';
for (var i=0; i <data.length;i++)
{
Class += '<div name="buy\''+data[i].id+'\'" class="btn btn-primary btn-small" onclick="buy(\''+data[i].identifier+'\',\''+data[i].id+'\',\''+data[i].url +'\'); return false;" href=""></div><div class="download\''+data[i].id+'\'" id="download">D<span style="font-size:15px"></span></div>';
}
return Class;
}
App = function(identifier, app_id, url) {
$.ajaxSetup({
data : {
csrf_test_name : $.cookie('csrf_cookie_name')
}
});
var jqxhr = $.post(SITE_URL + 'admin/appstore/purchaseApp', {
identifier : identifier,
ap_id : ap_id
}).done(function(data1) {
obj = JSON.parse(data1);
bootbox.alert(obj.status, obj.label);
$("#download").html('<a href='+download_url+app_id+'>Download!</a>');
});
};
it is for loop am using.. am passing '; now how do I hide buy id? $("#buys"+"'"+data[i].id+"'").hide(); is this the right way? It gives me error
if you look at the actual markup generated in Class, you will see that your buy buttons don't have an id at all. perhaps something like
Class += '<div id="buy-button-'+data[i].id+'" name="...
Now you have a unique id on each button. The next part of your problem is knowing which button to remove after a successful Ajax call. You will need to include that in the data1, returned from the server. For the sake of argument, let's say the server returns the value in your data1 object as app_id. Then all you need to do is
jQuery('#buy-button-'+data1.app_id).hide();
Slightly off-topic, I'm not too keen on the way you're using single quotes in the buttons' name attributes, either, but I don't think that's relevant here.

Two forms - two submit buttons. How the controller identify which button was clicked?

I have two forms with two submit buttons in one page, one view and one controller should manage them. I want it to perform one action if the first one is clicked, and another action - if the second. I tried this where edit is the name of the form but it doesn't work:
if($this->getRequest()->get('edit'))
I also tried setting value to the submit buttons but I could't make it go, too. Please help me to find a way how to identify which button was pressed. :)
Symfony 2.3 comes with the solution. It supports buttons in forms, and you have isClicked() method to check if a button was clicked.
http://symfony.com/blog/new-in-symfony-2-3-buttons-support-in-forms
Give buttons different "name" (not "id") attributes
<form ...>
...
<input type="submit" name="btnA" value="ActionA">
<input type="submit" name="btnB" value="ActionB">
</form>
Then the controller should analyze the POST data for a variable whose name will be the name of the clicked button:
if (isset($_POST['btnA'])) {
/* do A */
} else if (isset($_POST['btnB'])) {
/* do B */
}
You can use hidden fields and check their values :)
Inside your controller create two forms, handle their input and then check if they are submitted and valid.
$formOne = $this->formFactory->create();
$formTwo = $this->formFactory->create();
$formOne->handleRequest($request);
$formTwo->handleRequest($request);
if($formOne->isSubmitted() && $formOne->isValid()) {
die('form one submitted');
}
if($formTwo->isSubmitted() && $formTwo->isValid()) {
die('form two submitted');
}
return new Response($this->templating->render([template-name]), [
'formOne' => $formOne->createView(),
'formTwo' => $formTwo->createView(),
]));
Then inside your template create two forms with separate buttons:
form_start(formOne)
form_rest(formOne)
<button type="submit">one</button>
form_end(formOne)
form_start(formOne)
form_rest(formOne)
<button type="submit">one</button>
form_end(formOne)

Categories