Filtering theme_table in Drupal - mysql

I just created a data table based on a query and displayed it successfully using theme_table().
Now, I'd like to add some filters to the table but have no idea how to proceed.
Is there a built-in feature that allow me to do this easily, or should I manually add a form and update the query/redisplay the results each time the user selects something?
Thanks for your help!

I think you want to use pager_query and tablesort_sql: it's especially made for creating tables of data with pagination and sorting capabilities (and themes usually theme such tables nicely out of the box).
Example:
<?php
// The regular query without sorting or pagination parameters
$sql = 'SELECT cid, first_name, last_name, company, city FROM {clients}';
// Number of rows per page
$limit = 20;
// List of table columns ("field" is the matching database column from the sql query)
$header = array(
array('data' => t('Name'), 'field' => 'last_name', 'sort' => 'asc'),
array('data' => t('Company'), 'field' => 'company'),
array('data' => t('City'), 'field' => 'city')
);
// Calculates how to modify the SQL query according to the current pagination and sorting settings
// Then performs the database query
$tablesort = tablesort_sql($header);
$result = pager_query($sql . $tablesort, $limit);
$rows = array();
while ($client = db_fetch_object($result)) {
$rows[] = array(l($client->last_name.', '.$client->first_name, 'client/'.$client->cid), $client->company, $client->city);
}
// A message in case no results were found
if (!$rows) {
$rows[] = array(array('data' => t('No client accounts created yet.'), 'colspan' => 3));
}
// Then you can pass the data to the theme functions
$output .= theme('table', $header, $rows);
$output .= theme('pager', NULL, $limit, 0);
// And return the HTML output
print $output;
?>
(I added comments, but the original version of the example comes from this page)
Alternatively, maybe you don't need to make a module at all if you're just trying to make a page that displays a list of data, you may prefer using the Views module.

Related

cakephp3 select count(*) from other models

I have 3 models Employees Customers and Partners
I want to display the count of all the tables employees customers and partners in dashboard view of Employees model.
EmployeesController.php
<?php
namespace App\Controller;
class EmployeesController extends AppController
{
public function dashboard()
{
}
}
?>
I'm new to cakephp and I have no idea how to query other model tables at all.
Please point me to good tutorial or documentation for this. It will be helpful
I fixed it using the following codes.
// Controller
$this->loadModel("Customer");
$query = $this->Customers->find('all', [
'conditions' => ['Customers.area_cd =' => $this->Auth->user('area_cd')]
]);
$entity_count[0] = $query->count();
$this->loadModel("Employee");
$query = $this->Employees->find('all', [
'conditions' => ['Employees.area_cd =' => $this->Auth->user('area_cd')]
]);
$entity_count[1] = $query->count();
$this->loadModel("Partner");
$query = $this->Partners->find('all', [
'conditions' => ['Partners.area_cd =' => $this->Auth->user('area_cd')]
]);
$entity_count[2] = $query->count();
$this->set(compact('entity_count'));
// View
<?= $entity_count[0] ?>
The query to use would be a nested query, assigned to an array. Then you can access the values from there.
In particular, you would want to write something like:
$result = List();
$result->query('SELECT COUNT(SELECT * FROM usertable), COUNT(SELECT * FROM partnertable), COUNT(SELECT * FROM customertable)');
To then access the values, you would refere to $result based on the position in the array, ie. $result[0] would be the first value, $result[1] the second and so on.
If you need to specify the items for the counts (such as active users, active customers etc) add where clauses into the select statements within the count expression
Eg. SELECT * FROM usertable WHERE active="yes"
Once you have the data you need, you can then edit the source file where you require them to be displayed and decide where to place them using a php echo to the html stream

Implement tab view with sorting and pagination in Yii

Am trying to bring a tab view with list , sorting and pagination in Yii. I have 2 tables named service_request and favourites where the datas come from. In that page I need to display the service request and favourites added date and some other fields. I tried to implement it with join , but it is not successfully listing the datas from service request. In my controller action I had added
$criteria = new CDbCriteria;
$criteria->select = 'favourite_notes,s.service_request_id';
$criteria->join = 'LEFT JOIN service_request s ON service_request_id = 1';
$criteria->condition = 'favourite_type = 1';
$data=new CActiveDataProvider('ProviderFavourite',array('criteria'=>$criteria,'pagination'=>array('pageSize'=>1)
));
$this->renderPartial('viewtest', array(
'ModelInstance' => ProviderFavourite::model()->findAll($criteria),
'dataProvider'=>$data,
));
In viewtest I had provided,
$this->widget('zii.widgets.CListView', array('dataProvider'=>$dataProvider,'itemView'=>'view',
'id'=>'request-list',
'template' => ' {items}{pager}',
));
In view page, I had fetched the data
echo $data->service_request;
echo $data->favourite_notes;
All your suggestions are welcome..
You can build your own function for sorting using CDBCriteria
at model side you can orderby and orderById pass through get or post
$criteria=new CDbCriteria;
$criteria->alias='b';
$criteria->order='b.'.$orderById.' '.$orderBy.',b.type asc,b.smallimage desc';
$dataProvider=new CActiveDataProvider($this->tableName(), array(
'criteria' => $criteria,
'pagination'=>array(
'pageSize'=>$limit,
),
));
Now at view side you can do like here Web pager is pagination class and extrapara is array of parameter those need for pagination
$this->widget('application.extensions.WebPager',
array(
'cssFile'=>false,
'pages' => $pagination,
'extraPara'=>$extraPara,
'id'=>'link_pager'
));

How can I insert data from a table from sql into a dropdown list in zend framework 2?

I need to insert multioptions to a dropdown list, options taken from a table from my database.
I created the elements like:
$this->add(array(
'name' => 'company',
'type' => 'Zend\Form\Element\Select',
//'multiOptions'=> $options,
'options' => array(
'label' => 'Company',
),
'attributes' => array(
'style' => "float:right;",
),
));
I want to choose from a dropdown list some values that are in a table in my database. For example I have the entity Contacts and I need to choose for the contact a company that is in a table named companies in the database.
After reading on zend framework's site, I tried using this code:
$params = array(
'driver'=>'Pdo_Mysql',
'host'=>'localhost',
'username'=>'root',
'password'=>'',
'dbname' =>'myDataBase'
);
$db = new \Zend\Db\Adapter\Adapter($params);
$sql= new Sql($db);
$select = $sql->select();
$select ->from('companies')
->columns(array('id','company_name'))
->order(" 'company_name' ASC");
I also read on some other sites that I could use a function:
$options = $sql->fetchPairs('SELECT id, name FROM country ORDER BY name ASC');
but it seems it doesn't exist anymore in Zend Framework 2.
Please guys, give me a hand. If the code isn't good and you have a better idea, please tell me.
Thanks in advance!
This is just a quick and dirty answer, but i guess it can get you started.
Create a ServiceFactory, this should be done in a separate factory class instead of a closure, but i still use a closure - faster to write ;)
Get the config from the ServiceLocator so you have access to the DB-Params
Create your default SQL Stuff to retriefe the value_options
Populate the value_options using the setValueOptions($valueOptions) function of your given form-element
Module.php getServiceConfig()
return array(
'factories' => array(
'my-form-factory' => function($serviceLocator) {
$form = new My\Form();
$config = $serviceLocator->get('config');
$db = new \Zend\Db\Auth\Adapter\Adapter($config['dbParams']); //or whatever you named the array key
$sql = //do your SQL Stuff
// This is a fake array, it should be your $sql result in the given format
$result = array('value' => 'label', 'value2' => 'label2');
$form->get('elementToPopulate')->setValueOptions($result);
return $form;
}
)
);
SomeController.php someAction()
$form = $this->getServiceLocator()->get('my-form-factory');
return new ViewModel(array(
'form' => $form
));
I hope this gets you started
you have to add that field validation on controller for setting value in it.
$select = $db->select()->where("state_code = ?",$arr["state_code"]);
$resultSet = $cityObj->fetchAll($select);
$cityArr = $resultSet->toArray();
$city_ar = array();
foreach($cityArr as $city){
$city_ar[$city['id']] = $city['company'];
}
$form->company->setMultiOptions($city_ar);
$form->company->setValue($val["company"]);
by using this code drop down of country have the value that are in resultset array ($resultSet).

Parsing External Table Arguments in Wordpress

I have a client project that has posts assigned to their country of origin.
The client wants to be able to search the posts by continent and or region.
I have a separate table that assigns each country to its respective region, and I have the WP query that uses the resulting array:
$country_names = array('England','France','Germany',...); // this would be the result from fetching countries associated with a region.
$args = array(
'posts_per_page' => -1,
'meta_query' => array(
array(
'key' => 'country',
'value' => $country_names,
'compare' => 'IN'
)
)
);
$query = new WP_Query( $args );
What I'm having trouble with is the part in the middle. Normally, I'd use some standard PHP/MySQL to craft the array:
<?php
//Process incoming variable
if(!empty($_REQUEST['region'])){
$region = $_REQUEST['region'];
} else {
$region = NULL;
}
// Make a MySQL Connection
$query = "SELECT * FROM regions WHERE region='$region'";
$result = mysql_query($query) or die(mysql_error());
$row = mysql_fetch_array($result) or die(mysql_error());
echo $row['country'];
?>
However, I'm having trouble making it work within a WP template, since WP manages the incoming variables using its own internal functions.
Can anyone help me to connect the two together? I'm sure I'm overlooking some simple step here, or else I'm not using some built-in WP function.
Any help is appreciated.
Thanks!
ty
Add this in your functions.php
add_filter( 'query_vars', 'addnew_query_vars', 10, 1 );
function addnew_query_vars($vars)
{
$vars[] = 'region'; // region is the variable you want to add
$vars[] = 'anotherVar';
return $vars;
}
Then get it
$region=get_query_var('region')
Update
$regions = $wpdb->get_results("SELECT ".$region." FROM `".$wpdb->regions."`");
if($regions)
{
foreach($regions as $region)
{
// your code
}
}

Codeigniter - How to get records from database where one fields value is more than another?

In my database I have two columns named 'amount_raised' and 'funding_goal'.
I would like to get all records from my database where the 'amount_raised' is equal to or more than the 'funding_goal'.
I am using Codeigniters active record. This is what I have so far:
function get_recently_successful($limit, $offset){
$data = '';
$this->db->order_by('date','desc');
$this->db->where('published', '1');
$this->db->where('amount_raised >=', 'funding_goal');
$query = $this->db->limit($limit, $offset)->get('projects');
foreach ($query->result() as $row) {
$data[] = array(
'id' => $row->id,
'date' => $row->date,
'project_title' => $row->project_title,
);
}
return $data;
}
The code above just returns all values in the database. Not how I specified it with where. How can I make it work??
Try this instead.
$this->db->where('amount_raised >= funding_goal');
Right now you send the value 'funding_goal' through the query, thus making it:
WHERE amount_raised >= 'funding_goal'
You want it compare with a column and not a string:
WHERE amount_raised >= funding_goal
You can always troubleshoot your query by inserting:
echo $this->db->last_query();
After the $query = row.
If you are using multiple condition in array, you can try the below as well:
$this->db->where(array('status' => 'Active', 'category' => $catId));
You can use another condition as well like this:
$this->db->where('amount_raised >= funding_goal');
You can use the last_query() to see the sql query as well to understand it.