yii2
Components
Zoeken…
Applicatiecomponenten maken en gebruiken
Stappen om een component te maken:
- Maak een map met de naam
components
in uw projecthoofdmap - Maak uw component in de map Components, bijvoorbeeld:
MyComponent.php
namespace app\components;
use Yii;
use yii\base\Component;
use yii\base\InvalidConfigException;
class MyComponent extends Component
{
public function demo()
{
return "welcome";
}
}
- Registreer uw component in het
config/web.php
bestand
components' => [
'mycomponent' => [
'class' => 'app\components\MyComponent',
],
]
Nu kunt u uw componentmethode gebruiken:
namespace app\controllers;
use Yii;
class DemoController extends \yii\web\Controller
{
public function actionTest()
{
echo Yii::$app->mycomponent->demo();
}
}
Vervolgkeuzelijst met componentfunctie
Creëer functie in MyComponent.php
namespace app\components;
use Yii;
use yii\base\Component;
use yii\base\InvalidConfigException;
use yii\helpers\Url;
use yii\helpers\ArrayHelper;
use app\models\User;
class MyComponent extends Component
{
// Function return list of id & user Names,used for dropdownlist
public function getUserID()
{
$code = User::find()->select('id,name')
->where(['is_deleted'=>'n'])
->all();
$result = ArrayHelper::map($code, 'id', 'name');
if($result)
return $result;
else
return ["null"=>"No User"];
}
}
-> Registreer component in web.php
components' => [
'mycomponent' => [
'class' => 'app\components\MyComponent',
],
]
-> gebruik het in uw weergave
<?= $form->field($model, 'user_id')->dropDownList(Yii::$app->mycomponent->getUserID())?>
Modified text is an extract of the original Stack Overflow Documentation
Licentie onder CC BY-SA 3.0
Niet aangesloten bij Stack Overflow