submit params via link and post method?


(MetCrawl) #1

Hi Guys!

I would like to send params via a link and POST method…

In Yii 1.x I could do the following:




echo CHtml::link(

    'Link Text', 

    Yii::app()->createUrl("controller/action"), array(

        'submit'=>array('controller/action'),

        'params'=>array('myParam' => $myParam) 

    )

);  



And Yii automatically generated JQuery code like:

But I could not figure out how to do it in Yii 2.

I looked in yii\grid\ActionColumn.php how it was done with the delete button…

but I could not get it to work with my link:




echo Html::a(

	'Link Text', 

	Url::to(['controller/action']), 

	[

		'data-confirm' => "Want to submit?", // <-- confirmation works...

		'data-method' => 'post',

		'data-params' => 'myParam=anyValue'

	]

);



My Questions:

  • Is there a equivalent in Yii 2?

  • If yes: How to do it correctly?

  • Or do I have to write my own JQuery function for the links?

Thank you and best regards


(Ilaiyamdu) #2

<?php  echo Html::a('My Link',['controller/action','id'=>Yii::$app->['params'],

['class'=>'btn btn-primary'])?>

My link


(MetCrawl) #3

Thanks for your answer but as far as I have tested:

Your solution uses $_GET method to transmit the params like any normal link. :)

But I was looking for a solution to submit the params with $_POST method.

Anyway I now did the following:




echo Html::a(

    'My Link with POST submit',

    ['controller/action'],

    [

	'onclick' => "

	    $.ajax({

		url: '".Url::to(['controller/action'])."',

		type: 'POST',

		data: 'myParam=$model->myParam',

	    })

	",

    ]

);



And it seems to work.

If anybody knows a better way please share with me. :)

Thank you and best regards


(Locustv2) #4

<?= Html::a(‘test link’, Url::toRoute([’/test/index’, ‘param’ => ‘value’]), [‘data-method’ => ‘post’]) ?>


(tomsea) #5

Hello, I asked a very similar question to this one. Maybe a little late, but the equivalent in Yii2 would be like this:


<?= Html::a('Link Text', ['controller/action'], [

    'data'=>[

        'method' => 'post',

        'confirm' => 'Are you sure?',

        'params'=>['MyParam1'=>'100', 'MyParam2'=>true],

    ]

]) ?>

I hope this works better for you. However, this method ignores the rest of the ActiveForm controls (post parameters), which is what I’m trying to achieve. Please have a look here in case you found a better way to do that.

Thank you.