file commands/FlagController.php
namespace app\commands;
use yii;
use yii\console\Controller;
use yii\base\Component;
use app\components\flag\AbstractFlagService;
use app\components\flag\FlagService;
class FlagController extends Controller
{
public function actionCheck()
{
$flagService = \Yii::$app->get('flag-service');
if(Yii::$app->flag->run()) {
echo true;
}
}
}
config\console.php
<?php use \yii\console\controllers\MigrateController;
$config = [
'id' => 'basic-console',
'controllerNamespace' => 'app\commands',
'components' => [
'flag' => [
'class' => 'app/components/flag/FlagService',
]
],
];
if (YII_ENV_DEV) {
$config['bootstrap'][] = 'gii';
$config['modules']['gii'] = [
'class' => 'yii\gii\Module',
];
}
I have a error Exception 'ReflectionException' with message 'Class app/components/flag/FlagService does not exist'. How to use app-component in console application on yii2
Related
I don't know what going on, I was setting my mongodb before. then I refresh my page and suddenly there was an error notification
asking for namespace missing
Unable to find 'application\modules\home\models\User' in file: F:\aplikasi\laragon\www\yiiad\application/modules/home/models/User.php. Namespace missing?
I have already checked the codes I made before, and still don't know where my mistakes
This is my models user structure
\application\modules\home\models\user
this models\user code
<?php
namespace home\models;
use Yii;
use yii\behaviors\TimestampBehavior;
use yii\db\ActiveRecord;
use yii\db\Query;
use yii\web\IdentityInterface;
class User extends ActiveRecord implements IdentityInterface
{}
?>
My Alias
<?php
Yii::setAlias('#modules', dirname(dirname(__DIR__)) . '/application/modules');
My Path setting
'basePath' => '#modules/home',
'modules' => [
'admin' => [
'class' => 'admin\Module'
],
'home' => [
'class' => 'home\Module'
],
],
My modules
<?php
namespace home;
class Module extends \yii\base\Module{
public function init()
{
parent::init();
if (\Yii::$app instanceof \yii\console\Application) {
$this->controllerNamespace = 'home\controllers';
}
}
}
Namespace home is incorrect. You should use modules alias in the namespace of the module
namespace modules\home;
class Module extends \yii\base\Module
{
}
and in config
'modules' => [
'home' => [
'class' => 'modules\home\Module'
],
],
Or you must set alias for home directory
'aliases' => [
'#home' => 'path to home directory'
],
'modules' => [
'home' => [
'class' => 'home\Module'
],
],
I am a newbie in yii2. I want to use roxymce file manager in my yii2 project. I followed these docs for use in yii but when using this section, I get Undefined variable: form error and when use ActiveForm::begin() in I get Getting unknown property: navatech\roxymce\models\UploadForm::thumb error. I want to know when I must use that's controllers in my project. This code for my fileupload view:
<?php
use yii\widgets\ActiveForm;
use yii\web\View;
use yii\helpers\Url;
$this->title = Yii::t('app', 'Upload Course Files');
$this->params['breadcrumbs'][] = ['label' => Yii::t('app', 'Presented Courses'), 'url' => ['index']];
$this->params['breadcrumbs'][] = $this->title;
?>
<div class="row">
<?php $form = ActiveForm::begin(['options' => ['enctype' => 'multipart/form-data'], 'action' => '#']); ?>
<?php $form->field($model, 'file')->fileInput(['id' => 'fieldID1'])->label(false) ?>
<a href="<?=Url::to([
'/roxymce/default',
'type' => 'media',
'input' => 'fieldID1',
'dialog' => 'iframe',
]) ?>" id="fileup" class="fancybox" ><i class="fa fa-upload"></i></a>
<?php ActiveForm::end();?>
<?php
$this->registerJsFile('#web/js/jquery.fancybox.min.js', ['depends' => [\yii\web\JqueryAsset::className()]]);
$this->registerCssFile('#web/css/jquery.fancybox.min.css', ['depends' => [\yii\web\JqueryAsset::className()]]);
$this->registerJs('
$("#fileup").fancybox({ type: "iframe"});
', View::POS_END);
?>
And this code is for the controller of this view(fileupload):
public function actionUploadfile()
{
$model = new UploadForm();
return $this->render('uploadfile',['model'=>$model]);
}
And this my main config file in backend directory:
'modules' => [
'roxymce' => [
'class' => 'navatech\roxymce\Module',
'uploadFolder' => '#app/web/uploads/images',
'uploadUrl' => '/uploads/images',
],
],
I used yii2 advancd template. If anyone used this module, please hint me.
Simply becouse the variable $form is not defined if you use the code like int the example. In your view when you use the extension you need to use ActiveForm::begin() like this:
Simple example
<?php
$form = ActiveForm::begin(['id' => 'roxymce-form']);
echo $form->field($model, 'thumb')->textInput(['id' => 'fieldID'])->label(false);
?>
<a href="<?= \yii\helpers\Url::to([
'/roxymce/default',
'type' => 'image',
'input' => 'fieldID',
'dialog' => 'fancybox',
]) ?>"><i class="fa fa-upload"></i></a>
<script>
$("a").fancybox();
</script>
<?php ActiveForm::end(); ?>
[Edit]
It was pretty hard to run it but in the end I succeeded. I use basic template of Yii2.
Start with install package with composer like in the guide. After this create the classes of assets bundles to publish javascript packages. My assets bundles are these and they are locate in applicationroot/assets folder:
assets/AppAsset.php
<?php
namespace app\assets;
use yii\web\AssetBundle;
class AppAsset extends AssetBundle
{
public $basePath = '#webroot';
public $baseUrl = '#web';
public $css = [
'css/site.css',
];
public $js = [
];
public $depends = [
'yii\web\YiiAsset',
'yii\bootstrap\BootstrapAsset',
];
public $jsOptions = [
'position' => \yii\web\View::POS_HEAD,
];
}
assets/FancyBoxAsset.php
<?php
namespace app\assets;
use yii\web\AssetBundle;
class FancyBoxAsset extends AssetBundle
{
public $sourcePath = '#bower/fancybox/source';
public $js = [
'jquery.fancybox.pack.js',
];
}
assets/FontAwesomeAsset.php
<?php
namespace app\assets;
use yii\web\AssetBundle;
class FontAwesomeAsset extends AssetBundle
{
public $sourcePath = '#bower/fontawesome';
public $css = [
'css/font-awesome.min.css',
];
}
assets/LazyLoadAsset.php
<?php
namespace app\assets;
use yii\web\AssetBundle;
class LazyLoadAsset extends AssetBundle
{
public $sourcePath = '#bower/jquery.lazyload';
}
assets/PatternflyTreeviewAsset.php
<?php
namespace app\assets;
use yii\web\AssetBundle;
class PatternflyTreeviewAsset extends AssetBundle
{
public $sourcePath = '#bower/patternfly-bootstrap-treeview/dist';
public $css = [
'bootstrap-treeview.css',
];
public $js = [
'bootstrap-treeview.js',
];
}
assets/TinymceAsset.php
<?php
namespace app\assets;
use yii\web\AssetBundle;
class TinymceAsset extends AssetBundle
{
public $sourcePath = '#bower/tinymce';
public $jsOptions = [
'position' => \yii\web\View::POS_HEAD,
];
}
Now you must to add in your config file this lines of code:
config/web.php
return [
'id' => 'basic',
'basePath' => dirname(__DIR__),
...
'modules' => [
'roxymce' => [
'class' => 'navatech\roxymce\Module',
'uploadFolder' => '#app/web/uploads/images',
'uploadUrl' => '../uploads/images',
],
],
'urlManager' => [
'enablePrettyUrl' => true,
'showScriptName' => false,
'rules' => [
'' => 'site/index',
'<controller:\w+>/<action:\w+>/' => '<controller>/<action>',
'<module:\w+>/<controller:\w+>/<action:\w+>/' => '<module>/<controller>/<action>',
],
]
...
];
After you need to configure your application for work in a clean URL context. Follow this for more information about: Enable clean URL in Yii2
Now you can finally fully use the plugin in all its contexts. There are two methods for use it:
Integrated with TinyMce
views/site/tinymceIntegrated.php
<?php
use \app\assets;
assets\FontAwesomeAsset::register($this);
assets\LazyLoadAsset::register($this);
assets\FancyBoxAsset::register($this);
assets\PatternflyTreeviewAsset::register($this);
assets\TinymceAsset::register($this);
// Include ActiveRecord Model
echo \navatech\roxymce\widgets\RoxyMceWidget::widget([
'model' => app\models\YourModel::findOne(1),
'attribute' => 'content',
]);
// Sample HTML without ActiveRecord Model
echo \navatech\roxymce\widgets\RoxyMceWidget::widget([
'name' => 'Post[content]',
]);
Without TinyMce
views/site/tinymceWithout.php
<?php
use yii\helpers\Html;
use \app\assets;
assets\FontAwesomeAsset::register($this);
assets\LazyLoadAsset::register($this);
assets\FancyBoxAsset::register($this);
assets\PatternflyTreeviewAsset::register($this);
//assets\TinymceAsset::register($this);
$js = <<<JS
$("a").fancybox();
JS;
$this->registerJs($js, \yii\web\View::POS_READY, 'upload-handler');
?>
<a href="<?= \yii\helpers\Url::to([
'/roxymce/default',
'type' => 'image',
'dialog' => 'fancybox',
]) ?>"><i class="fa fa-upload"></i></a>
With this configuration for me work.
I am using Yii2 Advanced version.
This is Login Model:
namespace common\models;
use Yii;
use yii\base\Model;
use common\models\User;
class LoginForm extends Model{
public $username;
public $password;
public $rememberMe = true;
public $verifyCode;
const BACKEND_TEST = 'none';
const BACKEND_ID = 'test';
const BACKEND_USERNAME = 'backend_username';
private $user;
public function rules(){
return [ [['username','password'],'required','message'=>'{attribute}required...'],
['username','validateUser'], ['verifyCode','captcha','captchaAction'=>'login/captcha','message'=>'Wrong'],
];
}
public function validateUser($attribute,$params){
$user = User::findOne(['username'=>$this->username]);
if(!$user || (md5($this->password) != $user['password'])){
$this->addError('password','Wrong>_<...');
}else{
$this->user = $user;
}
}
public function login(){
if(!$this->user){
return false;
}
var_dump($this->userInfo());
$this->createSession();
return true;
}
private function createSession(){
//Yii::$app->session->open();
Yii::$app->set(self::BACKEND_ID,$this->user['id']);
Yii::$app->set(self::BACKEND_USERNAME,$this->user['username']);
}
public function userInfo(){
return $this->user;
}
Also, there is LoginController that I think have no issue, and next thing is when user try to login and session will be opened, and direct to site page.
Here is the sitecontroller:
namespace backend\controllers;
use Yii;
use yii\web\Controller;
use yii\filters\VerbFilter;
use yii\filters\AccessControl;
use common\models\LoginForm;
/**
* Site controller
*/
class SiteController extends Controller
{
public function actionIndex()
{
//var_dump(Yii::$app->session->get(common\models\LoginForm::BACKEND_ID));
var_dump(LoginForm::userInfo());
return $this->renderPartial('index');
}
Every time I try to login and the Error message comes out and provides:
Invalid Configuration – yii\base\InvalidConfigException
Unexpected configuration type for the "test" component: integer
How to solve the issue, and I try to get $user that stores all the data and it seems to fail?
main.php:
<?php
$params = array_merge(
require(__DIR__ . '/../../common/config/params.php'),
require(__DIR__ . '/../../common/config/params-local.php'),
require(__DIR__ . '/params.php'),
require(__DIR__ . '/params-local.php')
);
return [
'id' => 'app-backend',
'basePath' => dirname(__DIR__),
'controllerNamespace' => 'backend\controllers',
'bootstrap' => ['log'],
'modules' => ['smister' => [
'class' => 'backend\modules\smister\smister',
],],
'components' => [
'user' => [
'identityClass' => 'common\models\User',
'enableAutoLogin' => true,
],
'log' => [
'traceLevel' => YII_DEBUG ? 3 : 0,
'targets' => [
[
'class' => 'yii\log\FileTarget',
'levels' => ['error', 'warning'],
],
],
],
'errorHandler' => [
'errorAction' => 'site/error',
],
/*
'urlManager' => [
'enablePrettyUrl' => true,
'showScriptName' => false,
'rules' => [
],
],
*/
],
'params' => $params,
];
You are using
Yii::$app->set(self::BACKEND_ID,$this->user['id']);
probably for set a param value ..
but the Class yii\web\Application (alias Yii::$app->set ) contain a function named set() that register component ..(so your error : Unexpected configuration type for the "test" component: integer) in this way your code is misundestood by Yii2 because your costant BACKEND_ID = 'test'; is not a component id but the key for a param
see this reference for check
http://www.yiiframework.com/doc-2.0/yii-web-application.html
http://www.yiiframework.com/doc-2.0/yii-di-servicelocator.html#set()-detail
for you scope if you need param you can use the file param.php
returning the param you need
file config/param.php
<?php
return [
'test' => 'my_initial_value',
];
and you can access this param simply using
\Yii::$app->params['test'],
or you can simply setting runtime
\Yii::$app->params['test'] = 'Your_value';
I'm devising a codeception test to load a component,.... I have the following test file
<?php
namespace tests\codeception\common;
use Yii;
class FoursquareTest extends \Codeception\TestCase\Test
{
public $appConfig = '#tests/codeception/config/common/unit.php';
public function setUp()
{
parent::setUp();
$config = [
'components' => [
'foursquare' =>
[
'class' => 'garyrutland\foursquare\Foursquare',
'clientId' => '',
'secret' => ''
]
]];
Yii::configure(Yii::$app, $config);
}
// tests
public function testSearch()
{
//$this->assertInstanceOf('garyrutland\\foursquare\\Foursquare', Yii::$app->foursquare);
}
public function fixtures()
{
return [
'foursquare' => [
'class' => FoursquareFixture::className()
],
];
}
}
But when I run
codecept run unit FoursquareTest.php -vv
I get
PHPUnit_Framework_Exception: Creating default object from empty value
#1 /path/to/htdocs/yii/vendor/yiisoft/yii2/BaseYii.php:518
#2 /path/to/htdocs/yii/tests/codeception/common/unit/FoursquareTest.php:22
I instantiate the Foursquare class directly though there is no problem....
Whay do i gee the created Object Error
I am working on Yii2 rest API, When I call create action of enquiryontroller then I am getting this error : "NetworkError: 405 Method Not Allowed".
And also I go through YII2 documentation but not able to trace my issue.
Please check and revert, it will be a great help.
Here is controller code that is EnquiryController.php :
<?php
namespace frontend\controllers;
use Yii;
use common\models\Enquiry;
use yii\filters\ContentNegotiator;
use yii\web\Response;
use yii\filters\AccessControl;
use yii\rest\ActiveController;
use yii\filters\auth\HttpBearerAuth;
use yii\filters\VerbFilter;
use yii\data\ActiveDataProvider;
class EnquiryController extends ActiveController
{
/**
* #inheritdoc
*/
public $modelClass = 'common\models\Enquiry';
public $serializer = [
'class' => 'yii\rest\Serializer',
'collectionEnvelope' => 'items',
];
public function behaviors()
{
$behaviors = parent::behaviors();
$behaviors['authenticator'] = [
'class' => HttpBearerAuth::className(),
];
$behaviors['contentNegotiator'] = [
'class' => ContentNegotiator::className(),
'formats' => [
'application/json' => Response::FORMAT_JSON,
],
];
return $behaviors;
}
public function actions()
{
$actions = parent::actions();
// disable the "delete" and "create" actions
unset($actions['create']);
unset($actions['delete'], $actions['view']);
unset($actions['index']);
// customize the data provider preparation with the "prepareDataProvider()" method
return $actions;
}
public function actionCreate()
{
$model = new Enquiry();
return Yii::$app->getRequest()->getBodyParams();
if ($model->load(Yii::$app->getRequest()->getBodyParams(), '') && $model->validate()) {
$model->slug = \common\components\Helper::slugify($model->title);
$model->user_id = Yii::$app->user->id;
$model->save();
//mail functionality
return true;
}
return $model;
}
}
and code in config/main-local.php :
'urlManager' => [
'class' => 'yii\web\UrlManager',
'baseUrl' => $baseUrl,
'enablePrettyUrl' => true,
'showScriptName' => false,
//'enableStrictParsing' => true,
'rules' => [
['class' => 'yii\rest\UrlRule', 'controller' =>['api'], 'pluralize'=>true],
],
],
],
'as access' => [
'class' => 'mdm\admin\components\AccessControl',
'allowActions' => [
'site/*',
'api/login',
'profile/*',
'api/activate-user',
'api/contact',
'home/*',
'post/*',
'pages/*',
'categories/*',
'guestbook/*',
'faq/*',
'news/*',
'events/*',
'enquiry/*',
'partners/*',
'api/signup'// add or remove allowed actions to this list
]
],
Have a look to this guide
// disable the "delete" and "create" actions
unset($actions['delete'], $actions['create']);
because in your code you disable the create, delete, view and index action
public function actions()
{
$actions = parent::actions();
// disable the "delete" and "create" actions ?????
unset($actions['create']); ////????
unset($actions['delete'], $actions['view']); /// ????
unset($actions['index']); ////????
// customize the data provider preparation with the "prepareDataProvider()" method
return $actions;
}