Saving manyToMany data cakephp3 - forms

I'm struggling about this issue for a while. I have three tables prestation, tools and prestation_tools. And my entities are linked as follow :
#ToolsTable
public function initialize(array $config)
{
parent::initialize($config);
$this->table('tools');
$this->displayField('id');
$this->primaryKey('id');
$this->belongsToMany('Prestation', [
'joinTable' => 'prestation_tools',
'foreignKey' => 'tools_id'
]);
}
#PrestationTable
public function initialize(array $config)
{
parent::initialize($config);
$this->table('prestation');
$this->displayField('id');
$this->primaryKey('id');
$this->belongsToMany('Tools', [
'through' => 'PrestationTools'
]);
$this->belongsToMany('Competences', [
'through' => 'PrestationCompetences'
]);
}
#PrestationToolsTable
public function initialize(array $config)
{
parent::initialize($config);
$this->table('prestation_tools');
$this->displayField('prestation_id');
$this->primaryKey(['prestation_id', 'tools_id']);
$this->belongsTo('Prestation', [
'foreignKey' => 'prestation_id',
'joinType' => 'INNER'
]);
$this->belongsTo('Tools', [
'foreignKey' => 'tools_id',
'joinType' => 'INNER'
]);
}
And of my form is :
<?= $this->Form->input("Prestation.Tools.1.tools_id", [
'label' => false,
'type' => 'select',
'options' => $tools,
'empty' => "Sélectionner l'outil 1",
'templates' => [
'inputContainer' => '{{content}}'
],
'class' => 'form-control',
]) ?>
<label >Spécifications de l'outil 1</label>
<?= $this->Form->textarea('Prestation.Tools.1.details', [
'templates' => [
'inputContainer' => '<div class="form-group">{{content}}</div>'
],
'class' => 'form-control',
'placeholder' => 'Spécifications de l\'outil',
'label' => 'Spécifications de l\'outil'
]) ?>
When trying to save from PrestationController, on prestation record is saved. Can anyone help me ?
Update
My PrestationController's add() action looks like this :
public function add(){
#...
$prestation = $this->Prestation->patchEntity($prestation, $this->request->data, [
'associated' => [
'Tools',
'Competences'
]
]);
#...
}

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'],
],
],
],

ZF3 - Set field in fieldset required depnding on form

I have a fieldset with a field called "company" which is not required by default. Now there is a form which adds this fieldset and now "company" should be required. Is there a way to do this in e. g. the form factory? Or can I rewrite the input filters of the fieldset in my inputfilter class binded to the form?
Thanks for any response!
Fieldset
class MyFieldset extends Fieldset implements InputFilterProviderInterface {
public function init() {
$this->add([
'name' => 'company',
'options' => [
'label' => 'Firma'
],
'attributes' => [
'id' => 'address-company'
]
]);
}
public function getInputFilterSpecification() {
return [
'company' => [
'required' => false,
'filters' => [
['name' => 'StripTags'],
['name' => 'StringTrim'],
['name' => 'ToNull']
],
'validators' => [
[
'name' => 'StringLength',
'options' => [
'encoding' => 'UTF-8',
'min' => 1,
'max' => 128
]
]
]
],
];
}
}
Form
class MyForm extends Form {
public function init() {
$this->add([
'type' => MyFieldset::class,
'name' => 'test',
'options' => [
'use_as_base_fieldset' => true
]
]);
}
}
Form Factory
class MyFormFactory implements FactoryInterface {
public function __invoke(ContainerInterface $container, $requestedName, array $options = null) {
$hydratorManager = $container->get('HydratorManager');
$inputFilterManager = $container->get('InputFilterManager');
$form = new MyForm();
$form->setHydrator($hydratorManager->get(DoctrineObject::class));
$form->setInputFilter($inputFilterManager->get(MyInputFilter::class));
$form->bind(new Entity());
return $form;
}
}
The only way I can think of doing it is.
In your fieldset use:
private $companyRequired = FALSE;
public function setCompanyRequired($companyRequired)
{
$this->companyRequired = (bool) $companyRequired;
}
public function getInputFilterSpecification()
{
return [
'company' => [
'required' => $this->companyRequired,
'filters' => [
['name' => 'StripTags'],
['name' => 'StringTrim'],
['name' => 'ToNull']
],
'validators' => [
[
'name' => 'StringLength',
'options' => [
'encoding' => 'UTF-8',
'min' => 1,
'max' => 128
]
]
]
],
];
}
in the form where the company is required place this in your init() method after adding the fieldset:
$this->get('test')->setCompanyRequired(TRUE);
As the getInputFilterSpecification() method is not read until you validate your form this should work.
I have previously answered a similar question relating to over loading the default input filter options of a nested fieldset.
You can do the same inside the form using the Zend\InputFilter\InputFilterProviderInterface
class MyForm extends Form implements InputFilterProviderInterface
{
public function init()
{
//..
}
public function getInputFilterSpecification()
{
return [
'test' => [
'type' => 'Zend\\InputFilter\\InputFilter',
'company' => [
'required' => true,
],
],
];
}
}
Or alternately, you can achieve the same by manually configuring the fieldset's input filter inside MyFormFactory;
class MyFormFactory implements FactoryInterface
{
public function __invoke(ContainerInterface $container, $requestedName, array $options = null)
{
//.. same code
$form->getInputFilter() // fetch the input filter you just attached.
->get('test') // the name of the neseted fieldset (another input filter)
->get('company') // the name of the input
->setRequired(true); // set required to true :)
return $form;
}
}

edit action similar to tutorial doesn't work

I followed the ZF3 tutorial and I'm quite satisfied, but I'm something missing with the edit action in my controller. the add action works fine while the edit action doesn't. Probably I don't see it by myself, so I post it here, asking for help, even if it is really basic.
My model is nearly the same as in the tutorial, here a part of it:
public function exchangeArray(array $data)
{
$this->ProjectID= !empty($data['ProjectID']) ? $data['ProjectID'] : null;
$this->CI_Number= !empty($data['CI_Number']) ? $data['CI_Number'] : null;
$this->Description= !empty($data['Description']) ? $data['Description'] : null;
$this->Projectname= !empty($data['Projectname']) ? $data['Projectname'] : null;
$this->Shortcut= !empty($data['Shortcut']) ? $data['Shortcut'] : null;
$this->Component_Class= !empty($data['Component_Class']) ? $data['Component_Class'] : null;
}
public function getArrayCopy()
{
// echo var_dump(get_object_vars($this)
// );
//return get_object_vars($this);
return [
'ProjectID' => $this->ProjectID,
'CI_Number' => $this->CI_Number,
'Description' => $this->Description,
'Projectname' => $this->Projectname,
'Shortcut' => $this->Shortcut,
'Component_Class' => $this->Component_Class,
];
}
and here also my controlleraction:
public function editAction()
{
$id = (int) $this->params()->fromRoute('id', 0);
echo $id;
if (0 === $id) {
return $this->redirect()->toRoute('project', ['action' => 'add']);
}
else {
try {
$project = $this->projectTable->getProject($id);
} catch (\Exception $e) {
return $this->redirect()->toRoute('project', ['action' => 'index']);
}
$form = new ProjectForm();
$form->bind($project);
//$form->bind($project->current());
$form->get('submit')->setAttribute('value', 'save changes');
$request = $this->getRequest();
$viewData = ['ProjectID' => $id, 'form' => $form];
if (! $request->isPost()) {
return $viewData;
}
$form->setInputFilter($project->getInputFilter());
$form->setData($request->getPost());
if (! $form->isValid()) {
echo "nicht valide";
return $viewData;
}
else{
echo $project;
$this->projectTable->saveProject($project);
}
}
// Redirect to album list
// return $this->redirect()->toRoute('project', ['action' => 'index']);
}
here for completion reasons my view edit.phtml:
<?php
$title = 'projects';
$this->headTitle($title);
?>
<h1><?= $this->escapeHtml($title) ?></h1>
<?php
// This provides a default CSS class and placeholder text for the artist element:
$ProjectID= $form->get('ProjectID');
$ProjectID->setAttribute('class', 'form-control');
$ProjectID->setAttribute('placeholder', 'ProjectID');
$Projectname= $form->get('Projectname');
$Projectname->setAttribute('class', 'form-control');
$Projectname->setAttribute('placeholder', 'Projectname');
$CI_Number= $form->get('CI_Number');
$CI_Number->setAttribute('class', 'form-control');
$CI_Number->setAttribute('placeholder', 'CI_number');
$Shortcut= $form->get('Shortcut');
$Shortcut->setAttribute('class', 'form-control');
$Shortcut->setAttribute('placeholder', 'Shortcut');
$Description= $form->get('Description');
$Description->setAttribute('class', 'form-control');
$Description->setAttribute('placeholder', 'Description');
$Component_Class= $form->get('Component_Class');
$Component_Class->setAttribute('class', 'form-control');
$Component_Class->setAttribute('placeholder', 'Component_Class');
// This provides CSS classes for the submit button:
$submit = $form->get('submit');
$submit->setAttribute('class', 'btn btn-primary');
//$form->setAttribute('action', $this->url('project', ['action' => 'edit',])); //,'id'=> $id
$form->setAttribute('action', $this->url('project', [
'action' => 'edit',
'ProjectID' => $id,
]));
$form->prepare();
echo $this->form()->openTag($form);
?>
<?php // Wrap the elements in divs marked as form groups, and render the
// label, element, and errors separately within ?>
<div class="form-group">
<?= $this->formElement($ProjectID) ?>
<?= $this->formElementErrors()->render($ProjectID, ['class' => 'help-block']) ?>
</div>
<div class="form-group">
<?= $this->formLabel($CI_Number) ?>
<?= $this->formElement($CI_Number) ?>
<?= $this->formElementErrors()->render($CI_Number, ['class' => 'help-block']) ?>
</div>
<div class="form-group">
<?= $this->formLabel($Description) ?>
<?= $this->formElement($Description) ?>
<?= $this->formElementErrors()->render($Description, ['class' => 'help-block']) ?>
</div>
<div class="form-group">
<?= $this->formLabel($Projectname) ?>
<?= $this->formElement($Projectname) ?>
<?= $this->formElementErrors()->render($Projectname, ['class' => 'help-block']) ?>
</div>
<div class="form-group">
<?= $this->formLabel($Shortcut) ?>
<?= $this->formElement($Shortcut) ?>
<?= $this->formElementErrors()->render($Shortcut, ['class' => 'help-block']) ?>
</div>
<div class="form-group">
<?= $this->formLabel($Component_Class) ?>
<?= $this->formElement($Component_Class) ?>
<?= $this->formElementErrors()->render($Component_Class, ['class' => 'help-block']) ?>
</div>
<?php
echo $this->formSubmit($submit);
//echo $this->form->get('DCLID');
echo $this->formHidden($form->get('ProjectID'));
echo $this->form()->closeTag();
It will show the recordset properly, but won't save the changes to the database and afterwards redirects to my add action. I hope somebody sees what I'm missing, even it might be a stupid error.
EDIT1: Here is my routing link from index.phtml
Edit
EDIT2: Screenshot to show the routing parameter
EDIT3: describing test issues
here again my controller edit action, to follow up:
public function editAction()
{
$id = (int) $this->params()->fromRoute('id', 0);
echo "variable id: ". $id;
if (0 === $id) {
//return $this->redirect()->toRoute('project', ['action' => 'index']);
echo "id = 0";
}
else {
try {
$project = $this->projectTable->getProject($id);
} catch (\Exception $e) {
return $this->redirect()->toRoute('project', ['action' => 'index']);
}
$form = new ProjectForm();
$form->bind($project);
//$form->bind($project->current());
$form->get('submit')->setAttribute('value', 'save changes');
var_dump(get_object_vars($project));
$request = $this->getRequest();
$viewData = ['ProjectID' => $id, 'form' => $form];
if (!$request->isPost()) {
return $viewData;
}
else {
$form->setInputFilter($project->getInputFilter());
$form->setData($request->getPost());
if (!$form->isValid()) {
echo "nicht valide";
return $viewData;
}
else{
echo "valide";
echo $project;
$this->projectTable->saveProject($project);
}
}
}
// Redirect to album list
// return $this->redirect()->toRoute('project', ['action' => 'index']);
}
I get the output of the vardump, so the project to edit will be delivered correctly. If I send the form with the recordchanges the controller won't catch it, the controller action sees id=0 then, so the method saveProject will be never called. In my understanding it might has to do with the formvalid something, because after sending the data I come never further than if (0 === $id).
EDIT 4: After some actual tests I think it must be a routing issue. If I give the route manually via browser, I won't get the target page at all. If I dump the value, it is always NULL. So I think it could be a bracket to much/to less issue in my module.config.php I show it here because I couldn't finde the problem, I countedt the braskets several times and I won't get it. So any help is appreciated, it must be a very simple topic:
<?php
namespace Import;
use Zend\Router\Http\Segment;
use Zend\Router\Http\Literal;
use Zend\ServiceManager\Factory\InvokableFactory;
//use Zend\ServiceManager\Factory\InvokableFactory;
return [
/* 'controllers' => [
'factories' => [
Controller\ImportController::class => InvokableFactory::class,
],
], */
// hier die Einstellungen für die Routen
'router' => [
'routes' => [
'index' => [
'type' => Segment::class,
'options' => [
'route' => '/import[/:action[/:id]]',
'constraints' => [
'action' => '[a-zA-Z][a-zA-Z0-9_-]*',
'id' => '[0-9]+',
],
'defaults' => [
'controller' => Controller\IndexController::class,
'action' => 'index',
],
],
],
'import' => [
'type' => Segment::class,
'options' => [
'route' => '/import[/:action[/:id]]',
'constraints' => [
'action' => '[a-zA-Z][a-zA-Z0-9_-]*',
'id' => '[0-9]+',
],
'defaults' => [
'controller' => Controller\ImportController::class,
'action' => 'index',
],
],
],
'importdcl' => [
'type' => Segment::class,
'options' => [
'route' => '/importdcl[/:action[/:id]]',
'constraints' => [
'action' => '[a-zA-Z][a-zA-Z0-9_-]*',
'id' => '[0-9]+',
],
'defaults' => [
'controller' => Controller\ImportdclController::class,
'action' => 'index',
],
],
],
'project' => [
'type' => Segment::class,
'options' => [
'route' => '/project[/:action[/:id]]',
'constraints' => [
'action' => '[a-zA-Z][a-zA-Z0-9_-]*',
'id' => '[0-9]+',
],
'defaults' => [
'controller' => Controller\ProjectController::class,
'action' => 'index',
],
],
],
'unit' => [
'type' => Segment::class,
'options' => [
'route' => '/unit[/:action[/:id]]',
'constraints' => [
'action' => '[a-zA-Z][a-zA-Z0-9_-]*',
'id' => '[0-9]+',
],
'defaults' => [
'controller' => Controller\UnitController::class,
'action' => 'index',
],
],
],
'index' => [
'type' => Segment::class,
'options' => [
'route' => '/index[/:action[/:id]]',
'constraints' => [
'action' => '[a-zA-Z][a-zA-Z0-9_-]*',
'id' => '[0-9]+',
],
'defaults' => [
'controller' => Controller\IndexController::class,
'action' => 'index',
],
],
],
'user' => [
'type' => Segment::class,
'options' => [
'route' => '/user[/:action[/:id]]',
'constraints' => [
'action' => '[a-zA-Z][a-zA-Z0-9_-]*',
'id' => '[0-9]+',
],
'defaults' => [
'controller' => Controller\UserController::class,
'action' => 'index',
],
],
],
'followup' => [
'type' => Segment::class,
'options' => [
'route' => '/followup[/:action[/:id]]',
'constraints' => [
'action' => '[a-zA-Z][a-zA-Z0-9_-]*',
'id' => '[0-9]+',
],
'defaults' => [
'controller' => Controller\FollowupController::class,
'action' => 'index',
],
],
],
],
],
'view_manager' => [
'template_path_stack' => [
'import' => __DIR__ . '/../view',
],
],
/* ... */
'navigation' => [
'default' => [
[
'label' => 'Dashboard',
'route' => 'home',
],
[
'label' => 'Project',
'route' => 'project',
'pages' => [
[
'label' => 'Add',
'route' => 'project',
'action' => 'add',
],
[
'label' => 'Edit',
'route' => 'project',
'action' => 'edit',
],
[
'label' => 'Delete',
'route' => 'project',
'action' => 'delete',
],
],
],
[
'label' => 'Unit',
'route' => 'unit',
'pages' => [
[
'label' => 'Add',
'route' => 'unit',
'action' => 'add',
],
[
'label' => 'Edit',
'route' => 'unit',
'action' => 'edit',
],
[
'label' => 'Delete',
'route' => 'unit',
'action' => 'delete',
],
],
],
[
'label' => 'Importlog',
'route' => 'importdcl',
'action' => 'index',
'pages' => [
[
'label' => 'Add',
'route' => 'unit',
'action' => 'add',
],
[
'label' => 'Edit',
'route' => 'unit',
'action' => 'edit',
],
[
'label' => 'Delete',
'route' => 'unit',
'action' => 'delete',
],
],
],
[
'label' => 'Follow up',
'route' => 'followup',
'action' => 'index',
'pages' => [
[
'label' => 'Add',
'route' => 'unit',
'action' => 'add',
],
[
'label' => 'Edit',
'route' => 'unit',
'action' => 'edit',
],
[
'label' => 'Delete',
'route' => 'unit',
'action' => 'delete',
],
],
],
[
'label' => 'User',
'route' => 'user',
'pages' => [
[
'label' => 'Add',
'route' => 'unit',
'action' => 'add',
],
[
'label' => 'Edit',
'route' => 'unit',
'action' => 'edit',
],
[
'label' => 'Delete',
'route' => 'unit',
'action' => 'delete',
],
],
],
[
'label' => 'Logout',
'route' => 'user',
'action' => 'logout',
'pages' => [
[
'label' => 'Add',
'route' => 'unit',
'action' => 'add',
],
[
'label' => 'Edit',
'route' => 'unit',
'action' => 'edit',
],
[
'label' => 'Delete',
'route' => 'unit',
'action' => 'delete',
],
],
],
],
],
/* ... */
];
I'm testing in the usercontroller at the moment, but I have had the same problem in others routes, so I think the error might be in this file.
Based on your code, seem the problem is on $id. It mean the value is 0, that's why it is redirected to project/add.
$id = (int) $this->params()->fromRoute('id', 0);
echo $id;
if (0 === $id) {
return $this->redirect()->toRoute('project', ['action' => 'add']);
}
In your view script, the form action is set to project/edit/ProjectID/$id
$form->setAttribute('action', $this->url('project', [
'action' => 'edit',
'ProjectID' => $id,
]));
That's why your controller cannot retrieve $this->params()->fromRoute('id', 0), because the form send ProjectID param instead of id.
So, the solution please adjust your form (using id) or your controller (using ProjectID).
I at last solved it. My suggestion was right, it was a problem with the module.config.php, I have set an endbracket at the wrong place.
After writing it in parts new, tsting and complete the file, it now works.

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 girdview pagination id list are showing but not showing link

I am New in yii2 going to add pagination it is showing list of id only botstrap and link are not showing what is problem anyone explain me this is gridview
GridView::widget([
'dataProvider' => $dataProvider,
'filterModel' => $searchModel,
'id' => 'grid',
'columns' => [
['class' => 'yii\grid\SerialColumn'],
'user_fname',
'user_id',
'user_lname',
'user_mobile',
['class' => 'yii\grid\ActionColumn'],
[ 'class' => 'yii\grid\CheckboxColumn'],
],
]);
?>
<?php
echo yii\widgets\ListView::widget([
'dataProvider' => $dataProvider,
'View' => 'usermaster',
'layout' => "{pager}\n{items}\n{pager}",
]);
?>
This is search controller which is i have added pagignation class
public function search($params)
{
$query = UsermasterModel::find();
// add conditions that should always apply here
$dataProvider = new ActiveDataProvider([
'query' => $query,
'pagination' => [
'pageSize' => 10,
],
'sort' => [
'defaultOrder' => [
'user_fname' => SORT_DESC,
'user_fname' => SORT_ASC,
]
],
]);
$this->load($params);
if (!$this->validate()) {
// uncomment the following line if you do not want to return any records when validation fails
// $query->where('0=1');
return $dataProvider;
}
// grid filtering conditions
$query->andFilterWhere([
'user_id' => $this->user_id,
]);
$query->andFilterWhere(['like', 'user_fname', $this->user_fname])
->andFilterWhere(['like', 'user_lname', $this->user_lname])
->andFilterWhere(['like', 'user_mobile', $this->user_mobile]);
return $dataProvider;
}
}