Buy Now
Sign in

FAQ search

How can I ask new users for information and not ask logged in users?

Details
Published: Monday, 30 November -0001 00:00
If you have a form that needs contact information like name and email then this is already saved in the User data for registered users. It can be useful to show this saved information if the user is logged in but still ask new users to complete the form inputs. This FAQ shows a way to do this.
This code snippet can be used in a Custom Element element. If the user is logged in then it will show their saved named and email in readonly inputs, otherwise it will show empty inputs to be completed by the user.
<?php
$user =& JFactory::getUser();
$name = '';
$email = '';
$readonly = '';
if ( $user->id > 0 ) {
  $name = $user->name;
  $email = $user->email;
  $readonly = "readonly='readonly'";
}
?>
<div class="ccms_form_element cfdiv_text" id="name_container_div" style="">
  <label for="name">Name</label>
  <input id="name" maxlength="150" size="30" class="" 
    title="" value=" <?php echo $name; ?> /" name="name" 
    type="text" <?php echo $readonly; ?> />
  <div class="clear"></div>
  <div id="error-message-name"></div>
</div>
<div class="ccms_form_element cfdiv_text" id="email_container_div" style="">
  <label for="email">Email</label>
  <input id="email" maxlength="150" size="30" class="" 
    title="" value=" <?php echo $email; ?> /" name="email" 
    type="text" <?php echo $readonly; ?> />
  <div class="clear"></div>
  <div id="error-message-email"></div>
</div>
If you want logged in users to be able to edit these values then leave out the highlighted 'readonly' parts of the code.
This example shows the saved name and email, you could use similar code for other saved values like the username if you prefer. 

Note that registered users have to be logged in for this to work. If they are not logged in they will see the empty form like any other visitor.