Skip to content Skip to sidebar Skip to footer

How To Create Html Button Based On Condition?

I am using following code:

Solution 1:

If it works, then yes it's one correct method. Another way, using a ternary if statement might be:

<?PHP$button = $_SESSION['WorkMode'] == 'New' 
     || $_SESSION['WorkMode'] == '' ? "Submit" : "Update"; ?><inputid="<?phpecho$button;?>"name="<?phpecho$button;?>"value="<?phpecho$button;?>"type='button' />

Really it's a matter of personal preference and clarity. I prefer to write HTML as HTML (not as a PHP string) and echo variables into that HTML using PHP tags. Some might not like to use this method. If you have PHP short tags switched on you can even use <?=$button;?>

Solution 2:

This is totally valid and readable.

If the number of lines of code is important to you, you could also do:

<?php$action = ($_Session['WorkMode'] == 'New' || $_Session['WorkMode'])? "Submit" : "Update" %>
<input id="<?php echo $action ?>" name="<?php echo $action ?>" value="<?php echo $action ?>" type="button" />

My PHP is a bit rusty so I might be off on the syntax, but you get the idea.

If you use a framework such as cakephp or symphony you can use their helpers to generate buttons more easily.

Solution 3:

Basically, yes you can do it this way. Depending on the size of your application and on your programming experience you might want to consider to start using a templating system (e.g. Smarty). This way you could seperate php code and html markup.

Best wishes, Fabian

Solution 4:

It should be

<?PHPif ($_Session['WorkMode'] == 'New' || $_Session['WorkMode'] == "")     
      echo"<input id='Submit' name='Submit' value='Submit' type='button'/>";      
elseecho"<input id='Update' name='Update' value='Update' type='button'/>";?>

Solution 5:

The better way of doing this is using a template system, ou simply separate the layout code from logic:

view.php:

<?phpif ($new): ?><inputid='Submit'name='Submit'value='Submit'type='button'><?phpelse: ?><inputid='Update'name='Update'value='Update'type='button'><?phpendif; ?>

So, $new variable is sended by the logical code (controller):

controller.php:

$new = ($_Session['WorkMode'] == 'New' || $_Session['WorkMode'] == "");
include("view.php")

This is a better way to doing what you want :). Don't forget that is a good practice to also support internacionalization on view.

Post a Comment for "How To Create Html Button Based On Condition?"