Yii 2 Widget Factory


In Yii 1 there was such a thing as the Widget Factory to set global variables for widgets. Is there a way to set global variables in Yii 2 using a similar method?


I’m not completely sure but I am using some kartik widgets and his approach is to define all defaults in the module configuration (in config/web.php). Then they are overrideable per widget instance. This works well.

How did he define the defaults in config do you know?

'modules' => [

	'datecontrol' =>  [

		'class' => 'kartik\datecontrol\Module',

		// format settings for displaying each date attribute (ICU format example)

		'displaySettings' => [

			Module::FORMAT_DATE => 'dd-M-y',

			Module::FORMAT_TIME => 'HH:mm:ss a',

			Module::FORMAT_DATETIME => 'dd-MM-yyyy HH:mm:ss a',


		// format settings for saving each date attribute (PHP format example)

		'saveSettings' => [

			Module::FORMAT_DATE => 'php:Y-m-d',

			Module::FORMAT_TIME => 'php:H:i:s',

			Module::FORMAT_DATETIME => 'php:Y-m-d H:i:s',


		// set your display timezone

		'displayTimezone' => 'Europe/London',

		// set your timezone for date saved to db

		'saveTimezone' => 'UTC',

		// automatically use kartik\widgets for each of the above formats

		'autoWidget' => true,

		// default settings for each widget from kartik\widgets used when autoWidget is true

		/*			'autoWidgetSettings' => [

		Module::FORMAT_DATE => ['type'=>2, 'pluginOptions'=>['autoclose'=>true]], // example

		Module::FORMAT_DATETIME => ['pluginOptions'=>['autoclose'=>true]], // setup if needed

		Module::FORMAT_TIME => ['pluginOptions'=>['autoclose'=>true]], // setup if needed



		// custom widget settings that will be used to render the date input instead of kartik\widgets,

		// this will be used when autoWidget is set to false at module or widget level.

		/*			'widgetSettings' => [

		Module::FORMAT_DATE => [

		'class' => 'yii\jui\DatePicker', // example

		'options' => [

		'dateFormat' => 'php:d-M-Y',

		'options' => ['class'=>'form-control'],




		// other settings


Ok thanks, is the datecontrol a standard Yii module then?

Anyone have any other answers for this?


Here an example of using Dependency Injection Container, It works fine.

put it in index.php (entry script)

\Yii::$container->set('yii\widgets\ActiveForm', [

			'options' => ['class' => 'form-horizontal'],

			'fieldConfig' => [

			     'labelOptions' => ['class' => 'log-lab'],



Hi Abed,

Ok thanks, will give it a try.