Duplicate a sylius product - php

I try to duplicate a product. I have created a productController with a duplicate method
class ProductController extends ResourceController
{
public function duplicate(Request $request, Product $product): Response
{
$parentCreate = parent::createAction($request);
return $parentCreate;
}
}
My routes.yaml :
duplicate_product:
path: /admin/duplicate/{product}
defaults:
_controller: controller.duplicate_product:duplicate
_sylius:
template: "#SyliusAdmin/Crud/create.html.twig"
In my services.yaml :
controller.duplicate_product:
class: MyNamespace\Controller\Admin\ProductController
tags:
- { name: controller.service_arguments }
Also added the ref to my controller in _sylius.yaml:
sylius_product:
resources:
product:
classes:
model: MyNamespace\Entity\Product\Product
repository: MyNamespace\Repository\Product\ProductRepository
controller: MyNamespace\Controller\Admin\ProductController
And i still got the following error :
Too few arguments to function Sylius\Bundle\ResourceBundle\Controller\ResourceController::__construct(), 0 passed in /var/cache/dev/ContainerW7PrxgE/getController_DuplicateProductService.php on line 25 and exactly 17 expected
Any idea of what can fix this ?

Sylius: how to create my own Custom Resource with custom controller without getting "can not autowire"-exception?
Basicly, you have to remove from service.yaml
controller.duplicate_product:
class: MyNamespace\Controller\Admin\ProductController
tags:
- { name: controller.service_arguments }
and in your routes.yaml you should use as controller sylius.controller.product:duplicate

Related

paramconverter not converting parameters

I have a problem with symfony 4. i'm migrating an existing app from symfony 3.3 to symfony 4 and I get an error I can't correct.
here is my controller :
BaseController is the controller responding to sm_admin routes
class HomeController extends BaseController
{
public function __construct(ParamBagService $parambag, CacheService $cache) {
parent::__construct($parambag, $cache);
$this->routePrefix = 'sm_adminarea_';
}
/**
* #Route("/", name="adminarea_index")
* #Template("#SMAdmin/Home/index.html.twig")
*/
public function indexAction(Area $area = null)
{
$this->area = $area;
return parent::indexAction();
}
}
here is my routes.yaml
sm_admin:
resource: "#SMAdminBundle/Controller/"
type: annotation
prefix: /
sm_admin_area:
resource: "#SMAdminAreaBundle/Controller/"
type: annotation
prefix: /Area/{area}
When I go to the sm_admin route, everything is fine. when I go to /area/the_id_of_area I get the following error : argument 1 passed to indexAction must be of type Area or null, string provided This lets me think that the area parameter is not converted and the document is not retreived from the database.
I tried adding this paramConverter annotation : #ParamConverter("area", options={"mapping"={"area"="id"}}) but I get the same error...
What am I doing wrong ?
ok, I found the solution here https://matthiasnoback.nl/2012/10/symfony2-mongodb-odm-adding-the-missing-paramconverter/
The default paramconverter was using doctrine ORM and I use doctrine ODM so i just had to add ths in the servide.yaml :
param_converter:
class: 'Sensio\Bundle\FrameworkExtraBundle\Request\ParamConverter\DoctrineParamConverter'
arguments: ['#doctrine_mongodb']
tags:
- { name: 'request.param_converter', converter: 'doctrine.odm' }
Try using
#ParamConverter("area", class="YourBundle:Area")
as seen http://symfony.com/doc/current/bundles/SensioFrameworkExtraBundle/annotations/converters.html#usage

Symfony KnpMenuBundle showing error [MenuBuilder As a Service]

I'm using sumfony 3.3.10, I have installed a fresh project of symfony and I added knpMenuBundle using this command,
composer require knplabs/knp-menu-bundle "^2.0"
Now I followed everything exactly as mentioned here http://symfony.com/doc/master/bundles/KnpMenuBundle/menu_builder_service.html
and added this line {{ knp_menu_render('main') }} in default/index.html.twig file.
Now when I execute the project, its showing me this error,
[InvalidArgumentException]
Menu builder services must be public but "app.menu_builder" is a private service.
config.yml
knp_menu:
# use "twig: false" to disable the Twig extension and the TwigRenderer
twig:
template: KnpMenuBundle::menu.html.twig
# if true, enables the helper for PHP templates
templating: false
# the renderer to use, list is also available by default
default_renderer: twig
MenuBuilder.php
<?php
namespace AppBundle\Menu;
use Knp\Menu\FactoryInterface;
class MenuBuilder
{
private $factory;
/**
* #param FactoryInterface $factory
*
* Add any other dependency you need
*/
public function __construct(FactoryInterface $factory)
{
$this->factory = $factory;
}
public function createMainMenu(array $options)
{
$menu = $this->factory->createItem('root');
$menu->addChild('Home', array('route' => 'homepage'));
// ... add more children
return $menu;
}
}
services.yml
app.menu_builder:
class: AppBundle\Menu\MenuBuilder
arguments: ["#knp_menu.factory"]
tags:
- { name: knp_menu.menu_builder, method: createMainMenu, alias: main } # The alias is what is used to retrieve the menu
How can I resolve it. Any help is much appreciated. Thanks
I added public: true to the app.menu_builder service in services.php,
app.menu_builder:
class: AppBundle\Menu\MenuBuilder
public: true
arguments: ["#knp_menu.factory"]
tags:
- { name: knp_menu.menu_builder, method: createMainMenu, alias: main } # The alias is what is used to retrieve the menu
And everything is working fine now.
Refer : https://symfony.com/doc/current/service_container/alias_private.html#marking-services-as-public-private

Catch-all route in Symfony 3

I have a catch-all fallback route in Symfony2 that I couldn't get to work in Symfony3. I tried this exact syntax (a verbatim copy of my Symfony2 route) and that didn't work.
fallback:
path: /{req}
defaults: { _controller: MyBundle:Default:catchAll }
requirements:
req: ".+"
How can I get this working in Symfony3? (It's literally the only thing holding me back from using Symfony3 and keeping me at v2.8)
This should help you:
route1:
path: /{req}
defaults: { _controller: 'AppBundle:Default:index' }
requirements:
req: ".+"
Where, my controller is called "DefaultController", and I have a function called "indexAction()".
Here is my code for the DefaultController:
class DefaultController extends Controller
{
/**
* #Route("/", name="homepage")
*/
public function indexAction(Request $request)
...
I actually did try what you said in my environment, and it didn't work until I had the right controller settings specified.
EDIT:
For this to work, it was necessary to add the parameter Request $request (with the type hint) to the action's method signature.
I found the current accepted answer almost useful for Symfony 4, so I'm going to add my solution:
This is what I did to get it working in Symfony 4:
Open /src/Controller/DefaultController.php, make sure there is a function called index(){}
It's not required to add the Request $request as first param as some comment suggest.
This is the method that will handle all urls caught by the routes.yaml
Open /config/routes.yaml, add this:
yourRouteNameHere:
path: /{req}
defaults: { _controller: 'App\Controller\DefaultController::index' }
requirements: # the controller --^ the method --^
req: ".*"` # not ".+"
You can also override Exception controller.
# app/config/config.yml
twig:
exception_controller: app.exception_controller:showAction
# app/config/services.yml
services:
app.exception_controller:
class: AppBundle\Controller\ExceptionController
arguments: ['#twig', '%kernel.debug%']
namespace AppBundle\Controller;
use Symfony\Component\Debug\Exception\FlattenException;
use Symfony\Component\HttpKernel\Log\DebugLoggerInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
class ExceptionController
{
protected $twig;
protected $debug;
public function __construct(\Twig_Environment $twig, $debug)
{
$this->twig = $twig;
$this->debug = $debug;
}
public function showAction(Request $request, FlattenException $exception, DebugLoggerInterface $logger = null)
{
// some action
return new Response($this->twig->render('error/template.html.twig', [
'status_code' => $exception->getStatusCode()
]
));
}
}

Symfony Custom Validator not loading Dependency

Error:
...ThemeValidator::__construct() must be of the type array, null given...
For some reason the Service is not being called, but the Class is being loaded directly.
validation.yml
theme:
- NotBlank: ~
- DashboardHub\Bundle\AppBundle\Validator\Constraints\ThemeValidator: ~
Validator Class
<?php
namespace DashboardHub\Bundle\AppBundle\Validator\Constraints;
use Symfony\Component\Validator\Constraint;
use Symfony\Component\Validator\ConstraintValidator;
class ThemeValidator extends ConstraintValidator
{
protected $config;
public function __construct(array $config)
{
$this->config = $config;
}
public function validatedBy()
{
return 'theme.validator';
}
public function validate($value, Constraint $constraint)
{
var_dump($this->config); exit;
}
// ...
service.yml
dashboardhub_app_main.validator.constraints.theme:
class: DashboardHub\Bundle\AppBundle\Validator\Constraints\ThemeValidator
arguments: ["%dashboard_hub_app%"]
tags:
- { name: validator.constraint_validator, alias: theme.validator }
Edit
parameters:
dashboard_hub_app:
themes:
Github: DashboardHubAppBundle:Template:Github.html.twig
GithubTravis: DashboardHubAppBundle:Template:GithubTravis.html.twig
Edit2
It works find when used in the Form Service
dashboardhub_app_main.form.type.dashboard:
class: DashboardHub\Bundle\AppBundle\Form\DashboardType
arguments: ["%dashboard_hub_app%"]
tags:
- { name: form.type, alias: dashboard }
parameters:
dashboard_hub_app: -- !!!!! IS NULL yes
funny :)
parameters follow one by one, so you need to be careful, paramenters && themes - are different.
to inject an array you need provide a value for this paramenter, but i guess you need to inject this one
themes:
Github: DashboardHubAppBundle:Template:Github.html.twig
GithubTravis: DashboardHubAppBundle:Template:GithubTravis.html.twig
arguments: ["%themes%"]
and result will be an array inside your Validator class
array (size=2)
'Github' => string 'DashboardHubAppBundle:Template:Github.html.twig' (length=47)
'GithubTravis' => string 'DashboardHubAppBundle:Template:GithubTravis.html.twig' (length=53)

UnexpectedTypeException when trying to create a custom validation constraint

I'm trying to create a custom validation constraint, this is the relevant code:
ValidCoupon.php
<?php
namespace Bcg\UtilsBundle\Validator\Constraints;
use Symfony\Component\Validator\Constraint;
use Symfony\Component\Validator\ConstraintValidator;
/**
* #Annotation
*/
class ValidCoupon extends Constraint
{
public function validatedBy()
{
return 'valid_coupon';
}
public $message = 'The coupon is not valid.';
}
class ValidCouponValidator extends ConstraintValidator
{
public function validate($value, Constraint $constraint)
{
var_dump($value);
if (true) {
$this->context->addViolation(
$constraint->message,
array()
);
}
}
}
I call the service in the config.yml like this:
services:
validator.unique.valid_coupon:
class: Bcg\UtilsBundle\Validator\Constraints\ValidCoupon
tags:
- { name: validator.constraint_validator, alias: valid_coupon }
The validation.yml looks like this:
Bcg\UtilsBundle\Entity\Order:
properties:
coupon:
- Bcg\UtilsBundle\Validator\Constraints\ValidCoupon: ~
And the error I get is the following:
Expected argument of type
"Symfony\Component\Validator\ConstraintValidatorInterface",
"Bcg\UtilsBundle\Validator\Constraints\ValidCoupon" given 500 Internal
Server Error - UnexpectedTypeException
Full stack trace here.
I'm pretty stuck, it doesn't seem to find ValidCouponValidator I don't really know how to continue from here, I know that the public function validateBy() is executed, so it should be correctly overridden but it doesn't seem so...
Seems like you have a type in your validator service configuration :
You declare your ValidCoupon class as a validator instead of your ValidCouponValidator (which indeed implements the ConstraintValidatorInterface as the error complains about).
Try this:
services:
validator.unique.valid_coupon:
class: Bcg\UtilsBundle\Validator\Constraints\ValidCouponValidator
tags:
- { name: validator.constraint_validator, alias: valid_coupon }

Categories