John Davidson

php - Accessing $_post value via TWIG template

0 comments
Message:


I have a working home.php which renders the TWIG-style home.html template. home.php accesses my DB and renders the resulting DB rows in the twig template via a form. The form is a single field select list. I want to select one of the records an pass it on to a subsequent php pgm. For that I use $_post. But I can not access the posted value in the resulting php pgm. What is wrong with my code?
Sorry, I am new to twig (using it without symfony) and coding knowledge in php is just basic. Thanks for any tips!
Rendering twig template in home.php:


<?php
echo $template->render(array_merge(['mydata1' => $mydata1]),(['post' => $_POST]));
?>

Form in the TWIG template home.html. mydata1.Title is the DB-value that I want to post to action.php


<form action="action.php" method="post" name="tl1">
<label for="mydata1.Title" style="display:inline-table;">
<span>{% set k=1 %}
<select name="tl1">
{% if mydata1.records_count > 0 %}
{% for i in range(0, mydata1.records_count - 1) %}
<option value="{{ mydata1.Title[loop.index0] }}"> {{ mydata1.Title[loop.index0] }} </option>
{% endfor %}
{% endif %}
</select>
</span>
</label>
<input type="submit" value="Button Text" name="tl1" class="btn btn-primary" />
</form>

Finally echoing the posted value in action.php:


echo "The posted value from home.php is: ",$_post['mydata1.Title'];

What I want to do is hitting the button next to the form (named 'Button text' in the code above) I want to pass the selected list value of the form "mydata1.Title" (Title=fieldname) to action.php and use it there.


I have tried a lot of variations both in home.php and home.html, but none of my attempts ever showed any DB value in action.php.
Form rendering works as espected. Output in action.php is an empty $_post variable.



My Answer:
php
require_once 'vendor/autoload.php';

$loader = new \Twig\Loader\FilesystemLoader('templates');
$twig = new \Twig\Environment($loader);

// Accessing DB and getting rows
$rows = // fetch rows from DB

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$selectedRow = $_POST['selectedRow'];
// Redirect to another PHP program with selected row
header("Location: another_program.php?selectedRow=$selectedRow");
exit();
}

echo $twig->render('home.html', ['rows' => $rows]);
?>


html




Home










In the above code, when the form is submitted, the selected value from the select list is accessed using `$_POST['selectedRow']` in the PHP code. Make sure that the `name` attribute of the select element matches the key used to access the value in `$_POST`.

If you are still facing issues with accessing the posted value in the subsequent PHP program, please provide more details or code snippets for further assistance.

Rate this post

3 of 5 based on 9217 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us