Create button with link in Yii2

90.1k Views Asked by At

I am trying to setup a button with a link to a view. However yii\bootstrap\Button does not have a property url. I would rather use Yii as supposed to just use flat out php. The code as below would be the ideal situation, but since the url option does not exist, is there an other way to fix this using Yii?

echo Button::Widget([
    'label' => 'label',
    'options' => ['class' => 'btn btn-primary'],
    'url' => Url::toRoute(['/controller/action']),
]);
5

There are 5 best solutions below

0
soju On BEST ANSWER

You could simply use Html::a() :

<?= Html::a('label', ['/controller/action'], ['class'=>'btn btn-primary']) ?>

Or create your own version of Button class to handle this.

PS: you don't need Url::toRoute

0
Kalpesh Desai On

you can also pass parameter to url

<?= Html::a('Update', ['update', 'id' => $model->id], ['class' => 'btn btn-primary']) ?>

You can also render the html

<?= Html::a('<span class="btn-label">Update</span>', ['update', 'id' => $model->id], ['class' => 'btn btn-primary']) ?>
0
Federico Benedetti On

You can try this:

Html::button("<span class='glyphicon glyphicon-plus' aria-hidden='true'></span>",
                    ['class'=>'kv-action-btn',
                        'onclick'=>"window.location.href = '" . \Yii::$app->urlManager->createUrl(['/create','id'=>$model->id]) . "';",
                        'data-toggle'=>'tooltip',
                        'title'=>Yii::t('app', 'Create New Record'),
                    ]
                )
0
Mohan Prasad On

If you want your label name or button to have translations

<?= Html::a(Yii::t('app','label'), ['/controller/action'], ['class'=>'pull-right', 'style' => 'padding-right:10px;']) ?>

If you want to add an icon for this link

 <?= Html::a("<i class=\"fa fa-icon\"></i> ".Yii::t('app','label'), ['/controller/action'], ['class'=>'pull-right', 'style' => 'padding-right:10px;']) ?>

if you want to pass parameters

 <?= Html::a(Yii::t('app','label'), ['/controller/action', id => $model->id], ['class'=>'pull-right', 'style' => 'padding-right:10px;']) ?>
0
BartT On

For me works:

<?= Html::button('Press me!', ArrayHelper::merge(['value'=>Url::to(['controller/action'])], ['additionalOptions'])); ?>

So, use ['value'=> Url::to(),] instead of ['url' => ...]