Determining Button used to Submit with PHP

2020-05-08 06:51发布

问题:

I am creating a management engine that needs to manage sections and then pages within the sections.

For usability it has been decided that the display order fields will be displayed on the listing page, this results in the need to have a form that surrounds the sections as well as one for each of the groups of pages.

The obvious solution was nesting forms, which xhtml and html5 standards both prevent for pretty obvious reasons. As such I am now processing the entire page as a single form and then deciding what data to use based on the button pressed to submit the data.

The problem with this is that the buttons have dynamic names that generate based on the ID of the section.

<button type="submit" class="btn bg-blue2 btn-gradient btn-xs" name="order:pages:<?=$GAS['uid'];?>"><span class="glyphicons glyphicons-roundabout"></span> </button>

The name of the button is generated for each group of pages using it's parent 'section' ID. By doing this I can only select textfields that have a certain prefix and process that data.

My question is, how can I detect which button is used to submit the form on the processing page. I have considered the use of var_dump($_POST) and substr() but don't know / understand how to correctly approach it.

The final result should allow me to get the name of the button used (order:pages:id) and then seperate it using substr so I can use id to further determine textfields.

Thank you as always.

回答1:

Instead of having a different name attribute for your buttons, i suggest that you keep the name the same eg name="edit_btn".

Then you can simply put the ID in the buttons value attribute and read it with $_POST['edit_btn'] on the PHP side.

html:

<button type="submit" value="<?=$ID;?>" name="edit_btn">Edit</button>

PHP:

var_dump($_POST['edit_btn']);

If you for some reason INSIST on keeping the ID in the NAME, you COULD do something like this instead:

HTML:

<button name="edit_btn[123]" value="1">Edit</button>

PHP:

var_dump(key($_POST['edit_btn']));


回答2:

I have gone ahead and accepted the answer that assisted me in resolving the issue, however in the off chance that others read and want to better understand the final outcome, this is the code that was used:

Button Code:

<button type="submit" class="btn bg-blue2 btn-gradient btn-xs" name="reorder" value="pages:<?=$GAS['uid'];?>"><span class="glyphicons glyphicons-roundabout"></span> </button>

Determining the button used (Debug Testing Only!):

if($_POST['reorder'] == "sections"){ echo 'DEBUGGER ACTIVATED: SUBMITTED SECTIONS FOR RE-ORDER';  }
if(substr($_POST['reorder'], 0, 6) == "pages:"){ echo 'DEBUGGER ACTIVATED: SUBMITTED PAGES FOR RE-ORDER FOR SECTION #'.substr($_POST['reorder'], 6);  }


标签: php forms