Disabling Form Fields

I have an app I’m working on where the admins want to be able to disable certain form fields so they can’t be updated if your’e not an admin.  In other words, if you are a user updating your information, you can change xx and xxx fields, but not x or xxxx.  I figured, no problem, just add “disabled=’disabled'” to the fields you don’t want users updating if you’re not logged in as an admin.  

The problem…
When you add “disabled=’disabled'” to a form field, that form field doesn’t submit any data via _POST or _GET.  This translates to your app updating the fields with nothing,  effectively deleting the information in the database.  

The solution…
Instead of “disabled=’disabled'”, use “readonly=’readonly'”.  

The second problem…
“readonly=’readonly'” only works on <input> tags.  You can’t readonly a <select>.

The final solution…
I found this on Stack Overflow.  I’m not crazy about the solution because it simply creates a second variable of the same name.  This seems sloppy to me because, as the author admits, different web servers might deal with it differently.  I prefer to write code that is going to work everywhere.  

My solution was to change the form fields I didn’t want edited by anyone who isn’t an admin to unnamed <input>s with the “readonly=’readonly'” attribute set, then create a hidden form field with the proper name and the proper value that would take the place of the select field that couldn’t be made read only.

Hopefully that makes sense.  It means adding a bunch of code, but it’s going to work on any PHP script because it’s going to change what gets displayed depending on your user level.  If you’re an admin, you’ll see the <select> field with all the options.  If you’re not an admin, you’ll see a grayed out <input> that you can’t change, but you still see what is in the database.

Leave a Reply

Your email address will not be published. Required fields are marked *