How to create select list with field_create_field($field) drupal 7 with options - drupal-7

How to create select list, radio buttons, checkboxes with field_create_field() and how to specify the options to be given in these fields

Run this code with the details for an existing field with the properties that you want to copy:
$entity_type = 'node';
$field_name = 'body';
$bundle_name = 'article';
$info_config = field_info_field($field_name);
$info_instance = field_info_instance($entity_type, $field_name, $bundle_name);
unset($info_config['id']);
unset($info_instance['id'], $info_instance['field_id']);
include_once DRUPAL_ROOT . '/includes/utility.inc';
$output = "field_create_field(" . drupal_var_export($info_config) . ");\n";
$output .= "field_create_instance(" . drupal_var_export($info_instance) . ");";
drupal_set_message("<textarea rows=30 style=\"width: 100%;\">". $output .'</textarea>');
That will produce the PHP code used to create the field/field instance. Then you just need to go through the code and make the changes for your new field/instance.

Related

Insert random username to SharePoint 2013 column from array PowerShell script

I wrote script to create N number of items to custom SharePoint list in PowerShell. I made it work with fixed values, but now I would like to create items with random values.
I created internal variables that are array of values and I would like out of those to be set in list columns.
I made it work for some simple columns like date, single and multi line of text, etc. But I can't seem to make it work for lookup and people picker values. Bellow is example of script I made.
For this example, I don't get error in PowerShell I just get incorrect result in columns, example is I get username in people picker column that is not in value userName array. I get ID;#User8 (for example) that is not in array.
If you have any suggestion what I should change or add to get only values from array?
Add-PSSnapin Microsoft.SharePoint.PowerShell -EA SilentlyContinue
$webUrl = "site url"
$listName = "list name"
$numberItemsToCreate = N
# userName is array of values of usernames that would be set to people picker column
$userName = ID;#user1, ID;#User2, ID;#User3, ID;#User6, ID;#User10
# projectName is array of values of projects that are lookup column from another list
$projectName = 1;#Project1, 2;#Project2, 3;#Project3, 4;#Project4
#
$web = Get-SPWeb $webUrl
$list = $web.Lists[$listName]
for($i=1; $i -le $numberItemsToCreate; $i++)
{
$newItem = $list.AddItem()
$newItem["Title"] = "Title"
$newItem["Project"] = (Get-Random $projectName)
$newItem["DueDate"] = "2017-12-12 00:00:00"
$newItem["Assigned_x0020_To"] = (Get-Random $userName)
$newItem["EstimatedFinishDate"] = "2017-12-12 00:00:00"
#$newItem["Status"] = "ToDo"
$newItem["URLs"] = "www.google.com"
$newItem.Update()
}
$web.Dispose()
This "$userName = ID;#user1, ID;#User2, ID;#User3, ID;#User6, ID;#User10" is not a PowerShell array or hashtable
Using an array:
$userName = #("#user1", "#User2", "#User3", "#User6", "#User10")
$newItem["Assigned_x0020_To"] = Get-Random $userName
Using a hashtable:
$projectName = #{1="#Project1"; 2="#Project2"; 3="#Project3"; 4="#Project4"}
$newItem["Project"] = $ProjectName.(Get-Random #($ProjectName.Keys))
Or just:
$newItem["Project"] = Get-Random #($ProjectName.Values)

Wordpress admin - Where in database is it set?

I'm looking to grab admin user emails to use within a contact form. I have 2 admins that I've assigned. I'd like to grab them from the database. Where is/what is the designation point that I can use when I make the sql statment?
You can do the following
global $wpdb;
//comma separated list
$admins=$wpdb->get_var('select group_concat(`user_email`) as `admin_emails` from `' . $wpdb->prefix . 'users` as `users` inner join `' . $wpdb->prefix . 'usermeta` as `usermeta` on `usermeta`.`user_id`=`users`.`ID` where `meta_key`=\'wp_user_level\' and `meta_value` in (8,9,10);');
//array of associated arrays
$admins=$wpdb->get_results('select `user_email` from `' . $wpdb->prefix . 'users` as `users` inner join `' . $wpdb->prefix . 'usermeta` as `usermeta` on `usermeta`.`user_id`=`users`.`ID` where `meta_key`=\'wp_user_level\' and `meta_value` in (8,9,10);', ARRAY_A);
<?php $user_info = get_userdata(1);
echo 'Username: ' . $user_info->user_login . "\n";
echo 'User roles: ' . implode(', ', $user_info->roles) . "\n";
echo 'User ID: ' . $user_info->ID . "\n";
?>
You can pass the User id herer.....
The first thing to do is to create the function. To do so, paste the following code in your functions.php file:
function getUsersByRole($role) {
$wp_user_search = new WP_User_Search($usersearch, $userspage, $role);
return $wp_user_search->get_results();
}
Once done, you can call the function this way:
$editors = getUsersByRole('Administrator');
foreach($editors as $editor){
//$editor now holds the user ID of an editor
}

CakePHP - Saving and serving files outside of webroot

Using Cake version 2.4.3 stable
So I am having a time here, I have modified this plug in to save files to the app folder https://github.com/srs81/CakePHP-AjaxMultiUpload/
The uploaded files are being saved to /public_html/app/files
Now the strange thing is, when trying to serve these files to the view, I can read the file name, the file size, but not the file itself, image, pdf, etc.
When I try to access the file via direct url, i get this error :
Error: FilesController could not be found.
How can it be that I can read the file name, the file size, but not the file itself?
There is a need to save the files in the app folder. These files should be protected and therefore only be accessed by users who are logged into the application. I have tried to use cake send file response with no outcome.
Edit : I guess the real question at hand here is how can I read files from APP . DS . 'files' ?
View code :
public function view ($model, $id, $edit=false) {
$results = $this->listing ($model, $id);
$directory = $results['directory'];
$baseUrl = $results['baseUrl'];
$files = $results['files'];
$str = "<dt>" . __("Pictures") . "</dt>\n<dd>";
$count = 0;
$webroot = Router::url("/") . "ajax_multi_upload";
foreach ($files as $file) {
$type = pathinfo($file, PATHINFO_EXTENSION);
$filesize = $this->format_bytes (filesize ($file));
$f = basename($file);
$url = $baseUrl . "/$f";
if ($edit) {
$baseEncFile = base64_encode ($file);
$delUrl = "$webroot/uploads/delete/$baseEncFile/";
$str .= "<a href='$delUrl'><img src='" . Router::url("/") .
"ajax_multi_upload/img/delete.png' alt='Delete' /></a> ";
}
$str .= "<img src='$url' /> ";
$str .= "<a href='$url'>" . $f . "</a> ($filesize)";
$str .= "<br />\n";
}
$str .= "</dd>\n";
return $str;
}
And the upload / save
public function upload($dir=null) {
// max file size in bytes
$size = Configure::read ('AMU.filesizeMB');
if (strlen($size) < 1) $size = 20;
$relPath = Configure::read ('AMU.directory');
if (strlen($relPath) < 1) $relPath = "files";
$sizeLimit = $size * 1024 * 1024;
$this->layout = "ajax";
Configure::write('debug', 0);
$directory = APP . DS . $relPath;
if ($dir === null) {
$this->set("result", "{\"error\":\"Upload controller was passed a null value.\"}");
return;
}
// Replace underscores delimiter with slash
$dir = str_replace ("___", "/", $dir);
$dir = $directory . DS . "$dir/";
if (!file_exists($dir)) {
mkdir($dir, 0777, true);
}
$uploader = new qqFileUploader($this->allowedExtensions,
$sizeLimit);
$result = $uploader->handleUpload($dir);
$this->set("result", htmlspecialchars(json_encode($result), ENT_NOQUOTES));
}
The only real change from the original plug in is changing WWWROOT to APP to make the switch. Saving works fine and lovely. But its just weird that I can read the file name, file size in the view no problem but cannot view an image, pdf, etc.
The problem:
You cannot display files that are outside the webroot via a direct URL - that's the whole point in putting them above the webroot in the first place - to make them NOT directly accessible.
So building the image src path in the controller first (not good practice anyway) won't change the fact that when that path gets to the browser, and it reads the source of the image as trying to pull an image from above webroot, it won't/can't.
The Solution:
The solution is to use a CakePHP's Sending files (what used to be Media Views). Then, you set your img's "src" to a controller/action. In that action, it basically says "display this action as an image" (or pdf, or whatever else).
Path to use in Controller:
took this from one of my apps which is doing exactly the above, and here's the path I used for a file in 'files' (same level as webroot):
file_exists(APP . 'files' . DS . $your_filename)
Create a symbolic link to your folder inside of the webroot ;-)

How to fetch and display an array using PDO?

I understand there are MANY ways to do all of this, but trying to do it the best way.
I have created the db parameters, dns, dbh, sth, sql and generally quite happy with the result up to ... well ... the result part.
<?php
// db parameters
$dbhost = "localhost";
$dbname = "x";
$dbuser = "y";
$dbpass = "z";
// driver invocation (dsn is short for data source name)
$dsn = "mysql:host=$dbhost;dbname=$dbname";
// create db object (dbh is short for database handle)
$dbh = new PDO($dsn, $dbuser, $dbpass);
// execution of database query (sth is short for statement handle)
$sql = "SELECT * FROM a_aif_remaining";
$sth = $dbh->prepare($sql);
$sth->execute();
NOT SURE WHAT TO PUT BELOW.... (A) or (B)
I just want to present a simple array of the data. One row from the table per line.
Option A
echo $_POST['fieldname1'];
echo $_POST['fieldname2'];
echo $_POST['fieldname3'];
Option B
while ($rows = $sth->fetch(PDO::FETCH_ASSOC)) {
echo $row[fieldname1],'<br>';
}
AND I AM CONFIDENT WITH THE ENDING
$dbh = NULL;
?>
Any advise would be GREATLY appreciated.
UPDATED CODE: (Produces nothing on the page)
<?php
// db parameters
$dbhost = "localhost";
$dbname = "theaudit_db1";
$dbuser = "theaudit_user";
$dbpass = "audit1999";
$dsn = "mysql:host=$dbhost;dbname=$dbname"; // driver invocation (dsn is short for Data Source Name)
try {
$dbh = new PDO($dsn, $dbuser, $dbpass); // connect to new db object (dbh is short for Database Handle)
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); // set the PDO error mode to enable exceptions
$dbh->setAttribute(PDO::ATTR_EMULATE_PREPARES, false); // set the PDO emulate prepares to false
// execute query to database (sth is short for Statement Handle)
$sql = "SELECT * FROM a_aif_remaining";
$sth = $dbh->prepare($sql);
$sth->execute();
$data = $sth->fetchAll(PDO::FETCH_ASSOC);
$dbh = NULL;
}
catch(PDOException $e)
{
echo $e->getMessage();
}
?>
Though I can't get what's the connection between A anb B, I can answer the
I just want to present a simple array of the data. One row from the table per line.
question.
$sql = "SELECT * FROM a_aif_remaining";
$sth = $dbh->prepare($sql);
$sth->execute();
$data = $sth->fetchAll(PDO::FETCH_ASSOC);
where $data is a sought-for array.
The problem with your updated code is simple - you arent echo'ing your data out. You need to add something like..
foreach($data as $arKey=>$dataRow){
foreach($dataRow as $arKey=>$rowField){
echo $rowField.','; //concat with a ',' to give csv like output
}
echo '<br>'; //to get to next line for each row (may want to trim the last ','
}
I am also confused by the reference to $_POST. It is true both are associate arrays but that does not mean that the $_POST option is viable - the data would only be available in the $_POST if you put it there (eg $_POST = $data) which would be pointless. Or if you had posted the data from somewhere else. Neither seem to fit what you are asking so I would forget about the $_POST and just figure out how you access your multi dimensional $data array. There is endless tut's on this subject. Try using
var_dump($data)
to see whats inside that should help you visualise what is going on.
NOTE: in option B you are not correctly concatenating or referencing your array it should be:
while ($rows = $sth->fetch(PDO::FETCH_ASSOC)) {
echo $rows[fieldname1].'<br>'; //$row doesnt exist its $rows and you use . to concat not ,
}
Ah yes and probably better to use unset rather than setting $dbh to equal null
unset($dbh);

Database query to get decimal value in Joomla 2.5

I'm trying to make a query to a database in Joomla 2.5. I have a db named 'example', and I'm trying to get certain value named 'value' (very original) for a user whose id is 949:
$db =& JFactory::getDBO();
$query = $db->getQuery(true);
$user = 949;
$db->setQuery( 'SELECT value FROM example WHERE user_id = ' . $user );
$result = $db->loadObjectList();
echo $result;
However, I'm just getting 'Array' as result (the expected value is a decimal, e.g. 4.5).
Could someone please tell me what am I doing wrong?
$db =& JFactory::getDBO();
$query = $db->getQuery(true);
$user = 949;
$db->setQuery( "SELECT value FROM example WHERE user_id = '" . $user."'" );
$result = $db->loadObjectList();
echo $result;
try this one
$db->loadObjectList() returns an array of objects, which echo can't display. If you want to just return one value from one row, user $db->loadResult() instead.

Resources