How to Disable a button in Yii2

2019-05-24 11:05发布

I'm trying to disable the Create Project Button when the user is not logged in, the button will Hide or disable.

And this is my condition:

<p>
    <?php
    if (Yii::$app->user->isGuest) {
        Html::a('Create a Project', ['create'], ['class' => 'btn btn-primary btn-xs']);
    } elseif(Yii::$app->user->identity->username) {
        Html::a('Create a Project', ['create'], ['class' => 'btn btn-success']);
    }
    ?>
</p>

It's working, But, when the user is logged in, the button is already Hide!

How can disable or hide the button in Yii2 and fix that problem?

is there any tutorial about that?

标签: php button yii2
3条回答
小情绪 Triste *
2楼-- · 2019-05-24 11:31

You need to add a disabled attribute to disable the button, or to hide it completely you can use CSS style=display: none;

Both are used in the code below

<p>
    <?php
        if (Yii::$app->user->isGuest) {
            // This button will be displayed, but is disabled 
            Html::a('Create a Project', ['create'], ['class' => 'btn btn-primary btn-xs', 'disabled' => 'disabled']);
        } elseif(Yii::$app->user->identity->username) {
            Html::a('Create a Project', ['create'], ['class' => 'btn btn-success']);
        } else {
            // This button will not be displayed (it is hidden)
            Html::a('Create a Project', ['create'], ['class' => 'btn btn-primary btn-xs', 'style' => 'display: none;']);
        }
    ?>
</p>
查看更多
forever°为你锁心
3楼-- · 2019-05-24 11:40

If you are just checking for logged in user then Use !Yii::$app->user->isGuest and you forget echo:

if (!Yii::$app->user->isGuest) {
        echo Html::a('Create a Project', ['create'], ['class' => 'btn btn-primary btn-xs'])
} 
查看更多
女痞
4楼-- · 2019-05-24 11:45

First of all you cannot disable a tag. disabled attribute works fine on Button tags eg:

<?= Html::Button('Project', ['class' => 'btn btn-success', 'disabled' => Yii::$app->user->isGuest ]) ?>

If you really want to disable a tag then you can use this example:

HTML:

<a id="a1" href="http://www.google.com">Google 1</a>

Javascript:

$('#a1').attr('disabled', 'disabled');

$('a').on('click', function(e) {
    if ($(this).attr('disabled') == 'disabled') {
        e.preventDefault();
    }
});
查看更多
登录 后发表回答