drupal table with the edit link - drupal

I have a table in drupal which displays all the content from a table. I have added an edit link to each record . This link should take the user to the input form which has the values populated in it corresponding to the record. RIght now it is just populating the form with the last row.
For a row x, i need the form populated with the values for record x.
The table is created as
function _MYMODULE_sql_to_table($sql) {
$html = "";
// execute sql
$resource = db_query($sql);
// fetch database results in an array
$results = array();
while ($row = db_fetch_array($resource)) {
$results[] = $row;
$email = $row['p1'];
$comment = $row['p2'];
}
// ensure results exist
if (!count($results)) {
$html .= "Sorry, no results could be found.";
return $html;
}
// create an array to contain all table rows
$rows = array();
// get a list of column headers
$columnNames = array_keys($results[0]);
// loop through results and create table rows
foreach ($results as $key => $data) {
// create row data
$row = array(
'edit' => l(t('Edit'),"admin/content/test/$p1/$p2/Table1", $options=array()),);
// loop through column names
foreach ($columnNames as $c) {
$row[] = array(
'data' => $data[$c],
'class' => strtolower(str_replace(' ', '-', $c)),
);
}
// add row to rows array
$rows[] = $row;
}
// loop through column names and create headers
$header = array();
foreach ($columnNames as $c) {
$header[] = array(
'data' => $c,
'class' => strtolower(str_replace(' ', '-', $c)),
);
}
// generate table html
$html .= theme('table', $header, $rows);
return $html;
}
// then you can call it in your code...
function _MYMODULE_some_page_callback() {
$html = "";
$sql = "select * from {contactus}";
$html .= _MYMODULE_sql_to_table($sql);
return $html;
}
function display(){
$results = array();
$html = "";
$resource = db_query("select * from contactus");
$output = '';
while($row = db_fetch_array($resource)){
$results[] = $row;
}
if(!count($results)){
$html.= "Unable to display table";
return $html;
}
$rows = array();
$columnNames = array_keys($results[0]);
foreach($results as $key=>$data){
$row = array();
foreach($columnNames as $c){
$row = array(
'data' => $data[$c],
'class' => strtolower(str_replace(' ', '-', $c)),
);
}
$rows[] = $row;
}
$header = array();
foreach($columnNames as $c){
$header[] = array(
'data' => $c,
'class' => strtolower(str_replace(' ', '-', $c)),
);
}
$html .= theme('table', $header, $rows);
return $html;
}

You'll want to have $rows = array(); appear before your while loop. What you're doing is essentially destroying the array and redeclaring it as an empty array on each pass. This is why only the last row is appearing for you.

Related

How to export image in excel file from mysql database dynamically

I want to export image from mysql database into an excel file using phpexcel.I have done it with static value but can not do it dynamically.
<?php
include ('config.php');
function my_constants(){
$url = 'http://' . $_SERVER['HTTP_HOST'] . "/phpexcel_gd/";
$path = $_SERVER['DOCUMENT_ROOT'] . '/phpexcel_gd/';
define('SITEURL', $url);
define('SITEPATH', str_replace('\\', '/', $path));
}
function report_details($display = null) {
if($display){
$imagePath = SITEURL . "images/";
} else {
$imagePath = SITEPATH . "images/";
}
// $select_query = mysqli_query($conn,"SELECT orderid, image_name,image_path FROM tbl_order_details WHERE orderid = '240419-0001-A1-B1'");
// $select_query_row = mysqli_fetch_array($select_query);
// $orderid = $select_query['orderid'];
// $image_name= $select_query['image_name'];
// $image_path = $select_query['image_path'];
$reportdetails = array(
// array('Image' => $image_path . $image_name,'orderid' => $orderid),
array('BrandIcon' => $imagePath . "github.png",'Comapany' => "Github",'Rank' => "3",'Link' => "https://github.com/"),
array('BrandIcon' => $imagePath . "bootstrap.png",'Comapany' => "Bootstrap",'Rank' => "4",'Link' => "http://getbootstrap.com/"),
array('BrandIcon' => $imagePath . "so-icon.png",'Comapany' => "Stack Overflow",'Rank' => "3",'Link' => "http://stackoverflow.com/"),
);
return $reportdetails;
}
/**
* Create excel by from ajax request
*/
function xlscreation_ajax() {
$reportdetails = report_details();
require_once SITEPATH . 'PHPExcel/Classes/PHPExcel.php';
$objPHPExcel = new PHPExcel();
$objPHPExcel->getProperties()
->setCreator("user")
->setLastModifiedBy("user")
->setTitle("Office 2007 XLSX Test Document")
->setSubject("Office 2007 XLSX Test Document")
->setDescription("Test document for Office 2007 XLSX, generated using PHP classes.")
->setKeywords("office 2007 openxml php")
->setCategory("Test result file");
// Set the active Excel worksheet to sheet 0
$objPHPExcel->setActiveSheetIndex(0);
// Initialise the Excel row number
$rowCount = 0;
// Sheet cells
$cell_definition = array(
'A' => 'BrandIcon',
'B' => 'Company',
'C' => 'Rank',
'D' => 'Link'
);
// Build headers
foreach( $cell_definition as $column => $value )
{
$objPHPExcel->getActiveSheet()->getColumnDimension("{$column}")->setAutoSize(true);
$objPHPExcel->getActiveSheet()->setCellValue( "{$column}1", $value );
}
// Build cells
while( $rowCount < count($reportdetails) ){
$cell = $rowCount + 2;
foreach( $cell_definition as $column => $value ) {
$objPHPExcel->getActiveSheet()->getRowDimension($rowCount + 2)->setRowHeight(35);
switch ($value) {
case 'BrandIcon':
if (file_exists($reportdetails[$rowCount][$value])) {
$objDrawing = new PHPExcel_Worksheet_Drawing();
$objDrawing->setName('Customer Signature');
$objDrawing->setDescription('Customer Signature');
//Path to signature .jpg file
$signature = $reportdetails[$rowCount][$value];
$objDrawing->setPath($signature);
$objDrawing->setOffsetX(25); //setOffsetX works properly
$objDrawing->setOffsetY(10); //setOffsetY works properly
$objDrawing->setCoordinates($column.$cell); //set image to cell
$objDrawing->setWidth(32);
$objDrawing->setHeight(32); //signature height
$objDrawing->setWorksheet($objPHPExcel->getActiveSheet()); //save
} else {
$objPHPExcel->getActiveSheet()->setCellValue($column.$cell, "Image not found" );
}
break;
case 'Link':
//set the value of the cell
$objPHPExcel->getActiveSheet()->SetCellValue($column.$cell, $reportdetails[$rowCount][$value]);
//change the data type of the cell
$objPHPExcel->getActiveSheet()->getCell($column.$cell)->setDataType(PHPExcel_Cell_DataType::TYPE_STRING2);
///now set the link
$objPHPExcel->getActiveSheet()->getCell($column.$cell)->getHyperlink()->setUrl(strip_tags($reportdetails[$rowCount][$value]));
break;
default:
$objPHPExcel->getActiveSheet()->setCellValue($column.$cell, $reportdetails[$rowCount][$value] );
break;
}
}
$rowCount++;
}
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
$saveExcelToLocalFile = saveExcelToLocalFile($objWriter);
$response = array(
'success' => true,
'filename' => $saveExcelToLocalFile['filename'],
'url' => $saveExcelToLocalFile['filePath']
);
echo json_encode($response);
die();
}
function saveExcelToLocalFile($objWriter) {
$rand = rand(1234, 9898);
$presentDate = date('YmdHis');
$fileName = "report_" . $rand . "_" . $presentDate . ".xlsx";
// make sure you have permission to write to directory
$filePath = SITEPATH . 'reports/' . $fileName;
$objWriter->save($filePath);
$data = array(
'filename' => $fileName,
'filePath' => $filePath
);
return $data;
}
?>
Here the $reportdetails contains the static array. How can I pass the mysql database value to the array dynamically? Please suggest any alternative other than phpexcel.

Use delete_user_meta

I want to delete my usermeta in table database but give nothing. it give me an error because its not array expected string parameter
function remove_meta(){
$role = 'client'; //Select user role
$users = get_users('role='.$role);
global $wpdb;
$stats = $wpdb->get_results("
SELECT ".$wpdb->prefix." group_clients.client_id
FROM ".$wpdb->prefix." group_clients
WHERE ".$wpdb->prefix." group_clients.group_id IN (1, 2, 5, 6)
", $users); // Fetch data by selective group ID
$stats = array();
if (is_array($stats) || is_object($stats)){
//foreach ((array) $stats as $stat){
foreach ($stats as $stat) {
delete_user_meta($stat->ID, 'terms_and_conditions');
}
echo 'Fini!';
}
}
Try below code you are doing confusing code. Do not do sql query unless it is really required.
$args = array(
'role' => 'customer', //client or whatever you required
);
//geting all user
$users = get_users( $args );
foreach ($users as $result)
{
//each user id
$userId = $result->ID;
if($userId != '')
{
//getting all user meta of particular user
$all_meta_for_user = get_user_meta( $userId );
if(is_array($all_meta_for_user))
{
foreach ($all_meta_for_user as $key => $value) {
$terms =get_user_meta($userid,'terms_and_conditions',true);
if($terms !=''){
delete_user_meta($userId, 'terms_and_conditions');
}
}
}
}
}
with hook
add_action('init','deletedata');
function deletedata()
{
if(!is_admin())
return;
if(!current_user_can('manage_options'))
return false;
$args = array(
'role' => 'customer', //client or whatever you required
);
//geting all user
$users = get_users( $args );
foreach ($users as $result)
{
//each user id
$userId = $result->ID;
if($userId != '')
{
//getting all user meta of particular user
$all_meta_for_user = get_user_meta( $userId );
if(is_array($all_meta_for_user))
{
foreach ($all_meta_for_user as $key => $value) {
# code...
$terms =get_user_meta($userid,'terms_and_conditions',true);
if($terms !=''){
delete_user_meta($userId, 'terms_and_conditions');
}
}
}
}
}
}

Create form dynamically in Symfony 2

A simple question:
I have one form, it returns one number and I need create this number of labels in Controller.
I try:
$form2 = $this->createFormBuilder();
for($i = 0; $i < $num; $i++) {
$name = 'column'.$i;
$form2->add($name,'number');
}
$form2->getForm();
I think it should very simple, but i can't..
Yes, you can do it with an array / hash map instead of a real object.
Here is an example :
// Create the array
$dataObj = array();
$dataObj['data1'] = '';
$dataObj['data2'] = 'default';
// ... do a loop here
$dataObj['data6'] = 'Hello';
// Create the form
$formBuilder = $this->createFormBuilder($dataObj);
foreach($dataObj as $key => $val)
{
$fieldType = 'text'; // Here, everything is a text, but you can change it based on $key, or something else
$formBuilder->add($key, $fieldType);
}
$form = $formBuilder->getForm();
// Process the form
$request = $this->get('request');
if($request->getMethod() == 'POST')
{
$form->bind($request); // For symfony 2.1.x
// $form->bind($this->get('request')->request->get('form')); // For symfony 2.0.x
if($form->isValid())
{
$dataObj = $form->getData();
foreach($dataObj as $key => $val)
{
echo $key . ' = ' . $val . '<br />';
}
exit('Done');
}
}
// Render
return $this->render('Aaa:Bbb:ccc.html.twig', array(
'requestForm' => $form->createView()));

Extending WP_List_Table / handling checkbox options in plugin administration

I'm working on a WordPress plugin, and part of that plugin requires extending WP_List_Table and storing any of the items which are checked in that table to an option. I've managed to figure out how to properly setup and display the required table, but how do I handle storing the checked options?
Here's what I've got so far...
class TDBar_List_Table extends WP_List_Table {
// Reference parent constructor
function __construct() {
global $status, $page;
// Set defaults
parent::__construct( array(
'singular' => 'theme',
'plural' => 'themes',
'ajax' => false
));
}
// Set table classes
function get_table_classes() {
return array('widefat', 'wp-list-table', 'themes');
}
// Setup default column
function column_default($item, $column_name) {
switch($column_name) {
case 'Title':
case 'URI':
case'Description':
return $item[$column_name];
default:
return print_r($item, true);
}
}
// Displaying checkboxes!
function column_cb($item) {
return sprintf(
'<input type="checkbox" name="%1$s" id="%2$s" value="checked" />',
//$this->_args['singular'],
$item['Stylesheet'] . '_status',
$item['Stylesheet'] . '_status'
);
}
// Display theme title
function column_title($item) {
return sprintf(
'<strong>%1$s</strong>',
$item['Title']
);
}
// Display theme preview
function column_preview($item) {
if (file_exists(get_theme_root() . '/' . $item['Stylesheet'] . '/screenshot.png')) {
$preview = get_theme_root_uri() . '/' . $item['Stylesheet'] . '/screenshot.png';
} else {
$preview = '';
}
return sprintf(
'<img src="%3$s" style="width: 150px;" />',
$preview,
$item['Title'],
$preview
);
}
// Display theme description
function column_description($item) {
if (isset($item['Version'])) {
$version = 'Version ' . $item['Version'];
if (isset($item['Author']) || isset($item['URI']))
$version .= ' | ';
} else {
$version = '';
}
if (isset($item['Author'])) {
$author = 'By ' . $item['Author'];
if (isset($item['URI']))
$author .= ' | ';
} else {
$author = '';
}
if (isset($item['URI'])) {
$uri = $item['URI'];
} else {
$uri = '';
}
return sprintf(
'<div class="theme-description"><p>%1$s</p></div><div class="second theme-version-author-uri">%2$s%3$s%4$s',
$item['Description'],
$version,
$author,
$uri
);
}
// Setup columns
function get_columns() {
$columns = array(
'cb' => '<input type="checkbox" />',
'title' => 'Theme',
'preview' => 'Preview',
'description' => 'Description'
);
return $columns;
}
// Make title column sortable
function get_sortable_columns() {
$sortable_columns = array(
'title' => array('Title', true)
);
return $sortable_columns;
}
// Setup bulk actions
function get_bulk_actions() {
$actions = array(
'update' => 'Update'
);
return $actions;
}
// Handle bulk actions
function process_bulk_action() {
// Define our data source
if (defined('WP_ALLOW_MULTISITE') && WP_ALLOW_MULTISITE == true) {
$themes = get_allowed_themes();
} else {
$themes = get_themes();
}
if ('update' === $this->current_action()) {
foreach ($themes as $theme) {
if ($theme['Stylesheet'] . '_status' == 'checked') {
// Do stuff - here's the problem
}
}
}
}
// Handle data preparation
function prepare_items() {
// How many records per page?
$per_page = 10;
// Define column headers
$columns = $this->get_columns();
$hidden = array();
$sortable = $this->get_sortable_columns();
// Build the array
$this->_column_headers = array($columns, $hidden, $sortable);
// Pass off bulk action
$this->process_bulk_action();
// Define our data source
if (defined('WP_ALLOW_MULTISITE') && WP_ALLOW_MULTISITE == true) {
$themes = get_allowed_themes();
} else {
$themes = get_themes();
}
// Handle sorting
function usort_reorder($a,$b) {
$orderby = (!empty($_REQUEST['orderby'])) ? $_REQUEST['orderby'] : 'Title';
$order = (!empty($_REQUEST['order'])) ? $_REQUEST['order'] : 'asc';
$result = strcmp($a[$orderby], $b[$orderby]);
return ($order === 'asc') ? $result : -$result;
}
usort($themes, 'usort_reorder');
//MAIN STUFF HERE
//for ($i = 0; i < count($themes); $i++) {
//}
// Figure out the current page and how many items there are
$current_page = $this->get_pagenum();
$total_items = count($themes);
// Only show the current page
$themes = array_slice($themes,(($current_page-1)*$per_page),$per_page);
// Display sorted data
$this->items = $themes;
// Register pagination options
$this->set_pagination_args( array(
'total_items' => $total_items,
'per_page' => $per_page,
'total_pages' => ceil($total_items/$per_page)
));
}
}
Problem is, I can't get it to save properly. I select the rows I want, hit save and it just resets.
I assume you are talking about the checkboxes in your table listing, so this will be how to process bulk actions.
All you need to do is add two new methods to your class and initialize it in the prepare_items method. I use the code below in one of my plugins to delete or export, but you can just as easily run an update.
/**
* Define our bulk actions
*
* #since 1.2
* #returns array() $actions Bulk actions
*/
function get_bulk_actions() {
$actions = array(
'delete' => __( 'Delete' , 'visual-form-builder'),
'export-all' => __( 'Export All' , 'visual-form-builder'),
'export-selected' => __( 'Export Selected' , 'visual-form-builder')
);
return $actions;
}
/**
* Process our bulk actions
*
* #since 1.2
*/
function process_bulk_action() {
$entry_id = ( is_array( $_REQUEST['entry'] ) ) ? $_REQUEST['entry'] : array( $_REQUEST['entry'] );
if ( 'delete' === $this->current_action() ) {
global $wpdb;
foreach ( $entry_id as $id ) {
$id = absint( $id );
$wpdb->query( "DELETE FROM $this->entries_table_name WHERE entries_id = $id" );
}
}
}
Now, call this method inside prepare_items() like so:
function prepare_items() {
//Do other stuff in here
/* Handle our bulk actions */
$this->process_bulk_action();
}
There's a fantastic helper plugin called Custom List Table Example that makes figuring out the WP_List_Table class much easier.

Drupal, CCK -- remove draggable reorder for non-admins

Is there a clean way to remove the draggable option on multiple-value CCK fields? I assume I could style it out with CSS but that doesn't seem like the "right" way to do it.
Ideally, the draggable option wouldn't be available for any users except admins.
It looks like the tabledrag stuff is being built in the cck theme functions - eg theme_content_multiple_values it's adding a 'draggable' class to the table rows, and calling
drupal_add_tabledrag on the table.
You should be able to override this in your theme/module(?) and add a fairly simple switch to test for users with an appropriate permission before adding the drag.
Thanks for the tip #Andrew. Here's what I ended up coming up with:
function stannes_content_multiple_values($element) {
global $user;
$field_name = $element['#field_name'];
$field = content_fields($field_name);
$output = '';
if ($field['multiple'] >= 1) {
$table_id = $element['#field_name'] .'_values';
$order_class = $element['#field_name'] .'-delta-order';
$required = !empty($element['#required']) ? '<span class="form-required" title="'. t('This field is required.') .'">*</span>' : '';
$header = array(
array( 'data' => t('!title: !required', array('!title' => $element['#title'], '!required' => $required)), 'colspan' => 2)
);
if ($user->uid == 1) {
$header[] = t('Order');
}
$rows = array();
// Sort items according to '_weight' (needed when the form comes back after
// preview or failed validation)
$items = array();
foreach (element_children($element) as $key) {
if ($key !== $element['#field_name'] .'_add_more') {
$items[] = &$element[$key];
}
}
usort($items, '_content_sort_items_value_helper');
// Add the items as table rows.
foreach ($items as $key => $item) {
$item['_weight']['#attributes']['class'] = $order_class;
$delta_element = drupal_render($item['_weight']);
if ($user->uid == 1) {
$cells = array(
array('data' => '', 'class' => 'content-multiple-drag'),
drupal_render($item),
array('data' => $delta_element, 'class' => 'delta-order'),
);
} else {
$cells = array(
drupal_render($item)
);
}
$rows[] = array(
'data' => $cells,
'class' => 'draggable',
);
}
$output .= theme('table', $header, $rows, array('id' => $table_id, 'class' => 'content-multiple-table'));
$output .= $element['#description'] ? '<div class="description">'. $element['#description'] .'</div>' : '';
$output .= drupal_render($element[$element['#field_name'] .'_add_more']);
if ($user->uid == 1) {
drupal_add_tabledrag($table_id, 'order', 'sibling', $order_class);
}
} else {
foreach (element_children($element) as $key) {
$output .= drupal_render($element[$key]);
}
}
return $output;
}

Resources