Symfony - Admin generator filters - symfony-1.4

I changed the generator on my comments module so that the results listed by default were different. I only added a 'table_method' value:
list:
table_method: commentParent
Then I added the commentParent function like this:
public function commentParent(Doctrine_Query $q) {
$rootAlias = $q->getRootAlias();
$q->where($rootAlias . '.parent_id is null or ' . $rootAlias . '.parent_id = 0');
return $q;
}
The listed results are correct but using this method, now filters won't work. In Dev mode, I can see them being correctly set in user variables, but they have no effect.
What could I possibly be missing?

Use addWhere instead of where because it (where) removes all previous where clauses that were added.

Related

Array as parameter in Doctrine SQLFilter

I'm trying to create Doctrine SQLFilter. I need to filter for "deleted" field. But i want to make filter works with both (true and false) values too.
Something like this:
<?php
namespace Rem\CostsBundle\Doctrine;
use Doctrine\ORM\Mapping\ClassMetadata;
use Doctrine\ORM\Query\Filter\SQLFilter;
class ItemDeletedFilter extends SQLFilter
{
public function addFilterConstraint(ClassMetadata $targetEntity, $targetTableAlias)
{
if ($targetEntity->getReflectionClass()->name != 'Rem\CostsBundle\Entity\Item') {
return '';
}
$fdata = $this->getParameter('deleted');
$filter = '1<>1';
foreach ($fdata as $param) {
$filter .= sprintf('OR %s.deleted = %s', $targetTableAlias, $param);
}
return $filter;
}
}
But when I'm trying to set array of posible filter values in controller
$filters
->enable('costs_item_deleted')
->setParameter('deleted', [true, false]);
I get an error 500
Warning: PDO::quote() expects parameter 1 to be string, array given
This is clear situation. But, after all HOW to send array of params to my SQL filter?
UPD after Dmitry answer: This is not actualy what I wanted. Let say: what if I wanted to filter by few values of field? For records of 2015 and 2016 years for example... So i need to set some sort of array-of-years in ->setParameter. But it want only strings! And sends an error when i'm trying to set something else.
How do you solve this?
Or even more complicated example. What if I need to filter by relational field. In this case I need to set entity as param of filter. Or even ArrayCollection of entities!
For now I'm decide it like this: I json_encode array before set it to setParameter in controller. And then I json_decode it in Filter class. BUT! There in Filter class I need to make one more step. I need to remove single and doublequotes from json string. Because they was added by setParameter to escape string (thats why we love it )) ).
Code hacks like this we call "crutches" here in Russia. So I'd like to avoid of them and write more elegant code )
Make it IN instead of comparing.
foreach ($fdata as $param) {
$filter .= sprintf('OR %s.deleted IN (%s)', $targetTableAlias, param);
}

Populating a custom field from the Wordpress Postie Plugin

I am using the Postie plugin to auto post from email on my Wp blog.
I am trying to populate two custom fields (mail_meta_from and mail_meta_replyto") with the "from" and "reply to" fields
add_filter('postie_post_before', 'add_custom_field');
//Get the "from" and "replyto" email details
add_filter('postie_filter_email2', 'get_emaildetails', 10, 3);
function get_emaildetails( $from, $toEmail, $replytoEmail) {
DebugEcho("step-01b");
DebugDump("from " . $from);
DebugDump("toEmail " . $toEmail);
DebugDump("replytoEmail " . $replytoEmail);
$fromField = $from;
$replytoEmail = $replytoEmail;
return $from;
return $replytoEmail;
function add_custom_field($post) {
add_post_meta($post['ID'], 'mail_meta_from', '$from');
add_post_meta($post['ID'], 'mail_meta_replyto', $replytoEmail);
return $post;
}
}
This has been driving me nuts for the past 2 days, and I have tried multiple variations of the above but with no success.
At the moment, I am getting the error
Warning: call_user_func_array() expects parameter 1 to be a valid callback, function 'add_custom_field' not found or invalid function name in /home/sites/mysite.com/public_html/wp-includes/plugin.php on line 213
I try and learn from my mistakes, but I am not getting anywhere with this...
The default answer for help with this on the WP forum is to check out http://postieplugin.com/extending/.
Which I have... repeatedly.
Any help would be greatly appreciated!
You are defining the add_custom_field() function inside the scope of the get_emaildetails() function because it is within the curly braces. You should also consider using a more unique name for your function, or encapsulate it an an object namespace. The error you are getting indicates that when the apply_filter() is called for postie_post_before it can't find a function called add_custom_field(). Use the code below to properly scope the function, though note that you have some other syntax errors as well.
add_filter('postie_post_before', 'add_custom_field');
function add_custom_field($post) {
// the variable $from is not defined, and it will not evaluate if enclosed
// in single quotes. if you want the value of $from define it then use "{$from}"
add_post_meta($post['ID'], 'mail_meta_from', '$from');
// $replytoEmail is not defined
add_post_meta($post['ID'], 'mail_meta_replyto', $replytoEmail);
return $post;
}
//Get the "from" and "replyto" email details
add_filter('postie_filter_email2', 'get_emaildetails', 10, 3);
function get_emaildetails( $from, $toEmail, $replytoEmail) {
DebugEcho("step-01b");
DebugDump("from " . $from);
DebugDump("toEmail " . $toEmail);
DebugDump("replytoEmail " . $replytoEmail);
// what is this for?
$fromField = $from;
// setting to itself, then not used?
$replytoEmail = $replytoEmail;
return $from;
// this will never return?
return $replytoEmail;
}

How do I filter results in APYDataGridBundle in Symfony2?

I have been looking for hours for a way of setting a condition on the list of items that an APYDataGridBundle grid should return but could not find an answer.
Is there a way to set a DQL Query and pass it to the grid to display the exact query results I want to fetch?
This is the code:
public function filteredlistAction(){
// Create simple grid based on the entity
$source = new Entity('ACMEBundle:MyEntity');
// Get a grid instance
$grid = $this->get('grid');
// Attach the source to the grid
$grid->setSource($source);
...
...
**$grid->getColumns()->getColumnById('myentity_filter_column')->setData('the exact value I tried to match');**
// Manage the grid redirection, exports and the response of the controller
return $grid->getGridResponse('ACMEBundle:MyEntity:index_filteredlist.html.twig');
}
You can add a callback (closure or callable) to run before QueryBuilder execution - its done like this :
$source->manipulateQuery(
function ($query)
{
$query->resetDQLPart('orderBy');
}
);
$grid->setSource($source);
$query is an instance of QueryBuilder so you can change whatever you need to
Example taken from docs here
A more "complicated" query.
$estaActivo = 'ACTIVO';
$tableAlias = $source->getTableAlias();
$source->manipulateQuery(
function ($query) use ($tableAlias, $estaActivo)
{
$query->andWhere($tableAlias . '.estado = :estaActivo')
->andWhere($tableAlias . '.tipoUsuario IN (:rol)')
->setParameter('estaActivo', $estaActivo)
->setParameter('rol', array('VENDEDOR','SUPERVISOR'), \Doctrine\DBAL\Connection::PARAM_STR_ARRAY);
}
);
Cheers!

Drupal 6 getting the node title from a submitted form

I am using form_alter to edit the submit function when editing content. In my custom function I wish to edit a custom message to the screen with the title name. I thought a way I could do this is something as follows
function mymodule_myfunction(&$form) {
drupal_set_message(t('Some text ' . $form['#node']->title));
}
The title is not being joined to the 'Some text'
I am calling my function by using the following line in my form_alter:
$form['#submit'][] = 'mymodule_myfunction';
All submit functions get two parameters passed to them: $form, which is the final form array after all of the adjustments for hook_form_alter and the like, and $form_state which among other values contains the submitted values, which have been cleaned and checked for ranges. (For instance, if you have three items in a select box, the data in $form_state['values'] already has made sure that the value for that input is one of the three legal values.)
Generally, you shouldn't use $form['#post'] - it's not part of the published way to get at values, and an update to the core to handle some problem with FAPI could conceivably break your code.
Try this:
function mymodule_myfunction($form, &$form_state) {
drupal_set_message(t('Some Message #title'),
array('#title' => $form_state['values']['title'])));
}
Note the corrected use of the t() function - the intent of that function is to allow other users to translate text, and so by using 'Some Message #title' the translator knows more about what is going on. Additionally you get the advantage that text fed through the t function in this way also is fed through check_plain(), which prevents someone from doing something malicious with the input.
DKinzer recommended using dsm($form)to see the variables. The Node title is not populated. It can be found in the Post array. The following line allowed me to do what I wanted.
drupal_set_message(t('Some Text '.$form['#post']['title']));
Try changing the signature of your
function mymodule_myfunction(&$form) {
drupal_set_message(t('Some text ' . $form['#node']->title));
}
To:
function mymodule_myfunction($form, &$form_state) {
drupal_set_message(t('Some text ' . $form['#node']->title));
}
Also try installing the devel module so you can do things like
dsm($form);
dsm($form_state);
And see exactly what you are dealing with.
Also, if all you want to do is give a message when a new node of type 'X' is created a better way is to use hook_nodeapi;
It could look something like this;
function modulename_nodeapi(&$node, $op, $a3 = NULL, $a4 = NULL) {
if ($op == 'insert' && $node->type == 'my node type') {
drupal_set_message($node-title . ' is cool.');
}
}

Custom logic for exposed filters in a Drupal view

I'm working on a Drupal site and would love some advice on this. Currently, a user enters his level for a number of different skills. This is stored in a CCK integer field and exposed to the user as a drop-down widget containing the key/value pairs 1|Beginner, 2|Intermediate, 3|Advanced.
In a view, I expose the allowed values for each skill, which are presented to the user as checkboxes (using the Better Exposed Filters module) and then listed in a sortable table. In practice, users generally search for people who have "at least knowledge level X in skill Y". Is there a module or straightforward way to display the allowed values as a drop-down and use a "greater than" operator in the query instead of a "one of"?
Any sample code or advice on how to dynamically change the filter logic or the WHERE clause of the query would be very appreciated.
You want to use hook_views_query_alter(), while I haven't specifically altered the WHERE clause, I have altered the SORTBY clause and the idea behind both should be relatively similar.
Here's a quick piece of code:
function my_module_views_query_alter(&$view, &$query) {
switch ($view->name) {
case 'view1':
$args = _my_module_get_querystring();
switch ($args['condition']) {
case 'condition1':
$query->where[0]['args'][0] = 1;
break;
case 'condition2':
$query->where[0]['args'][0] = 2;
break;
}
break;
}
}
/**
* Returns querystring as an array.
*/
function _my_module_get_querystring() {
$string = drupal_query_string_encode($_REQUEST, array_merge(array('q'), array_keys($_COOKIE)));
$args = explode('&', $string);
foreach ($args as $id => $string) {
unset($args[$id]);
$string = explode('=', $string);
$args[$string[0]] = str_replace(' ', '-', $string[1]);
}
return $args;
}
This particular piece would allow you to alter the WHERE clause using a querystring (?condition=condition1), but you could alter it to get the arguments however you wish.
Hope this helps.
Using Decipher's sample and spending a few hours reading up and playing around, I've gotten a basic module that works perfectly for my needs. Thanks again!
Here's my code if anyone else comes across a similar need:
<?php
// $Id$
/**
* #file
* Module for modifying the views query to change an EQUALS
* to a GREATER THAN for specific filters.
*/
function views_greater_than_views_query_alter(&$view, &$query) {
//only implement for views that have Search in their name
if(strstr($view->name, "search")) {
$whereclauses = $query->where[0]['clauses'];
foreach ($whereclauses as $i=>$currentrow) {
$currentrow = str_replace('= %d', '>= %d', $currentrow);
$query->where[0]['clauses'][$i] = $currentrow;
}
unset($whereclauses);
}
}

Resources