Access translator in Shopware 6 Plugin - plugins

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

Related

Magento 2 admin custom save button send request twice

Basically, I want to send 'store' as a parameter when I save the form. For this, I customized the save button and added store_id there, but now save method is called twice. Any idea why this is happening and how can I fix it?
This is the button:(Vendor\Module\Block\Adminhtml\Entity\Edit\SaveButton.php)
public function getButtonData()
{
return [
'label' => __('Save'),
'class' => 'save primary',
'data_attribute' => [
'mage-init' => [
'buttonAdapter' => [
'actions' => [
[
'targetName' => 'vendor_module_entity_form.vendor_module_entity_form',
'actionName' => 'save',
'params' => [
true,
['store' => 5]
]
]
]
]
]
],
'sort_order' => 90,
];
}
and this is the ui_component (vendor_entity_entity_form.xml):
......
<settings>
<buttons>
<button class="Vendor\Module\Block\Adminhtml\Entity\Edit\SaveButton" name="save"/>
</buttons>
</settings>
<dataSource name="entiity_form_data_source">
<settings>
<submitUrl path="*/*/save"/>
<validateUrl path="*/*/validate"/>
</settings>
</dataSource>
......
Please try:
public function getButtonData(): array
{
return [
'label' => __('Save'),
'class' => 'save primary',
'data_attribute' => [
'mage-init' => ['button' => ['event' => 'save']],
'form-role' => 'save',
],
'sort_order' => 10
];
}
please try the below code.
$this->buttonList->add(
'select_all',
[
'label' => __('Select All Rates and Save'),
'class' => 'save',
'onclick' => "jQuery('#testhidden').val(1)",
'data_attribute' => [
'mage-init' => ['button' => ['event' => 'save', 'target' => '#edit_form']],
]
],
10
);
Create a hidden field in the form.php where fields are defined
$fieldset->addField(
'testhidden',
'hidden',
['name' => 'testhidden', 'value' => 0, 'no_span' => true]
);

zf3 __construct() not working

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

Method not allowed(#405)

following code throws out error like this:
"Method Not Allowed (#405)
Method Not Allowed. This url can only handle the following request methods: ."
Any ideas,how to fix this?
['label' => 'Logout', 'url' => ['/site/logout'], 'linkOptions' => ['data' => ['method' => 'post']]],
Here is still method in SiteController:
public function actionLogout() {
Yii::$app->user->logout();
return $this->goHome();
}
use data-method in linkOptions
['label' => 'logOut',
'url' => ['/site/logout'],
'linkOptions' => ['data-method' => 'post']
],
notice:check behavior in sitecontroller
public function behaviors() {
return [
'access' => [
'class' => AccessControl::className(),
'only' => ['logout', 'dashboard'],
'rules' => [
[
'actions' => ['logout'],
'allow' => true,
'roles' => ['#'],
],
],
],
'verbs' => [
'class' => VerbFilter::className(),
'actions' => [
'logout' => ['post'],
],
],
];
}

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

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

$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'
);
}
}