Accessing location field in Drupal 7, via hosting entity object and wrapper - drupal-7

I'm using Location module (particularly its Location CCK part) with Drupal 7. Added location field 'field_location' to User (as an example of hosting entity), and initialized location values for test users in user edit interface. However, I'm unable to access location data of the current user:
global $user;
$user_id = $user->uid;
$loc = $user->field_location;
or:
$wrapper = entity_metadata_wrapper('user', $user_id);
$loc = $wrapper->field_location;
The statements with $loc don't work for object and wrapper (while both user object and wrapper are initialized successfully). Same for:
$loc = $wrapper->field_location[0];
$loc = $wrapper->field_location->raw();
I've read a number of posts on this topic, however haven't found a workable solution, would appreciate insights on this.

The location module, by itself, does not support the Entity API/Metadata Wrapper out-of-box. However, it is packaged with the Location Entity module, which will enable it for entity api support.
Once enabled,
$wrapper = entity_metadata_wrapper('user', $user_id);
$loc = $wrapper->field_location->value();
Works as expected.
If you want a quick workaround, you can also do:
$user_wrapper = entity_metadata_wrapper('user', $user_id);
$raw_user = $user_wrapper->raw();
$loc = $raw_user->field_location['und'][0];
This isn't elegant, but it's a solution without additional modules. Take your pick.

Related

Terraform Resource Group ID as a Variable

I am currently migrating our cloud infrastructure over to Terraform; it's all gone well so far. Right now, though, I am trying to set up the SQL Server app, and the current setup, which I need to mirror to migrate, takes the existing resource group Object ID and appends it onto a unique string, for example, sqldatabase23456-resource group object id.
In arm this is done the following way:
"sqlServerAdministratorUsername": "[concat('l', uniqueString(resourceGroup().id))]",
Except I am making the resource group in Terraform, so the variable needs to use the meta argument depends on as the variable value can not exist before the resource group exists. I don't think this is possible when reading the depends on the material from Terraform; it only seems to work for resources, not other items. Link to document: https://www.terraform.io/docs/language/meta-arguments/depends_on.html
I have seen it slightly discussed on here:
Terraform, can a resource be passed as a variable into a module?
I am happy to build this SQL server as a module. I need this to work this way; otherwise, we won't migrate over to Terraform. As we can't change the current setup with SQL, too much depends on it.
I need to pass the values into the login part of SQL server code example below:
resource "azurerm_mssql_server" "example" {
name = "mssqlserver"
resource_group_name = azurerm_resource_group.example.name
location = azurerm_resource_group.example.location
version = "12.0"
administrator_login = var.resourcegroup_withuniquestring
administrator_login_password = var.resourcegroup_withuniquestring_password
minimum_tls_version = "1.2"
tags = {
environment = "production"
}
}
I don't really know what do you mean by variable in this context.
Terraform has locals. Locals can reference other Terraform resources, by this making the dependency implicit, so there is no need for depends_on. Example:
resource "random_string" "random" {
length = 16
special = true
override_special = "/#£$"
}
locals {
sql_server_administrator_name = join("", "sqldatabase", random_string.random.result, "-", azurerm_resource_group.example.name,
}
Locals can be referenced in other resources:
resource "azurerm_mssql_server" "example" {
name = "mssqlserver"
resource_group_name = azurerm_resource_group.example.name
location = azurerm_resource_group.example.location
version = "12.0"
administrator_login = local.sql_server_administrator_name
administrator_login_password = local.password
minimum_tls_version = "1.2"
}
I actually figured this out using the prompting of Ervins anwser.
I used locals to put the resource group id as a variable but the problem with that is it will output a huge string that can not be used for account names, so here is the following steps that I took, to trim it down and make it usable.
I first made three local variables one to trim down the string and get the ID number of the resource group and disregard everything else.
Another to output the whole string so I could work out the string value and how many characters to count in.
And a Third to put both the unique string and the Resource Group ID number on the end.
Below is the code to trim the string.
resource_group_id = substr(("${azurerm_resource_group.Example_Terraform_Testing.id}"),15,36)
This is using the function substr in Terraform which allows you to chop up strings, as most of the functions will only let you work with maps, or lists.
Link to substr: https://www.terraform.io/docs/language/functions/substr.html
To work out the exact number I first used format as a local value then outputed the value through an output variable like this:
resource_group_id_full_value = format("${azurerm_resource_group.Example_Terraform_Testing.id}")
output "resource_group_id__full_value" { value = local.resource_group_id_full_value }
This will then output the whole string like this when running Terraform Plan or Apply: resource_group_id__full_value = "/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/Example_Terraform_Testing"
To user substr you need to count the characters from the first / and the first / is 0 all / are a value. Unlike other languages that disregard special characters.
Once I had that as a local value I could then append that onto my local variable string like this:
sql_admin_login = format("${random_string.myrandom.id}-${local.resource_group_id}")
This will then give me the format I wanted like this, "qpncxt-00000000-0000-0000-0000-000000000000" and meet the account name requirements set by Azure, to be unique and to not have any special characters in and not to be too long. Also the great thing about substr is If I need the value to be shorter I just put in a lower number in the string.
Here is my full code to get this working:
locals {
# Ids for Resource Group, merged together with unique string
resource_group_id_full_value = format("${azurerm_resource_group.Example_In_The_Cloud_Terraform_Testing.id}")
resource_group_id = substr(("${azurerm_resource_group.Example_Terraform_Testing.id}"), 15, 36)
sql_admin_login = format("${random_string.myrandom.id}-${local.resource_group_id}")
sql_admin_password = format("${random_string.myrandom.id}-${local.resource_group_id}")
sql_server_name = format("sqlserver-${local.resource_group_id}")
}
resource "azurerm_mssql_server" "example_sql_server" {
name = local.sql_server_name
location = azurerm_resource_group.Example_Terraform_Testing.location
resource_group_name = azurerm_resource_group.Example_Terraform_Testing.name
version = "12.0"
administrator_login = local.sql_admin_login
administrator_login_password = local.sql_admin_password
minimum_tls_version = "1.2"
tags = {
environment = "production"
}
}
Links used to work this out:
Terraform Local Values: https://www.terraform.io/docs/language/values/locals.html
Terraform String Functions:
https://www.terraform.io/docs/language/functions/substr.html

2sxc - Access other app's entities

In some contexts, entities are common to a group of apps. For example, I use a list of departments in my institution for at least 4 apps (different projects that cannot and should not be merged in a single app). Another example is the type of employes or even the list of employees.
Is it possible to create an entity accessible to every app in an easy and fast way?
I searched it, but can't find any documentation about this.
Is it related to the dotnet external use?
// the app id
var appId = 42;
// create a simple app object to then access datavar appSimple =
ToSic.SexyContent.Environment.Dnn7.Factory.App(appId);
// example getting all data of content type Tagvar tags =
appSimple.Data["Tag"];
If you are working with razor and just want to access the data in code, you can create an AppDataSource and tell it what App you need. Here's some Pseudo-code:
var otherApp = CreateSource<AppDataSource>();
otherApp.ZoneId = 74;
otherApp.AppId = 203;
// do this after setting the values
var categories = otherApp.Data["Categories"];

LDAPMAP - Mapping SAP data to LDAP via RSLDAPSYNC_USER function

We are looking at syncing some of our LDAP (Active Directory) data with what is stored in SAP. SAP provides several function modules that allow you to write a custom program to handle mapping the data, but we are looking to use the provided solution that makes use of RSLDAPSYNC_USER.
The issue I'm having is understanding how the mapping of fields is performed in LDAPMAP. In particular, when performing the Mapping Overview, where are the structures as shown below defined?
Also, we have a function module that is currently available for grabbing all of the fields we would like to send to LDAP, but can the screen shown below be used to call a custom function module to grab the data I require? If so, then please give an example.
Thanks,
Mike
I am not sure if that is what you ask. As an answer to your second question:
You can give attributes that you want to get. The LDAP_READ function will return the results in entries parameter.
CALL FUNCTION 'LDAP_READ'
EXPORTING
base = base
* scope = 2
filter = filter
* attributes = attributes_ldap
timeout = s_timeout
attributes = t_attributes_ldap
IMPORTING
entries = t_entries_ldap "<< entries will come
EXCEPTIONS
no_authoriz = 1
conn_outdate = 2
ldap_failure = 3
not_alive = 4
other_error = 5
OTHERS = 6.
Entries parameter looks like:
Attributes parameter looks like:

cakePHP get a variable from each Model and Controller

I got a question. I have a db table with settings (id, name).
If I read them from the db
$settings = $this->Setting->find('list');
How can I do this in the AppController or something like that to access from each Controller and Model?
Hope someone can help me.
Thanks
Explanation:
I would assume you're looking for something like below (Obviously you'll want to tweak it per your own application, but - it's the idea).
In the app controller, it
finds the settings from the table
repeats through each and puts each one into a "Configure" variable
Code:
/**
* Read settings from DB and populate them in constants
*/
function fetchSettings(){
$this->loadModel('Setting');
$settings = $this->Setting->findAll();
foreach($settings as $settingsData) {
$value = $settingsData['Setting']['default_value'];
//note: can't check for !empty because some values are 0 (zero)
if(isset($settingsData['Setting']['value'])
&& $settingsData['Setting']['value'] !== null
&& $settingsData['Setting']['value'] !== '') {
$value = $settingsData['Setting']['value'];
}
Configure::write($settingsData['Setting']['key'], $value);
}
}
Then, you can access them anywhere in your app via Configure::read('myVar');
A warning from the CakePHP book about Configure variables. (I think they're fine to use in this case, but - something to keep in mind):
CakePHP’s Configure class can be used to store and retrieve
application or runtime specific values. Be careful, this class allows
you to store anything in it, then use it in any other part of your
code: a sure temptation to break the MVC pattern CakePHP was designed
for. The main goal of Configure class is to keep centralized variables
that can be shared between many objects. Remember to try to live by
“convention over configuration” and you won’t end up breaking the MVC
structure we’ve set in place.

the best way to make codeigniter website multi-language. calling from lang arrays depends on lang session?

I'm researching hours and hours, but I could not find any clear, efficient way to make it :/
I have a codeigniter base website in English and I have to add a Polish language now. What is the best way to make my site in 2 language depending visitor selection?
is there any way to create array files for each language and call them in view files depends on Session from lang selection? I don't wanna use database.
Appreciate helps! I'm running out of deadline :/ thanks!!
Have you seen CodeIgniter's Language library?
The Language Class provides functions
to retrieve language files and lines
of text for purposes of internationalization.
In your CodeIgniter system folder you'll
find one called language containing sets
of language files. You can create your
own language files as needed in order
to display error and other messages in
other languages.
Language files are typically stored in
your system/language directory. Alternately
you can create a folder called language
inside your application folder and store
them there. CodeIgniter will look first
in your application/language directory.
If the directory does not exist or the
specified language is not located there
CI will instead look in your global
system/language folder.
In your case...
you need to create a polish_lang.php and english_lang.php inside application/language/polish
then create your keys inside that file (e.g. $lang['hello'] = "Witaj";
then load it in your controller like $this->lang->load('polish_lang', 'polish');
then fetch the line like $this->lang->line('hello'); Just store the return value of this function in a variable so you can use it in your view.
Repeat the steps for the english language and all other languages you need.
Also to add the language to the session, I would define some constants for each language, then make sure you have the session library autoloaded in config/autoload.php, or you load it whenever you need it. Add the users desired language to the session:
$this->session->set_userdata('language', ENGLISH);
Then you can grab it anytime like this:
$language = $this->session->userdata('language');
In the controller add following lines when you make the cunstructor
i.e, after
parent::Controller();
add below lines
$this->load->helper('lang_translate');
$this->lang->load('nl_site', 'nl'); // ('filename', 'directory')
create helper file lang_translate_helper.php with following function and put it in directory system\application\helpers
function label($label, $obj)
{
$return = $obj->lang->line($label);
if($return)
echo $return;
else
echo $label;
}
for each of the language, create a directory with language abbrevation like en, nl, fr, etc., under
system\application\languages
create language file in above (respective) directory which will contain $lang array holding pairs label=>language_value as given below
nl_site_lang.php
$lang['welcome'] = 'Welkom';
$lang['hello word'] = 'worde Witaj';
en_site_lang.php
$lang['welcome'] = 'Welcome';
$lang['hello word'] = 'Hello Word';
you can store multiple files for same language with differently as per the requirement
e.g, if you want separate language file for managing backend (administrator section) you can use it in controller as $this->lang->load('nl_admin', 'nl');
nl_admin_lang.php
$lang['welcome'] = 'Welkom';
$lang['hello word'] = 'worde Witaj';
and finally
to print the label in desired language, access labels as below in view
label('welcome', $this);
OR
label('hello word', $this);
note the space in hello & word you can use it like this way as well :)
whene there is no lable defined in the language file, it will simply print it what you passed to the function label.
I second Randell's answer.
However, one could always integrate a GeoIP such as http://www.maxmind.com/app/php
or http://www.ipinfodb.com/. Then you can save the results with the codeigniter session class.
If you want to use the ipinfodb.com api You can add the ip2locationlite.class.php file to your codeigniter application library folder and then create a model function to do whatever geoip logic you need for your application, such as:
function geolocate()
{
$ipinfodb = new ipinfodb;
$ipinfodb->setKey('API KEY');
//Get errors and locations
$locations = $ipinfodb->getGeoLocation($this->input->ip_address());
$errors = $ipinfodb->getError();
//Set geolocation cookie
if(empty($errors))
{
foreach ($locations as $field => $val):
if($field === 'CountryCode')
{
$place = $val;
}
endforeach;
}
return $place;
}
For easier use CI have updated this so you can just use
$this->load->helper('language');
and to translate text
lang('language line');
and if you want to warp it inside label then use optional parameter
lang('language line', 'element id');
This will output
// becomes <label for="form_item_id">language_key</label>
For good reading
http://ellislab.com/codeigniter/user-guide/helpers/language_helper.html
I've used Wiredesignz's MY_Language class with great success.
I've just published it on github, as I can't seem to find a trace of it anywhere.
https://github.com/meigwilym/CI_Language
My only changes are to rename the class to CI_Lang, in accordance with the new v2 changes.
When managing the actual files, things can get out of sync pretty easily unless you're really vigilant. So we've launched a (beta) free service called String which allows you to keep track of your language files easily, and collaborate with translators.
You can either import existing language files (in PHP array, PHP Define, ini, po or .strings formats) or create your own sections from scratch and add content directly through the system.
String is totally free so please check it out and tell us what you think.
It's actually built on Codeigniter too! Check out the beta at http://mygengo.com/string
Follow this https://github.com/EllisLab/CodeIgniter/wiki/CodeIgniter-2.1-internationalization-i18n
its simple and clear, also check out the document # http://ellislab.com/codeigniter/user-guide/libraries/language.html
its way simpler than
I am using such code in config.php:
$lang = 'ru'; // this language will be used if there is no any lang information from useragent (for example, from command line, wget, etc...
if (!empty($_SERVER['HTTP_ACCEPT_LANGUAGE'])) $lang = substr($_SERVER['HTTP_ACCEPT_LANGUAGE'],0,2);
$tmp_value = $_COOKIE['language'];
if (!empty($tmp_value)) $lang = $tmp_value;
switch ($lang)
{
case 'ru':
$config['language'] = 'russian';
setlocale(LC_ALL,'ru_RU.UTF-8');
break;
case 'uk':
$config['language'] = 'ukrainian';
setlocale(LC_ALL,'uk_UA.UTF-8');
break;
case 'foo':
$config['language'] = 'foo';
setlocale(LC_ALL,'foo_FOO.UTF-8');
break;
default:
$config['language'] = 'english';
setlocale(LC_ALL,'en_US.UTF-8');
break;
}
.... and then i'm using usualy internal mechanizm of CI
o, almost forget! in views i using buttons, which seting cookie 'language' with language, prefered by user.
So, first this code try to detect "preffered language" setted in user`s useragent (browser). Then code try to read cookie 'language'. And finaly - switch sets language for CI-application
you can make a function like this
function translateTo($language, $word) {
define('defaultLang','english');
if (isset($lang[$language][$word]) == FALSE)
return $lang[$language][$word];
else
return $lang[defaultLang][$word];
}
Friend, don't worry, if you have any application installed built in codeigniter and you wanna add some language pack just follow these steps:
1. Add language files in folder application/language/arabic (i add arabic lang in sma2 built in ci)
2. Go to the file named setting.php in application/modules/settings/views/setting.php. Here you find the array
<?php /*
$lang = array (
'english' => 'English',
'arabic' => 'Arabic', // i add this here
'spanish' => 'Español'
Now save and run the application. It's worked fine.

Resources