Magento 2.1 Can't get form create observer like 2.0.x - magento2

$actionsSelect = $observer->getForm()->getElement('simple_action');
Magento 2.0.x variable $actionsSelect is working
on new ver magento 2.1:
variable $actionsSelect use var_dump() is return Null.
public function execute(\Magento\Framework\Event\Observer $observer)
{
$actionsSelect = $observer->getForm()->getElement('simple_action');
if ($actionsSelect){
$vals = $actionsSelect->getValues();
$vals[] = [
'value' => 'freegift_items',
'label' => __('Free gifts with products'),
];
$vals[] = [
'value' => 'freegift_cart',
'label' => __('Free gifts for the whole cart'),
];
$vals[] = [
'value' => 'freegift_product',
'label' => __('Free gift with same product'),
];
$vals[] = [
'value' => 'freegift_spent',
'label' => __('Free gifts with amount $X spent'),
];
$actionsSelect->setValues($vals);
$fldSet = $observer->getForm()->getElement('action_fieldset');
$fldSet->addField('freegift_type', 'select', [
'name' => 'freegiftrule[type]',
'label' => __('Type'),
'values' => [
0 => __('All SKUs Below'),
1 => __('One of the SKUs Below')
],
],
'discount_amount'
);
$fldSet->addField('freegift_sku', 'text', [
'name' => 'freegiftrule[sku]',
'label' => __('SKUs as Free gift'),
'note' => __('Comma separated list of the SKUs'),
],
'freegift_type'
);
}
}

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

routing after authentication doesn't work properly

I probably have an understanding issue how the routing works. I tried a bit with zend-authentication, you can see the controllercode below.
If the authentication is valide I want a routing to another controller index action. Should be quite simple, but the routing doesn't work I stay at the loginform. I added an echo just to see where I am after authentication and the authentication is valide. Here is the code:
$form = new LoginForm();
//return ['form' => $form];
$form->get('submit')->setValue('Login');
//echo "hier";
//$this->layout()->setTemplate('layout/login-layout');
$request = $this->getRequest();
if (! $request->isPost()) {
return ['form' => $form];
}
else {
$username=$request->getPost('accessname');
$password=$request->getPost('passwort');
//echo $password;
$adapter = $this->authService->getAdapter();
$adapter->setIdentity($request->getPost('accessname'));
$adapter->setCredential($request->getPost('passwort'));
$result = $this->authService->authenticate();
if ($result->isValid()){
echo "valide";
//return $this->redirect()->toRoute('import');
return $this->redirect()->toRoute('import', ['action' => 'index']);
}
else{
return ['form' => $form, 'messages' => $result->getMessages()];
}
}
as you can see I tried several possibilities. The other controller is placed in the same module.
Here additional the index action of the destinationcontroller.
I'm not finished there, because of the false routing I toggled everything else, so it just shows the echotext when I land there.
public function indexAction()
{
echo "importcontroller";
// $result = $this->authService->has
// $auth=Zend_Auth::getInstance();
// $adapter = $this->authService->getAdapter();
// if(!$this->authService->hasIdentity())
// {
// return $this->redirect()->toRoute('./index/index');
// }
// else {
// return new ViewModel([
// 'projects' => $this->projectTable->fetchAll(),
// ]);
// }
}
EDIT1: Add module.confg.php
'router' => [
'routes' => [
'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',
],
],
],
'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',
],
],
],
Can you show contents of module.config.php with routing configuration?
Maybe your routing was wrong and redirect to the same page where you are before correct authentication?
P.s. I think, You should always filternig data from form and get it by $form->getDate() function. Of course before you should apply appropriate filters.
this concept is described in zend framework tutorial:
https://docs.zendframework.com/tutorials/getting-started/forms-and-actions/

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

ZF 2.4 File Validator Required False Doesn't Work

Today I updated to ZF 2.4 to use float validator but unfortunately i realized that my file upload form field gives unexpected error messages.
Here is my form object
$this->add([
'name' => 'profileimage',
'type' => '\Zend\Form\Element\File',
'attributes' => [
'id' => 'profileimage',
'class' => 'styled',
],
]
);
And Here is my validator
$inputFilter->add([
'name' => 'profileimage',
'required' => false,
'allow_empty' => true,
'priority' => 300,
'filters' => [
['name' => 'StripTags'],
['name' => 'StringTrim'],
],
'validators' => [
[
'name' => '\Zend\Validator\File\IsImage',
],
[
'name' => '\Zend\Validator\File\UploadFile',
],
[
'name' => '\Zend\Validator\File\ImageSize',
'options' => [
'minWidth' => 300,
'minHeight' => 300,
]
],
[
'name' => '\Zend\Validator\File\Size',
'options' => [
'max' => '20MB',
]
],
]
]);
As you see the image upload field is not required and may be empty. But in my form I get these errors:
array (size=1)
'profileimage' =>
array (size=4)
'fileIsImageNotReadable' => string 'File is not readable or does not exist' (length=38)
'fileUploadFileErrorNoFile' => string 'File was not uploaded' (length=21)
'fileImageSizeNotReadable' => string 'File is not readable or does not exist' (length=38)
'fileSizeNotFound' => string 'File is not readable or does not exist' (length=38)
How can I handle this issue? I need to this field to be optional.
change your filter
$inputFilter->add([
'name' => 'profileimage',
'type' => '\Zend\InputFilter\FileInput',
'required' => false,
'allow_empty' => true,
'priority' => 300,
'filters' => [
['name' => 'StripTags'],
['name' => 'StringTrim'],
],
'validators' => [
[
'name' => '\Zend\Validator\File\IsImage',
],
[
'name' => '\Zend\Validator\File\UploadFile',
],
[
'name' => '\Zend\Validator\File\ImageSize',
'options' => [
'minWidth' => 300,
'minHeight' => 300,
]
],
[
'name' => '\Zend\Validator\File\Size',
'options' => [
'max' => '20MB',
]
],
]
]);
read about it here: http://framework.zend.com/manual/current/en/modules/zend.input-filter.file-input.html