Sonata Admin configureListFields show through query - symfony

I am using sonata admin bundle for admin panel. I want to show data in configureListFields through query. I have table userChoiceProduct and fields :-
User_Id
Product_Id
These fields automatically fill when user select any product and submit form. But these fields no relationship to other table.and I want to show User Email and Product Name in configureListFields
bases on User_Id and Product_Id.
Thanks!

I solved this:-
In Sonata Admin list :-
->add('User Email', null, array('template' => 'ABCAdminBundle:UserChoiceProduct:user.html.twig'))
->add('Product Name', null, array('template' => 'ABCAdminBundle:UserChoiceProduct:prodcut.html.twig'))
I mentioned one twig file (user.html.twig) for example :
<td>{{object.userId|getUserDetail()}}</td>
And create getUserDetail() in twig extension :-
class ABCExtension extends \Twig_Extension {
private $generator;
private $container;
public function __construct(UrlGeneratorInterface $generator, Container $container) {
$this->generator = $generator;
$this->container = $container;
}
public function getFilters() {
return array(
'getUserDetail' => new \Twig_Filter_Method($this, 'getUserDetail'),
);
}
public function getUserDetail($userId)
{
$em = $this->container->get('doctrine')->getManager();
$user = $em->getRepository('ABCUserBundle:User')->findOneBy(array('id' =>$userId));
if(empty($user)){
$userEmail = 'User does not Exist';
return $userEmail;
}else{
$userEmail = $user->getEmail();
return $userEmail;
}
}
}
And then all work is done successfully.

You can use the createQuery method in your admin to customize the parent query, like that :
public function createQuery($context = 'list') {
$query = parent::createQuery($context);
$query
->addSelect('u')
->leftJoin('Path\To\User\Entity', 'u', \Doctrine\ORM\Query\Expr\Join::ON, 't0_.User_Id = u.id')
;
return $query;
}
By getting and replacing t0_ by the prefix of userChoiceProduct table in main query.

Related

Exclude some fields in findAll Symfony2

I use this code for getting all users in the database
$users= $this->getDoctrine()
->getRepository('AppBundle:Users')
->findAll();
return $this->render('livre/users.html.twig',array(
'users' => $users,
));
But me I want get only some fields sush as name,email and hide fields like password..
Thanks.
You can do it by this way:
1/ Create a specific method in the UserRepository class:
public function findByNameAndEmail()
{
$query = $this->createQueryBuilder('u')
->select('u.name, u.email') // where name & email are properties of your User entity
;
return $query->getQuery()->getResult();
}
2/ And, call it in your controller:
public function someAction()
{
$users = $this->getDoctrine()->getRepository('AppBundle:Users')->findByNameAndEmail();
return $this->render('livre/users.html.twig',array(
'users' => $users,
));
}

How to implement a nice solution for multilang entity slug based routes in Symfony2

I'd like to create a simple bundle to handle some multilingual pages in a website with translated slugs.
Based on translatable, sluggable and i18nrouting
implemented an entity (Page) with title, content, slug fields + locale property as the doc says
created a new Page set its title and content then translated it by $page->setTranslatableLocale('de'); and set those fields again with the german values, so that the data in the tables looks fine, they are all there
implemented the controller with type hinting signature: public function showAction(Page $page)
generated some urls in the template by: {{ path("page_show", {"slug": "test", "_locale": "en"}) }} and {{ path("page_show", {"slug": "test-de", "_locale": "de"}) }}, routes are generated fine, they look correct (/en/test and /de/test-de)
clicking on them:
Only the "en" translation works, the "de" one fails:
MyBundle\Entity\Page object not found.
How to tell Symfony or the Doctrine or whatever bundle to use the current locale when retrieving the Page? Do I have to create a ParamConverter then put a custom DQL into it the do the job manually?
Thanks!
Just found another solution which I think is much nicer and i'm going to use that one!
Implemented a repository method and use that in the controller's annotation:
#ParamConverter("page", class="MyBundle:Page", options={"repository_method" = "findTranslatedOneBy"})
public function findTranslatedOneBy(array $criteria, array $orderBy = null)
{
$page = $this->findOneBy($criteria, $orderBy);
if (!is_null($page)) {
return $page;
}
$qb = $this->getEntityManager()
->getRepository('Gedmo\Translatable\Entity\Translation')
->createQueryBuilder('t');
$i = 0;
foreach ($criteria as $name => $value) {
$qb->orWhere('t.field = :n'. $i .' AND t.content = :v'. $i);
$qb->setParameter('n'. $i, $name);
$qb->setParameter('v'. $i, $value);
$i++;
}
/** #var \Gedmo\Translatable\Entity\Translation[] $trs */
$trs = $qb->groupBy('t.locale', 't.foreignKey')->getQuery()->getResult();
return count($trs) == count($criteria) ? $this->find($trs[0]->getForeignKey()) : null;
}
It has one disadvantage there is no protection against same translated values ...
I found out a solution which i'm not sure the best, but works.
Implemented a PageParamConverter:
class PageParamConverter extends DoctrineParamConverter
{
const PAGE_CLASS = 'MyBundle:Page';
public function apply(Request $request, ParamConverter $configuration)
{
try {
return parent::apply($request, $configuration);
} catch (NotFoundHttpException $e) {
$slug = $request->get('slug');
$name = $configuration->getName();
$class = $configuration->getClass();
$em = $this->registry->getManagerForClass($class);
/** #var \Gedmo\Translatable\Entity\Translation $tr */
$tr = $em->getRepository('Gedmo\Translatable\Entity\Translation')
->findOneBy(['content' => $slug, 'field' => 'slug']);
if (is_null($tr)) {
throw new NotFoundHttpException(sprintf('%s object not found.', $class));
}
$page = $em->find($class, $tr->getForeignKey());
$request->attributes->set($name, $page);
}
return true;
}
public function supports(ParamConverter $configuration)
{
$name = $configuration->getName();
$class = $configuration->getClass();
return parent::supports($configuration) && $class == self::PAGE_CLASS;
}
}
TranslationWalker nicely gets the entity in active locale:
class PagesRepository extends \Doctrine\ORM\EntityRepository
{
public function findTranslatedBySlug(string $slug)
{
$queryBuilder = $this->createQueryBuilder("p");
$queryBuilder
->where("p.slug = :slug")
->setParameter('slug', $slug)
;
$query = $queryBuilder->getQuery();
$query->setHint(
Query::HINT_CUSTOM_OUTPUT_WALKER,
'Gedmo\\Translatable\\Query\\TreeWalker\\TranslationWalker'
);
return $query->getSingleResult();
}
}
And in controller
/**
* #Entity("page", expr="repository.findTranslatedBySlug(slug)")
* #param $page
*
* #return Response
*/
public function slug(Pages $page)
{
// thanks to #Entity annotation (Sensio\Bundle\FrameworkExtraBundle\Configuration\Entity)
// Pages entity is automatically retrieved by slug
return $this->render('content/index.html.twig', [
'page' => $page
]);
}

Silverstripe remove irrelevant has_one relationship fields in CMS tab

I have a DataObject called ContentSection that has 2 has_one relationships: to a page type LandingPage and another DataObject Person.
class ContentSection extends DataObject {
protected static $has_one = array(
'Person' => 'Person',
'LandingPage' => 'LandingPage'
);
}
Both LandingPage and Person define a has_many relationship to ContentSection.
class LandingPage extends Page {
protected static $has_many = array(
'ContentSections' => 'ContentSection'
);
}
class Person extends DataObject {
protected static $has_many = array(
'ContentSections' => 'ContentSection'
);
}
ContentSections are editable through the LandingPage and Person with the GridFieldConfig_RelationEditor e.g.:
function getCMSFields() {
$fields = parent::getCMSFields();
$config = GridFieldConfig_RelationEditor::create(10);
$fields->addFieldToTab('Root.Content', new GridField('ContentSections', 'Content Sections', $this->ContentSections(), $config));
return $fields;
}
My question is how can you hide/remove irrelevant has_one fields in the CMS editor tab? The Person and LandingPage relationship dropdown fields both display when you are editing a ContentSection, whether it is for a Person or LandingPage. I only want to show the relevant has_one relationship field. I've tried using dot notation on the has_many relationships:
class Person extends DataObject {
protected static $has_many = array(
'ContentSections' => 'ContentSection.Person'
);
}
I've also tried using the removeFieldFromTab method in the getCMSFields method of the ContentSection class, where I define the other CMS fields for the ContentSection:
$fields->removeFieldFromTab('Root.Main', 'Person');
Instead of removeFieldFromTab use the removeByName function. removeFieldFromTab will not work if there is no 'Root.Main' tab.
Also we remove PersonID, not Person. has_one variables have ID appended to the end of their variable name.
function getCMSFields() {
$fields = parent::getCMSFields();
$fields->removeByName('PersonID');
$fields->removeByName('LandingPageID');
return $fields;
}
If you would like to selectively hide or display these fields you can put in some if statements in your getCMSFields function.
function getCMSFields() {
$fields = parent::getCMSFields();
if (!$this->PersonID) {
$fields->removeByName('PersonID');
}
if (!$this->LandingPageID) {
$fields->removeByName('LandingPageID');
}
return $fields;
}

What should I do? Doctrine relations

I want to create a dynamic form Photo with these fields:
title
album
Album is a checkboxes field ( with 'multiple' attr ).
Photo has a manyToOne relationship with Album.
What I want to do is persist several times the photo with different album values, not persist an arrayCollection of albums in one photo.
I tried to do
if ($request->getMethod() == 'POST') {
$form->bind($request);
if ($form->isValid()) {
$data = $form->getData();
$listeAlbum = $data['album'];
foreach ($listeAlbum as $album) {
$em->persist($photo);
$em->flush();
}
I get the error ( at the line bind->($request) )
Catchable Fatal Error: Argument 1 passed to MySite\TestBundle\Entity
\Photo::setAlbum() must be an instance of MySite\TestBundle\Entity\Album,
instance of Doctrine\Common\Collections\ArrayCollection given, ...
Is there a way to do this?
EDIT : more code.
my form type
class PhotoType extends AbstractType {
private $securityContext;
public function __construct(SecurityContext $securityContext)
{
$this->securityContext = $securityContext;
}
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder->add('file', 'file') // , array("attr" => array("multiple" => "multiple", ))
->add('titre');
$user = $this->securityContext->getToken()->getUser();
if (!$user) {
throw new \LogicException(
'The FriendMessageFormType cannot be used without an authenticated user!'
);
}
$builder->addEventListener(
FormEvents::PRE_SET_DATA,
function (FormEvent $event) use ($user) {
$form = $event->getForm();
$formOptions = array(
'multiple' => true, //several choices
'expanded' => true, // activate checkbox instead of list
'class' => 'EVeilleur\DefuntBundle\Entity\Album',
'property' => 'titre',
'query_builder' => function (EntityRepository $er) use ($user) {
// build a custom query
return $er->createQueryBuilder('u')->add('select', 'u')
->add('from', 'EVeilleurDefuntBundle:Album u');
// ->add('where', 'u.id = ?1')
// ->add('orderBy', 'u.name ASC');
},
);
// create the field, = $builder->add()
// field name, field type, data, options
$form->add('album', 'entity', $formOptions);
}
);
}
/**
* #param OptionsResolverInterface $resolver
*/
public function setDefaultOptions(OptionsResolverInterface $resolver)
{
$resolver->setDefaults(array(
'data_class' => 'EVeilleur\DefuntBundle\Entity\Photo'
));
}
/**
* #return string
*/
public function getName()
{
return 'eveilleur_defuntbundle_photo';
} }
entity relation, in Photo.php
/**
* #ORM\ManyToOne(targetEntity="EVeilleur\DefuntBundle\Entity\Album")
* #ORM\JoinColumn(nullable=true)
*/
private $album;
I think the problem is that you are adding Album to your Photo form as a single entity field, but your options mean it gets translated into a set of checkboxes that is logically turned on submit by Symfony into an ArrayList. Your Photo entity expects only a single Album.
Could you post the rest of your Photo entity, specifically the setAlbum method (apologies if you don't actually need to create one in this case, I always create mine even if they're trivial!)?
If Photo is ManyToOne with Album, then many Photos can be in one Album, and the Album field should probably be a dropdown - you shouldn't be able to choose multiple Albums. This may be the root of the issue.
If many Photos can be in one Album, but also each Photo can be in many Albums, then you really have a ManyToMany relationship, doesn't seem to be modelled like that here.

Getting server error when trying to use GridField to create relationship between DataObjects

I'm learning SilverStripe by creating a small website that lets the user manage their fragrances (i.e. perfumes/colognes). The user adds ingredients (that are used in the fragrances they have), then adds their fragrances, at which point they choose which ingredients are in the fragrance they're adding.
I've created the Ingredient and Fragrance classes which both extend DataObject. I've also created the IngredientsPage page which lets the user add/edit/delete ingredients (made up of a name and description) and lists all of the ingredients added so far, and this page is fully functional. I'm now trying to create the FragrancesPage page which will let the user add/edit/delete fragrances (made up of a name, description and ingredients) and list all the ones added so far, but I'm having some trouble.
The only way I know of to create the relationship between a Fragrance and Ingredients (one fragrance has many ingredients, and one ingredient belongs to many fragrances) is using a GridField (if there's a better way, let me know!), as this is what the SilverStripe tutorials get you to do (although in the tutorial it's for the CMS rather than the front-end). However, as soon as I try to add a GridField into the mix, I just get taken to an error page that says "Server Error: Sorry, there was a problem with handling your request.".
My code is as follows.
Ingredient.php:
<?php
class Ingredient extends DataObject {
private static $db = array(
'Name' => 'Text',
'Description' => 'Text'
);
private static $belongs_many_many = array(
'Fragrances' => 'Fragrance'
);
}
?>
Fragrance.php:
<?php
class Fragrance extends DataObject {
private static $db = array(
'Name' => 'Text',
'Description' => 'Text'
);
private static $many_many = array(
'Ingredients' => 'Ingredient'
);
}
?>
FragrancesPage.php:
<?php
class FragrancesPage extends Page {
private static $icon = 'cms/images/treeicons/reports-file.png';
private static $description = 'Fragrances page';
}
class FragrancesPage_Controller extends Page_Controller {
private static $allowed_actions = array('FragranceAddForm');
function FragranceAddForm() {
$config = GridFieldConfig_RelationEditor::create();
$config->getComponentByType('GridFieldDataColumns')->setDisplayFields(array(
'Name' => 'Name',
'Ingredient.Name' => 'Ingredient'
));
$fragrances_field = new GridField(
'Ingredients',
'Ingredient',
$this->Ingredients(),
$config
);
$fields = new FieldList(
new TextField('Name', 'Fragrance Name'),
new TextareaField('Description', 'Fragrance Description'),
$fragrances_field
);
$actions = new FieldList(
new FormAction('doFragranceAdd', 'Add Fragrance')
);
$validator = new RequiredFields('Name', 'Description');
return new Form($this, 'FragranceAddForm', $fields, $actions, $validator);
}
public function doFragranceAdd($data, $form) {
$submission = new Fragrance();
$form->saveInto($submission);
$submission->write();
return $this->redirectBack();
}
public function FragranceList() {
$submissions = Fragrance::get()->sort('Name');
return $submissions;
}
}
?>
If I remove everything from FragrancesPage.php relating to the GridField, the page works fine. I just can't seem to get the GridField working, and don't know of any other way to create the relationship between Fragrances and Ingredients on the front-end. If the code for IngredientsPage.php will be helpful also, let me know and I'll add it.
my guess is that you have error reporting turned off, and that is why you only see such a meaning less error message.
you should turn on display_errors and error_reporting in your php.ini, .htaccess or _ss_environment.php (IMPORTANT: setting it in _config.php will NOT work, as it gets overwritten by the error handler)
the problem I see in your code is that trying to use $this->Ingredients() on FragrancesPage, but as far as I can see only the class Fragrances has a method Ingredients (method is 'magically' created for the many_many relation).
also, I think your setDisplayFields()
so basically you need to use $fragrance->Ingredients() instead of $this->Ingredients().
but that leads us to the next problem: you don't have a fragrance yet.
unfortunately, at this time, GridField only works if you already have an object. this means you have to split it into two forms or use an alternative.
Option 1: use CheckboxSetField to manage the many_many relation.
this will not allow creating Ingredients on the fly, it will only give you check boxes that you can tick to link the items.
public function FragranceAddForm() {
$fragrances_field = new CheckboxSetField('Ingredients', 'Ingredient', Ingredient::get()->map());
$fields = new FieldList(
new TextField('Name', 'Fragrance Name'),
new TextareaField('Description', 'Fragrance Description'),
$fragrances_field
);
$actions = new FieldList(
new FormAction('doFragranceAdd', 'Add Fragrance')
);
$validator = new RequiredFields('Name', 'Description');
return new Form($this, __FUNCTION__, $fields, $actions, $validator);
}
public function doFragranceAdd($data, $form) {
$submission = new Fragrance();
$form->saveInto($submission);
$submission->write();
return $this->redirectBack();
}
Option 2: use GridField in a second form
this will allow creating Ingredients on the fly, but is a bit more work. and you might run into some troubles with GridField as it is not fully tested in the frontend yet.
(there is a recent question where I wrote a bit about GridField problems in frontends https://stackoverflow.com/a/22059197/1119263)
I guess this place is as good as any to finally write a tutorial/working example for frontend GridFields.
I took the liberty of refactoring your code a bit to include a edit functionality, its much nicer to have the GridField on the edit page than on a separate form.
As mentioned before, the GridField is not working that well in the frontend, there is a module to ease the pain, but it will still be rough around the edges and will require you to do some styling to make it look pretty.
Find the module on Packagist or GitHub
(you will need t
class Ingredient extends DataObject {
private static $db = array(
'Name' => 'Text',
'Description' => 'Text'
);
private static $belongs_many_many = array(
'Fragrances' => 'Fragrance'
);
public function getCMSFields() {
// fields used by the GridField, don't let the CMSFields mislead you
return new FieldList(
TextField::create('Name', 'Name'),
TextAreaField::create('Description', 'Description')
);
}
}
class Fragrance extends DataObject {
private static $db = array(
'Name' => 'Text',
'Description' => 'Text'
);
private static $many_many = array(
'Ingredients' => 'Ingredient'
);
}
/**
* Form in a separate class, so we can reuse it.
* #param Controller $controller
* #param string $name
* #param Null|Fragrance $fragrance Either null to create a new one, or pass an existing to edit it and add Ingredients
* #return Form
*/
class FragranceForm extends Form {
public function __construct($controller, $name, $fragrance = null) {
if ($fragrance && $fragrance->isInDB()) {
// we can only use a GridField if the object exists and has already been saved
// gridfield needs jQuery
Requirements::javascript(THIRDPARTY_DIR . '/jquery/jquery.min.js');
// ensure we don't have 2 versions of jQuery
Requirements::block(THIRDPARTY_DIR . '/jquery/jquery.js');
$config = FrontEndGridFieldConfig_RelationEditor::create();
$config->getComponentByType('GridFieldDataColumns')->setDisplayFields(array(
'Name' => 'Name',
'Description' => 'Description',
));
$ingredientField = new FrontEndGridField(
'Ingredients',
'Ingredient',
$fragrance->Ingredients(),
$config
);
} else {
$ingredientField = new LiteralField('Ingredients', '<p>Ingredients can be added after saving</p>');
}
$fields = new FieldList(
new HiddenField('ID', ''),
new TextField('Name', 'Fragrance Name'),
new TextareaField('Description', 'Fragrance Description'),
$ingredientField
);
$actions = new FieldList(
new FormAction('doFragranceSave', 'Save Fragrance')
);
$validator = new RequiredFields('Name', 'Description');
// populate the fields (ID, Name and Description) with the values from $fragrance. This does not effect the GridField
if ($fragrance && $fragrance->exists()) {
$fields->fieldByName('ID')->setValue($fragrance->ID);
$fields->fieldByName('Name')->setValue($fragrance->Name);
$fields->fieldByName('Description')->setValue($fragrance->Description);
// there is actually a method for that, but we can't use it here,
// because fields are not set yet. we could do it after __construct, but then we would
// overwrite things set by the error handler, so lets just do it by hand
// $this->loadDataFrom($fragrance);
}
parent::__construct($controller, $name, $fields, $actions, $validator);
}
public function doFragranceSave($data, $form) {
if (isset($data['ID']) && $data['ID']) {
$id = (int)$data['ID'];
$fragrance = Fragrance::get()->byID($id);
}
if (!isset($fragrance) || !$fragrance || !$fragrance->exists()) {
// if the ID was invalid or we don't have one, create a new Fragrance
$fragrance = new Fragrance();
}
$form->saveInto($fragrance);
$fragrance->write();
// redirect to the edit page.
$controller = $this->getController();
$editLink = $controller->EditLink($fragrance->ID);
return $controller->redirect($editLink);
}
}
class FragrancesPage extends Page {
}
class FragrancesPage_Controller extends Page_Controller {
private static $allowed_actions = array(
'edit',
'AddForm',
'EditForm',
);
/**
* the default action
* #return ViewableData_Customised
*/
public function index() {
// $this->customise() lets you overwrite variables that you can use in the template later.
return $this->customise(array(
// set the AddForm to $Form instead of $AddForm, this way you can use $Form in template and can reuse the template
'Form' => $this->AddForm(),
));
}
/**
* edit action to edit an existing Fragrance
* links will look like this /FragrancesPage/edit/$ID
*
* #param SS_HTTPRequest $request
* #return SS_HTTPResponse|ViewableData_Customised
*/
public function edit(SS_HTTPRequest $request) {
$id = (int)$request->param('ID');
$fragrance = Fragrance::get()->byID($id);
if (!$fragrance || !$fragrance->exists()) {
// fragrance not found? display a 404 error page
return ErrorPage::response_for(404);
}
// now that we have a $fragrance, overwrite EditForm with a EditForm that contains the $fragrance
$form = $this->EditForm($fragrance);
$return = $this->customise(array(
// also overwrite Title and Content, to display info about what the user can do here
// if you don't overwrite that, it will display the Title and Content of the page
'Title' => 'Edit: ' . $fragrance->Name,
'Content' => '<p>you are editing an existing fragrance</p>',
// set the Form to $Form instead of $EditForm, this way you can use $Form in template and can reuse the template
'Form' => $form,
));
// per default SilverStripe will try to use the following templates: FragrancesPage_edit.ss > FragrancesPage.ss > Page.ss
// if you want to use a custom template here, you can specify that with ->renderWith()
// but you probably won't need that anyway
// $return = $return->renderWith(array('MyCustomTemplateName', 'Page'));
return $return;
}
public function AddForm() {
return new FragranceForm($this, __FUNCTION__);
}
public function EditForm($fragranceOrRequest = null) {
// unfortunately, GridField / FormFields in general are a bit clumsy and do forget what item they where
// suppose to edit, so we have to check what $fragranceOrRequest is and set/get the fragrance to/from session
if ($fragranceOrRequest && is_a($fragranceOrRequest, 'Fragrance')) {
$fragrance = $fragranceOrRequest;
Session::set('FragrancesPage.CurrentFragrance', $fragrance->ID);
} else {
$fragrance = Fragrance::get()->byID(Session::get('FragrancesPage.CurrentFragrance'));
}
if (!$fragrance || !$fragrance->exists()) {
// that's bad, some error has occurred, lets display an ugly 404 page
return $this->httpError(404);
}
return new FragranceForm($this, __FUNCTION__, $fragrance);
}
public function EditLink($ID) {
return $this->Link("edit/$ID");
}
}
I know that's a lot to take in as someone still learning SilverStripe, if you have any questions, feel free to comment or just poke me on IRC

Resources