I'm developing a module for PS1.7.8.6 which add datas to a stock movement. In order to do that, I have decorate the PrestaShop\PrestaShop\Core\Stock\StockManager following the doc.
I don't know if the decoration was made in a good way because the stock movement in the BO still use PrestaShop\PrestaShop\Core\Stock\StockManager instead of my class CustomStockManager.
But in my module, if I call my CustomStockManager, the movement is not made. I've found that the function SymfonyContainer::getInstance(); return null so the function saveMovement() return false.
Is there a way to know why the SymfonyContainer return null ?
Thanks
Finally I have found a solution. The function SymfonyContainer::getInstance() return null because the function is called from an ajax.php file which call a function from the module.
To resolve it, first, I have put the function getKernel() from this article in the file mymodule.php.
Then, il my CustomStockManager, in the function saveMovement(), I have change this
$sfContainer = SymfonyContainer::getInstance();
if (null === $sfContainer) {
return false;
}
To
$sfContainer = SymfonyContainer::getInstance();
if (null === $sfContainer) {
$moduleObj = Module::getInstanceByName('mymodule');
$sfContainer = $moduleObj->getKernel()->getContainer();
}
And because there is no context and so no user to to the movement, at the beginning of the function I add :
if (is_null(Context::getContext()->employee)) {
$context = Context::getContext();
$context->employee = new Employee(1);
}
It works now but I think this is not the best way to do that. So I will change my ajax.php file in a controller for the module.
Related
In my web file, I have a route that accepts a $id as a value to be passed to a function within my PagesController. However, I want the function to still execute and show the intended form even when the $id is not passed to the function.
web.php file
Route::get('/request/{id}', 'PagesController#makeRequest');
PagesController.php file
public function makeRequest($id)
{
if(!empty($id)){
$target = Partner::find($id);
}
return view('pages.makeRequest')->with('target', $target);
}
makeRequest.blade.php
<input type="text" class="form-control" value="{{$target->inst_name}}" required disabled>
I want the page to display details from the database with the $id when provided or have empty spaces when the $id isn't provided.
As the Laravel Documentation states: Use Optional Parameters like this:
Route::get('/request/{id?}', 'PagesController#makeRequest'); //Optional parameter
Controller
public function makeRequest($id = null)
{
if(!empty($id)){
$target = User::find($id);
return view('pages.makeRequest')->with('target', $target);
} else {
return view('pageslist'); ///set default list..
}
}
This is the way I did it:
Route::get('index', 'SeasonController#index');
// controller
public function index(Request $request )
{
$id= $request->query('id');
}
The way you call it:
localhost/api/index?id=7
All your solutions were helpful. The main thing was that when I called just the view without passing $target to the view, the page displayed an error. So this is what I did.
Route::get('/request/{id?}', 'PagesController#makeRequest');
Then in the controller,
public function makeRequest(Request $request, $id=null)
{
if ($id != null) {
$target = Partner::find($id);
return view('pages.makeRequest')->with('target', $target);
}
return view('pages.makeNullRequest');
}
If you didn't understand what happened, I created a new view which had this instead of what I had posted in the question.
<input type="text" class="form-control" value="" required readonly>
Sorry I didn't update you guys in time. I think Jignesh Joisar came closest to helping me solve this issue. really appreciate all you guys. You're just awesome
You can use optional parameter :
Route::get('/request/{id?}', 'PagesController#makeRequest');
Now, as the parameter is optional, while defining the controller function you need to assign its default value to null in argument declaration.
<?php
public function makeRequest($id = null)
{
if($id){
$target = Partner::findOrFail($id);
return view('pages.makeRequest')->with(compact('target'));
}
// Return different view when id is not present
// Maybe all targets if you want
$targets = Partner::select('column1', 'column2')->get();
return view('pages.all')->with('targets');
}
I am using findOrFail instead of find. Its Laravel's very handy function which automatically throws a ModelNotFound exception and for frontend user throws a simple 404 page.
So if anyone is accessing www.url.com/request/2, its a valid id then it will show a valid page with data. If the accessed url is www.url.com/request/blahblah then it will throw 404. It avoids efforts of handling this manually.
For optional parameter pass id with ? in route and give $id = null in your function's parameter like this:
Route::get('/request/{id?}', 'PagesController#makeRequest'); //Optional parameter
makeRequest($id = null) {
// Code here...
...
}
in your routes file (web.php , as mentioned in your question)
Route::get('/request/{id?}', 'PagesController#makeRequest');
and in your controller PagesController.php
public function makeRequest($id = null)
{
}
To read more about this, just read https://laravel.com/docs/5.7/routing#parameters-optional-parameters
For me the answer was in the order that I listed the Routes in the routes file.
The routes file will call the first one that matches the pattern.
Route::get('/ohmy/{id?}', 'OhMyController#show');
Route::get('/ohmy/all', 'OhMyController#all'); //never gets called
Instead, put optional parameters at end of list:
Route::get('/ohmy/all', 'OhMyController#all');
Route::get('/ohmy/{id?}', 'OhMyController#show');
the answer has been said. just a side note: optional parameters won't work if you are using resource routes.
for example:
Route::resource('items',itemController::class)->except([
'create',
]);
Route::get('/items/create/{category_id?}',function($category_id = 'abc'){
dd($category_id);
});
if i go to " items/create/1 ", the result will be "1".
if i go to " items/create ", it will return 404. ( but we expect it to say "abc".)
this happens because other routes that start with "items" are expected to be generated from "resource" functionality.
so if you use resource routes, you should consider that.
i have small trouble...
class Controller {
init() {
// initializing...
// render header && footer
$header = (new HeaderAction)->run();
$footer = (new FooterAction)->run();
// redirect to called action, what renders all the content
}
}
What i can detect diff between ->run() and called action?
Answer found in:
AfterRender -> parse Route -> compare action names. If match - echo, if not match - Return.
Yii is SHIT!!!
I will write new class MyAction with method AddData, what can render for me some viewfile. Creating class CAction for this, what can't rendering? Maybe i must create controller? Are you noob, Quang, ha?
Lol, i can't create the header with action. I must create it in Controller. Controller file now is 1200 lines. >_<
class MyAction {
public $data = array();
public function addData($name, $val) {
$this->data[$name] = $val;
}
public function render($file) {
ob_start;
// ... something
return ob_get_clean;
};
}
/// ITS ALL WHAT NEED ALL THE DEVELOPERS>>>>
BEHAVIORS? EVENTS? FILTERS? WIDGETS? MODULES? MAYBE WE NEED "CAMOBAP" AS AUTOCAR?
REASOOOONS????
===
Lol, there is model cannot to render at all. I have products with views as "tr-tr", and i must create controller, create action, create route for rendering funcking 10 SYMBOLS.... Its Rage. About u, Quang.
Russian Bear will kill you.
Scenario: Modify and save an incomplete change to a Campaign
Given I click on the Campaign section folder
And I press Save in the selected Campaign
Then I should see an error balloon informing the changes cannot be saved
Point is that this 'error balloon' in the final step is a ajax call which will then bring a green or red balloon according to the success of the operation. Currently what I do is after
'And I press Save...' I will do a sleep(3) to give it time for this balloon to show up. This doesn't seem very smart coz you are wasting time and also because some times it can take more or less time for this call to be processed.
How do you guys make your behat tests wait for Ajax do be done instead of just putting the beasts to sleep?
thank you very much for any feedback!
This is done by waiting for your outstanding ajax calls to hit 0. jQuery.active will check just that for you.
In your FeatureContext.php, you can do something like;
public function iShouldSeeAnErrorBalloon($title)
{
$time = 5000; // time should be in milliseconds
$this->getSession()->wait($time, '(0 === jQuery.active)');
// asserts below
}
And do make sure you use a Mink Driver that runs javascript and ajax (the default does not).
I do it by waiting for the DOM to change as a result of the Ajax Call. I made a subclass of DocumentElement, calling it AsyncDocumentElement and overriding the findAll method:
public function findAll($selector, $locator, $waitms=5000)
{
$xpath = $this->getSession()->getSelectorsHandler()->selectorToXpath($selector, $locator);
// add parent xpath before element selector
if (0 === strpos($xpath, '/')) {
$xpath = $this->getXpath().$xpath;
} else {
$xpath = $this->getXpath().'/'.$xpath;
}
$page = $this->getSession()->getPage();
// my code to wait until the xpath expression provides an element
if ($waitms && !($this->getSession()->getDriver() instanceof \Behat\Symfony2Extension\Driver\KernelDriver)) {
$templ = 'document.evaluate("%s", document, null, XPathResult.UNORDERED_NODE_SNAPSHOT_TYPE, null ).snapshotLength > 0;';
$waitJs = sprintf($templ, $xpath);
$this->getSession()->wait($waitms, $waitJs);
}
return $this->getSession()->getDriver()->find($xpath);
}
Then in \Behat\Mink\Session I changed the constructor to use that class.
public function __construct(DriverInterface $driver, SelectorsHandler $selectorsHandler = null)
{
$driver->setSession($this);
if (null === $selectorsHandler) {
$selectorsHandler = new SelectorsHandler();
}
$this->driver = $driver;
$this->page = new AsyncDocumentElement($this);
$this->selectorsHandler = $selectorsHandler;
}
Once I did this, I found my AngularJS tests were working. So far, I've only tested in Firefox.
In case you are using Prototypejs (e.g Magento), the equivalent code is:
public function iShouldSeeAnErrorBalloon($title)
{
$this->getSession()->wait($duration, '(0 === Ajax.activeRequestCount)');
// asserts below
}
I'm using PHP 5.3's class_alias to help process my Symfony 1.4 (Doctrine) forms. I use a single action to process multiple form pages but using a switch statement to choose a Form Class to use.
public function executeEdit(sfWebRequest $request) {
switch($request->getParameter('page')) {
case 'page-1':
class_alias('MyFormPage1Form', 'FormAlias');
break;
...
}
$this->form = new FormAlias($obj);
}
This works brilliantly when browsing the website, but fails my functional tests, because when a page is loaded more than once, like so:
$browser->info('1 - Edit Form Page 1')->
get('/myforms/edit')->
with('response')->begin()->
isStatusCode(200)->
end()->
get('/myforms/edit')->
with('response')->begin()->
isStatusCode(200)->
end();
I get a 500 response to the second request, with the following error:
last request threw an uncaught exception RuntimeException: PHP sent a warning error at /.../apps/frontend/modules/.../actions/actions.class.php line 225 (Cannot redeclare class FormAlias)
This makes it very hard to test form submissions (which typically post back to themselves).
Presumably this is because Symfony's tester hasn't cleared the throughput in the same way.
Is there a way to 'unalias' or otherwise allow this sort of redeclaration?
As an alternate solution you can assign the name of the class to instantiate to a variable and new that:
public function executeEdit(sfWebRequest $request) {
$formType;
switch($request->getParameter('page')) {
case 'page-1':
$formType = 'MyFormPage1Form';
break;
...
}
$this->form = new $formType();
}
This doesn't use class_alias but keeps the instantiation in a single spot.
I do not know for sure if it is possible, but judging from the Manual, I'd say no. Once the class is aliased, there is no way to reset it or redeclare it with a different name. But then again, why do use the alias at all?
From your code I assume you are doing the aliasing in each additional case block. But if so, you can just as well simply instantiate the form in those blocks, e.g.
public function executeEdit(sfWebRequest $request) {
switch($request->getParameter('page')) {
case 'page-1':
$form = new MyFormPage1Form($obj);
break;
...
}
$this->form = $form;
}
You are hardcoding the class names into the switch/case block anyway when using class_alias. There is no advantage in using it. If you wanted to do it dynamically, you could create an array mapping from 'page' to 'className' and then simply lookup the appropriate class.
public function executeEdit(sfWebRequest $request) {
$mapping = array(
'page-1' => 'MyFormPage1Form',
// more mappings
);
$form = NULL;
$id = $request->getParameter('page');
if(array_key_exists($id, $mapping)) {
$className = $mapping[$id];
$form = new $className($obj);
}
$this->form = $form;
}
This way, you could also put the entire mapping in a config file. Or you could create FormFactory.
public function executeEdit(sfWebRequest $request) {
$this->form = FormFactory::create($request->getParameter('page'), $obj);
}
If you are using the Symfony Components DI Container, you could also get rid of the hard coded factory dependency and just use the service container to get the form. That would be the cleanest approach IMO. Basically, using class_alias just feels inappropriate here to me.
function class_alias_once($class, $alias) {
if (!class_exists($alias)) {
class_alias($class, $alias);
}
}
This doesn't solve the problem itself, but by using this function it is ensured that you don't get the error. Maybe this will suffice for your purpose.
This situation arises from someone wanting to create their own "pages" in their web site without having to get into creating the corresponding actions.
So say they have a URL like mysite.com/index/books... they want to be able to create mysite.com/index/booksmore or mysite.com/index/pancakes but not have to create any actions in the index controller. They (a non-technical person who can do simple html) basically want to create a simple, static page without having to use an action.
Like there would be some generic action in the index controller that handles requests for a non-existent action. How do you do this or is it even possible?
edit: One problem with using __call is the lack of a view file. The lack of an action becomes moot but now you have to deal with the missing view file. The framework will throw an exception if it cannot find one (though if there were a way to get it to redirect to a 404 on a missing view file __call would be doable.)
Using the magic __call method works fine, all you have to do is check if the view file exists and throw the right exception (or do enything else) if not.
public function __call($methodName, $params)
{
// An action method is called
if ('Action' == substr($methodName, -6)) {
$action = substr($methodName, 0, -6);
// We want to render scripts in the index directory, right?
$script = 'index/' . $action . '.' . $this->viewSuffix;
// Script file does not exist, throw exception that will render /error/error.phtml in 404 context
if (false === $this->view->getScriptPath($script)) {
require_once 'Zend/Controller/Action/Exception.php';
throw new Zend_Controller_Action_Exception(
sprintf('Page "%s" does not exist.', $action), 404);
}
$this->renderScript($script);
}
// no action is called? Let the parent __call handle things.
else {
parent::__call($methodName, $params);
}
}
You have to play with the router
http://framework.zend.com/manual/en/zend.controller.router.html
I think you can specify a wildcard to catch every action on a specific module (the default one to reduce the url) and define an action that will take care of render the view according to the url (or even action called)
new Zend_Controller_Router_Route('index/*',
array('controller' => 'index', 'action' => 'custom', 'module'=>'index')
in you customAction function just retrieve the params and display the right block.
I haven't tried so you might have to hack the code a little bit
If you want to use gabriel1836's _call() method you should be able to disable the layout and view and then render whatever you want.
$this->_helper->layout()->disableLayout();
$this->_helper->viewRenderer->setNoRender(true);
I needed to have existing module/controller/actions working as normal in a Zend Framework app, but then have a catchall route that sent anything unknown to a PageController that could pick user specified urls out of a database table and display the page. I didn't want to have a controller name in front of the user specified urls. I wanted /my/custom/url not /page/my/custom/url to go via the PageController. So none of the above solutions worked for me.
I ended up extending Zend_Controller_Router_Route_Module: using almost all the default behaviour, and just tweaking the controller name a little so if the controller file exists, we route to it as normal. If it does not exist then the url must be a weird custom one, so it gets sent to the PageController with the whole url intact as a parameter.
class UDC_Controller_Router_Route_Catchall extends Zend_Controller_Router_Route_Module
{
private $_catchallController = 'page';
private $_catchallAction = 'index';
private $_paramName = 'name';
//-------------------------------------------------------------------------
/*! \brief takes most of the default behaviour from Zend_Controller_Router_Route_Module
with the following changes:
- if the path includes a valid module, then use it
- if the path includes a valid controller (file_exists) then use that
- otherwise use the catchall
*/
public function match($path, $partial = false)
{
$this->_setRequestKeys();
$values = array();
$params = array();
if (!$partial) {
$path = trim($path, self::URI_DELIMITER);
} else {
$matchedPath = $path;
}
if ($path != '') {
$path = explode(self::URI_DELIMITER, $path);
if ($this->_dispatcher && $this->_dispatcher->isValidModule($path[0])) {
$values[$this->_moduleKey] = array_shift($path);
$this->_moduleValid = true;
}
if (count($path) && !empty($path[0])) {
$module = $this->_moduleValid ? $values[$this->_moduleKey] : $this->_defaults[$this->_moduleKey];
$file = $this->_dispatcher->getControllerDirectory( $module ) . '/' . $this->_dispatcher->formatControllerName( $path[0] ) . '.php';
if (file_exists( $file ))
{
$values[$this->_controllerKey] = array_shift($path);
}
else
{
$values[$this->_controllerKey] = $this->_catchallController;
$values[$this->_actionKey] = $this->_catchallAction;
$params[$this->_paramName] = join( self::URI_DELIMITER, $path );
$path = array();
}
}
if (count($path) && !empty($path[0])) {
$values[$this->_actionKey] = array_shift($path);
}
if ($numSegs = count($path)) {
for ($i = 0; $i < $numSegs; $i = $i + 2) {
$key = urldecode($path[$i]);
$val = isset($path[$i + 1]) ? urldecode($path[$i + 1]) : null;
$params[$key] = (isset($params[$key]) ? (array_merge((array) $params[$key], array($val))): $val);
}
}
}
if ($partial) {
$this->setMatchedPath($matchedPath);
}
$this->_values = $values + $params;
return $this->_values + $this->_defaults;
}
}
So my MemberController will work fine as /member/login, /member/preferences etc, and other controllers can be added at will. The ErrorController is still needed: it catches invalid actions on existing controllers.
I implemented a catch-all by overriding the dispatch method and handling the exception that is thrown when the action is not found:
public function dispatch($action)
{
try {
parent::dispatch($action);
}
catch (Zend_Controller_Action_Exception $e) {
$uristub = $this->getRequest()->getActionName();
$this->getRequest()->setActionName('index');
$this->getRequest()->setParam('uristub', $uristub);
parent::dispatch('indexAction');
}
}
You could use the magic __call() function. For example:
public function __call($name, $arguments)
{
// Render Simple HTML View
}
stunti's suggestion was the way I went with this. My particular solution is as follows (this uses indexAction() of whichever controller you specify. In my case every action was using indexAction and pulling content from a database based on the url):
Get an instance of the router (everything is in your bootstrap file, btw):
$router = $frontController->getRouter();
Create the custom route:
$router->addRoute('controllername', new Zend_Controller_Router_Route('controllername/*', array('controller'=>'controllername')));
Pass the new route to the front controller:
$frontController->setRouter($router);
I did not go with gabriel's __call method (which does work for missing methods as long as you don't need a view file) because that still throws an error about the missing corresponding view file.
For future reference, building on gabriel1836 & ejunker's thoughts, I dug up an option that gets more to the point (and upholds the MVC paradigm). Besides, it makes more sense to read "use specialized view" than "don't use any view".
// 1. Catch & process overloaded actions.
public function __call($name, $arguments)
{
// 2. Provide an appropriate renderer.
$this->_helper->viewRenderer->setRender('overload');
// 3. Bonus: give your view script a clue about what "action" was requested.
$this->view->action = $this->getFrontController()->getRequest()->getActionName();
}
#Steve as above - your solution sounds ideal for me but I am unsure how you implmeented it in the bootstrap?