Displaying a custom twig template with Sonata and Symfony2 - templates

For my need, I'm planning to add a custom column to a entity list.
I've written this inside the configureListFields :
->add('_action', 'actions', array(
'actions' => array(
'code' => array('template' => 'BOBAdminBundle:test:custom.html.twig'),
)
))
My twig :
<img src="{{ asset('bundles/sonataadmin/famfamfam/delete.png') }}" />
It works.
Problem : I don't know why :S, since I've just copy/paste the code from somewhere.
I figured out than the '_action' determined the name of the column. But what if I want to change it ?
Where does this 'actions' name come from ? Where can I change it ?

The _action is used to add custom actions for the list items. Like edit and delete which are set by default. Here is a full documentation:
List actions
You can set actions for the list items by adding an ‘_action’ field in configureListFields:
<?php
$listMapper->add('_action', 'actions', array(
'actions' => array(
'view' => array(),
'edit' => array(),
)
))
Edit and delete actions are enabled in the default configuration. You can add your own! Default template file is: *SonataAdminBundle:CRUD:list_action[ACTION_NAME].html.twig*
You can specify your own by setting up the ‘template’ option like so:
<?php
$listMapper->add('_action', 'actions', array(
'actions' => array(
'view' => array(),
'edit' => array(),
'delete' => array('template' => 'MyBundle:MyController:my_partial.html.twig'),
)
))

Related

Silex and Doctrine - ORMException: Unknown Entity namespace alias [semi fixed]

I'm trying to use the Doctrine components in my app built using silex. I was able to get it to work - well almost.
I have my "User" entity and the corresponding repository
When doing
$app['em']->getRepository('Foo\Entity\User')->findAll()
works as expected, however when trying to make a custom query
$this->getEntityManager()
->createQuery(
'SELECT
u
FROM
Foo:User u
WHERE c.id = :x'
)
->setParameter('x',$in)
->getResult();
I get this exception
ORMException: Unknown Entity namespace alias 'Foo'
Please ignore the fact that I can make a select with findById() or findBy(array('id'=>$in)) the problem is with the custom query
This are my configs
$app['orm.em.options'] = array(
'mappings' => array(
array(
'type' => 'annotation',
'namespace' => 'Foo\Entity',
'alias' => 'core',
'path' => '%app.path%/src/Foo/Entity',
'use_simple_annotation_reader' => false,
)
));
and
$config = Setup::createAnnotationMetadataConfiguration(array(__DIR__."/src/Foo/Entity"));
$params = $app['db.options'];
$app['em'] = EntityManager::create($params, $config);
After some research possible solutions:
auto_mapping: true => tried, no success
registering the namespace => tried, not sure if right was done so may be the solution, please advice how to do it right
besides all this I have tried to search for git repos with similar 'usage' but didn't get it :(
UPDATE
for the moment I use the following line in my query and it works
FROM
InstaLikes\Entity\User u
When you create custom queries, you should use the fully namespace, in this case:
Foo\Entity\User
I am assuming you have checked the alias you have given in the mappings options?
$app['orm.em.options'] = array(
'mappings' => array(
array(
'type' => 'annotation',
'namespace' => 'Foo\Entity',
'alias' => 'core',
'path' => '%app.path%/src/Foo/Entity',
'use_simple_annotation_reader' => false,
)
));
Should that alias option not be set to Foo instead?

How to set the default selected value for a Doctrine ObjectRadio element

I've got a simple user registration form where a user can choose their own user type. The user type maps to a role. This is part of a zf2 application using the doctrine2 module.
The relevant part of the init() method of my user fieldset looks like this:
public function init()
{
// ... other field definitions ...
$roleRadio = new ObjectRadio('role');
$roleRadio->setLabel('What type of user are you?')
->setOptions(
array(
'object_manager' => $this->objectManager,
'target_class' => 'MyUser\Entity\Role',
'property' => 'roleId',
'is_method' => true,
'find_method' => array(
'name' => 'findBy',
'params' => array(
'criteria' => array('userselectable' => true),
'orderBy' => array('displayorder' => 'ASC'),
),
),
)
);
$this->add($roleRadio);
// ... more stuff ...
}
I'm using Doctrine's ObjectRadio class for this element to automatically populate the value options. Is there any way to set the default selected value?
I know I can just do something like this:
$form->get('user')->get('role')->setValue(3);
But I don't want to hard code this and I also don't want to put that kind of logic in my controller.
Any suggestions?
I don't know what do you mean by "I don't want to hard code this", but you can do it as you said in your controller, or you can do it in the form definition by setting attributes as the following:
$roleRadio->setAttributes(array('value' => 3));

How to use DoctineModule ObjectSelect based on custom repository method?

I have a table with a list of person that belong to different categories A and B for example. My problem is that i have a form with DoctrineModule ObjectSelect and i want to show in the ObjectSelect only the name of persons of Category A.
I find this https://github.com/doctrine/DoctrineModule/blob/master/docs/form-element.md#example-3--extended-version but the example is not clear for me and i don't know how to adapt it to my case.
Thank you.
excuse me for my english.
It's actually quite similar to the example you were looking at (I guess that's why there is no example for it), the only difference is that instead of using find/findBy/... you pass your custom repository name as name key, with code similar to this:
$this->add(array(
'name' => 'my-select-object',
'type' => 'DoctrineModule\Form\Element\ObjectSelect',
'attributes' => array(
),
'options' => array(
'label' => 'My Label',
'object_manager' => $entityManager,
'target_class' => 'Application\Entity\MyEntity',
'property' => 'name',
'is_method' => true,
'find_method' => array(
'name' => 'myCustomRepositoryMethod',
'params' => array(
),
),
),
));
Also notice that your entity needs to know about repository existence, so make sure it uses this line:
#ORM\Entity(repositoryClass="Application\Entity\Repository\MyCustomRepository")
So when you open the form with this ObjectSelect it will call you repository method instead of loading the dropdown directly. That method should just return an array of entity objects which are then used by ObjectSelect to generate select element's options.

Custom Prestashop Admin Module

I am developing a module for prestashop (basically, it's a very custom import of data and the only thing I need is to have a form and process data). I have created controller class derived from the ModuleAdminController but the problem is where should I put the tpl file containing the look of my custom form?
I realize that I can put tpl file to the templates but I want to keep all files within my module folder, is it possible (probably somewhere like "/views/templates/admin")?
This is the most easy method to create a basic admin controller / action in Prestashop 1.6
Create basic configuration :
./config.xml
<?xml version="1.0" encoding="UTF-8" ?>
<module>
<name>foo</name>
<displayName><![CDATA[Foo]]></displayName>
<version><![CDATA[2.1.3]]></version>
<description><![CDATA[Bar.]]></description>
<author><![CDATA[your-name]]></author>
<tab><![CDATA[administration]]></tab>
<is_configurable>0</is_configurable>
<need_instance>0</need_instance>
<limited_countries></limited_countries>
</module>
./foo.php
if (!defined('_PS_VERSION_'))
exit;
class BarcodeEasyPrint extends Module
{
public function __construct()
{
$this->name = 'foo';
$this->tab = 'administration';
$this->version = '1.0.0';
$this->author = 'your-name-here';
$this->need_instance = 0;
$this->bootstrap = true;
parent::__construct();
$this->displayName = $this->l('Foo');
$this->description = $this->l('Bar.');
if ((int)Tools::getValue('p'))
$this->page = (int)Tools::getValue('p');
}
}
You need to create the controller with base functions :
./controllers/admin/AdminFooController.php
class AdminFooController extends ModuleAdminController {
public function __construct() {
$this->bootstrap = true;
parent::__construct();
}
public function createTemplate($tpl_name) {
if (file_exists($this->getTemplatePath() . $tpl_name) && $this->viewAccess())
return $this->context->smarty->createTemplate($this- >getTemplatePath() . $tpl_name, $this->context->smarty);
return parent::createTemplate($tpl_name);
}
public function initContent(){
parent::initContent();
$tpl = $this->createTemplate('content.tpl')->fetch();
/* DO STUFF HERE */
$posts = array();
$this->context->smarty->assign('posts', $posts);
}
}
You can use boostrap directly in the template file :
./views/templates/admin/content.tpl
<div class="row">
<div class="col-md-6">
</div>
<div class="col-md-6">
</div>
</div>
If it is an admin module only, then you will have no need to create any views. Because Prestashop provides a nice structure for admin section which is easy to use and we dont need to use any views or .tpl files. For admin section, normally three types of views or .tpl files are required, one for data display in grid, second for form and third for displaying a single record.
Prestashop already created .tpl files for them which you can find in "admin_folder/themes/default/templates". In our controllers for admin, for form and for data grid, we just create arrays and PS handles to view the form and data grid according to the arrays we created.
So if you need a custom form at admin, then create a public function renderForm and create the form array in it, like below:
$this->fields_form = array(
'legend' => array(
'title' => $this->l('Video'),
'image' => '../img/admin/tab-genders.gif'
),
'input' => array(
array(
'type' => 'text',
'label' => $this->l('Video Title:'),
'name' => 'title',
'lang' => true,
'size' => 70,
'hint' => $this->l('Invalid characters:').' 0-9!<>,;?=+()##"�{}_$%:',
'required' => true
),
array(
'type' => 'textarea',
'label' => $this->l('Video Code'),
'name' => 'video_code',
'rows' => 5,
'cols' => 70,
'desc' => $this->l('Place the embed code for the video')
),
),
'submit' => array(
'title' => $this->l('Save'),
'class' => 'button'
)
);
return parent::renderForm();
} /* End of render member */
For other fields, checkout other prestashop admin controllers and you will see that how easily we can create forms in PS using that simple definitions in the arrays and we dont need to create .tpl files.
For front end, we can use the new modules MVC structure, where our module folder have sub folders for controllers (controllers/front, controllers/admin) , views and models .
Hope this will help you.
Thank you
You need to use the helper form, here is the documentation for it, it is really easy to use ;) .
http://doc.prestashop.com/display/PS15/HelperForm
You also can find more information about how and where to use helper form, look for the function getContent() and displayForm().
http://doc.prestashop.com/display/PS15/Creating+a+PrestaShop+module
unfortunately any document not exist to point directly to solve this question but hear i have some URLs really useful and you should combine theme and get your realize:
http://presthemes.com/prestashop-news/modules-classes-and-controller-override-by-julien-breux-4.html
http://doc.prestashop.com/display/PS15/Diving+into+PrestaShop+Core+development
http://doc.prestashop.com/display/PS15/New+Developers+Features+In+PrestaShop+1.5
http://blog.belvg.com/how-to-implement-a-controller.html
best regards
extending the answer from #altafhussain create a folder views/templates/admin in your module and place your customview.tpl
Than append the free text block as below.
$this->fields_form = array(
'legend' => array(
'title' => $this->l('Legend')
),
'input' => array(
array(
'type' => 'free',
'label' => 'Whatever label text',
'desc' => $this->display(__FILE__,'views/templates/admin/customview.tpl'),
'name' => 'FREE_TEXT',
'required' => false
)
),
'submit' => array(
'title' => $this->l('Save'),
'class' => 'button'
)
);
return parent::renderForm();
}

CakePHP 2.0 twitter-like follow button

I can't help myself and it's currently annoying, and yes, I used google a lot.
What I need:
A twitterlike follow button with the action to follow user.
What I already did:
Database
users table: id, username, password, ...
users_users table: id, user_id, follower_id
Code
In model User.php
public $hasAndBelongsToMany = array(
'Follower' => array(
'className' => 'User',
'joinTable' => 'users_users',
'foreignKey' => 'user_id',
'associationForeignKey' => 'follower_id',
'unique' => 'keepExisting',
)
);
In UsersController.php
public function follow() {
/*need help here*/
}
In Users\index.ctp
<?php if ($current_user['id'] != $user['User']['id']) echo $this->Html->link('Follow', array('action' => 'follow', $user['User']['id'])); ?>
Personally, I don't find hasAndBelongsToMany to be a good fit for situations like this. It's a good fit for when you want to display a list of checkboxes, or a select list, and allow the user to select/manage all their followings (or whatever the relationships might be) in one form.
It might just be my personal preference, but in situations like yours, where you're adding/deleting single links without worrying about any of the other links related to that user, I prefer to just create a separate 'Relationships' (or similarly named) Model / Controller, and consider the records as things in their own right, as opposed to just hasAndBelongsToMany links that are all sort of 'automagically' managed.
Here's how I'd do it:
Name your users_users table 'relationships'. And name the columns 'followed_by_id' and 'following_id' (or similar) to avoid any ambiguity as to which user is the follower / followee (if that was a word!).
In your users Model, you'd have these relationships:
var $hasMany = array(
'Followers' => array(
'className' => 'Relationship',
'foreignKey' => 'following_id',
'dependent'=> true
),
'FollowingUsers' => array(
'className' => 'Relationship',
'foreignKey' => 'followed_by_id',
'dependent'=> true
),
);
Then you'd have a Relationships model that looks something like this (the $belongsTo relationships are the important part):
<?php
class Relationship extends AppModel {
var $name = 'Relationship';
var $validate = array(
'followed_by_id' => array(
'numeric' => array(
'rule' => array('numeric'),
),
),
'following_id' => array(
'numeric' => array(
'rule' => array('numeric'),
),
),
);
var $belongsTo = array(
'FollowedBy' => array(
'className' => 'User',
'foreignKey' => 'followed_by_id'
),
'Following' => array(
'className' => 'User',
'foreignKey' => 'following_id'
)
);
}
?>
And then in your Relationships controller, you'd have something like this:
function add($following_id = null) {
$this->Relationship->create();
$this->Relationship->set('followed_by_id',$this->Auth->User('id'));
$this->Relationship->set('following_id',$following_id);
if ($this->Relationship->save($this->data)) {
// all good
} else {
// You could throw an error here if you want
$this->Session->setFlash(__('Error. Please, try again.', true));
}
$this->redirect($this->referer());
}
Then to add relationships, you obviously just call the add method of your relationships controller.
NOTE: Ideally, since adding a relationship is changing the database, it ideally shouldn't be done with a GET request accessed by a regular URL. It should be done via submitting a form via POST. I know that seems overkill when it's so easy to just do it via a regular link with GET. I haven't bothered to use forms/POST in this example - but if you want to stick to best practices, that's what you should do. See this for more info: https://softwareengineering.stackexchange.com/questions/188860/why-shouldnt-a-get-request-change-data-on-the-server