Yii2 createurl with integer parameter - url

I got the error
syntax error, unexpected '‌' (T_STRING)
that's my link
<?php $url=Yii::$app->getUrlManager()->createUrl('admin/message/chat',array('idUser'=>$contact['id'])‌);?>
and inside the rules function i add the following link:
[['admin/message/chat/idUser/' => 'admin/message/chat']],
and my action's script looks like:
public function actionChat($idUser = null)
{
$searchModel = new MessageSearch();
$dataProvider = $searchModel->search(Yii::$app->request->queryParams);
return $this->render('index', [
'searchModel' => $searchModel,
'dataProvider' => $dataProvider,
'$idUser' => $idUser,
]);
}

Your error is in
'$idUser' => $idUser,
It should be
'idUser' => $idUser,

Could be you missed some closing } eg: at the end of an action or at the end of the controller class
class MessageController extends Controller
{
public function actionChat()
{
......
}
} // check for this

Related

Yii2 post request in controller

I have two submit buttons (submit1 and submit2). When I click "submit2", the controller should write a value (1) in a specific column (abgerechnet) in my db.
public function actionUpdate($id)
{
$model = $this->findModel($id);
if ($model->load(Yii::$app->request->post()) && $model->save()) {
if(isset($_POST['submit2']) )
{
$request = Yii::$app->request;
$test= $request->post('test', '1');
}
return $this->redirect(['view', 'id' => $model->ID]);
}
return $this->render('update', [
'model' => $model,
]);
}
But when I click the button "submit2" the column "test" remains empty.
With the lines $request = Yii::$app->request;
$test= $request->post('test', '1');
it should write the value in the column "test".
If you want update the colum abgerechnet in your model based on $_POST['submit2'] then you should set the the value before invoking model->save()
public function actionUpdate($id)
{
$model = $this->findModel($id);
if ($model->load(Yii::$app->request->post()) ) {
if(isset($_POST['submit2']) )
{
$model->abgerechnet = 1;
}
$model->save();
return $this->redirect(['view', 'id' => $model->ID]);
}
return $this->render('update', [
'model' => $model,
]);
}

Laravel 5.1 Pass middleware parameters as array

i have a route group in which i will check the rank of the user by middleware:
Route::group(['prefix' => 'expert'], function () {
Route::group(['prefix' => 'partner', 'middleware' => 'rank:4,5'], function () {
Route::get('/search', 'PartnerController#getSearch');
Route::post('/result', 'PartnerController#postSearch');
});
});
the middleware is registred in the kernel.php :
protected $routeMiddleware = [
'auth' => \App\Http\Middleware\Authenticate::class,
'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
'rank' => \App\Http\Middleware\checkRank::class,
];
here is my class :
namespace App\Http\Middleware;
use Closure;
use Auth;
class checkRank {
public function handle($request, Closure $next, $ranks) {
//return $next($request);
return print_r($ranks);
}
}
all i wanna see is the array with the values [4,5]
but all i get is 4
PHP-Version is 5.6.11
trying this way according to : http://laravel.com/docs/5.1/middleware#middleware-parameters
public function handle($request, Closure $next, ...$ranks) {}
i forgot the three dots in front of $ranks

Zend Framework 2 Custom elements using ServiceManager not work

I want create a custom element and use the short name for add the element into Form, using the new ServiceManager tecnique for ZF2 V.2.1+
I am try to copy the same sample of the zend documentation step to step but it not works.
When I use the service writting the short name, it raises a exception because service not found:
Zend\ServiceManager\Exception\ServiceNotFoundException
File:
Zend\ServiceManager\ServiceManager.php:456
Message:
Zend\ServiceManager\ServiceManager::get was unable to fetch or create an instance for Test
I think I have all classes identically, see follows
This is my custom element:
namespace SecureDraw\Form\Element;
use Zend\Form\Element\Text;
class ProvaElement extends Text {
protected $hola;
public function hola(){
return 'hola';
}
}
This is my Module.php I have my invokable service be able to use short name:
class Module implements FormElementProviderInterface {
//Rest of class
public function getFormElementConfig() {
return array(
'invokables' => array(
'Test' => 'SecureDraw\Form\Element\ProvaElement'
)
);
}
}
In my form I use for add the element, the commented line works ok, but with short name not works:
$this->add(array(
'name' => 'prova',
//'type' => 'SecureDraw\Form\Element\ProvaElement',
'type' => 'Test', //Fail
));
In my action:
$formManager = $this->serviceLocator->get('FormElementManager');
$form = $formManager->get('SecureDraw\Form\UserForm');
$prova = $form->get('prova');
echo $prova->hola();
The problem is that the elements created via FormElementManager have to be created into init method instead __Construct method how it can see in this page.
The zend documentation is badly explained
Workaround:
In your own module, create the following two files:
FormElementManagerConfig with the invokables short names of your custom form elements;
Subclass Form\Factory and override getFormElementManager and pass the config to the FormElementManager constructor;
You then use your own Factory to create your Form, like this (you can pass a very rudimentary, e.g. empty array, or a more or less full-fledged $spec to $factory->createForm()):
$factory = new Factory();
$spec = array();
$form = $factory->createForm($spec);
FormElementManagerConfig.php:
class FormElementManagerConfig implements ConfigInterface
{
protected $invokables = array(
'anything' => 'MyModule\Form\Element\Anything',
);
public function configureServiceManager(ServiceManager $serviceManager)
{
foreach ($this->invokables as $name => $service) {
$serviceManager->setInvokableClass($name, $service);
}
}
}
MyFactory.php:
class Factory extends \Zend\Form\Factory
{
public function getFormElementManager()
{
if ($this->formElementManager === null) {
$this->setFormElementManager(new FormElementManager(new FormElementManagerConfig()));
}
return $this->formElementManager;
}
}

ZF2 - The Forward Plugin returns the ViewModel Object. How to make it to return other values, e.g. simple or associative array?

I call the Forward plugin from one Controller's action method to get the value from the other Controller's action method:
namespace Foo/Controller;
class FooController {
public function indexAction() {
// I expect the $result to be an associative array,
// but the $result is an instance of the Zend\View\Model\ViewModel
$result = $this->forward()->dispatch('Boo/Controller/Boo',
array(
'action' => 'start'
));
}
}
And here's Boo Controller I apply to:
namespace Boo/Controller;
class BooController {
public function startAction() {
// I want this array to be returned,
// but an instance of the ViewModel is returned instead
return array(
'one' => 'value one',
'two' => 'value two',
'three' => 'value three',
);
}
}
And if I print_r($result) it is the ViewModel of the error/404 page:
Zend\View\Model\ViewModel Object
(
[captureTo:protected] => content
[children:protected] => Array
(
)
[options:protected] => Array
(
)
[template:protected] => error/404
[terminate:protected] =>
[variables:protected] => Array
(
[content] => Page not found
[message] => Page not found.
[reason] => error-controller-cannot-dispatch
)
[append:protected] =>
)
What is going on? How to change this behavior and get the required data type from the Forward plugin?
UPD 1
For now found only this here:
The MVC registers a couple of listeners for controllers to automate
this. The first will look to see if you returned an associative array
from your controller; if so, it will create a View Model and make this
associative array the Variables Container; this View Model then
replaces the MvcEvent‘s result.
And this doesn't work:
$this->getEvent()->setResult(array(
'one' => 'value one',
'two' => 'value two',
'three' => 'value three',
));
return $this->getEvent()->getResult(); // doesn't work, returns ViewModel anyway
It means instead of to get just an array I have to put variable into a ViewModel, return a ViewModel and get those variable from the ViewModel. Very good design, I can say.
You have to disable view in your action in ZF2. You can do this in this way:
namespace Application\Controller;
use Zend\Mvc\Controller\AbstractActionController;
class IndexController extends AbstractActionController
{
public function indexAction()
{
$result = $this->forward()->dispatch('Application/Controller/Index', array( 'action' => 'foo' ));
print_r($result->getContent());
exit;
}
public function fooAction()
{
$response = $this->getResponse();
$response->setStatusCode(200);
$response->setContent(array('foo' => 'bar'));
return $response;
}
}

Multi-select foreign key filter

I'm trying to set up a multi-select filter on a foreign key in the symfony admin. I think I've set up everything correctly but for some reason it's not working:
public function configure()
{
parent::configure();
$s = Doctrine_Query::create()->
from('Status s')->
execute();
$status_choices = array();
foreach ($s as $key => $value) {
$status_choices[$value->getId()] = $value->getName();
}
$this->widgetSchema['status_id'] = new sfWidgetFormChoice(array('choices' => $status_choices, 'multiple' => true, 'expanded' => true));
$this->validatorSchema['status_id'] = new sfValidatorChoice(array('required' => false, 'choices' => $status_choices, 'multiple' => true));
}
public function getFields()
{
$fields = parent::getFields();
$fields['status_id'] = 'StatusId';
return $fields;
}
public function addStatusIdQuery(Doctrine_Query $query, $field, $values)
{
$fieldName = $this->getFieldName($field);
if (!empty($values))
{
$query->addWhereIn(sprintf('%s.%s', $query->getRootAlias(), $fieldName), $values);
}
}
Any help would be greatly appreciated...
In your validatorSchema, to validate data posted, you have to use array_keys($status_choices)
because values sent after posting the form are keys and not labels.
And the addWhereIn is not a Doctrine_Query method, use andWhereIn or whereIn
Hope that will help you

Resources