drupal custom views filter - filter

First time on stackoverflow so , i will try to be as clear as possible.
I'm using drupal 7 and views 3.
I needed to create a custom views filter that handle dates range. So i looked at example and tried to mimic the behavior and i get some trouble.
It seems that when i extend my own class from views_handler_filter , the query method is never invoked BUT if i extend my class from let's say views_handler_filter_string, it works oO...
I must forget something but i'm stuck here ...
Here is my code, if someone can take a look and advise me about what happend , i would be very grateful.
Thanks everyone !
Here is my .views.inc file :
<?php
class v3d_date_custom_filter extends views_handler_filter {
var $always_multiple = TRUE;
function value_form(&$form, &$form_state) {
//parent::value_form($form, $form_state);
$form['value']['v3d_date']['period'] = array(
'#type' => 'select',
'#title' => 'Period',
'#options' => array(
'7_days' => 'Last 7 days',
'yesterday' => 'Yesterday',
'today' => 'Today',
'custom' => 'Custom dates'),
'#default_value' => 'custom',
'#attributes' => array("onclick" => "period_click(this);"),
);
$form['value']['v3d_date']['start_date'] = array(
'#type' => 'date_popup',
'#date_format' => 'Y-m-d',
'#title' => 'Start date',
'#size' => 30);
$form['value']['v3d_date']['end_date'] = array(
'#type' => date_popup',
'#title' => 'End date',
'#date_format' => 'Y-m-d',
'#size' => 30);
}
function exposed_validate(&$form, &$form_state) {
if(is_null($form_state['values']['start_date']) &&
is_null($form_state['values']['start_date'])) {
return TRUE;
}
/*
* If we get array for start_date or end_date
* errors occured, but the date module will handle it.
*/
if(!is_string($form_state['values']['start_date']) ||
!is_string($form_state['values']['end_date'])) {
return TRUE;
}
/* Get day, month and year from start_date string */
if(!preg_match('/(\d+)-(\d+)-(\d+)/',
$form_state['values']['start_date'],
$start_date
)) {
return TRUE; }
/* Get day, month and year from end_date string */
if(!preg_match('/(\d+)-(\d+)-(\d+)/',
$form_state['values']['end_date'],
$end_date
)) {
return TRUE; }
/* Create timestamps and compare */
$start_date = mktime(0,0,0,$start_date[1],$start_date[2],$start_date[3]);
$end_date = mktime(0,0,0,$end_date[1],$end_date[2],$end_date[3]);
if($start_date >= $end_date) {
form_set_error('start_date','Start date must be anterior to end date.');
}
}
function query() {
die('fdsfds');
$this->ensure_my_table();
$field = "$this->table_alias.$this->real_field";
dsm($this);
}
}
?>
And my .module file
<?php
function custom_filters_views_api() {
return array(
'api'=>3,
'path' => drupal_get_path('module','custom_filters') . '/views',
);
}
?>
And part of my views_data that use my custom filter :
<?php
function voice_views_data() {
$data['v_tp_voice']['date_utc_agent'] = array(
'title' => t('date_utc_agent'),
'help' => 'date_utc_agent',
'field' => array('handler' => 'views_handler_field'),
'filter' => array('handler' => 'v3d_date_custom_filter'),
'sort' => array('handler' => 'views_handler_sort')
);

I am working on this same problem. My setup looks very much like yours, though I do call parent::value_form($form, $form_state) in my value_form function.
I found that in the value_form function, I had to have something like
$form['value'] = array(
'#type' => 'checkbox',
'#title' => "Filter by Date",
'#default_value' => $this->value,
);
in order to have my query() function called. Doing something like $form['value']['before'] = array( ...
didn't work.

Related

Returning user input after AJAX call in Drupal 7 hook_form_FORM_ID_alter

I am using the hook_form_FORM_ID_alter in Drupal 7 to create a custom form so that the user can enter and edit data which is then attached to a custom node type.
For a new node the default number of input boxes in a group is 10, this can then be added to in groups of 5. When the node is reloaded for editing the saved data is used to create the form with whatever number of inputs have been saved previously and also the ability to add more fields in the same manner as required.
I have managed to get both the initial version of the form and the editing version to work using the following code however when the 'add five' button is pressed and the AJAX called (in both cases), any values which have been entered without saving are removed.
<?php
/**
* Implements hook_form_FORM_ID_alter().
*/
function entries_form_form_entries_node_form_alter(&$form, &$form_state, $form_id) {
$node = $form['#node'];
// fieldset
$form["section"] = array(
'#type' => 'fieldset',
'#title'=> 'Section 1',
);
$form["section"]["termwrapper"] = array(
"#type" => 'container',
"#attributes" => array(
"id" => 'groupWrapper',
),
);
$form["section"]["termwrapper"]["terms"]["#tree"] = TRUE;
if(!isset($form_state['fired'])){
$form_state['terms'] = $node->entries_form['term'];
}
foreach ($form_state['terms'] as $key => $values) {
$form["section"]["termwrapper"]["terms"][$key] = array(
'#type' => 'textfield',
'#size' => 20,
'#attributes' => array(
'class' => array('left'),
),
'#value' => $values,
);
}
$form['section']['addFive_button'] = array(
'#type' => 'submit',
'#value' => t('+5'),
'#submit' => array('entries_form_add_five_submit'),
'#ajax' => array(
'callback' => 'entries_form_commands_add_callback',
'wrapper' => 'groupWrapper',
),
'#prefix' => "<div class='clear'></div>",
);
dpm($form_state);
}
function entries_form_commands_add_callback($form, $form_state) {
return $form["section"]["termwrapper"];
}
function entries_form_add_five_submit($form, &$form_state){
$form_state['rebuild'] = TRUE;
$form_state['fired'] = 1;
$values = $form_state['values'];
$form_state['terms'] = $values['terms'];
$numterms = count($values['terms']);
$addfivearray = array_fill($numterms,5,'');
$form_state['terms'] = array_merge($values['terms'],$addfivearray);
}
/**
* Implements hook_node_submit().
*/
function entries_form_node_submit($node, $form, &$form_state) {
$values = $form_state['values'];
$node->entries_form['term'] = $values['term'];
}
/**
* Implements hook_node_prepare().
*/
function entries_form_node_prepare($node) {
if (empty($node->entries_form)){
$node->entries_form['term'] = array_fill(0, 10, '');
}
}
/**
* Implements hook_node_load().
*/
function entries_form_node_load($nodes, $types) {
if($types[0] == 'entries'){
$result = db_query('SELECT * FROM {mytable} WHERE nid IN(:nids)', array(':nids' => array_keys($nodes)))->fetchAllAssoc('nid');
foreach ($nodes as &$node) {
$node->entries_form['term'] = json_decode($result[$node->nid]->term);
}
}
}
/**
* Implements hook_node_insert().
*/
function entries_form_node_insert($node) {
if (isset($node->entries_form)) {
db_insert('mytable')
->fields(array(
'nid' => $node->nid,
'term' => json_encode($node->entries_form['term']),
))
->execute();
}
}
How can I keep the values which have been typed in and retain the ajax functionality?
Any help or pointers much appreciated. This is my first dip into Drupal so I'm sure there is something which hopefully is quite obvious that I'm missing.
Ok, I think I finally have the answer.
Within the foreach that builds the form input boxes I had set '#value' => $values, when it seems that '#default_value' => $values, should have been set instead.
The updated section of the code that is now working for me is as follows
foreach ($form_state['terms'] as $key => $values) {
$form["section"]["termwrapper"]["terms"][$key] = array(
'#type' => 'textfield',
'#size' => 20,
'#attributes' => array(
'class' => array('left'),
),
'#default_value' => $values,
);
}
Seems to be as simple as that. Hope this helps someone else.

Searching sales order grid redirects to dashboard in magento 1.7

I have used a custom module to add new columns to Sales_Order_Grid in Magento but If I search for Order_Id the page redirects to the Dashboard.
If I try to select sales/orders again I get an error:
a:5:{i:0;s:104:"SQLSTATE[23000]: Integrity constraint violation: 1052 Column 'increment_id' in where clause is ambiguous";i:1;s:6229:"#0
I have no idea how to solve this and could really do with some guidance please?
Here's the Grid.php code:
<?php
class Excellence_Salesgrid_Block_Adminhtml_Sales_Order_Grid extends Mage_Adminhtml_Block_Sales_Order_Grid
{
protected function _addColumnFilterToCollection($column)
{
if ($this->getCollection()) {
if ($column->getId() == 'shipping_telephone') {
$cond = $column->getFilter()->getCondition();
$field = 't4.telephone';
$this->getCollection()->addFieldToFilter($field , $cond);
return $this;
}else if ($column->getId() == 'shipping_city') {
$cond = $column->getFilter()->getCondition();
$field = 't4.city';
$this->getCollection()->addFieldToFilter($field , $cond);
return $this;
}else if ($column->getId() == 'shipping_region') {
$cond = $column->getFilter()->getCondition();
$field = 't4.region';
$this->getCollection()->addFieldToFilter($field , $cond);
return $this;
}else if ($column->getId() == 'shipping_postcode') {
$cond = $column->getFilter()->getCondition();
$field = 't4.postcode';
$this->getCollection()->addFieldToFilter($field , $cond);
return $this;
}else if($column->getId() == 'product_count'){
$cond = $column->getFilter()->getCondition();
$field = ( $column->getFilterIndex() ) ? $column->getFilterIndex() : $column->getIndex();
$this->getCollection()->getSelect()->having($this->getCollection()->getResource()->getReadConnection()->prepareSqlCondition($field, $cond));
return $this;
}else if($column->getId() == 'skus'){
$cond = $column->getFilter()->getCondition();
$field = 't6.sku';
$this->getCollection()->joinSkus();
$this->getCollection()->addFieldToFilter($field , $cond);
return $this;
}else{
return parent::_addColumnFilterToCollection($column);
}
}
}
protected function _prepareColumns()
{
$this->addColumnAfter('shipping_description', array(
'header' => Mage::helper('sales')->__('Shipping Method'),
'index' => 'shipping_description',
),'shipping_name');
$this->addColumnAfter('method', array(
'header' => Mage::helper('sales')->__('Payment Method'),
'index' => 'method',
'type' => 'options',
'options' => Mage::helper('payment')->getPaymentMethodList()
),'shipping_description');
$this->addColumnAfter('shipping_city', array(
'header' => Mage::helper('sales')->__('Shipping City'),
'index' => 'shipping_city',
),'method');
$this->addColumnAfter('shipping_telephone', array(
'header' => Mage::helper('sales')->__('Shipping Telephone'),
'index' => 'shipping_telephone',
),'method');
$this->addColumnAfter('shipping_region', array(
'header' => Mage::helper('sales')->__('Shipping Region'),
'index' => 'shipping_region',
),'method');
$this->addColumnAfter('shipping_postcode', array(
'header' => Mage::helper('sales')->__('Shipping Postcode'),
'index' => 'shipping_postcode',
),'method');
/*$this->addColumnAfter('product_count', array(
'header' => Mage::helper('sales')->__('Product Count'),
'index' => 'product_count',
'type' => 'number'
),'increment_id');
/*$this->addColumnAfter('skus', array(
'header' => Mage::helper('sales')->__('Product Purchased'),
'index' => 'skus',
),'increment_id');*/
return parent::_prepareColumns();
}
}
This is what worked in my case:
$collection->addFilterToMap('increment_id', 'main_table.increment_id');
Looks like you are adding some more columns to the admin sales grid? It also sounds like you are working with a collection containing a join against a second table, you need to add the table alias name into the where statement with the increment_id column definition, so table_alias.increment_id.
To check this, and assuming calling $this->getCollection() from Excellence_Salesgrid_Block_Adminhtml_Sales_Order_Grid returns the collection, get the select object from the collection:
$select = $this->getCollection()->getSelect();
Hopefully you are using xdebug with an IDE and can set breakpoints in your code. If so set a breakpoint and inspect the the $select object pulled by the line above. Inside this object you will see a _parts array which describes the way your select statement is constructed. Inside this you will see a from array which contains information about the tables which are part of the statement. If you have a JOIN, this will contain more than one entry.
Under here you can also see where which will describe the where clauses which are part of the statement - this is where the problem likely lies. You need to identify the alias for the correct table inside the from array and then where the where clause is added, instead of doing something like:
$this->getCollection()->getSelect()->where('increment_id = ?', $id);
instead do:
$this->getCollection()->getSelect()->where('table_alias.increment_id = ?', $id);

Magento - How to create "decimal" attribute type

I've done a bit of searching online but I have not found any answers to this question yet. I have a situation where I need a product attribute that is a decimal value and it must support negative numbers as well as positive and must also be sortable. For some reason, Magento does not have a "decimal" attribute type. The only type that uses decimal values is Price, but that doesn't support negative numbers. If I use "text" as the type, it supports whatever I want, but it doesn't sort properly because it sees the values as strings rather than floating point numbers. I have been able to work around this issue, as others have in posts I've found, by manually editing the eav_attribute table and changing 'frontend_input' from 'price' to 'text', but leaving the 'backend_type' as 'decimal'. This works great...until someone edits the attribute in the admin panel. Once you save the attribute, Magento notices that the frontend_input is 'text' and changes the 'backend_type' to 'varchar'. The only way around this that I can think of is by creating a custom attribute type, but I'm not sure where to start and I can't find any details online for this.
Has anyone else experienced this problem? If so, what have you done to correct it? If I need to create a custom attribute type, do you have any tips or can you point me at any tutorials out there for doing this?
Thanks!
What you want to do is create a custom attribute type.
This can be done by first creating a installer script (this updates the database).
startSetup();
$installer->addAttribute('catalog_product', 'product_type', array(
'group' => 'Product Options',
'label' => 'Product Type',
'note' => '',
'type' => 'dec', //backend_type
'input' => 'select', //frontend_input
'frontend_class' => '',
'source' => 'sourcetype/attribute_source_type',
'backend' => '',
'frontend' => '',
'global' => Mage_Catalog_Model_Resource_Eav_Attribute::SCOPE_WEBSITE,
'required' => true,
'visible_on_front' => false,
'apply_to' => 'simple',
'is_configurable' => false,
'used_in_product_listing' => false,
'sort_order' => 5,
));
$installer->endSetup();
After that you need to create a custom php class named:
Whatever_Sourcetype_Model_Attribute_Source_Type
And in there paste this in:
class Whatever_Sourcetype_Model_Attribute_Source_Type extends Mage_Eav_Model_Entity_Attribute_Source_Abstract
{
const MAIN = 1;
const OTHER = 2;
public function getAllOptions()
{
if (is_null($this->_options)) {
$this->_options = array(
array(
'label' => Mage::helper('sourcetype')->__('Main Product'),
'value' => self::MAIN
),
array(
'label' => Mage::helper('sourcetype')->__('Other Product'),
'value' => self::OTHER
),
);
}
return $this->_options;
}
public function toOptionArray()
{
return $this->getAllOptions();
}
public function addValueSortToCollection($collection, $dir = 'asc')
{
$adminStore = Mage_Core_Model_App::ADMIN_STORE_ID;
$valueTable1 = $this->getAttribute()->getAttributeCode() . '_t1';
$valueTable2 = $this->getAttribute()->getAttributeCode() . '_t2';
$collection->getSelect()->joinLeft(
array($valueTable1 => $this->getAttribute()->getBackend()->getTable()),
"`e`.`entity_id`=`{$valueTable1}`.`entity_id`"
. " AND `{$valueTable1}`.`attribute_id`='{$this->getAttribute()->getId()}'"
. " AND `{$valueTable1}`.`store_id`='{$adminStore}'",
array()
);
if ($collection->getStoreId() != $adminStore) {
$collection->getSelect()->joinLeft(
array($valueTable2 => $this->getAttribute()->getBackend()->getTable()),
"`e`.`entity_id`=`{$valueTable2}`.`entity_id`"
. " AND `{$valueTable2}`.`attribute_id`='{$this->getAttribute()->getId()}'"
. " AND `{$valueTable2}`.`store_id`='{$collection->getStoreId()}'",
array()
);
$valueExpr = new Zend_Db_Expr("IF(`{$valueTable2}`.`value_id`>0, `{$valueTable2}`.`value`, `{$valueTable1}`.`value`)");
} else {
$valueExpr = new Zend_Db_Expr("`{$valueTable1}`.`value`");
}
$collection->getSelect()
->order($valueExpr, $dir);
return $this;
}
public function getFlatColums()
{
$columns = array(
$this->getAttribute()->getAttributeCode() => array(
'type' => 'int',
'unsigned' => false,
'is_null' => true,
'default' => null,
'extra' => null
)
);
return $columns;
}
public function getFlatUpdateSelect($store)
{
return Mage::getResourceModel('eav/entity_attribute')
->getFlatUpdateSelect($this->getAttribute(), $store);
}
}
Hope this helps.
For further info see here.

CakePHP data not saving and validation not working

When my model goes to validate my form
it always come as false,
it doesn't save in the database.
I dont understand why this isn't working, it was working until I unbind on a few of my functions.
Here is my invoice model, it's supposed to check if there is to/biller in relationships_users table (relationship model).
<?php
class Invoice extends AppModel{
var $name='Invoice';
public $belongsTo = array(
'Relationship' =>array(
'className' => 'Relationship',
'foreignKey' =>'relationship_id',
)
);
var $validate = array(
'to' => array(
'relationshipExists' => array(
'rule' => array(
'relationshipExists'),
'message' => 'sorry you dont have a relationship with that user.'
),
),
);
public function relationshipExists($check){
$relationshipExists=$this->Relationship->find('count', array(
'conditions' => array(
'Relationship.partyone' => current($check),
'Relationship.partytwo' => current($check)
// get the value from the passed var
)
)
);
if ($relationshipExists>0) {
return TRUE;
}
else
return FALSE;
}
Here is my function in the invoices table
public function addinvoice(){
$this->set('title_for_layout', 'Create Invoice');
$this->set('stylesheet_used', 'homestyle');
$this->set('image_used', 'eBOXLogoHome.jpg');
$this->layout='home_layout';
if($this->request->is('post')){
($this->Invoice->set($this->request->data));
if($this->Invoice->validates(array('fieldList'=>array('to','Invoice.relationshipExists')))){
$this->Invoice->save($this->request->data);
$this->Session->setFlash('The invoice has been saved');
}}else {
$this->Session->setFlash('The invoice could not be saved. Please, try again.');
}
}
What it's supposed to do is to check that to/biller are in the relationships_users table and then save the invoice to the invoice table, otherwise throw a message.
The conditions array seems strange to me:
'conditions' => array(
'Relationship.partyone' => current($check),
'Relationship.partytwo' => current($check)
// get the value from the passed var
)
That would search for Relationships with both partyone and partytwo set to to. You probably want to check if either of them is set to to:
'conditions' => array(
'OR' => array(
'Relationship.partyone' => current($check),
'Relationship.partytwo' => current($check)
)
// get the value from the passed var
)

AJAX Error Drupal-7

I am creating a module in which there is a dependency between combo boxes. There are three combo boxes: country, state, and district. If I select India in the country combo box, then the state combo box will contain all states of India, and the same in the case of district.
I have done this by using AJAX. It works properly in add form, but when I am going to update any one, the following error occurs:
An AJAX HTTP error occurred.
HTTP Result Code: 500
Debugging information follows.
Path: /drupal/?q=system/ajax
StatusText: Service unavailable (with message)
ResponseText: PDOException: SQLSTATE[42S22]: Column not found: 1054 Unknown column 'ajax' in 'where clause': SELECT district_name, country_id,state_id FROM {ajax_district} where id = ajax; Array
(
)
in edit_district_form() (line 291 of /home/mansmu/www/drupal/sites/default/modules/ajaxtest/ajaxtest.district.inc).
My code is:
////////////////////////////////////////////////////////
///////// FUNCTION FOR EDIT
////////////////////////////////////////////////////////
function edit_district_form($form, &$form_state) {
$request_url = request_uri();
// $request_id to get id of edit district.
$request_id = drupal_substr(strrchr($request_url, '/'), 1);
//// FOR country
$rows = array();
$result = db_query("SELECT id,country_name from {ajax_country} order by country_name");
while ($data = $result->fetchObject()) {
$id = $data->id;
$rows[$id] = $data->country_name;
}
//// FOR state
$state = array();
$result = db_query("SELECT id,state_name from {ajax_state} order by state_name");
while ($data = $result->fetchObject()) {
$id = $data->id;
$state[$id] = $data->state_name;
}
// $district_name varible to get name from database for a requested id.
$district_name = db_query("SELECT district_name, country_id,state_id FROM {ajax_district} where id = ".$request_id);
// Loop For show vehicle district name in text field to be update.
foreach ($district_name as $district) {*/
$form['values']['edit_country_name'] = array(
'#type' => 'select',
// '#default_value' => "{$district->country_id}",
'#required' => TRUE,
'#options' => $rows,
'#ajax' => array(
'effect' => 'fade',
'progress' => array('type' => 'none'),
'callback' => 'state_callback_edit',
'wrapper' => 'replace_edit_state',
),
);
$form['values']['edit_state_name'] = array(
'#type' => 'select',
// '#default_value' => "{$district->state_id}",
'#required' => TRUE,
'#options' => array(),
// The prefix/suffix provide the div that we're replacing, named by #ajax['wrapper'] above.
'#prefix' => '',
'#suffix' => '',
);
$form['values']['edit_district_name'] = array(
'#type' => 'textfield',
'#size' => 30,
//'#default_value' => "{$district->district_name}",
'#maxlength' => 80,
'#required' => TRUE,
);
}
$form['edit_district_submit'] = array(
'#type' => 'submit',
'#value' => t('Update'),
);
$form['actions']['cancel'] = array(
'#markup' => l(t('Cancel'), 'district'),
);
return $form;
}
////////////////////////////////////////////////////////
///////// FUNCTION FOR AJAX CALL BACK
////////////////////////////////////////////////////////
function state_callback_edit($form, &$form_state) {
// An AJAX request calls the form builder function for every change.
// We can change how we build the form based on $form_state.
if (!empty($form_state['values']['edit_country_name'])) {
$country_id = $form_state['values']['edit_country_name'];
$rows1 = array();
$result = db_query("SELECT id, state_name from {ajax_state} where country_id = $country_id order by state_name");
while ($data = $result->fetchObject()) {
$id = $data->id;
$rows1[$id] = $data->state_name;
}
$form['edit_state_name']['#options'] = $rows1;
}
return $form['values']['edit_state_name'];
}
Your line of code here:
$request_id = drupal_substr(strrchr($request_url, '/'), 1);
is returning the string 'ajax', making your third SQL statement look like this:
SELECT district_name, country_id,state_id FROM {ajax_district} where id = ajax;
Obviously 'ajax' is wrong there, I guess you want a value from the URL? You could use the arg() function to extract this so you don't need to run drupal_substr etc.
If your path is ajax/12 then arg(0) will return 'ajax', arg(1) will return 12 and so on.
Hope that helps
UPDATE
If you need to save the request ID in the form do something like this in your form function:
$form['request_id'] = array('#type' => 'value', '#value' => $request_id);
Then when you get into your ajax callback you can either get it from $form_state['values']['request_id'] or $form['request_id']['#value']

Resources