Calling unknown method: yii2mod\cms\controllers\CmsController::setInstance() - php

I don't understand why this error occur.
get error on call a cms
http://localhost/yii-cms/web/cms
Calling unknown method: yii2mod\cms\controllers\CmsController::setInstance()
i am try to use of yii2-cms
cmsController
<?php
namespace yii2mod\cms\controllers;
use Yii;
use yii2mod\cms\models\CmsModel;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
use yii2mod\cms\models\search\CmsModelSearch;
use yii2mod\editable\EditableAction;
use yii2mod\toggle\actions\ToggleAction;
/**
* Class CmsController
* #package yii2mod\cms\controllers
*/
class CmsController extends Controller
{
/**
* #var string view path
*/
public $viewPath = '#vendor/yii2mod/yii2-cms/views/cms/';
/**
* #inheritdoc
*/
public function behaviors()
{
return [
'verbs' => [
'class' => VerbFilter::className(),
'actions' => [
'index' => ['get'],
'create' => ['get', 'post'],
'update' => ['get', 'post'],
'delete' => ['post']
],
]
];
}
/**
* #inheritdoc
*/
public function actions()
{
return [
'edit-page' => [
'class' => EditableAction::className(),
'modelClass' => CmsModel::className(),
'forceCreate' => false
],
'toggle' => [
'class' => ToggleAction::className(),
'modelClass' => CmsModel::className(),
]
];
}
/**
* Lists all CmsModel models.
* #return mixed
*/
public function actionIndex()
{
$searchModel = new CmsModelSearch();
$dataProvider = $searchModel->search(Yii::$app->request->queryParams);
return $this->render($this->viewPath . 'index', [
'dataProvider' => $dataProvider,
'searchModel' => $searchModel
]);
}
/**
* Creates a new CmsModel model.
* If creation is successful, the browser will be redirected to the 'view' page.
* #return mixed
*/
public function actionCreate()
{
$model = new CmsModel();
if ($model->load(Yii::$app->request->post()) && $model->save()) {
Yii::$app->session->setFlash('success', Yii::t('yii2mod.cms', 'Page has been created.'));
return $this->redirect(['index']);
}
return $this->render($this->viewPath . 'create', [
'model' => $model,
]);
}
/**
* Updates an existing CmsModel model.
* If update is successful, the browser will be redirected to the 'view' page.
*
* #param integer $id
*
* #return mixed
*/
public function actionUpdate($id)
{
$model = $this->findModel($id);
if ($model->load(Yii::$app->request->post()) && $model->save()) {
Yii::$app->session->setFlash('success', Yii::t('yii2mod.cms', 'Page has been updated.'));
return $this->redirect(['index']);
}
return $this->render($this->viewPath . 'update', [
'model' => $model,
]);
}
/**
* Deletes an existing CmsModel model.
* If deletion is successful, the browser will be redirected to the 'index' page.
*
* #param integer $id
*
* #return mixed
*/
public function actionDelete($id)
{
$this->findModel($id)->delete();
Yii::$app->session->setFlash('success', Yii::t('yii2mod.cms', 'Page has been deleted.'));
return $this->redirect(['index']);
}
/**
* Finds the CmsModel model based on its primary key value.
* If the model is not found, a 404 HTTP exception will be thrown.
*
* #param integer $id
*
* #return CmsModel the loaded model
* #throws NotFoundHttpException if the model cannot be found
*/
protected function findModel($id)
{
if (($model = CmsModel::findOne($id)) !== null) {
return $model;
} else {
throw new NotFoundHttpException(Yii::t('yii2mod.cms', 'The requested page does not exist.'));
}
}
}

i have following yii2-cms and it's work great
set instance error occur due to they can not find out given class and that's possible due to miss configuration.
follow Configuration Link https://github.com/yii2mod/yii2-cms#configuration
1) To use this extension first you need to configure the comments extension, after that you have to configure the main config in your application:
'modules' => [
'admin' => [
'controllerMap' => [
'cms' => 'yii2mod\cms\controllers\CmsController'
// You can set your template files
// 'layout' => '#app/modules/backend/views/layouts/main',
// 'viewPath' => '#app/modules/backend/views/cms/',
],
],
],
You can then access to management section through the following URL:
http://localhost/path/to/index.php?r=admin/cms/index
2) Add new Rule class to the urlManager array in your application configuration by the following code:
'components' => [
'urlManager' => [
'rules' => [
['class' => 'yii2mod\cms\components\PageUrlRule'],
]
],
],
3) Add to SiteController (or configure via $route param in urlManager):
/**
* #return array
*/
public function actions()
{
return [
'page' => [
'class' => 'yii2mod\cms\actions\PageAction',
// You can set your template files
'view' => '#app/views/site/page'
],
];
}
And now you can create your own pages via the admin panel, and access them via the url of each page.

Yes error is solved by following proper Configuration STEP.
Error is occur due to miss configure second step
2) Add new Rule class to the urlManager array in your application configuration by the following code:
'components' => [
'urlManager' => [
'rules' => [
['class' => 'yii2mod\cms\components\PageUrlRule'],
]
],
],
Full Configuration you need to did :
1) To use this extension first you need to configure the comments extension, after that you have to configure the main config in your application:
'modules' => [
'admin' => [
'controllerMap' => [
'cms' => 'yii2mod\cms\controllers\CmsController'
// You can set your template files
// 'layout' => '#app/modules/backend/views/layouts/main',
// 'viewPath' => '#app/modules/backend/views/cms/',
],
],
],
You can then access to management section through the following URL:
http://localhost/path/to/index.php?r=admin/cms/index
2) Add new Rule class to the urlManager array in your application configuration by the following code:
'components' => [
'urlManager' => [
'rules' => [
['class' => 'yii2mod\cms\components\PageUrlRule'],
]
],
],
3) Add to SiteController (or configure via $route param in urlManager):
/**
* #return array
*/
public function actions()
{
return [
'page' => [
'class' => 'yii2mod\cms\actions\PageAction',
// You can set your template files
'view' => '#app/views/site/page'
],
];
}
And now you can create your own pages via the admin panel, and access them via the url of each page.

You seem to be using the cms extension in your site component as-is.
In your web.php file, add this:
'components' => [
...
'i18n' => [
'translations' => [
'*' => [
'class' => 'yii\i18n\PhpMessageSource',
'basePath' => '#app/messages'
'sourceLanguage' => 'en',
],
],
],
]
...,
'controllerMap': => [
'cms' => 'yii2mod\cms\controllers\CmsController'
],
NOTE: You should exclude the path about configuring it as a component in the admin module since you're not using it anyway.
If you were using it in a module, then the steps documented in the README is just fine for you.

Related

i cant directly going to login page with codeigniter 4, and using myth-auth

i tried to using codeigniter-4 and try using MYTH\AUTH, and i get a problem,
if put restricted in my filters its not loading the login page
here my filter file
public $aliases = [
'csrf' => CSRF::class,
'toolbar' => DebugToolbar::class,
'honeypot' => Honeypot::class,
'invalidchars' => InvalidChars::class,
'secureheaders' => SecureHeaders::class,
'login' => LoginFilter::class,
'role' => RoleFilter::class,
'permission' => PermissionFilter::class,
];
/**
* List of filter aliases that are always
* applied before and after every request.
*
* #var array
*/
public $globals = [
'before' => [
'honeypot',
'login',
// 'csrf',
// 'invalidchars',
],
'after' => [
'toolbar',
// 'honeypot',
// 'secureheaders',
],
];
here my config/App
public $baseURL = 'http://localhost:8080/';
/**
* --------------------------------------------------------------------------
* Index File
* --------------------------------------------------------------------------
*
* Typically this will be your index.php file, unless you've renamed it to
* something else. If you are using mod_rewrite to remove the page set this
* variable so that it is blank.
*
* #var string
*/
public $indexPage = ' ';
here my filters view
but if i add index this is work

Prooph into Laravel CommandBus was not able to identify a CommandHandler

I have a laravel 5.7 application where I want to add prooph for event sourcing. I have follow the instructions but I retrieve this error:
Prooph\ServiceBus\Exception\RuntimeException: CommandBus was not able to identify a CommandHandler for command App\src\Prooph\Model\Procedure\Command\ChangeProcedureState in /var/www/html/vendor/prooph/service-bus/src/CommandBus.php:58
This is my config/prooph.php file
return [
'event_store' => [
'adapter' => [
'type' => \Prooph\EventStore\Pdo\MySqlEventStore::class,
'options' => [
'connection_alias' => 'laravel.connections.pdo',
],
],
'plugins' => [
\Prooph\EventStoreBusBridge\EventPublisher::class,
\Prooph\EventStoreBusBridge\TransactionManager::class,
],
'procedure_collection' => [
'repository_class' => App\src\Prooph\Infrastructure\Repository\EventStoreProcedureCollection::class,
'aggregate_type' => App\src\Prooph\Model\Procedure\Procedure::class,
],
],
'service_bus' => [
'command_bus' => [
'router' => [
'type' => \Prooph\ServiceBus\Plugin\Router\CommandRouter::class,
'routes' => [
// list of commands with corresponding command handler
\App\src\Prooph\Model\Procedure\Command\ChangeProcedureState::class => App\src\Prooph\Model\Procedure\Handler\ChangeProcedureStateHandler::class,
],
],
],
'event_bus' => [
'plugins' => [
\Prooph\ServiceBus\Plugin\InvokeStrategy\OnEventStrategy::class,
],
'router' => [
'routes' => [
// list of events with a list of projectors
],
],
],
/*'event_bus' => [
'router' => [
'routes' => [
// list of events with a list of projectors
App\src\Prooph\ProophessorDo\Model\User\Event\UserWasRegistered::class => [
\App\src\Prooph\ProophessorDo\Projection\User\UserProjector::class
],
],
],
],*/
],
];
This is my service that dispatch the command
class ProcedureRetrieveStateChanged
{
/** #var \FluentProceduresRepository $procedureRepository */
private $procedureRepository;
/**
* #var CommandBus
*/
private $commandBus;
public function __construct(\FluentProceduresRepository $procedureRepository, CommandBus $commandBus)
{
$this->procedureRepository = $procedureRepository;
$this->commandBus = $commandBus;
}
public function execute($procedureId, array $groups)
{
$procedure = $this->procedureRepository->find($procedureId);
if (null === $procedure) {
return false;
}
foreach ($groups as $group) {
$actualState = $procedure->getStatebyGroup($group['pivot']['group_id']);
if ($actualState !== $group['pivot']['state']) {
$command = new ChangeProcedureState(
[
'procedure_id' => $procedureId,
'group_id' => $group['pivot']['group_id'],
'old_state' => $actualState,
'new_state' => $group['pivot']['state'],
]
);
$this->commandBus->dispatch($command);
}
}
}
}
This is my command
final class ChangeProcedureState extends Command implements PayloadConstructable
{
use PayloadTrait;
public function procedureId(): ProcedureId
{
return ProcedureId::fromString($this->payload['procedure_id']);
}
public function state(): string
{
return $this->payload['state'];
}
protected function setPayload(array $payload): void
{
Assertion::keyExists($payload, 'procedure_id');
Assertion::keyExists($payload, 'group_id');
Assertion::keyExists($payload, 'old_state');
Assertion::keyExists($payload, 'new_state');
$this->payload = $payload;
}
}
And this is my handler
class ChangeProcedureStateHandler
{
/**
* #var ProcedureCollection
*/
private $procedureCollection;
public function __construct(ProcedureCollection $procedureCollection)
{
$this->procedureCollection = $procedureCollection;
}
public function __invoke(ChangeProcedureState $command): void
{
$procedure = $this->procedureCollection->get($command->procedureId());
$procedure->changeState($command->state());
$this->procedureCollection->save($procedure);
}
}
Can someone help me with this problem?
To use handlers as a string you need to use ServiceLocatorPlugin, but before that you need to register all handlers in laravel container, like $app->singletor...or $app->bind.
Cheers.

Yii2 Allow action access only by POST request

I have created a yii2 controller, which meant to display statistics from database, for a specific user. There is a ajax request, performed to my controller action, but i want to restrict to allow only POST method for this action.
<?php
use yii\web\Response;
namespace app\controllers;
use Yii;
use yii\filters\AccessControl;
use yii\web\Controller;
use yii\web\Response;
use yii\filters\VerbFilter;
use app\models\StatsModel;
class DataController extends Controller
{
/**
* {#inheritdoc}
*/
public function behaviors()
{
return [
[
'class' => 'yii\filters\ContentNegotiator',
'only' => ['stats'],
'formats' => [
'application/json' => Response::FORMAT_JSON
],
],
];
}
/**
* {#inheritdoc}
*/
public function actions()
{
return [
'error' => [
'class' => 'yii\web\ErrorAction',
],
'captcha' => [
'class' => 'yii\captcha\CaptchaAction',
'fixedVerifyCode' => YII_ENV_TEST ? 'testme' : null,
],
];
}
public function actionStats()
{
//how can i restrict this action to only POST http method?
return StatsModel::find()->all();
}
}
I need to restrict actionStats() to HTTP Post method only.
Usually you'd allow post only adding something like this to your behaviors:
'verbs' => [
'class' => VerbFilter::className(),
'actions' => [
'stats' => ['POST'],
],
],
And if you are accessing this action only through ajax, in your action you could add the following check
if(Yii::$app->request->isAjax)
{
//in case you want to return JSON formatted response
Yii:$app->response->format = Response::FORMAT_JSON;
}
You can check this cookbook as well:
https://books.google.com.sv/books?id=CJrcDgAAQBAJ&pg=PA193&lpg=PA193&dq=yii2+isajax&source=bl&ots=lRFEiPbN3K&sig=MFGo7VostVkxNZDbXGemXrm-qA8&hl=es&sa=X&ved=0ahUKEwjE9ZXSh7nbAhWPk1kKHW3wCeEQ6AEIYTAF#v=onepage&q=yii2%20isajax&f=false
Finally, you can just make the check for post in your action like this
public function actionStats()
{
if(Yii::$app->request->isPost())
{
//your logic here
return StatsModel::find()->all();
}
else
//throw an exception or return false
}

yii2 Search model sometimes not found

I am using yii2 basic app. On local host, my site was running perfect, when I turned to another computer there is a problem with the site, where after login to the admin panel, the user is redirected to ..../breaking-news/index.
The problem is that on one computer (local host) it is running perfect, on the other computer (local host or on the internet) it worked perfect for a while then while trying to test after some hours, it gives me the following error after login:
Error
Class 'app\controllers\app\models\appModels\BreakingNewsSearch' not
found
my controller is:
<?php
namespace app\controllers;
use app\models\appmodels\AppBreakingNews;
use app\models\appModels\BreakingNewsSearch;
use Yii;
use yii\filters\AccessControl;
use yii\filters\VerbFilter;
use yii\helpers\Url;
use yii\web\NotFoundHttpException;
use yii\web\Response;
/**
* BreakingNewsController implements the CRUD actions for AppBreakingNews model.
*/
class BreakingNewsController extends BEController {
public function behaviors() {
return [
'verbs' => [
'class' => VerbFilter::className(),
'actions' => [
'delete' => ['POST'],
],
],
'access' => [
'class' => AccessControl::className(),
'only' => ['index', 'view', 'create', 'update', 'delete', 'find-model'],
'rules' => [
[
'allow' => TRUE,
'actions' => [ 'index', 'view', 'create', 'update', 'delete', 'find-model'],
'roles' => ['#'],
],
[
'allow' => FALSE,
'actions' => ['index', 'view', 'create', 'update', 'delete', 'find-model'],
'roles' => ['?'],
],
],
'denyCallback' => function ($rule, $action) {
return $this->redirect(Url::toRoute(['site/index']));
}
],
];
}
public function actionGetMainNews() {
if (Yii::$app->request->isAjax) {
$data = Yii::$app->request->post();
$news = AppBreakingNews::find()->all();
Yii::$app->response->format = Response::FORMAT_JSON;
return [
'data' => $news,
];
}
}
/**
* Lists all AppBreakingNews models.
* #return mixed
*/
public function actionIndex() {
`// $searchMod`el = new BreakingNewsSearch();
$searchModel = new app\models\appModels\BreakingNewsSearch();
$dataProvider = $searchModel->search(Yii::$app->request->queryParams);
return $this->render('index', [
'searchModel' => $searchModel,
'dataProvider' => $dataProvider,
]);
}
/**
* Displays a single AppBreakingNews model.
* #param integer $id
* #return mixed
*/
public function actionView($id) {
return $this->render('view', [
'model' => $this->findModel($id),
]);
}
/**
* Creates a new AppBreakingNews model.
* If creation is successful, the browser will be redirected to the 'view' page.
* #return mixed
*/
public function actionCreate() {
$model = new AppBreakingNews();
if ($model->load(Yii::$app->request->post()) && $model->save()) {
return $this->redirect(['view', 'id' => $model->id]);
} else {
return $this->render('create', [
'model' => $model,
]);
}
}
/**
* Updates an existing AppBreakingNews model.
* If update is successful, the browser will be redirected to the 'view' page.
* #param integer $id
* #return mixed
*/
public function actionUpdate($id) {
$model = $this->findModel($id);
if ($model->load(Yii::$app->request->post()) && $model->save()) {
return $this->redirect(['view', 'id' => $model->id]);
} else {
return $this->render('update', [
'model' => $model,
]);
}
}
/**
* Deletes an existing AppBreakingNews model.
* If deletion is successful, the browser will be redirected to the 'index' page.
* #param integer $id
* #return mixed
*/
public function actionDelete($id) {
$this->findModel($id)->delete();
return $this->redirect(['index']);
}
/**
* Finds the AppBreakingNews model based on its primary key value.
* If the model is not found, a 404 HTTP exception will be thrown.
* #param integer $id
* #return AppBreakingNews the loaded model
* #throws NotFoundHttpException if the model cannot be found
*/
protected function findModel($id) {
if (($model = AppBreakingNews::findOne($id)) !== null) {
return $model;
} else {
throw new NotFoundHttpException('The requested page does not exist.');
}
}
}
The search model is here: ...\mywebsite\models\appmodels\BreakingNewsSearch.php
And the error is : class app\models\appModels\BreakingNewsSearch not found
assuming your use statement is correct, ie
use app\models\appModels\BreakingNewsSearch;
would include your BreakingNewsSearch, then you can create a new instance without the qualified name.
/**
* Lists all AppBreakingNews models.
* #return mixed
*/
public function actionIndex() {
$searchModel = new BreakingNewsSearch();
$dataProvider = $searchModel->search(Yii::$app->request->queryParams);
return $this->render('index', [
'searchModel' => $searchModel,
'dataProvider' => $dataProvider,
]);
}
If yii still can't autoload the BreakingNewsSearch class then your path is wrong; try
use app\models\appModels\BreakingNewsSearch;
to match
use app\models\appmodels\AppBreakingNews;
As the others said, it was a problem in models/appModels/...
The correct file path is models/appmodels/...
The error was not observable on windows, but on ubuntu it resulted in the mentioned issue.
Thanks for all of you...

ZF2 form element collection validation

So I have a "simple" form
class SiteAddForm extends Form
{
public function __construct()
{
parent::__construct('add_site_form');
$site = new SiteFieldSet();
$this->add($site);
}
public function getTemplate()
{
return 'site_add.phtml';
}
}
The form it self does nothing. It adds a field_set and returns a template name.
The SiteFieldSet looks likes:
class SiteFieldSet
extends FieldSet
implements InputFilterProviderInterface
{
public function __construct()
{
parent::__construct('site');
$name = new Text('name');
$this->add($name);
$domains = new Collection('domains');
$domains->setTargetElement(new DomainFieldSet())
->setShouldCreateTemplate(true);
$this->add($domains);
}
public function getTemplate()
{
return 'site.phtml';
}
/**
* Should return an array specification compatible with
* {#link Zend\InputFilter\Factory::createInputFilter()}.
*
* #return array
*/
public function getInputFilterSpecification()
{
return [
'name' => [
'required' => true,
'validators' => [
new StringLength([
'min' => 200,
])
]
],
'domains' => [
'required' => true,
],
];
}
}
It adds a text and collection element to the fieldset. The field set implements InputFilterProviderInterface to validate the data thrown into it.
The name must be at least 200 chars (for testing) and the collection is required.
But now comes my problem. With the field set that is thrown into the collection, code:
class DomainFieldSet
extends FieldSet
implements InputFilterProviderInterface
{
public function __construct()
{
parent::__construct('domain');
$host = new Url('host');
$this->add($host);
$language = new Select('language', [
'value_options' => [
'nl_NL' => 'NL',
],
]);
$this->add($language);
$theme = new Select('theme', [
'value_options' => [
'yeti' => 'Yeti',
]
]);
$this->add($theme);
}
public function getTemplate()
{
return 'domain.phtml';
}
/**
* Should return an array specification compatible with
* {#link Zend\InputFilter\Factory::createInputFilter()}.
*
* #return array
*/
public function getInputFilterSpecification()
{
return [
'host' => [
'required' => true,
'validators' => [
new StringLength([
'min' => 200,
])
]
],
'language' => [
'required' => true,
],
'theme' => [
'required' => true,
],
];
}
}
Again nothing special. There are now three elements defined host, theme & language. Again the field set implements InputFilterProviderInterface. So there must be an getInputFilterSpecification in the class.
When I fill in the form
site[name] = "test"
site[domains][0][host] = 'test'
site[domains][0][theme] = 'yeti'
site[domains][0][language] = 'nl_NL'
It gives an error for site[name] saying it must be atleast 200 chars, so validations "works"
But it should also give an error on site[domains][0][host] that it needs to be atleast 200 chars (code was copy pasted, and the use is correct).
So why doesn't the validation kicks in, and or how can I solve the issue so a element/field set inside a collection is properly validated
Try using setValidationGroup in the form __construct method
like:
public function __construct()
{
$this->add(array(
'type' => 'Your\Namespace\SiteFieldSet',
'options' => array(
'use_as_base_fieldset' => true,
),
));
$this->setValidationGroup(array(
'site' => array(
'domain' => array(
'host',
'language',
'theme',
),
),
));
}
or this may also work...
$this->setValidationGroup(FormInterface::VALIDATE_ALL);

Categories