SK111
SK111

Reputation: 43

Passing a variable value through a html button

I'm using HTML within a PHP script. I've set the 'client_id' as '1' but 'client_id' is a variable itself which is being used in a controller to retrieve the client id ($client_id). I don't want to pass through a default value but rather pass through the variable so it can retrieve the value $client_id holds. If I set 'client_id => 'null' then I just get an error saying the client can't be found (which is correct, as there is no client being passed through). If I set 'client_id' => '1', it works but I don't want to pass through a static value.

This is the code for the button:

<?= Html::a('<span class="glyphicon glyphicon-export"></span> Download full questions template', ['export/export-template', 'client_id' => '1', 'type' => 'full'], ['class' => 'btn btn-primary pull-right']); ?>

This is the code to retrieve the $client_id:

```public function actionExportTemplate( $client_id= null, $type = null)
{
    // Get client
    $Client = self::getClient($client_id);```
private function getClient($client_id)
    {
        if (isset(Yii::$app->user->identity->client_id)) {
            $client_id = Yii::$app->user->identity->client_id;
        }
        
        $Client = Client::findOne($client_id);
        
        if (is_null($Client)) {
            throw new NotFoundHttpException('Client not found');
        }

        return $Client;
    }

so my question is, how would I pass through '$client_id' in the HTML button?

Upvotes: 0

Views: 70

Answers (1)

Basir khan
Basir khan

Reputation: 168

Hi you have not mentioned the controller code , but you can pass variable form controller to view like that suppose this is controller class code

function actionExportTemplate( $client_id= null, $type = null){
  $clientId = getClient($client_id);
  return $this->render('demo', ['clientId' => $clientId]);
}

private function getClient($client_id)
{
    if (isset(Yii::$app->user->identity->client_id)) {
        $client_id = Yii::$app->user->identity->client_id;
    }
    
    $Client = Client::findOne($client_id);
    
    if (is_null($Client)) {
        throw new NotFoundHttpException('Client not found');
    }

    return $Client;
}

now suppose this is your view code I name it demo.php on my side.

<?= Html::a('<span class="glyphicon glyphicon-export"></span> Download full questions template', ['export/export-template', 'client_id' => $clientId, 'type' => 'full'], ['class' => 'btn btn-primary pull-right']); ?>

Upvotes: 1

Related Questions