Don’t use get_fields(‘options’) with ACF’s admin options!

I thought I was being smart by running
get_fields('options');
in a hook on load. Instead of having to call get_field for every option, I could just access this global. I mean, I knew globals were frowned upon but it seemed to make my life easier.

However, I was making 50+ unnecessary queries! It gets every single option, even those that are within groupings or repeater fields, by itself. So it would make 10 calls for one field grouping, but that field grouping only required calling the initial field.

In this example below, I am making one call to grab three fields that are grouping the admin. If I used get_fields, I’d be making at least 3!

    $colors = get_field('color', 'options);
    $background = $colors['background_field'];
    $primary_color = $colors['primary_color'];

Deleting duplicate scrobbles on Last.FM website

Updated 7/24/19

This works for the website as of July 24th 2019. Future site updates will probably break it.

If you accidentally scrobbled each track three times or some shit and you need to fix your scrobbles, try this.

In Chrome or Firefox, open up the developer console and paste this code:

jQuery('.js-focus-controls-container').on('click', function() {
 
    if(jQuery(this).hasClass('clicked')) { return; }
    jQuery(this).addClass('clicked').find('button.more-item--delete').click();
});


Then, you can click each scrobble you want deleted and it will delete it for you. It’s slightly faster than right clicking each one… You will need to repaste the code into the developer console every single time you change the page. Annoying AF.

apex:outputPanel and layout=”none”

If you’re like me, a web developer first and visualforce “expert” second, you might hate the way Salesforce adds spans and crazy string ID’s to everything. It makes the HTML incredibly, well, ugly.

I had fixed this by using layout=”none” on everything possible. It made the HTML very pretty. It also caused a ton of problems when my team tried to add rerenders later.

Some notes on apex:outputPanel and rerendering and layout.

  • If there is no rerendering required, you can use layout=”none”.
  • If you don’t have layout set, it will default to “inline”. What this means is you will have a ton of invalid HTML if you put a
    or an tag inside of your code. So make sure you always set something to keep your HTML valid and pretty.
  • If you have to rerender your panel, make sure that you don’t have anything set to layout=”none” and make sure your HTML validates. Wacky stuff happens if you try to rerender something with invalid HTML or layout=”none”. In other words, always manually write in layout=”block” or layout=”inline”. Don’t trust Visualforce to fix it for you.

best of luck!

Loop through an apex:repeat and split the contents into multiple containers

I was trying to build a slider from a list.
<apex:repeat value="{!People}" var="item"> 
	<div class="user-card">
		<div class="thumb">{!item.ImageUrl}</div>
		<div class="name">{!item.Name}</div>
		<div class="department">{!item.Department}</div>
	</div>                                        
</apex:repeat>
The problem is I needed to show FOUR User Cards in one slide. The above method will only do one person per slide. So – with apex:variable and MOD(), we can make make magic happen!

<ul class="birthday-slider">
    <li class="birthday-slide">
        <apex:variable value="{!1}" var="count"/>
        <apex:repeat value="{!People}" var="item"> 
            
            <div class="user-card">
                <div class="thumb">{!item.ImageUrl}</div>
                <div class="name">{!item.Name}</div>
                <div class="department">{!item.Department}</div>
            </div>     
            
            {!MOD(count, 4)} <br/>
            <apex:outputText value="</li><li class='birthday-slide'>" rendered="{!MOD(count, 4) == 0}" escape="false" />
            
            <apex:variable value="{!count + 1}" var="count"/>
        </apex:repeat>
    </li>
</ul>



WordPress Query: sort by meta_key && compare by meta_key

I needed to run a query that pulled all posts that had a specific value ( or values ), and sort them by another meta key.

The custom fields (meta keys) I am using in this example are:
  • Age
  • Favorite_Color
The Requirements:
  • Sort by “Age”, showing the youngest first.
  • Show all posts that have Favorite_Color == to $favorite_color.
    • Note: $favorite_color can be an array that has multiple colors.
Here is the query I found that works!
	$args = array(
			'post_type' => 'custom_post_slug', // or 'posts' if you don't have one.
			'posts_per_page' => -1, // get ALL posts
			'order_by' => 'title',
			'title_li' => '',
			'order' => 'ASC',
			'meta_key' => 'age',
 			'orderby' => 'meta_value_num', // sort by age.  use 'meta_value' if the values aren't just numeric.
			'meta_query' => array(
				array(
					'key' => 'favorite_color', 
					'value' => $favorite_color,
					'compare' => 'IN'	// because $favorite_color might be an array.  This will look IN the array.
				)
			)
		);
$results = get_posts($args);

Hopefully this is helpful!

SOQL Queries: Handling GROUP BY aggregation with the Force.com PHP Toolkit

I needed to run a query and pull a distinct set of values. Easy in Force.com Explorer.
SELECT Field_Name FROM Table_Name GROUP BY Field_Name

Not so easy when querying though, as the result looks like this:
print_r($response->records); // print the response...

Array
(
    [0] => stdClass Object
        (
            [Id] => 
            [any] => <sf:Field_Name>Unique Value</sf:Field_Name>
        )

    [1] => stdClass Object
        (
            [Id] => 
            [any] => <sf:Field_Name>Unique Value 1</sf:Field_Name>
        )

    [2] => stdClass Object
        (
            [Id] => 
            [any] => <sf:Field_Name>Unique Value 2</sf:Field_Name>
        )

Okay… at least the response is unique.
Here’s a foreach to parse the results into a pretty array.
foreach($response->records as $record) {
     $results[] = strip_tags($record->any);
}

Now you have something to work with.
Array
(
    [0] => Unique Value
    [1] => Unique Value 1
    [2] => Unique Value 2
)

Using GREP with Magento to Help Locate Files

When looking for something specific, if you’re working in Magento, it’s going to be difficult. Before I knew about GREP, I would just open every file and cmd-f till I found what I was looking for.

And then I learned about GREP.

I was looking for references to “Subtotal” on the front end, so I entered terminal, SSH’ed in, cd’ed to /app/ and entered this line.
grep -rn "('Subtotal')" .
and a long list appeared. One of the files was titled Totals.php and I knew I hadn’t modified it before. When I modified the line in that file, it did exactly what I wanted!

Long story short, don’t modify core files like I did, and use GREP to save time.

Query Multiple Meta Values in WordPress and use CONCAT()

I needed to pull two specific meta values for each custom post type into an array. I wanted them to be combined as one reference, and I wanted to use only one query.

With the help of multiple online sources, I was able to figure it out.
function get_your_meta($key1 = '', $key2 = '', $type = 'post', $status = 'publish') {
    global $wpdb;
    if(empty($key1) || (empty($key2))) {
		return;
	}
    $r = $wpdb->get_results( $wpdb->prepare(
    "
        SELECT
			CONCAT(pm.meta_value, ' ', pm2.meta_value) AS `name`,
			pm.post_id
		FROM {$wpdb->posts} p
		INNER JOIN {$wpdb->postmeta} pm
			ON p.ID = pm.post_id
        INNER JOIN {$wpdb->postmeta} pm2
			ON p.ID = pm2.post_id
		WHERE pm.meta_key = '%s'
		AND pm2.meta_key = '%s'
        AND p.post_status = '%s' 
        AND p.post_type = '%s'
    ",
    $key1, $key2, $status, $type) );
    return $r;
}
Simply call the function using
$arr = get_your_meta("meta_key_1", "meta_key_2", "post"); 
Of course, if you’re using a custom post type, change as such.

Cheers

Creating a ContentDocumentLink to a Custom Object in Salesforce

It’s not possible.

At least not at the time of writing this.

After countless hours, we have determined that it is not possible. We get a pretty blatant error from Salesforce though.

FIELD_INTEGRITY_EXCEPTION, You cannot create a link for this type of entity.

Of course, that wasn’t enough. We tried to link Chatter files, we checked permissions, we did the whole shebang. If you come to this page in your search, and you get a similar error, do yourself a favor and stop. I would LOVE to be able to modify this article and say it’s possible, so if you don’t stop coding, please leave me a comment!

So I don’t leave you empty handed, here is the code that I used to, at the very least, create a file and add it to a Content Library, specified by the $contentLibraryId variable. I clearly use the PHP Toolkit with Salesforce.
$sObject = array();
$sObject[0] = new stdclass();
$sObject[0]->Title = $fileName;
$sObject[0]->PathOnClient = $_FILES["uploaded_file"]["name"];
$sObject[0]->VersionData = $encoded_file;
$sObject[0]->FirstPublishLocationId = $contentLibraryId;
$response = $mySforceConnection->create($sObject, 'ContentVersion');

And of course, the code that created the error…
$query = "SELECT Id FROM ContentDocument WHERE LatestPublishedVersionId = '" . $contentDocumentId . "'";
$response = $mySforceConnection->query($query);
$contentId = $doc_response->records[0]->Id; // note - this is used below!
$sObject = array();
$sObject[0] = new stdclass();
$sObject[0]->ContentDocumentId = $contentId;
$sObject[0]->ShareType = "C";
$sObject[0]->LinkedEntityId = $CustomObjectId;
$response = $mySforceConnection->create($sObject, 'ContentDocumentLink');

This, by the way, is what I’m struggling to achieve: adding files to this “Related Content” area.


Stack Overflow link reference