Adding a new custom field/column to the content admin - php

I've been able to add an element to the bottom of the table. Although I am unsure how you ADD a coloumn into the body of the table?
function seven_form_alter(&$form, &$form_state, $form_id) {
drupal_set_message("Form ID is : " . $form_id);
//get node_admin_content
//$nodeAdmin = drupal_get_form("node_admin_content");
// Add a checkbox to registration form about agreeing to terms of use.
$form['node_admin_content']['poland'] = array(
'#type' => 'checkbox',
'#title' => t("I agree with the website's terms and conditions."),
'#required' => TRUE,
);
}

The table is built by node_admin_nodes() and comes in a nice render array so you can override it:
// Get the header array and add your new column header
$header = $form['admin']['nodes']['#header'];
$header['new_column'] = array('data' => 'New Col Header');
$form['admin']['nodes']['#header'] = $header;
// Get the table rows and add your new column to each.
// The function used to output the table depends on the user permissions
// so you need to check what type of object is being rendered.
if (isset($form['admin']['nodes']['#options'])) {
$row_key = '#options';
}
else {
$row_key = '#rows';
}
$rows = $form['admin']['nodes'][$row_key];
foreach ($rows as $nid => $row) {
$form['admin']['nodes'][$row_key][$nid]['new_column'] = array('data' => 'Text');
}

Related

In Drupal, if a field is empty, then use another field as the return. proper syntax?

I have come across a problem that I hope is an easy fix but I am just not seeing it. I have wrote some code that targets a certain content type's field.. in that field if it is empty then I want the code to return the value of another field in that content type. I have reworked this several times but I am stuck. I am hoping someone can point out what I am doing wrong. Thanks
Here is the code:
function randomname_preprocess_node__events__sfa_teaser(&$variables) {
// Populates the title variable from the node revision being viewed.
$route_match = \Drupal::routeMatch();
$node = $route_match->getParameter('node');
if ($node) {
if (is_string($node)) {
$node = Node::load($node);
}
$content_type = $node->getType();
if ($content_type === 'randomcontenttypename') {
$parent_title = $node->title->value;
$generic_link = $node->get('field_generic')->uri;
$populated_link_text = $node->get('field_populated_link_text')->value;
if ($entity->get('populated_link_text')) {
$populated_link_text = $entity->get('populated_link_text')->entity;
$variables['populated_link_text'] = [
'#type' => 'link',
'#title' => $populated_link_text->value,
'#url' => $populated_link_text,
];
}
else {
if ($generic_link) {
$generic_link = Url::fromUri($generic_link);
$variables['generic_link'] = [
'#type' => 'link',
'#url' => $generic_link,
'#title' => t('This page will display #parent_title', ['#parent_title' => $parent_title]),
'#attributes' => ['class' => 'viewalllink'],
];
}
$variables['#cache']['max-age'] = 0;
}
}
}
thanks for any help that can be tossed my way.

How do I implement search filter query using mongodb?

i have few search filter user like the following image. User can select any one two or both
these are my filters language,format and status I have written a query but its not working
$lang_id =2;
$format = ''; //user not selected
$status = ''; //user not selected
$request = $collection->find(array
( '$and' => array(
array(
'language' => $lang_id ,
),
array(
'format' => $format,
),
array(
'status' => $status,
)
)
));
I have check with or also then also its not working
if filters are empty no need to find the empty field but if it is not empty need to find the field .
Please give me a solution I am new in mongodb
Thank you
As a solution to above mentioned issue please try executing following code snippet
$lang_id = 2;
$format = ''; //user not selected
$status = ''; //user not selected
$filter=array();
if(!empty($lang_id))
{
$filter['language']=$lang_id;
}
if(!empty($format))
{
$filter['format']=$format;
}
if(!empty($status))
{
$filter['status']=$status;
}
$request = $collection->find($filter);

get all currencies available for website/store in magento

thanks for reading, I'm new to magento. I'm working on api application,so if I have the website id how can I get all available currencies for this website and same thing if I have store id
any idea will be appreciated
try this one:
$CurrencyCode = Mage::getModel('core/config_data')
->getCollection()
->addFieldToFilter('path','currency/options/allow')
->addFieldToFilter('scope_id',<you store id>)
->getData();
$currencies_array = explode(',',$CurrencyCode[0]['value']);
if($currencies_array[0] == '')
{
$currencies_array[]= Mage::app()->getStore($site_id)->getCurrentCurrencyCode();
}
echo "<pre>";print_r($currencies_array);echo "</pre>";
where should be replaced by store id.
Remember, if you have not set value for specific store, you need to pass 0 (default store scope id).
Try following, haven't tested it.
$currencies = array();
$codes = Mage::app()->getStore()->getAvailableCurrencyCodes(true);
if (is_array($codes) && count($codes) > 1) {
$rates = Mage::getModel('directory/currency')->getCurrencyRates(
Mage::app()->getStore()->getBaseCurrency(),
$codes
);
foreach ($codes as $code) {
if (isset($rates[$code])) {
$currencies[$code] = Mage::app()->getLocale()
->getTranslation($code, 'nametocurrency');
}
}
}
echo "<pre>";
print_r($currencies);
You can try this to get allowed currencies:
$CurrencyCode = Mage::getStoreConfig('currency/options/allow');
Please let me know if you need more help.
I needed some currencies for a drop down on a custom grid. To get the list of currencies used in all stores and render a drop down, this worked for me in Grid.php
$stores = Mage::app()->getStores();
foreach($stores as $store) {
$currency = Mage::getStoreConfig('currency/options/allow', $store);
$currencies[$currency] = $currency;
}
$currencies = array_unique($currencies);
For the grid column:
$this->addColumn('currency', array(
'header' => Mage::helper('erp')->__('Currency'),
'align' => 'left',
'width' => '100px',
'index' => 'currency',
'type' => 'options',
'options' => $currencies,
));
I did not need the option labels of the currency names in long form, just the three letter codes.

Having issues with the from

I have an issue with the form. For some reason it does not populate the table I named About
Table info (About):
user_id,
aboutme_id,
about,
Table info (Users):
user_id,
...,
...,
...,
etc.
Form:
$this->addElement('textarea', 'description', array(
'label' => 'Body Content',
'required' => true,
'allowEmpty' => false,
));
Verification
public function onProcess()
{
// In this case, the step was placed before the account step.
// Register a hook to this method for onUserCreateAfter
if( !$this->_registry->user ) {
// Register temporary hook
Engine_Hooks_Dispatcher::getInstance()->addEvent('onUserCreateAfter', array(
'callback' => array($this, 'onProcess'),
));
return;
}
$user = $this->_registry->user;
$data = $this->getSession()->data;
$form = $this->getForm();
if( !$this->_skip && !$this->getSession()->skip ) {
if( $form->isValid($data) ) {
$values = $form->getValues();
$table = Engine_Api::_()->getDbtable('about', 'user');
$rName = $table->info('name');
$userTable = Engine_Api::_()->getDbtable('users', 'user')->info('name');
$select = $select
->setIntegrityCheck(false)
->from($userTable)
->joinLeft($userTable, "$userTable.user_id = $rName.user_id")
->where($userTable, "$userTable.user_id = $rName.user_id");
}
}
}
Any idea what is going on with this picture?
Try to test database table operations in a sample empty action of some controller using echo "<pre>"; print_r(); echo "</pre>"; die(); to debug results. You can also use $select->__toString() to get raw sql of constructed query.
Also take a look at /temporary/log/main.log for some notices/errors.

Is there a free PHP Wrapper or backend script for a JQUERY Grid Control (JQGRID or Datatables)

I am looking to implement a best-practice JQUERY grid control, with a PHP backend. I want it to be able to support large datasets, and inline cell editing.
I am struggling to find a PHP backend script which is integrated with the control and abstracts away the complexities of this stuff. I want to be able to implement a grid based on an underlying MYSQL table with a minimum of configuration. Really I can't be the only one who wants to be able to specify basic database details and table/sql and have an operating grid.
JQGrid has a paid PHP script backend you can use which sounds like what I want...only its expensive.
http://www.trirand.net/documentation/php/index.htm
There's also a cheaper thing trying to do the same thing, but it doesn't work.
http://azgtech.wordpress.com/2010/08/01/jqgrid-php-datagrid/
I've also looked at DataTables, but once you add the inline-editing capabilities, developing the PHP backend started becoming its own project.
I have spend ages researching this, and mucking about with various solutions.
Does anybody know of a powerful, free, easy to use solution which has a complete PHP backend script?
I've included some of the description of the paid JQGrid PHP control, which contains the kind of functionality I'm looking for.
JQGRid PHP
This is a brand new product created for PHP developers and teams that radically decreases development time with jqGrid and makes it fun and easy. The product will be offered with commercial licenses that will include fast and accurate technical support, source code and subscription based benefits.
Highlight points include:
- all functionality jqGrid has is supported
- no need for tricky javascript – everything is handled in PHP
- the PHP component automatically handles data retrieval, paging, sorting, searching and all CRUD operations (create, read, update, delete). No need for custom code.
- you can have a fully functional grid with just a few lines of PHP
- export to Excel is supported
- database engines supported: MySql, Postgre SQL, Microsoft SQL server
Have you checked out phpGrid. It's a PHP jqgrid wrapper. It just two lines of code to get started. Is that something you are looking for?
$dg = new C_DataGrid(“SELECT * FROM orders”, “orderNumber”, “orders”);
$dg -> display();
I wrote this small library a while back as a a booze filled weekend project a while ago, it's a bit messy but it'll provide some of the default back end functionality that you're looking for.]
<?php
/*
Grid.php
Lirbary of function for the translation of Array() objects into json
*/
/*--- INCLUDE DEPENDENCIES ---*/
include_once "lib/sql.php";
/*--- HEADER UPDATE ---*/
header("Content-type: application/json");
/*--- GLOBALS ---*/
/*Default sort order*/
define('GRID_DEFAULT_SORT_ORDER', "ASC");
/*Default page index*/
define('GRID_DEFAULT_PAGE', 0);
/*Default results per page*/
define('GRID_DEFAULT_RP', 15);
/*--- FUNCTIONS ---*/
/*
Build Grid Queries
desc: Build the queries used to provide the grid results
params:
$select: 2D associative array
field: name of field
alias: field alias
$from: table data is to be selected from
return: An array containing the query to select entries and the query to get the result count
*/
function buildGridQueries($select, $from)
{
/*Create select statement*/
$selectStr = "SELECT ";
for($i = 0; $i < count($select);$i++){
/*append field name to str*/
$selectStr .= $select[$i]['field'];
/*If an alias has provided*/
if(isset($select[$i]['alias']))
$selectStr .= " AS '". $select[$i]['alias']. "'";
/*if current field is not the last */
if($i < count($select) - 1)
$selectStr .= ", ";
}
/*Create from statement*/
$fromStr = " FROM $from";
/*Set sort by value by $_POST value if available or by $select[0][field]*/
$sortStr = " ORDER BY ";
if(isset($_POST['sortname']))
if($_POST['sortname'] == "undefined")
$sortStr .= $select[0]['field'];
else
$sortStr .= $_POST['sortname'];
else
$sortStr .= $select[0]['field'];
/*Set sort order by $_POST if available or by ASC*/
if(isset($_POST['sortorder']))
$sortStr .= " ". $_POST['sortorder'];
else
$sortStr .= " ". GRID_DEFAULT_SORT_ORDER;
/*Set query conditional WHERE statement if passed*/
$queryStr = "";
if(isset($_POST['qtype'])&&isset($_POST['query']))
if($_POST['query']!= "")
$queryStr .= " WHERE ". $_POST['qtype']. " LIKE '%" . $_POST['query']. "%' ";
/*Create limit statement by passed values or by defaults*/
$limitStr = " LIMIT ";
if(isset($_POST['page']))
if($_POST['rp'])
$limitStr .= ($_POST['page'] - 1) * $_POST['rp'] . ",". $_POST['rp'];
else
$limitStr .= $_POST['page'] . ", ". GRID_DEFAULT_RP;
else
$limitStr .= GRID_DEFAULT_PAGE. ", ". GRID_DEFAULT_RP;
/*return queries array*/
return Array("query" => $selectStr. $fromStr. $queryStr. $sortStr. $limitStr,
"count" => "SELECT COUNT(id) AS 'total' $fromStr $queryStr ");
}
/*
Commit Data
desc: Commit data edits (Passed by a client side flexigrid object
params:
$table: table name
$rows: rows array of data to be committed
$index: Field name of index column, used in where statement
return: An array of update results for each passed row;
*/
function commitGridData($table,$rows,$indexField, $sqlConnection)
{
/*Declare return array*/
$return = Array();
/*With every row which is to be committed*/
foreach($rows as $row){
/*Create update statement base and iterate through cells*/
$statement = "UPDATE $table SET ";
for($i = 0;$i<count($row['fields']);$i++){
/*If value is a string check to see if it's a date*/
if(!is_numeric( $row['fields'][$i]['value'])){
/*Encapsulate str it isn't a date, convert to time if it is*/
$val = "'". $row['fields'][$i]['value']. "'";
}else
$val = $row['fields'][$i]['value'];
/*Append field name and value to statement*/
$statement .= $row['fields'][$i]['field'] . "=". $val;
/*Append delimiter to the statement if this cell is not the last in $orw*/
if($i<count($row['fields']) - 1)
$statement .= ", ";
}
if($row['entryIndex'] < 0)
$row['entryIndex'] = mysqlCreateEntry($table, $sqlConnection);
/*Append where statement*/
$statement .= " WHERE $indexField = ". $row['entryIndex'];
/*Update row information*/
$return[] = Array("id" => $row['tableId'], "success" => mysqlQuery($statement, $sqlConnection), "error" => mysql_error());
}
/*Return result set*/
return $return;
}
/*
Generate Grid Array
desc: generate Array object which is compatible with FlexiGrid when it is json encoded
params:
$queries: Queries for retrieving data entries and result set size
$fields: 2D associative array or false to prevent inline generation
field: name of field
alias: field alias
$sql: An Sql connection identifier
return: An array of FlexiGrid properties
*/
function generateGridArray($queries, $fields, $sqlConnection)
{
/*Get the total number of results matching the search query*/
$res = mysqlQuery($queries['count'], $sqlConnection);
$total = mysql_fetch_assoc($res);
/*Get matching result set*/
$res = mysqlQuery($queries['query'], $sqlConnection);
/*Create result FlexGrid-compatible Array*/
$data =Array(
"page" => (isset($_POST['page']))? $_POST['page']: 1,
"total" => $total['total'],
"width" => 500,
"height" => (isset($_POST['rp']))? $_POST['rp']: mysql_num_rows($res) * 20 + 45,
"title" => " ",
"propertyCount" => count($fields),
"rows" => sqlToGridRows($fields, $res));
/*If initial request (no $_POST equals passive data collection by the client side*/
if(count($_POST) < 1 ){
$data['colModel'] = sqlToGridColModel($fields, $res);
$data['searchitems'] = arrayToGridSearchItems($fields);
}
/*Return*/
return $data;
}
function sqlToGridRows($fields, $sqlResult)
{
/*Identify the entry index column*/
$fieldTypes = Array();
foreach($fields as $field){
/*if the field is the entry index*/
if(isset($field['entryIndex']))
/*Set field as entryIndex*/
$entryIndexCol = (isset($field['alias']))? $field['alias']: $field['field'];
}
/*Iterate through result set*/
$return = Array();
for($i = 0;$i < mysql_num_rows($sqlResult);$i++){
/*Get entry data*/
$row = mysql_fetch_assoc($sqlResult);
/*modify values based on fieldType*/
foreach($fields as $field){
/*If the fieldType value is set, no changes otherwise*/
if(isset($field['fieldType'])){
/*Field type specific formating*/
switch ($field['fieldType']){
/*Format field as a date*/
case "date":
/*Update by either field label if the label key exists in row or use alias*/
if(isset($row['field']))
$row[$field['field']] = date("d/m/Y", $row[$field['field']]);
else
$row[$field['alias']] = date("d/m/Y", $row[$field['alias']]);
break;
case "time":
if(isset($row['field']))
$row[$field['field']] = date("H:i", $row[$field['field']]);
else
$row[$field['alias']] = date("H:i", $row[$field['alias']]);
break;
}
}
}
/*if the entry index column was identified*/
if(isset($entryIndexCol)){
/*Set entryIndex value*/
$entryIndex = $row[$entryIndexCol];
/*remove the entryIndexCol from the row*/
unset($row[$entryIndexCol]);
}else
/*Set the entry index as the default*/
$entryIndex = $i;
/*Create entry*/
$entry = Array("id" => $i,
"entryIndex" => $entryIndex,
"cell" => $row);
/*iterate $fields and replace aliased keys with field names*/
for($m = 0;$m < count($fields);$m++){
/*if field has an alias update the key value*/
if(isset($fields[$m]['alias'])){
/*Replace and rebuild field->cell*/
$cell = Array();
foreach($entry['cell'] as $key => $val){
/*if culprit cell change key*/
if($key == $fields[$m]['alias'])
$cell[$fields[$m]['field']] = $val;
else
$cell[$key] = $val;
}
/*Update entry->cell value*/
$entry['cell'] = $cell;
}
}
/*Map sql result to grid table row structure*/
$return[] = $entry;
}
/*Return grid-ready array*/
return $return;
}
function sqlToGridColModel($fields, $sqlResult)
{
/*Iterate through result set*/
$return = Array();
for($i = 0;$i < mysql_num_fields($sqlResult);$i++){
/*Replace aliased cell name attributes with associted field name*/
$alias = mysql_field_name($sqlResult, $i);
$name = false;
$isEntryIndex = false;
for($m = 0;$m < count($fields);$m++){
/*If current field has an alias which equals $name, replace name with $field[[$m]['field']*/
if(isset($fields[$m]['alias'])){
/*if field has an alias*/
if($fields[$m]['alias'] == $alias){
$name = $fields[$m]['field'];
}
}else{
if($fields[$m]['field'] == $alias){
$name = $fields[$m]['field'];
}
}
/*Add field data etc*/
$fieldData = false;
if(isset($fields[$m]['fieldType'])){
/*Get field type*/
$fieldType = $fields[$m]['fieldType'];
/*Attach select options to field if available*/
if($fieldType == "select")
/*Set default field type*/
$fieldData = $fields[$m]['fieldData'];
}else
$fieldType = "input";
/*If the field is the entry index flag it for exclusion*/
if($name){
/*If the field is the entry index*/
if(isset($fields[$m]['entryIndex']))
$isEntryIndex = true;
/*Exit for loop*/
$m = count($fields);
}
}
/*If no name was set (alias is also name)*/
if(!$name)
$name = $alias;
/*If the field is to be included in the column model*/
if($isEntryIndex == false){
/*Append column data to return*/
$return[] = Array("display" => $alias, "name" => $name,
"width" => 200, "sortable" => "true",
"fieldType" => $fieldType, "fieldData" => $fieldData);
}
}
/*Return grid-ready array*/
return $return;
}
function arrayToGridSearchItems($fields)
{
/*iterate fields*/
$return = Array();
for($i = 0;$i < count($fields);$i++){
/*if field has an alias use it for the display name*/
$alias = (isset($fields[$i]['alias']))? $fields[$i]['alias']: $fields[$i]['field'];
/*If field is not the entry index*/
if(!isset($fields[$i]['entryIndex']))
/*Create searchitem and append to return*/
$return[] = Array("display" => $alias,
"name" => $fields[$i]['field'],
"isdefault" => ($i == 0)? "true": "false");
}
/*return*/
return $return;
}
?>
This is designed to allow the development of Grid data tables using a standard template, Below is an example template.
<?php
/*include grid lib*/
include "lib/grid.php";
/*Create sql connection*/
$sqlConnection = mysqlConnect($_USER->sqlUser, $_USER->sqlPass);
/*----------------------*/
/*--- Create fieldData ---*/
$userTypes = Array(
Array("value" =>0, "text" => "Staff"),
Array("value" => 1, "text" => "Manager"));
/*----------------------*/
/*---
Define selection array
Create field selection and rules Array. Defines output.
---*/
$array = Array();
$array[] = Array("field" => "id", "entryIndex" => true); /*Entry index is the Sql row id, isn't show in table but is used for commits*/
$array[] = Array("field" => "username", "alias" => "User Name");
$array[] = Array("field" => "name", "alias" => "Name");
$array[] = Array("field" => "address", "alias" => "Address");
$array[] = Array("field" => "postcode", "alias" => "Postcode");
$array[] = Array("field" => "tel", "alias" => "Telephone");
$array[] = Array("field" => "mobile", "alias" => "Mobile");
$array[] = Array("field" => "email", "alias" => "Email Address");
$array[] = Array("field" => "user_type", "alias" => "User Type", "fieldType" => "select", "fieldData" => $userTypes);
$table = "staff";
/*---
Commit data template
Inlcude a the following if
---*/
/*If an action is to be carried out prior to data load*/
if(isset($_GET['method'])){
/*If transaction is a data commit*/
if($_GET['method'] == "commit"){
/*Check that edit requests were sent*/
if(isset($_POST['rows'])){
/*Pre-update validation*/
foreach($_POST['rows'] as &$row){
/*Any preprocessing for entries prior to commit*/
}
echo json_encode(commitGridData($table, $_POST['rows'], "id", $sqlConnection));
exit;
}
}
}
/*Buildd queries - Opportunity to debug queries, alternatively pass to generateGridArray*/
$queryStrs = buildGridQueries($array, "staff");
/*Generate grid data*/
$resArray = generateGridArray($queryStrs, $array, $sqlConnection);
/*Pre grid build extend and/or alter settings*/
if(count($_POST) < 1){
$resArray['buttons'] = Array(Array("name" => "Add", "bclass" => "add", "onpress" => "add"));
$resArray['title'] = "Staff Details";
$resArray['editable'] = true;
}
echo json_encode($resArray);
exit;
?>
I've extended Flexgrid to accommodate for field formatting, committing data and adding field events but I can't for the life of me find it. I'll post it if I do.
Disclaimer: $_POST is used recklessly throughout grid.php. It is recommended that it's replaced with something more fitting.
I've just found a github project which seems to be really great for this: https://github.com/lampjunkie/php-datatables
It provides a wrapper for Jquery Datatables plugin, handles the initial setup and the ajaq data feeds also. It has an object-oriented approach and seems to be very logically designed.
You also can find an example project in the package.

Categories