Drupal Views variable $rows outputs as a String - drupal-7

I've developed a custom .tpl.php file for my View and in the past it has worked. Suddenly, while working on my Macbook using MAMP, Drupal decided that the $views->rows needs to be output as a String type and not an array. I've searched online and here for an answer but can't find one. I'm not doing any pre-process or views_render hooks in my template.php file for the theme. Does anyone have any ideas or have seen this before?
Thanks

After going through the Views module code, I couldn't find a _render hook that I would alter to cause the $rows to go back to an Array type. I did go through the modules/views/theme/views-view.tpl.php
So I replaced most of the code in my own template with the views-view.tpl.php code, as well as replacing the database with a previous version so I could start completely over. Turns out the issue was with my template file not outputting the exposed filters and such, as well as Views using
print $rows
instead of using $rows as an array. Seems like whatever version of Views I'm using uses the $rows variable as a String. So I've put in a %SPLIT% string in the Rewrite Results box so that I can do a PHP preg_split, feed that resulting array into my function to generate what I need, then do a preg_replace to get rid of the %SPLIT% strings in $rows. The result looked like what I had.
So, bottom line, looks like Unformatted Fields in Views now outputs $rows as a String variable instead of an array.

I also discovered this when trying to theme a certain row differently if a condition was met. Most things can be done in the Views UI but I couldn't figure out this one like that. I was finally able to do this with yourtheme_preprocess_views_view_unformatted(&$vars) in my template.php file. $rows seemed to still behave like an array there (although it went back to being a string later).
function yourtheme_preprocess_views_view_unformatted(&$vars) {
if ($vars['view']->name == "name_of_view") {
$rows = $vars['rows'];
$newRows = array();
foreach ($rows as $r) {
$test = strpos($r, "string_i_looked_for");
if ($test) {
$newRows[] = "<hr>$r"; // I needed to put in a divider if the condition was met.
}
else {
$newRows[] = $r;
}
}
$vars['rows'] = $newRows; // So that the array of new rows is what will be sent along.
}
}
My actual problem required the divider only in the first instance of the test, so I also used a counter, but I think the example above gives the idea.

Related

Why was I able to get away with not using a splat operator sometimes

I have some ruby code from my Ruby on Rails project.
I am formatting some data so I am calling attributes.extract! to get the fields I need from my model.
I noticed recently that every now and then the data wouldn't get extracted as expected. I realized that I needed a splat operator. But it is strange because I do notice that sometimes when the method is called in my Rails project it will sometimes extract the data without the use of the splat operator. But when I run the code from my Rails console it never extracts the data unless I add the splat operator.
Here is the code in question
# in a service file, let's call it service.rb
def self.format_user_home_address_data(user)
# This doesn't work in the console but sometimes works when run in my Rails project
home_address_data = user.attributes.extract!(User::HOME_ADDRESS_FIELDS)
home_address_data[:address_type] = "home"
home_address_data
end
# at the end this method will sometimes return { address_type: "home" } or
# sometimes it'll actually return the extracted attributes as expected
HOME_ADDRESS_FIELDS is just an array with the values ["address_line_1", "city", "state", "zip"]
Anyway I know that to get it to run correctly I need to do this
home_address_data = user.attributes.extract!(*User::HOME_ADDRESS_FIELDS)
But does anyone know why I was able to get away without adding the splat operator for so long? Is there some Ruby on Rails magic that is only sometimes happening? What's the deal?
Well, let's check it out. There is no any magic behind attributes.extract! in the end. Here is an actual implementation of this method from Rails source code:
def extract!(*keys)
keys.each_with_object(self.class.new) { |key, result|
result[key] = delete(key) if has_key?(key)
}
end
Link: click. As you can see, it creates new hash, goes over the keys one by one and moves value from self to this new array. So, if you give an Array argument to this method then key in the block will be an Array as well. So, it won't be found. So, no way it may work for array argument. The only one possibility is that something else is passed instead of User::HOME_ADDRESS_FIELDS.

How to get CheckBoxList values in Umbraco using ContentService

Anyone knows how to get list of selected CheckBoxList values from Umbraco using ContentService?
I use contentService.GetValue("currencies")
and I get string with numbers and commas something like "154,155,156,157"
How can I get actual values?
Does anyone know how to do it using DataTypeService?
As it was mentioned above, you can use Umbraco helpers method to retrieve string value for the PreValue id.
Umbraco.GetPreValueAsString([PreValueId])
You can find more about it here: https://our.umbraco.org/documentation/reference/querying/umbracohelper/#getprevalueasstring-int-prevalueid
It's calling database directly through the DataTypeService behind the scene. It's worth to reconsider it and close it on another type of property / data type to avoid calling database on the frontend layer and just retrieve data from IPublishedContent cached model.
Read also about common pitfalls and anti-patterns in Umbraco: https://our.umbraco.org/documentation/Reference/Common-Pitfalls/
Those are prevalues.
From that given string, you have to split those and get the real value by calling one of umbraco library umbraco.library.GetPreValueAsString(123);
For example.
foreach(var item in contentService.GetValue("currencies").Split(',')) {
var realValue = umbraco.library.GetPreValueAsString(int.Parse(item);
}
You have 2 nulls because prevalues sometimes has blank values on it, like "121,56,,15,145".
You need then to modify your split code like this
foreach (var item in value.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries))
{
}
StringSplitOptions.RemoveEmptyEntries will ignore empty spaces.

Filtering an array based on a second array?

I have two data arrays:
$arrnames=('a','b','c')
$arrtypes=('x','y','z')
and I have a lookup array:
$arrlookup=('y','z')
I need to return the elements in $arrnames where the matching element in $arrtypes is contained in $arrlookup. I've been playing with foreach looping over $arrnames and looking at the same element in $arrtypes by index but it's getting sloppy and I know there has to be a better way.
I've seen some similar questions, but not anything that strikes me as specifically answering this problem. Being a Powershell very newbie I'm still learning how to adapt examples to my needs. Any help is greatly appreciated.
My code (technique used as applied to above example - actual code is using complex arrays derived from an XML file and has a lot of debugging code so copy/paste is impractical)
foreach ($a in $arrnames) {
$t=$arrtypes[$arrnames.IndexOf($a)]
if ($arrlookup.Contains($t)) {
$arrresult+=$a
}
)
$arrresult should contain the members of $arrnames that have a type (from $arrtypes) that is in $arrlookup.
Is there a way to use object methods, filtering and the pipeline to simply extract the elements without a foreach loop
Edit - here's the actual code that creates the actual arrays - $builds is an XML document:
$names=$builds.builds.project.name
$types=$builds.builds.project.type
The lookup table is known:
$FXCopTypes=#('batch','component','web')
The XML file I also have control over, but I don't see any way to simplify it more than implementing the hash table code but with the above arrays.
I think you need to change you input inorder to be able to do anything different here. What you are asking for is $arrnames and $arrtypes to really be a hashtable. That way you can access the values using keys.
As it stands I would do this to create the hashtable. The second loop shows how to return each matching value.
$hash = #{}
for($index = 0; $index -lt $arrtypes.Count; $index++){
$hash.($arrtypes[$index]) = $arrnames[$index]
}
$arrresult = $arrlookup | ForEach-Object{
$hash[$_]
}
This would return
b
c
If you could get your input to create that hash table then it reduces the need to rebuild it. Also if you know the lookup before hand as well you can filter it then and just have the output you want.

Use Array of Values of Object in a Foreach Loop

I cannot seem to find anything about using the values of one property of an object in a foreach loop (without having the entire object placed into the loop).
I first create a function called UFGet-Servers that uses Get-ADComputer and returns the names of the servers in a specific OU in my environment and places them in an array. That's great, except that when I use the array in a foreach loop, each object that it grabs has #[Name=serverName] in it, which I cannot use in any useful manner. The following pseudo-code is an abbreviated example:
foreach($Computer in $ComputerNames){do code... code is adding the server name into a UNC path such as "\\$Computer\C$\"}
The problem with the above is that you can't add the whole object to a path -- it ends up looking like "\#[Name=serverNameHere]\C$\" which totally bombs out. How do I get rid of the "#[property=" part, and simply use the value as the $Computer in the loop?
What really weirds me out is that I can't find a straightforward article on this anywhere... would have thought everyone and their mom would have wanted to do something like this.
So, your issue isn't with ForEach loops, it is with string formatting. There are two ways that I know of to take care of what you need. First is going to be string formatting, which allows you to use {0}m {1} and so on to inject values into a string, providing that you follow the string with -f and a list of said values. Such as:
ForEach($Computer in $ComputerNames){
"The Server Path is \\{0}\Share$" -f $Computer.Name
}
The second way is a sub-expression (I'm sure somebody will correct me if I used the wrong term there). This one involves enclosing the variable and desired property (or a function, or whatever) inside $(). This will evaluate whatever is inside the parenthesis before evaluating the string. See my example:
ForEach($Computer in $ComputerNames){
"The Server Path is \\$($Computer.name)\Share$"
}

Drupal hook_file_insert issue

I'm working with the hook_file_insert function and keep running into the same issue over and over again.
Let's take a look at the code:
function mymodule_file_insert($file) {
$src = $file->source // the file field a.k.a field_upload_und_0
file_save_upload($src, array(), 'public://styles/'); // <-- Here's where the issue is.
$file->description = 'Change desc value';
dsm($file) // debug
}
So basically when i upload a file i get this error:
The file MyDocument.doc could not be saved. An unknown error has occurred.
Other than that, I'm also trying to change the description value when the file is uploaded/saved. But that's not happening either. It does however, show as changed in the array when i look in the dsm results.
Am i misunderstanding this function? I suppose it only changes the files array and hangs on to. My thinking originally was that it modifies the actual field values but that doesn't seem to be the case.
How could i grab these values and pass them along in my hook_form_submit function? Is this possible?
Thanks,
The proper solution was to pass the $file variable by reference
function mymodule_file_insert(&$file) {...

Resources