简体   繁体   中英

YII2 how to handle condition as per login usertype?

在此处输入图片说明 vendorinfo.php I have to hide and show button as per login usertype.Here if login user is 'Visitor' then only show the rating button ow in any condition like may be user is admin or now any user without login condition is also there. My code is work if usertype is 'Visitor' or 'Admin' but it fails when no one login. Actually that time this condition can not able to getting the type of user For that please help me I am not able to understand to handle this condition

<?php
if(!\Yii::$app->user->isGuest) {
$user = \Yii::$app->user->identity->id;
  $userType = \Yii::$app->user->identity->type;
  echo ''.$userType;
  echo '<input type="text" value='.$userType.' id="usertype"/>';
} else {
  echo '<div>Div if user is not visitor</div>';
}
?>

Script: script for hide and show the div

<script type="text/javascript">
  $(document).ready(function(){
    var userType= document.getElementById('usertype').value;

    if(userType == 'Visitor') {  
      $('#divUserRate').show();
    } else {  
      $('#divUserRate').hide();  
    }
});

</script>

You can use isGuest property from user model.

echo (Yii::$app->user->isGuest) ? '<div>Div if user is visitor</div>' : '<div>Div if user is not visitor</div>';

You can also use Rbac to manage roles and access.

if(Yii::$app->authManager->checkAccess(Yii::$app->user->id, "editor"){
    //do something
}

For hide div.I have add class in button after that hide that class instead of div

<script type="text/javascript">
 $(document).ready(function(){

    $('.btnRating').hide(); 
    $('#divliveventGallery').hide();
    var userType= document.getElementById('usertype').value;
    if(userType == 'Visitor' || userType == 'FB' || userType == 'GL') {  
      $('.btnRating').show(); 
    } else if(userType == 'Vendor'){ 
      $('.btnRating').hide();  
    } else if(userType == "") {
      $('.btnRating').hide(); 
    }
});
**************Button html**************
 echo '<button type="button" id="btnRate" onClick="rateDetail('.$dp['ven_id'].','.$userId.');" class=" btnRating btn btn-default btn-block" data-toggle="modal" data-target="#rcrate">';
             echo '<strong>Rate</strong>';
             echo '</button> ';

</script>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM