I am a newbie to zf.I downloaded the album project from github and started working on it . I did all the configuration as been written in the tutorial .
But i am getting this error continuously .
Unable to resolve service "Zend\Db\Adapter\AdapterInterface" to a factory; are you certain you provided it during configuration?
I started looking for some solutions and found same issue posted in Stack Overflow and went through them but none of the solution worked for me . Below i am pasting the pages code , pls assist i am stuck here for 2 days now. I am working on my local system . I have windows 10 and xampp installed.
Module.php
<?php
namespace Album;
use Zend\Db\Adapter\Adapter;
use Zend\Db\Adapter\AdapterInterface;
use Zend\Db\ResultSet\ResultSet;
use Zend\Db\TableGateway\TableGateway;
use Zend\ModuleManager\Feature\ConfigProviderInterface;
class Module implements ConfigProviderInterface
{
public function getConfig()
{
echo "Module.php";
return include __DIR__ . '/config/module.config.php';
}
public function getServiceConfig()
{
return [
'factories' => [
Model\AlbumTable::class => function ($container) {
$tableGateway = $container->get('Model\AlbumTableGateway');
return new Model\AlbumTable($tableGateway);
},
'Model\AlbumTableGateway' => function ($container) {
$dbAdapter = $container->get(AdapterInterface::class);
$resultSetPrototype = new ResultSet();
$resultSetPrototype->setArrayObjectPrototype(new Model\Album());
return new TableGateway('album', $dbAdapter, null, $resultSetPrototype);
},
],
];
}
public function getControllerConfig()
{
return [
'factories' => [
Controller\AlbumController::class => function ($container) {
return new Controller\AlbumController(
$container->get(Model\AlbumTable::class)
);
},
],
];
}
}
module.config.php
namespace Album;
use Zend\Router\Http\Segment;
return [
'router' => [
'routes' => [
'album' => [
'type' => Segment::class,
'options' => [
'route' => '/album[/:action[/:id]]',
'constraints' => [
'action' => '[a-zA-Z][a-zA-Z0-9_-]*',
'id' => '[0-9]+',
],
'defaults' => [
'controller' => Controller\AlbumController::class,
'action' => 'index',
],
],
],
],
],
'view_manager' => [
'template_path_stack' => [
'album' => __DIR__ . '/../view',
],
],
];
composer.json
{
"name": "zendframework/skeleton-application",
"description": "Skeleton Application for Zend Framework zend-mvc applications",
"type": "project",
"license": "BSD-3-Clause",
"keywords": [
"framework",
"mvc",
"zf"
],
"homepage": "http://framework.zend.com/",
"minimum-stability": "dev",
"prefer-stable": true,
"require": {
"php": "^5.6 || ^7.0",
"zendframework/zend-component-installer": "^1.0 || ^0.7 || ^1.0.0-dev#dev",
"zendframework/zend-mvc": "^3.0.1",
"zfcampus/zf-development-mode": "^3.0"
},
"autoload": {
"psr-4": {
"Application\\": "module/Application/src/",
"Album\\": "module/Album/src/"
}
},
"autoload-dev": {
"psr-4": {
"ApplicationTest\\": "module/Application/test/",
"Album\\": "module/Album/src/"
}
},
"extra": [],
"scripts": {
"cs-check": "phpcs",
"cs-fix": "phpcbf",
"development-disable": "zf-development-mode disable",
"development-enable": "zf-development-mode enable",
"development-status": "zf-development-mode status",
"post-create-project-cmd": [
"#development-enable"
],
"serve": "php -S 0.0.0.0:8080 -t public public/index.php",
"test": "phpunit"
}
}
global.php
return array(
'db' => array(
'driver' => 'Pdo',
'adapters' => array(
'default_db' => array(
'driver' => 'Pdo',
'dsn' => 'mysql:dbname=zf2tutorial;host=localhost',
'username' => 'root',
'password' => '',
'driver_options' => array(
PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES \'UTF8\'' // optional
),
),
),
),
);
AlbumController.php
<?php
namespace Album\Controller;
use Album\Form\AlbumForm;
use Album\Model\Album;
use Album\Model\AlbumTable;
use Zend\Mvc\Controller\AbstractActionController;
use Zend\View\Model\ViewModel;
class AlbumController extends AbstractActionController
{
private $table;
public function __construct(AlbumTable $table)
{
$this->table = $table;
}
public function indexAction()
{
// Grab the paginator from the AlbumTable:
$paginator = $this->table->fetchAll(true);
// Set the current page to what has been passed in query string,
// or to 1 if none is set, or the page is invalid:
$page = (int) $this->params()->fromQuery('page', 1);
$page = ($page < 1) ? 1 : $page;
$paginator->setCurrentPageNumber($page);
// Set the number of items per page to 10:
$paginator->setItemCountPerPage(10);
return new ViewModel(['paginator' => $paginator]);
}
public function addAction()
{
$form = new AlbumForm();
$form->get('submit')->setValue('Add');
$request = $this->getRequest();
if (!$request->isPost()) {
return ['form' => $form];
}
$album = new Album();
$form->setInputFilter($album->getInputFilter());
$form->setData($request->getPost());
if (!$form->isValid()) {
return ['form' => $form];
}
$album->exchangeArray($form->getData());
$this->table->saveAlbum($album);
return $this->redirect()->toRoute('album');
}
public function editAction()
{
$id = (int) $this->params()->fromRoute('id', 0);
if (0 === $id) {
return $this->redirect()->toRoute('album', ['action' => 'add']);
}
// Retrieve the album with the specified id. Doing so raises
// an exception if the album is not found, which should result
// in redirecting to the landing page.
try {
$album = $this->table->getAlbum($id);
} catch (\Exception $e) {
return $this->redirect()->toRoute('album', ['action' => 'index']);
}
$form = new AlbumForm();
$form->bind($album);
$form->get('submit')->setAttribute('value', 'Edit');
$request = $this->getRequest();
$viewData = ['id' => $id, 'form' => $form];
if (!$request->isPost()) {
return $viewData;
}
$form->setInputFilter($album->getInputFilter());
$form->setData($request->getPost());
if (!$form->isValid()) {
return $viewData;
}
$this->table->saveAlbum($album);
// Redirect to album list
return $this->redirect()->toRoute('album', ['action' => 'index']);
}
public function deleteAction()
{
$id = (int) $this->params()->fromRoute('id', 0);
if (!$id) {
return $this->redirect()->toRoute('album');
}
$request = $this->getRequest();
if ($request->isPost()) {
$del = $request->getPost('del', 'No');
if ($del == 'Yes') {
$id = (int) $request->getPost('id');
$this->table->deleteAlbum($id);
}
// Redirect to list of albums
return $this->redirect()->toRoute('album');
}
return [
'id' => $id,
'album' => $this->table->getAlbum($id),
];
}
}
configure your "config/autoload/local.php" Or "config/autoload/global.php",
return array(
'db' => array(
'driver' => 'Pdo',
'adapters' => array(
'default_db' => array(
'driver' => 'Pdo',
'dsn' => 'mysql:dbname=YOURDBNAME;host=localhost',
'username' => 'xxx',
'password' => 'xxx',
'driver_options' => array(
PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES \'UTF8\'' // optional
),
),
),
),
'service_manager' => array(
'factories' => array(
'Zend\Db\Adapter\Adapter' => 'Zend\Db\Adapter\AdapterServiceFactory',
),
'abstract_factories' => array(
'Zend\Db\Adapter\AdapterAbstractServiceFactory',
),
),
);
You can set your credential on "config/autoload/local.php".
public function getServiceConfig()
{
return [
'factories' => [
Model\AlbumTable::class => function ($container) {
$tableGateway = $container->get('Model\AlbumTableGateway');
return new Model\AlbumTable($tableGateway);
},
'Model\AlbumTableGateway' => function ($container) {
$dbAdapter = $container->get('default_db'); // return driver instance
$resultSetPrototype = new ResultSet();
$resultSetPrototype->setArrayObjectPrototype(new Model\Album());
return new TableGateway('album', $dbAdapter, null, $resultSetPrototype);
},
],
];
}
In config/application.config.php,
return array(
'modules' => array(
'Zend\Db', // make sure you have `'Zend\Db'` to top
update your composer.json file as below,
"require": {
"php": "^5.6 || ^7.0",
"zendframework/zend-component-installer": "^1.0 || ^0.7 || ^1.0.0-dev#dev",
"zendframework/zend-mvc": "^3.0.1",
"zfcampus/zf-development-mode": "^3.0",
"zendframework/zendframework": "^3.0",
"zendframework/zend-db": "^2.8.2",
},
for rendering update "module.config.php" with below,
'view_manager' => array(
'template_path_stack' => array(
__DIR__ . '/../view',
),
),
I have also faced the same problem. I used minimal installation of zend framework.
Check the composer.json whether you have installed the zend-db.
If zend-db doesn't exist, install zend-db via composer,
composer require zendframework/zend-db
During installation, it will ask for configuration file injection, choose 1 for config.modules.php.
Related
I have to models 'User' and 'Admin'. 'User' is the default model in Laravel. I want to authenticate these models separately.
class Admin extends Authenticatable implements JWTSubject
{
use HasFactory, Notifiable;
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'email',
'name',
'contact',
'password'
];
/**
* The attributes that should be hidden for arrays.
*
* #var array
*/
protected $hidden = [
'password',
'remember_token',
];
/**
* The attributes that should be cast to native types.
*
* #var array
*/
protected $casts = [
'email_verified_at' => 'datetime',
];
public function getJWTIdentifier()
{
return $this->getKey();
}
/**
* Return a key value array, containing any custom claims to be added to the JWT.
*
* #return array
*/
public function getJWTCustomClaims()
{
return [];
}
}
In auth.php,
'guards' => [
'web' => [
'driver' => 'session',
'provider' => 'users',
],
'api' => [
'driver' => 'jwt',
'provider' => 'users',
'hash' => false,
],
'admins' => [
'driver' => 'jwt',
'provider' => 'admins',
],
'admin-api' => [
'driver' => 'jwt',
'provider' => 'admins',
],
],
'providers' => [
'users' => [
'driver' => 'eloquent',
'model' => App\Models\User::class,
],
// 'users' => [
// 'driver' => 'database',
// 'table' => 'users',
// ],
'admins' => [
'driver' => 'eloquent',
'model' => App\Models\Admin::class,
],
],
In AdminController.php,
/**
* Create a new controller instance.
*
* #return void
*/
public function __construct()
{
$this->middleware('auth:admins');
}
public function register(Request $request){
$creds = [
'email' => $request->input('email'),
'name' => $request->input('name'),
'password' => bcrypt($request->input('password')),
'contact' => $request->input('contact'),
];
try {
$admin = Admin::create($creds);
} catch (\Throwable $th) {
return response(
[
'message' => $th,
'success' => false
],
);
}
event(new Registered($admin));
$token = JWTAuth::fromUser($admin);
return response(
[
'user' => $admin,
'message' => 'register success',
'token' => $token,
'success' => true
],
201
);
}
public function login(Request $request){
$creds = [
'email' => $request->input('email'),
'password' => $request->input('password')
];
if(!Auth()->attempt($creds)){
return response([
'message' => 'login faild!',
'success' => false
]);
}
$admin = Auth()->user();
$token = JWTAuth::fromUser($admin);
return response(
[
'user' => $admin,
'token' => $token,
'success' => true
],
201
);
}
can you help me?
I do not know how to use register and login function correctly. Can you explain what is happening in those functions. How to use a middleware correctly?
I am using the bootstrap datepicker in my view and every time I call the update method, the date sets fine but the date picker suddenly reverts from dd/mm/yyyy format to mm/dd/yyyy format.
Controller
public function actionDias(){
Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
if (isset($_POST['anio']) and isset($_POST['cuatrimestre'])) {
$cuatrimestre = $_POST['cuatrimestre'];
$anio = $_POST['anio'];
$fechaMin = CampusActividadDia::find()->where(['cuatrimestre' => $cuatrimestre])->andWhere(['anio' => $anio])->min('fecha');
$fecha_desde = date("d/m/Y", strtotime($fechaMin));
$fechaMax = CampusActividadDia::find()->where(['cuatrimestre' => $cuatrimestre])->andWhere(['anio' => $anio])->max('fecha');
$fecha_hasta = date("d/m/Y", strtotime($fechaMax));
return ([
'fecha_desde' => $fecha_desde,
'fecha_hasta' => $fecha_hasta
]);
} else return null;
}
View
<div id="dias" class="form-group hidden">
<label class="control-label">Rango de Fechas:</label>
<?php
echo DatePicker::widget([
'model' => $model,
'attribute' => 'fecha_desde',
'attribute2' => 'fecha_hasta',
'options' => ['id'=>'fecha_desde','disabled' => ($model->fecha_desde == "")],
'options2' => ['id'=>'fecha_hasta','disabled' => ($model->fecha_desde == "")],
'type' => DatePicker::TYPE_RANGE,
'separator' => 'hasta',
'pluginOptions' => [
'autoclose' => true,
'format' => 'dd/mm/yyyy'
]
]); ?>
</div>
Js
$.ajax({
url: URL_BASE + "/campus/dias",
type: "post",
dataType: "json",
data: {
cuatrimestre: this.value,
anio: $('#anio').val()
},
success: function (res) {
const fecha_desde = res.fecha_desde;
const fecha_hasta = res.fecha_hasta
$(fechaDesdeRef).kvDatepicker('update',new Date(fecha_desde));
$(fechaHastaRef).kvDatepicker('update', new Date(fecha_hasta));
$(fechaDesdeRef).prop('disabled', false);
$(fechaHastaRef).prop('disabled', false);
},
error: function (xhr, ajaxOptions, thrownError) {
alert("ERROR " + xhr.status);
},
});
I've also tried to change date format both ways setting the global default format and locally but without success, like the following:
$.fn.kvDatepicker.defaults.format = 'dd/mm/yyyy'
$(datePickerRef).kvDatepicker({
formatDate: 'd/m/Y',
date:'d/m/Y'
})
I've also read this issue, but there isn't a conclution about it:
https://github.com/uxsolutions/bootstrap-datepicker/issues/1775
Sounds like that your DatePicker is overwriting pluginOptions when model is loaded. Might need to config DatePicker or overwrite it to stop missing format
config/main.php
'modules' => [
'datecontrol' => [
'class' => 'kartik\datecontrol\Module',
'displaySettings' => [
'date' => 'php:d-M-Y',
'time' => 'php:H:i:s A',
'datetime' => 'php:d-m-Y H:i:s A',
],
'saveSettings' => [
'date' => 'php:Y-m-d',
'time' => 'php:H:i:s',
'datetime' => 'php:Y-m-d H:i:s',
],
// automatically use kartikwidgets for each of the above formats
'autoWidget' => true,
],
],
'components' => [
//http://webtips.krajee.com/override-bootstrap-css-js-yii-2-0-widgets/
'assetManager' => [
'bundles' => [
'yii\bootstrap4\BootstrapAsset' => [
'sourcePath' => '#npm/bootstrap/dist'
],
'yii\bootstrap4\BootstrapPluginAsset' => [
'sourcePath' => '#npm/bootstrap/dist'
],
'#frontend\modules\invoice\assets\CoreCustomCssJsAsset'=>[
'sourcePath' => '#frontend/modules/invoice/assets'
],
],
composer.json
"require": {
"php": ">=7.4.9",
"guzzlehttp/guzzle":"*",
"yiisoft/yii2": "~2.0.41.1",
"yiisoft/yii2-bootstrap": "~2.0.9",
"yiisoft/yii2-bootstrap4": "^2.0.8",
"bower-asset/bootstrap": "~3.4.1",
"bower-asset/ladda": "*",
"bower-asset/font-awesome": "~4.7.0.0",
"npm-asset/jquery": "^2.2",
"vlucas/phpdotenv": "*",
"insolita/yii2-migration-generator": "~3.1",
"ifsnop/mysqldump-php": "*",
"warrence/yii2-kartikgii": "dev-master",
"kartik-v/yii2-bootstrap4-dropdown": "#dev",
"kartik-v/bootstrap-fileinput": "dev-master",
"kartik-v/yii2-editable": "#dev",
"kartik-v/yii2-grid":"#dev",
"kartik-v/yii2-widget-timepicker": "#dev",
"kartik-v/yii2-date-range": "*",
"kartik-v/yii2-social": "#dev",
"kartik-v/yii2-dynagrid": "dev-master",
"kartik-v/yii2-tree-manager": "#dev",
"kartik-v/yii2-mpdf":"dev-master",
"kartik-v/bootstrap-star-rating": "#dev",
"kartik-v/yii2-slider": "dev-master",
"kartik-v/yii2-number" : "#dev",
"kartik-v/yii2-editors": "#dev",
"kartik-v/yii2-validators": "dev-master",
},
"require-dev": {
"yiisoft/yii2-debug": "~2.1.0",
"yiisoft/yii2-gii": "~2.1.0",
"yiisoft/yii2-faker": "~2.0.0",
"codeception/codeception": "^4.0",
"codeception/verify": "~0.5.0 || ~1.1.0"
},
"config": {
"process-timeout": 1800
},
"fxp-asset": {
"installer-paths": {
"npm-asset-library": "vendor/npm-asset",
"bower-asset-library": "vendor/bower-asset"
}
},
These settings have worked for me. You might considering modifying your AppAsset.php as follows to incorporate bootstrap 4.
<?php
namespace frontend\assets;
use yii\web\AssetBundle;
use yii\bootstrap4\BootstrapAsset;
use yii\web\YiiAsset;
use yii\web\JqueryAsset;
/**
* Main frontend application asset bundle.
*/
class AppAsset extends AssetBundle
{
public $sourcePath = '#app/assets/app';
public $baseUrl = '#app';
public $css = [
'css/site.css',
'//netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap-glyphicons.css',
'//use.fontawesome.com/releases/v5.3.1/css/all.css',
'//cdnjs.cloudflare.com/ajax/libs/font-awesome/5.9.0/css/all.min.css'
];
public $js = [
'//kit.fontawesome.com/85ba10e8d4.js',
];
public $depends = [
BootstrapAsset::class,
YiiAsset::class,
JqueryAsset::class,
];
}
I've created a module with name Commerce in zend 3 which is working fine. Now when I inject a dependency through __construct() it throws error
Too few arguments to function
Commerce\Controller\IndexController::__construct(), 0 passed in
/var/www/html/zf3/vendor/zendframework/zend-servicemanager/src/Factory/InvokableFactory.php
on line 30 and exactly 1 expected
Here is the controller code.
<?php
namespace Commerce\Controller;
use Zend\Mvc\Controller\AbstractActionController;
use Zend\View\Model\ViewModel;
use Commerce\Model\Commerce;
class IndexController extends AbstractActionController
{
private $commerce;
/**
* IndexController constructor.
* #param Commerce $commerce
*/
public function __construct(Commerce $commerce)
{
$this->commerceModel = $commerce;
}
public function indexAction()
{
return new ViewModel();
}
}
module.config.php code
<?php
namespace Commerce;
use Zend\Router\Http\Literal;
use Zend\Router\Http\Segment;
use Zend\ServiceManager\Factory\InvokableFactory;
return [
'router' => [
'routes' => [
'home' => [
'type' => Literal::class,
'options' => [
'route' => '/',
'defaults' => [
'controller' => Controller\IndexController::class,
'action' => 'index',
],
],
],
'commerce' => [
'type' => Segment::class,
'options' => [
'route' => '/commerce[/:action][/:id]',
'defaults' => [
'controller' => Controller\IndexController::class,
'action' => 'index',
],
],
],
],
],
'controllers' => [
'factories' => [
Controller\IndexController::class => InvokableFactory::class
],
],
'view_manager' => [
'display_not_found_reason' => true,
'display_exceptions' => true,
'doctype' => 'HTML5',
'not_found_template' => 'error/404',
'exception_template' => 'error/index',
'template_map' => [
'layout/layout' => __DIR__ . '/../view/layout/layout.phtml',
'commerce/index/index' => __DIR__ . '/../view/commerce/index/index.phtml',
'error/404' => __DIR__ . '/../view/error/404.phtml',
'error/index' => __DIR__ . '/../view/error/index.phtml',
],
'template_path_stack' => [
__DIR__ . '/../view',
],
],
];
Where is the issue? zend-di is already installed.
Your error is caused in line
Controller\IndexController::class => InvokableFactory::class
this does not provide a "Commerce\Model\Commerce" to the constructor of your IndexController. You need to change this to provide the dependency:
'controllers' => [
'factories' => [
Controller\IndexController::class => function($container) {
return new Controller\IndexController(
$container->get(\Commerce\Model\Commerce::class)
);
},
],
],
'service_manager' => [
'factories' => [
\Commerce\Model\Commerce::class => function($sm) {
/* provide any dependencies if needed */
/* Create the model here. */
return new \Commerce\Model\Commerce($dependencies);
},
]
],
The best approach is to provide its own factory for your Commerce\Model\Commerce class, as seen above in the setting 'factories' of 'service_manager'.
EDIT: as request, if you want to do everything inside the controller Factory, here is a simple example:
'controllers' => [
'factories' => [
Controller\IndexController::class => function($container) {
$dbAdapter = $container->get('Zend\Db\Adapter\Adapter');
$resultSetPrototype = new ResultSet();
$tableGateway = new TableGateway('commerceTableName', $dbAdapter, null, $resultSetPrototype);
return new Controller\IndexController(
new \Commerce\Model\Commerce($tableGateway)
);
},
],
],
Can anyone explain me the easiest way to populate select field in form from db?
ChartsForm.php
<pre>
<?php
namespace Charts\Form;
use Zend\Form\Form;
use Charts\Model\PostRepositoryInterface;
class ChartsForm extends Form
{
private $postRepository;
public function __construct(PostRepositoryInterface $postRepository)
{
$this->postRepository = $postRepository;
// We will ignore the name provided to the constructor
parent::__construct('album');
$this->add([
'name' => 'id',
'type' => 'hidden',
]);
$this->add([
'name' => 'title',
'type' => 'text',
'options' => [
'label' => 'Title',
],
]);
$this->add(array(
'type' => 'Radio',
'name' => 'select',
'options' => array(
'label' => 'select type',
'value_options' => array(
'1' => 'Index',
'2' => 'Security',
),
),
'attributes' => array(
'value' => '1'
)
));
$this->add(array(
'type' => 'Zend\Form\Element\Select',
'name' => 'gender',
'options' => array(
'value_options' => $this->postRepository->findAllPosts(),
),
'attributes' => array(
'value' => '1'
)
));
$this->add([
'name' => 'submit',
'type' => 'submit',
'attributes' => [
'value' => 'Go',
'id' => 'submitbutton',
],
]);
}
}
</pre>
module.config.php
<pre>
<?php
namespace Charts;
use Zend\ServiceManager\Factory\InvokableFactory;
use Zend\Db\Adapter\AdapterAbstractServiceFactory;
return [
'controllers' => [
'factories' => [
Model\ChartSqlRepository::class => Factory\ChartSqlRepositoryFactory::class,
],
],
'service_manager' => [
'aliases' => [
Model\PostRepositoryInterface::class => Model\PostRepository::class,
],
'factories' => [
Model\PostRepository::class => InvokableFactory::class,
],
],
'view_manager' => [
'template_path_stack' => [
'charts' => __DIR__ . '/../view',
],
],
'router' => [
'routes' => [
'charts' => [
'type' => 'segment',
'options' => [
'route' => '/charts[/:action[/:id]]',
'constraints' => [
'action' => '[a-zA-Z][a-zA-Z0-9_-]*',
'id' => '[0-9]+',
],
'defaults' => [
'controller' => Controller\ChartsController::class,
'action' => 'index',
],
],
],
],
],
// 'service_manager' => [
// 'factories' => [
// 'Zend\Db\Adapter\Adapter' => AdapterAbstractServiceFactory::class,
// ],
// ],
];
</pre>
module.php
<pre>
<?php
namespace Charts;
use Zend\ModuleManager\Feature\ConfigProviderInterface;
use Zend\Db\Adapter\AdapterInterface;
use Zend\Db\ResultSet\ResultSet;
use Zend\Db\TableGateway\TableGateway;
class Module implements ConfigProviderInterface
{
public function getConfig()
{
return include __DIR__ . '/../config/module.config.php';
}
public function getServiceConfig()
{
return [
'factories' => [
Model\BKPagesTable::class => function($container) {
$tableGateway = $container->get(Model\BKPagesTableGateway::class);
return new Model\BKPagesTable($tableGateway);
},
Model\BKPagesTableGateway::class => function ($container) {
$dbAdapter = $container->get(AdapterInterface::class);
$resultSetPrototype = new ResultSet();
$resultSetPrototype->setArrayObjectPrototype(new Model\BKPages());
return new TableGateway('bkpages', $dbAdapter, null, $resultSetPrototype);
},
Model\BuyOrdersTable::class => function($container) {
$tableGateway = $container->get(Model\BuyOrdersTableGateway::class);
return new Model\BuyOrdersTable($tableGateway);
},
Model\BuyOrdersTableGateway::class => function($container) {
$dbAdapter2 = $container->get('api2web');
$resultSetPrototype = new ResultSet();
$resultSetPrototype->setArrayObjectPrototype(new Model\BuyOrders());
return new TableGateway('BuyOrders', $dbAdapter2, null, $resultSetPrototype);
},
//Stocklist Table
Model\StockListTable::class => function($container) {
$tableGateway = $container->get(Model\StockListTableGateway::class);
return new Model\StockListTable($tableGateway);
},
Model\StockListTableGateway::class => function($container) {
$dbAdapter2 = $container->get('api2web');
$resultSetPrototype = new ResultSet();
$resultSetPrototype->setArrayObjectPrototype(new Model\StockList());
return new TableGateway('StockList', $dbAdapter2, null, $resultSetPrototype);
},
//Fulldayquot Table
Model\FulldayquotTable::class => function($container) {
$tableGateway = $container->get(Model\FulldayquotTableGateway::class);
return new Model\FulldayquotTable($tableGateway);
},
Model\FulldayquotTableGateway::class => function($container) {
$dbAdapter2 = $container->get('api2web');
$resultSetPrototype = new ResultSet();
$resultSetPrototype->setArrayObjectPrototype(new Model\Fulldayquot());
return new TableGateway('fulldayquot', $dbAdapter2, null, $resultSetPrototype);
},
],
];
}
public function getControllerConfig()
{
return [
'factories' => [
Controller\ChartsController::class => function($container) {
return new Controller\ChartsController(
$container->get(Model\BKPagesTable::class)
);
},
],
];
}
}
</pre>
ChartSqlRepositoryFactory.php
<pre>
<?php
namespace Charts\Factory;
use Charts\Model\ChartSqlRepository;
use Zend\Db\Adapter\AdapterInterface;
use Blog\Model\PostRepositoryInterface;
use Interop\Container\ContainerInterface;
use Zend\ServiceManager\Factory\FactoryInterface;
class ChartSqlRepositoryFactory implements FactoryInterface
{
public function __invoke(ContainerInterface $container, $requestedName, array $options = null)
{
return new ChartSqlRepository(
$container->get($container->get(PostRepositoryInterface::class)
);
}
}
</pre>
ChartSqlRepository.php
<pre>
<?php
namespace Charts\Model;
use InvalidArgumentException;
use RuntimeException;
use Zend\Db\Adapter\AdapterInterface;
use Zend\Db\Adapter\Driver\ResultInterface;
use Zend\Db\ResultSet\ResultSet;
class ChartSqlRepository implements PostRepositoryInterface
{
private $db;
private $repository;
public function __construct( ChartSqlRepository $repository)
{
$this->repository = $repository;
}
public function findAllPosts()
{
$sql = new Sql($this->db);
$select = $sql->select('BKPages');
$stmt = $sql->prepareStatementForSqlObject($select);
$result = $stmt->execute();
var_export($result);
die();
}
public function IndexesOptions()
{
$sql = new Sql($this->db);
$select = $sql->select('BKPages');
$stmt = $sql->prepareStatementForSqlObject($select);
$result = $stmt->execute();
$selectData = array();
foreach ($result as $res) {
$selectData[$res['MenuID']] = $res['MenuID'];
}
return $selectData;
}
public function findPost($id)
{
}
}
</pre>
I am trying to populate select field in ChartsForm.php from db and created a factory, maybe some error in module.config.php it's says.
Catchable fatal error: Argument 1 passed to Charts\Form\ChartsForm::__construct() must be an instance of Charts\Model\PostRepositoryInterface, none given, called in C:\wamp\www\bw\module\Charts\src\Controller\ChartsController.php on line 60 and defined in C:\wamp\www\bw\module\Charts\src\Form\ChartsForm.php on line 24
Help me out please.
Can you be more specific? What type of database?
You have two options: PDO (For all driver) and MySQLy (for MySQL).
Look here for a greater response:
https://stackoverflow.com/a/8255054/6784143
UPDATE:
You can connect your Sql Server with this line code (running good on .php).
resource mssql_connect ([ string $servername [, string $username [, string $password [, bool $new_link = false ]]]] )
You can execute a query with this line code.
mixed sqlsrv_query ( resource $conn , string $sql [, array $params [, array $options ]] )
I have created a module in Yii2 using Gii code generator. My new generated module location is
backend/modules/cms
cms is new generated module name.
backend/config/main.php after setting module configuration looks as following
return [
'id' => 'app-backend',
'basePath' => dirname(__DIR__),
'controllerNamespace' => 'backend\controllers',
'bootstrap' => ['log'],
'modules' => [
'gii' => [
'class' => 'yii\gii\Module', //adding gii module
'allowedIPs' => ['127.0.0.1', '::1'] //allowing ip's
],
'cms' => [
'class' => 'backend\modules\cms\Cms',
],
],
'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' => [
'class' => 'yii\web\UrlManager',
'enablePrettyUrl' => true,
'showScriptName' => false,
'rules' => [
'<controller:\w+>/<action:\w+>/<id:\w+>' => '<controller>/<action>',
'<controller:\w+>/<action:\w+>' => '<controller>/<action>',
'<module:\w+>/<controller:\w+>/<action:\w+>' => '<module>/<controller>/<action>',
'<module:\w+><controller:\w+>/<action:update|delete>/<id:\d+>' => '<module>/<controller>/<action>',
]
],
'assetManager' => [
'bundles' => [
'yii\web\JqueryAsset' => [
'js' => []
],
],
],
],
'params' => $params,
];
behaviors function in controller looks as after setting access rules
public function behaviors() {
return [
'access' => [
'class' => AccessControl::className(),
'rules' => [
[
'actions' => ['login', 'error'],
'allow' => true,
],
[
'actions' => ['logout', 'index', 'create', 'update', 'delete'],
'allow' => true,
'roles' => ['#'],
],
],
],
'verbs' => [
'class' => VerbFilter::className(),
'actions' => [
'delete' => ['post'],
],
],
];
}
Only index action of my controller is accessible. when i access any other action in controller url changes but shows index action contents.
How can i access all actions in controller?
It will be appreciable if someone help me resolving this issue.
my controller
namespace backend\modules\cms\controllers;
use Yii;
use yii\filters\AccessControl;
use backend\modules\cms\models\Pages;
use backend\modules\cms\models\PagesSearch;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
/**
* PagesController implements the CRUD actions for Pages model.
*/
class PagesController extends Controller
{
public function behaviors() {
return [
'access' => [
'class' => AccessControl::className(),
'rules' => [
[
'actions' => ['login', 'error'],
'allow' => true,
],
[
'actions' => ['logout', 'index', 'create', 'update', 'delete'],
'allow' => true,
'roles' => ['#'],
],
],
],
'verbs' => [
'class' => VerbFilter::className(),
'actions' => [
// 'delete' => ['post'],
],
],
];
}
/**
* Lists all Pages models.
* #return mixed
*/
public function actionIndex()
{
$searchModel = new PagesSearch();
$dataProvider = $searchModel->search(Yii::$app->request->post());
return $this->render('index', [
'searchModel' => $searchModel,
'dataProvider' => $dataProvider,
]);
}
/**
* Displays a single Pages model.
* #param integer $id
* #return mixed
*/
public function actionView($id)
{
return $this->render('view', [
'model' => $this->findModel($id),
]);
}
/**
* Creates a new Pages model.
* If creation is successful, the browser will be redirected to the 'view' page.
* #return mixed
*/
public function actionCreate()
{
echo "here";
exit;
$model = new Pages();
if ($model->load(Yii::$app->request->post()) && $model->save()) {
return $this->redirect(['index']);
} else {
return $this->render('create', [
'model' => $model,
]);
}
}
/**
* Updates an existing Pages 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 Pages 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 Pages model based on its primary key value.
* If the model is not found, a 404 HTTP exception will be thrown.
* #param integer $id
* #return Pages the loaded model
* #throws NotFoundHttpException if the model cannot be found
*/
protected function findModel($id)
{
if (($model = Pages::findOne($id)) !== null) {
return $model;
} else {
throw new NotFoundHttpException('The requested page does not exist.');
}
}
}
I am using Url as follows:
http://localhost/yii2-demo/backend/cms/pages/index
http://localhost/yii2-demo/backend/cms/pages/create
What Url(s) are you using?
For a module it should be:
?r=cms/pages/index,
?r=cms/pages/create
etc...
The only problem I can spot is on your $matchCallback attribute on the second AccessControl rule. It should use this signature
function ($rule, $action)
And it should return a boolean that indicates wheter this rule should be applied or not. In your case, you're saying that it should be applied to users that are not guests and that have the role '0'. You're also calling a redirect inside the function, and it doesn't return a boolean. See more info here http://www.yiiframework.com/doc-2.0/yii-filters-accessrule.html#$matchCallback-detail
Try to remove this attribute completely and see if you get a different result.