Datepicker change format ufter updating - datepicker

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,
];
}

Related

Access translator in Shopware 6 Plugin

I am developing my first Shopware 6 plugin and was wondering how to access snippets in the Plugin class. I checked the Developer Guide but could not make it work.
I want to use the plugin translation as label in customField select options.
myfirstplugin.en-GB.json
{
"myfirstplugin": {
"my_custom_field_option_1": "Option 1",
"my_custom_field_option_2": "Option 2",
}
}
MyFirstPlugin.php
class MyFirstPlugin extends Plugin
{
// ....
private function createCustomFields(Context $context): void
{
if ($this->customFieldSetExists($context)) {
return;
}
$customFieldSetRepository = $this->container->get('custom_field_set.repository');
$customFieldSetRepository->create([
[
'id' => '294865e5c81b434d8349db9ea6b4e135',
'name' => 'my_custom_field_set',
'customFields' => [
[
'name' => 'my_custom_field',
'type' => CustomFieldTypes::SELECT,
'config' => [
'label' => [ 'en-GB' => 'My custom field'],
'options' => [
[
'value' => '294865e5c81b434d8349db9ea6b4e487',
// Access my_custom_field_option_1 of snippet myfirstplugin.en-GB.json
'label' => 'my_custom_field_option_1',
],
[
'value' => '1ce5abe719a04346930c7e43514ed4f1',
// Access my_custom_field_option_2 of snippet myfirstplugin.en-GB.json
'label' => 'my_custom_field_option_2',
],
],
'customFieldType' => 'select',
'componentName' => 'sw-single-select',
'customFieldPosition' => 1,
],
],
]
],
], $context);
}
}
You can inject an argument of type Translator to your service
in services.xml
<argument type="service" id="translator"/>
in your service
use Shopware\Core\Framework\Adapter\Translation\Translator;
/**
* #var Translator
*/
private $translator;
public function __construct($translator)
{
$this->translator = $translator;
}
then down the way you can use this pretty much the same as in a twig template:
$translated = $this->translator
->trans(
'myfirstplugin.product.detail.294865e5c81b434d8349db9ea6b4e487');
I think you can use the snippet repository and search the label as you want in the Plugin class like
$sRepo = $this->container->get('snippet.repository');
$labels = $sRepo->search((new Criteria())
->addFilter(
new MultiFilter(
MultiFilter::CONNECTION_OR,
[
new ContainsFilter('translationKey', 'my_custom_field_option_1'),
new ContainsFilter('translationKey', 'my_custom_field_option_2')
]
)
), $context)->getElements();
When you create the custom field you don't have to reference a translation snippet. Instead you can just provide the translations in the payload directly.
'config' => [
'label' => ['en-GB' => 'Label english', 'de-DE' => 'Label german'],
'type' => CustomFieldTypes::SELECT,
'options' => [
[
'value' => '294865e5c81b434d8349db9ea6b4e487',
'label' => ['en-GB' => 'Option english', 'de-DE' => 'Option german'],
],
[
'value' => '1ce5abe719a04346930c7e43514ed4f1',
'label' => ['en-GB' => 'Option english', 'de-DE' => 'Option german'],
],
],
],

Unable to resolve service "Zend\Db\Adapter\AdapterInterface" to a factory

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.

ZF3 unable to populate select field from db

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 ]] )

Yii2 REST other actions

I have a controller called DepartementsController which extends the yii\rest\ActiveController.
I have to know which are the department in my region.
When I test my action http://localhost/yii_2/ws_localisation/web/regions/01/departements
I have this error :
{
"name": "PHP Notice",
"message": "Trying to get property of non-object",
"code": 8,
"type": "yii\base\ErrorException",
"file": "E:\wamp\www\yii_2\ws_localisation\controllers\DepartementsController.php",
"line": 58,
"stack-trace": [
"#0 E:\wamp\www\yii_2\ws_localisation\controllers\DepartementsController.php(58): yii\base\ErrorHandler->handleError(8, 'Trying to get p...', 'E:\\wam...', 58, Array)",
"#1 [internal function]: app\controllers\DepartementsController->actionDepartements('01')",
"#2 E:\Laetitia\wamp\www\yii_2\ws_localisation\vendor\yiisoft\yii2\base\InlineAction.php(55): call_user_func_array(Array, Array)",
"#3 E:\Laetitia\wamp\www\yii_2\ws_localisation\vendor\yiisoft\yii2\base\Controller.php(154): yii\base\InlineAction->runWithParams(Array)",
"#4 E:\Laetitia\wamp\www\yii_2\ws_localisation\vendor\yiisoft\yii2\base\Module.php(454): yii\base\Controller->runAction('departements', Array)",
"#5 E:\Laetitia\wamp\www\yii_2\ws_localisation\vendor\yiisoft\yii2\web\Application.php(84): yii\base\Module->runAction('departements/de...', Array)",
"#6 E:\Laetitia\wamp\www\yii_2\ws_localisation\vendor\yiisoft\yii2\base\Application.php(375): yii\web\Application->handleRequest(Object(yii\web\Request))",
"#7 E:\Laetitia\wamp\www\yii_2\ws_localisation\web\index.php(12): yii\base\Application->run()",
"#8 {main}"
]
}
Can you help me please.
Regards.
web.php
'urlManager' => [
'enablePrettyUrl' => true,
'enableStrictParsing' => true,
'showScriptName' => false,
'rules' => [
[
'class' => 'yii\rest\UrlRule',
'controller' => ['departements'],
'prefix' => '/regions/<id:\\w+>',
'patterns' => [
'GET,HEAD' => 'departements',
],
],
[
'class' => 'yii\rest\UrlRule',
'controller' => ['regions','departements','communes','sylvoecoregions'],
'tokens' => ['{id}' => '<id:\\w+>'],
'except' => ['create','update','delete'],
],
],
],
DepartementsController.php
namespace app\controllers;
use yii\rest\ActiveController;
use yii\db\ActiveRecord;
use yii\web\ServerErrorHttpException;
class DepartementsController extends ActiveController
{
public $modelClass = 'app\models\Departements';
public function behaviors()
{
return
\yii\helpers\ArrayHelper::merge(parent::behaviors(), [
'corsFilter' => [
'class' => \yii\filters\Cors::className(),
],
]);
}
public function actionDepartements($id)
{
$model = new $this->modelClass;
$model_departement = $model->find()->where('region_id=:id',[':id'=>$id])->all();
if($model_departement)
{
//$this->setHeader(200);
echo json_encode(array('status'=>1,'data'=>array_filter($model_departement->attributes)),JSON_PRETTY_PRINT);
}
else
{
//$this->setHeader(400);
echo json_encode(array('status'=>0,'error_code'=>400,'errors'=>$model->errors),JSON_PRETTY_PRINT);
}
}}
If do you know what class that $model_departement is an instance
just change your if condition as
`if ($model_departement instanceof ModelDepartmentClass) {`
But if you have no idea about that. Below line also works.
if (is_object($model_departement)) {
if ($model_departement) is not a qualified check.
Please check related documents for more information.
http://php.net/manual/tr/function.is-object.php
http://php.net/manual/en/language.operators.type.php
http://php.net/manual/en/language.expressions.php

dereferencing data from multiple hash and array data structure in perl

Trying to extract data from detailed -> doc -> params -> parameters -> name in following DoxyDocs1.pm file; also including sample of script that extracts some data, but having trouble extracting params -> parameters -> name. Uncomment commented sections to see data.
#!/bin/perl
use Data::Dumper;
use warnings;
require "DoxyDocs1.pm";
print "API Content Analyzer\n";
&GenerateClassInfo($doxydocs->{classes});
sub GenerateClassInfo()
{
my ($classes) = #_;
foreach my $class (#$classes) {
print "\nClass name is: $class->{name}\n";
foreach my $pubmeth (#{$class->{public_methods}->{members}}) {
print "\n" if exists $pubmeth->{name};
print "\tpublic methods include: $pubmeth->{name}\n";
my ($key, $pmcontent) = each (#{$pubmeth->{detailed}->{doc}});
print "\t\tdescription: $pmcontent->{content}\n" if exists $pmcontent->{content};
# foreach my $pmp (#{$pubmeth->{detailed}->{doc}}) {
# print "\t\t";
# print Dumper($pmp);
# }
print "\t\tkind: $pubmeth->{kind}\n";
print "\t\ttype: $pubmeth->{type}\n" if exists $pubmeth->{type};
}
foreach my $privmeth (#{$class->{private_methods}->{members}}) {
print "\n" if exists $privmeth->{name};
print "\tprivate methods include: $privmeth->{name}\n";
my ($key, $pmcontent) = each (#{$privmeth->{detailed}->{doc}});
print "\t\tdescription: $pmcontent->{content}\n" if exists $pmcontent->{content};
# foreach my $info (#{$privmeth->{detailed}->{doc}}) {
# print "\t\t";
# print Dumper($info);
# }
print "\t\tkind: $privmeth->{kind}\n";
print "\t\ttype: $privmeth->{type}\n" if exists $privmeth->{type};
}
}
}
Example DoxyDocs1.pm file
$doxydocs=
{
classes => [
{
name => 'Panoply::Composite',
public_methods => {
members => [
{
kind => 'function',
name => 'addChild',
virtualness => 'non_virtual',
protection => 'public',
static => 'no',
brief => {},
detailed => {
doc => [
{
type => 'text',
content => 'Add a child to the container '
},
params => [
{
parameters => [
{
name => 'child'
}
],
doc => [
{
type => 'text',
content => 'is the child element to add'
}
]
}
]
]
},
type => 'void',
const => 'no',
volatile => 'no',
parameters => [
{
declaration_name => 'child',
type => 'Ptr'
}
]
},
{
kind => 'function',
name => 'operator<',
virtualness => 'non_virtual',
protection => 'public',
static => 'no',
brief => {},
detailed => {
doc => [
{
type => 'text',
content => 'Less than operator'
},
{
type => 'parbreak'
},
params => [
{
parameters => [
{
name => 'rval'
}
],
doc => [
{
type => 'text',
content => 'The '
},
{
type => 'url',
link => 'classPanoply_1_1Package',
content => 'Package'
},
{
type => 'text',
content => ' against which we are comparing this one. '
}
]
}
],
{
return => [
{
type => 'text',
content => 'true if this.packageID < rval.packageID, false otherwise.'
}
]
}
]
},
type => 'bool',
const => 'yes',
volatile => 'no',
parameters => [
{
declaration_name => 'rval',
type => 'const Composite &'
}
]
},
]
},
private_methods => {
members => [
{
kind => 'function',
name => 'addChild',
virtualness => 'virtual',
protection => 'private',
static => 'no',
brief => {},
detailed => {
doc => [
{
type => 'text',
content => 'Add a child to the container '
},
params => [
{
parameters => [
{
name => 'child'
}
],
doc => [
{
type => 'text',
content => 'is the child element to add '
}
]
},
{
parameters => [
{
name => 'parent'
}
],
doc => [
{
type => 'parbreak'
},
{
type => 'text',
content => 'is this own parent, except in weak pointer format to avoid a memory leak'
}
]
}
]
]
},
type => 'virtual void',
const => 'no',
volatile => 'no',
parameters => [
{
declaration_name => 'child',
type => 'Ptr'
},
{
declaration_name => 'parent',
type => 'Ptr'
}
]
},
]
},
}
]
};
1;
You said you wanted
detailed -> doc -> params -> parameters -> name
but that's missing many indexes. Which doc, param and parameters do you want?
detailed -> doc -> ??? -> params -> ??? -> parameters -> ??? -> name
The syntax is:
$member->{detailed}->{doc}->[$i]->{params}->[$j]->{parameters}->[$k]->{name}
Or for short:
$member->{detailed}{doc}[$i]{params}[$j]{parameters}[$k]{name}
If you want to loop over every doc, params, parameter, you can use:
my $docs = $member->{detailed}{doc};
for my $doc (#$docs) {
my $params = $doc->{params};
for my $param (#$params) {
my $parameters = $param->{parameters};
for my $parameter (#$parameters) {
...
}
}
}
(Why is doc singular and params and parameters plural??? Why do params have parameters???)