Codeigniter change form action by clicking buttons

2019-06-05 22:49发布

问题:

I have 2 submit buttons in my form and I'm trying to make each one go to a different controller method. I'm trying not avoid the use of multiple forms.

I'm currently using

<button type="submit" onclick="javascript: form.action='restore'">Restore</button>
<button type="submit" onclick="javascript: form.action='delete'">Delete</button>

...which works but I'm not sure if that's the best method. Any thoughts?

回答1:

Usually I'd like to handle the multiple submits by giving button/input tag a name attr. In this way you can submit and call to one function/action in one same controller, just by checking which button was submitted. e.g:

<form id="your_form" action="your_controller/process" method="post">
<input type="submit" name="restore" id="restore" value="Restore" />
<input type="submit" name="delete"  id="delete" value="Delete" />
</form>

Then in your controller, there will be a function called "process" doing this:

function process(){
  if(isset($_POST["restore"])) {
    //do your restore code
  }

  if(isset($_POST["delete"])){
    //do your delete code
  }   
}

Hope this would help.



回答2:

Best to do is with javascript, after all it's being done after page is rendered. This is an alternative solution (sorry it's jQuery I'm not very good at vanilla JS).

View:

<div id="submit-buttons" action="<?php echo site_url('controller/postmethod1'); ?>​"​​​​​>Submit 1</div>

<div id="submit-buttons" action="<?php echo site_url('controller/postmethod2'); ?>">Submit 2</div>​

JS:

​$(function(){
    $('.submit-buttons').click(function(){
        $('form').attr('action',$(this).attr('action')).submit();
        return false;
    });

});​

So when after buttons were clicked, it will update the form action parameter from the action attribute of the submit button, and then submit the form right after that.

P.s: I didn't test it, but it should work.



回答3:

What about this?

<?php echo form_open('controller/method',array('id'=>'my_form')); ?>
<!--Form-->
<input type="submit" value="Submit" />
<?php echo form_close();?>

Hope it helps