Where do I put my widget controller action?

Fairly new to yii2 and am creating a mailchimp sign up widget I currently have the following in my controller however I was wondering where do I put my code for the post form action etc as I see widgets have run and init but unsure on where to but my mailchimp code that will send the data to mailchimp through the API

Current Widget (Controller)


<?php

namespace common\widgets;


use yii\base\Widget;

use frontend\models\Newsletter;

use yii\data\ActiveDataProvider;

use Yii;

use sammaye\mailchimp\Mailchimp;


/**

 * MailchimpWidget

 */

class NewsletterWidget extends Widget

{


    public function run()

    {

		$mc = new Mailchimp(['apikey' => 'xxxxxxxx']);

		$mc->lists->getList();


		$model = new Newsletter();


        return $this->render('newsletterform', [

		'model' => $model

		]);

    }

}



You have to put widget in your view, not in controller.

Yeah the widget is in my view I’ll edit the question, I was wondering where do I put my post action login

So that when the user submits the form the controller action is executed and the user is signed up.

OK. You could write a new controller, MailChimpController for example, that

will be called from form in widget.




class MailChimpController

{

     public function actionSignup()

     {

           // here you signup user

     }

}



So even if you put widget in all pages of your site, same controller will be always called.

So could I put the signup action in my class NewsletterWidget extends Widget? Or should I create it seperate and then set the action url point to the controller action say in frontend/controllers?

Put it in the model. That is better practice I think.

models\User\SignUp perhaps?

No, widgets haven’t controller (as we intend in Yii).

So you have to write a controller class where send form action. If following is code generated from widget:




<?php

ActiveForm::begin(['action' => 'mail-chimp/signup-user']);

......

......

ActiveForm::end();

?>



Controller will be:




<?php

class MailChimpController

{

     public function actionSignupUser()

     {

     }

}

?>



that receives action request from form.

Thank you, I thought that might be the case just wanted to clarify just so I know I am following best practices and keeping my code/folder structure clean. :)

You did well. Think that actions ( = requests ) are always dispatched from controllers’ actions.