query_builder on sonataAdminBundle is ignored - doctrine-orm

I am using sonataAdminBundle and symfony2
I made this script.
it filter the search box candidates.
but this query_builder is ignored.
Are there any other points to check ?
public function configureDatagridFilters(DatagridMapper $datagridMapper)
{
$datagridMapper
->add('user',null,
array(
'query_builder' =>
function (\Doctrine\ORM\EntityRepository $rep) {
return $rep->
createQueryBuilder('s')
->where('s.id','1');
})
adding...
I am using this script for new entry,it works
$formMapper
->with('General')
->add('teacher',
null,
array(
'query_builder' =>
function (\Doctrine\ORM\EntityRepository $rep) {
return $rep->
createQueryBuilder('s')
->join('s.groups', 'g') // Assuming the association on your user entity is 'groups'
->where('g.name = :group')->setParameter('group','TeacherGroup');
})
)
but for datagridMapper ,it doesnt work.
$datagridMapper
->add('teacher',null,
array(
'query_builder' =>
function (\Doctrine\ORM\EntityRepository $rep) {
return $rep->
createQueryBuilder('s')
->join('s.groups', 'g') // Assuming the association on your user entity is 'groups'
->where('g.name = :group')
->setParameter('group','TeacherGroup');
}))

I have achieved this in the following way
$datagridMapper
->add('user',null,
array(
'field_type' => 'entity',
'field_options => array(
'query_builder' => function (\Doctrine\ORM\EntityRepository $rep) {
return $rep->
createQueryBuilder('s')
->where('s.id','1');
}
)
});

you should use 'query_builder' in in fourth parameter, something like:
$datagridMapper
->add('teacher',null,null,
array(
'query_builder' =>
function (\Doctrine\ORM\EntityRepository $rep) {
return $rep->
createQueryBuilder('s')
->join('s.groups', 'g') // Assuming the association on your user entity is 'groups'
->where('g.name = :group')
->setParameter('group','TeacherGroup');
}))

Check out the documentation about this. You have the wrong syntax.
http://sonata-project.org/bundles/doctrine-orm-admin/master/doc/reference/filter_field_definition.html#callback

Related

show categories in search.twig using event opencart

i'm trying to show categories in search.twig using events for this i have create a module file to add event.
i am assuming after common/search controller is called the event will add categories to existing data variable and will send categories along all data from common/search controller. i have copied the code below
admin/controller/extention/module/cc_add_search_categories.php
public function install(){
$this->load->model('setting/event');
$this->model_setting_event->addEvent('ccaddsearchcategorise', 'catalog/controller/common/search/after', 'extension/module/cc_add_search_categories/addCategoriesToSearch');
}
public function uninstall(){
$this->load->model('setting/event');
$this->model_setting_event->deleteEventByCode('ccaddsearchcategorise');
}
and in
catalog/controller/extention/module/cc_add_search_categories.php
public function addCategoriesToSearch(&$route, &$data, &$output){
$this->load->model('catalog/category');
$this->load->language('extention/module/cc_add_search_category');
$data['categories'] = array('data');
$categories_1 = $this->model_catalog_category->getCategories(0);
foreach ($categories_1 as $category_1) {
$level_2_data = array();
$categories_2 = $this->model_catalog_category->getCategories($category_1['category_id']);
foreach ($categories_2 as $category_2) {
$level_3_data = array();
$categories_3 = $this->model_catalog_category->getCategories($category_2['category_id']);
foreach ($categories_3 as $category_3) {
$level_3_data[] = array(
'category_id' => $category_3['category_id'],
'name' => $category_3['name'],
);
}
$level_2_data[] = array(
'category_id' => $category_2['category_id'],
'name' => $category_2['name'],
'children' => $level_3_data
);
}
$data['categories'][] = array(
'category_id' => $category_1['category_id'],
'name' => $category_1['name'],
'children' => $level_2_data
);
}
}

SF2: How to custom the form type messages?

I want to know how I can modify the error message on my ContactType.
It's possible directly in the Type ?
My current code:
class ContactType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
//...
}
public function setDefaultOptions(OptionsResolverInterface $resolver)
{
$collectionConstraint = new Collection(array(
'name' => array(
new NotBlank(array('message' => 'My custon message.')),
new Length(array('min' => 2), array('message' => 'My custon message.'))
),
'email' => array(
new NotBlank(array('message' => 'My custon message.')),
new Email(array('message' => 'My custon message.'))
),
'subject' => array(
new NotBlank(array('message' => 'My custon message.')),
new Length(array('min' => 10), array('message' => 'My custon message.'))
),
'message' => array(
new NotBlank(array('message' => 'My custon message')),
new Length(array('min' => 5))
)
));
$resolver->setDefaults(array(
'constraints' => $collectionConstraint
));
}
public function getName()
{
return 'contact';
}
}
Thanks you all for your helping.
Best regards,
It's recommend to change the message of the assertion instead, but you can also use the invalid_message setting of a form type.

CakePHP & AuthComponent unit test doesn't appear to call isAuthorized()

I am writing unit tests for my UsersController so that users can only edit their own profile. I am using CakePHP 2.4.2 and AuthComponent with Controller authorize to do this.
Auth config:
public $components = array(
'Auth' => array(
'loginRedirect' => '/',
'logoutRedirect' => '/',
'authenticate' => array('Ldap'),
'authError' => 'You are not allowed to access this page',
'authorize' => 'Controller'));
isAuthorized() in UsersController:
public function isAuthorized($user = null) {
if($this->Auth->loggedIn()) {
return $this->request->params['pass'][0] == $user['id'];
}
return false;
}
Unit test for edit:
public function testEdit() {
$result = $this->testAction('/users/view/1', array('return' => 'view'));
$this->assertRegExp('/Adam C Hobaugh/', $result);
$user = $this->generate('Users', array(
'components' => array(
'Session',
'Auth' => array('user'))));
$test = array('id' => 1);
$user->Auth->expects($this->once())->method('loggedIn')
->with($this->returnValue(true));
$user->Auth->expects($this->any())->method('user')
->with($this->returnValue($test));
$user->Session->expects($this->any())->method('setFlash');
$result = $this->testAction('/users/edit/1', array(
'return' => 'headers',
'data' => array('User' => array( {user array} ))));
debug($result);
$this->assertContains('/users', #$result['Location']);
$result = $this->testAction('/users/view/1', array('return' => 'view'));
$this->assertRegExp('/John Jacob Doe/', $result);
}
I am getting Expectation failed for method name is equal to <string:loggedIn> when invoked 1 time(s). Method was expected to be called 1 times, actually called 0 times. when I run the test. Also when I changed this->once() to $this->any() and the id in the $test array to 2, a situation that should fail and does from the browser, it succeeds in passing the test.
With those combined, it appears that isAuthorized() is not being called during the unit test. I am at a loss. Thanks for any help that you could give.
First: In your test code you call the view method and not the edit method
Second: isAuthorized() is not for this. With this method you should just define who could acces what functions, there should not be any application business logic.
Third: If you want to limit normal users to edit just their own profile you should change the dit() method to something like this.
public function edit() {
$this->request->data['User']['id'] = $this->Auth->User('id');
if ($this->request->is('post') || $this->request->is('put')) {
if ($this->User->save($this->request->data)) {
$this->Session->setFlash(__('The user has been saved.'));
return $this->redirect(array('action' => 'index'));
} else {
$this->Session->setFlash(__('The user could not be saved. Please, try again.'));
}
} else {
$this->request->data = array('User' => $this->Auth->User());
}
}
And remove echo $this->Form->input('id'); from your edit view.
I am writing a book about this topic. It will be available here soon: https://leanpub.com/CakePHPUserAuthentication/

zend framework 2 Unable to render template resolver could not resolve to a file

I'm learning how to use Zend Framework2. According to some tutorials available on the Net I've wrote some pieces of code . The most important tutorial for me is this one: https://github.com/psamatt/zf2-doctrine-example It covers most of the basics that i've planned to write. I've stuck on one problem that looks strange to me. On my summary page, that display all the records from DB I have a links to add new record, edit existing record, and delete record. Routing is covered by module.config.php:
'router' => array(
'routes' => array(
'incident' => array(
'type' => 'segment',
'options' => array(
'route' => '/incident[/][:action][/:id]',
'constraints' => array(
'action' => '[a-zA-Z][a-zA-Z0-9_-]*',
'id' => '[0-9]+',
),
'defaults' => array(
'controller' => 'Helpdesk\Controller\Incident',
'action' => 'index',
),
),
),
),
),
When I use a link to a new record (h.t.t.p://helpdesk/incident/add) everything works correctly. But when I use a link to edit my record (h.t.t.p://helpdesk/incident/edit/1 - where 1 is example record ID) I receive an error:
Zend\View\Renderer\PhpRenderer::render: Unable to render template "helpdesk/incident/edit"; resolver could not resolve to a file
This is my IncidentController.php:
<?php
namespace Helpdesk\Controller;
use Application\Controller\EntityUsingController;
use DoctrineModule\Stdlib\Hydrator\DoctrineObject;
use Doctrine\ORM\EntityManager;
use Zend\View\Model\ViewModel;
use Helpdesk\Form\IncidentForm;
use Helpdesk\Entity\Incident;
class IncidentController extends EntityUsingController
{
/**
* Index action
*
*/
public function indexAction()
{
$em = $this->getEntityManager();
$incidents = $em->getRepository('Helpdesk\Entity\Incident')->findAll();
return new ViewModel(array(
'incidents' => $incidents
));
}
/**
* Edit action
*
*/
public function editAction()
{
$incident = new Incident();
if ($this->params('id') > 0) {
$incident = $this->getEntityManager()->getRepository('Helpdesk\Entity\Incident')->find($this->params('id'));
}
$form = new IncidentForm($this->getEntityManager());
$form->bind($incident);
$form->setHydrator(new DoctrineObject($this->getEntityManager(),'Helpdesk\Entity\Incident'));
$request = $this->getRequest();
if ($request->isPost()) {
$form->setInputFilter($incident->getInputFilter());
$form->setData($request->getPost());
if ($form->isValid()) {
$em = $this->getEntityManager();
$em->persist($incident);
$em->flush();
$this->flashMessenger()->addSuccessMessage('Incident saved');
// Redirect to list of incidents
return $this->redirect()->toRoute('incident');
}
}
return array(
'incident' => $incident,
'form' => $form,
);
}
/**
* Add action
*
*/
public function addAction()
{
return $this->editAction();
}
/**
* Delete action
*
*/
public function deleteAction()
{
$id = (int)$this->getEvent()->getRouteMatch()->getParam('id');
if (!$id) {
return $this->redirect()->toRoute('incident');
}
$request = $this->getRequest();
if ($request->isPost()) {
$del = $request->post()->get('del', 'No');
if ($del == 'Yes') {
$id = (int)$request->post()->get('id');
$incident = $this->getEntityManager()->find('Helpdesk\Entity\Incident', $id);
if ($incident) {
$this->getEntityManager()->remove($incident);
$this->getEntityManager()->flush();
}
}
// Redirect to list of incidents
return $this->redirect()->toRoute('default', array(
'controller' => 'incident',
'action' => 'index',
));
}
return array(
'id' => $id,
'incident' => $this->getEntityManager()->find('Helpdesk\Entity\Incident', $id)->getArrayCopy()
);
}
}
What is the difference between these two? Why one works fine, while the second one generates an error?
Thanks for your help
Smok.
Most likely helpdesk/incident/edit.phtml does not exist, while add action is rendering an existing helpdesk/incident/add.phtml.
You can reuse the existing helpdesk/incident/add.phtml or create a new one.

Can nusoap returns arrray of string?

I would like to return an array of string in my web services
I've tryed :
<?php
require_once('nusoap/nusoap.php');
$server = new soap_server();
$server->configureWSDL('NewsService', 'urn:NewsService');
$server->register('GetAllNews',
array(),
array('return' => 'xsd:string[]'),
'urn:NewsService',
'urn:NewsService#GetAllNews',
'rpc',
'literal',
''
);
// Define the method as a PHP function
function GetAllNews()
{
$stack = array("orange", "banana");
array_push($stack, "apple", "raspberry");
return $stack;
}
but it doesn't work.
What is the correct syntax for that ?
Thanks in advance for any help
You can't return an array like this. To return an array, you have to define a complex type.
I'll provide u an example...
The server program service.php:
<?php
// Pull in the NuSOAP code
require_once('lib/nusoap.php');
// Create the server instance
$server = new soap_server();
// Initialize WSDL support
$server->configureWSDL('RM', 'urn:RM');
//Define complex type
$server->wsdl->addComplexType(
'User',
'complexType',
'struct',
'all',
'',
array(
'Id' => array('name' => 'Id', 'type' => 'xsd:int'),
'Name' => array('name' => 'Name', 'type' => 'xsd:string'),
'Email' => array('name' => 'Email', 'type' => 'xsd:string'),
'Description' => array('name' => 'Description', 'type' => 'xsd:string')
)
);
// Register the method
$server->register('GetUser', // method name
array('UserName'=> 'xsd:string'), // input parameters
array('User' => 'tns:User'), // output parameters
'urn:RM', // namespace
'urn:RM#GetUser', // soapaction
'rpc', // style
'encoded', // use
'Get User Details' // documentation
);
function GetUser($UserName) {
return array('Id' => 1,
'Name' => $UserName,
'Email' =>'test#a.com',
'Description' =>'My desc'
);
}
// Use the request to (try to) invoke the service
$HTTP_RAW_POST_DATA = isset($HTTP_RAW_POST_DATA) ? $HTTP_RAW_POST_DATA : '';
$server->service($HTTP_RAW_POST_DATA);
?>
And the client program client.php:
<?php
// Pull in the NuSOAP code
require_once('lib/nusoap.php');
// Create the client instance
$client = new soapclient('http://localhost/Service/service.php');
// Call the SOAP method
$result = $client->call('GetUser', array('UserName' => 'Jim'));
// Display the result
print_r($result);
?>