ThomasK
ThomasK

Reputation: 2220

How can I get/extract the name value of a submit button?

When I create i form - I do something like this:

<form name="form-name" method="post" action="?<?=$_SERVER['QUERY_STRING']?>">
    [...some elements...]
    <input type="submit" name="form-name" value="button">
</form>

Now I need to get the value of the name="" of the submit button, and not the actual value="". In this case : "form-name".

And here's why:
When I submit a form; I write the action to database - and therefor need the name of the form submitted.

I know I can just have a hidden field with the form name. But I would like to make it simpler by just extracting the name from the submit button because I have a couple of other hidden form elements that I need to add on every single form I create to make my template system work.

And no javascript...

Upvotes: 0

Views: 960

Answers (2)

ThomasK
ThomasK

Reputation: 2220

I might have come up with a solution to my question...

Here's a example form:

<form name="vehicle-vinNr" method="post" action="?<?=$_SERVER['QUERY_STRING']?>">
    <input type="hidden" name="hello" value="world" readonly>
    <input type="text" name="element">
    <input type="submit" name="vehicle-vinNr" value="send">
</form>

First I need to extract and place the element-names into a new array:

<?php
if ($_POST){
    foreach($_POST as $_FORM_ELEMENT_name => $_FORM_ELEMENT_value){
        $_FORM_ELEMENT_names[] = $_FORM_ELEMENT_name;
    }
}
?>

In this case the array now contains:

hello
element
vehicle-vinNr

If the submit-button is, and always is, the last element in the form - this would work:

$_FORM_name = end($_FORM_ELEMENT_names);  //  vehicle-vinNr

But sometimes the submit-button is not the last element, so I needed to make a change:

If I always start the name of the submit-button with submit_ - e.g. submit__vehicle-vinNr or with multiple submit buttons for different actions like submit_update__vehicle-vinNr/submit_delete_vehicle-vinNr I can just do this:

if ($_POST){
    foreach($_POST as $_FORM_ELEMENT_name => $_FORM_ELEMENT_value){     
        if(strstr($_FORM_ELEMENT_name,'submit_')){
            $_FORM_ELEMENT_submit_name = explode('__',$_FORM_ELEMENT_name);
            $_FORM_name = $_FORM_ELEMENT_submit_name[1];  //  vehicle-vinNr
        }
    }
}

This is the solution I came up with - any thoughts?

Upvotes: 0

samayo
samayo

Reputation: 16495

So, let's say your HTML form is this:

<form name="form-name" method="post" action="">
    <input type="submit" name="form-name" value="button">
</form>

And you want to get what is inside name="form-name" in this case the form-name

Well, then in the PHP side you can, treat the $_POST global as associative array, and extract the key from it like this:

<?php

  if(isset($_POST)){

  foreach($_POST as $key=>$each){
    echo $key; // this will output "form-name"
  } 
}

Upvotes: 1

Related Questions