Skip to content
Advertisement

Adding Attribute to Form Element Using PHP

I’m using a CMS and a form builder extension, the extension allows me to run PHP scripts when on page load.

I’m also able to add custom ‘Additional Attributes’ to individual elements, the ‘Additional Attributes’ section is a free text field allowing me to enter custom text e.g. maxlength="20", placeholder="Admin Only" you can see below.

I have a form that contains the following elements (showing only four for brevity, actual form contains many more);

// user fields
<input type="text" value="" name="form[Name]" id="Name" class="form-control" maxlength="20">
<input type="text" value="" name="form[Address]" id="Address" class="form-control" maxlength="20">
// admin only fields
<input type="text" value="" name="form[AdminName]" id="AdminName" class="form-control" maxlength="20" placeholder="Admin Only">
<input type="text" value="" name="form[AdminComment]" id="AdminComment" class="form-control" maxlength="50" placeholder="Admin Only">

Using only PHP (and not a DOM Parser) I need to be able to add the readonly attribute all form elements that are for admins only. In the form above that is the last two inputs.

<?php
    if (userid == something) {
        // add 'readonly' attribute to all admin inputs
    } 
?>

I was thinking of using str_replace or the form ‘Additional Attributes’ feature somehow?

I can’t use Javascript / JQuery.

Advertisement

Answer

The solution I found was to add a custom attribute to the html element e.g. xyz, then use str_replace in order to replace this attribute with readonly.

The form inputs weer generated from a PHP variable $formData.

<input type="text" value="" name="form[Name]" id="Name" class="form-control" maxlength="20" xyz>

<?php
    if (userid == something) {
        str_replace("xyz","readonly",$formData)
    } 
?>
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement