Benjam,on the topic of  PHP, Usability
06.23.2011   |   0comment

I have a flat MPTT array (really any tree ordered array will work, not necessarily an MPTT array) which has it’s elements output in order as follows:

  • Top Parent 1
  • Child 1-1
  • Child 1-2
  • Sub-Child 1-2-1
  • Sub-Child 1-2-2
  • Child 1-3
  • Top Parent 2
  • Child 2-1

Each element is it’s own entry in the one dimensional array. This makes outputting that data in any kind of readable form very difficult, where keeping track of parents and branches are required in order to make sense of it. This gets pretty messy, pretty quickly. And the deeper the tree, the more complicated the process.

To make this easier to deal with, the array should be built in a tree format as follows:

  • Top Parent 1
    • Child 1-1
    • Child 1-2
      • Sub-Child 1-2-1
      • Sub-Child 1-2-2
    • Child 1-3
  • Top Parent 2
    • Child 2-1

Where the children of the elements in the tree are actually children of the elements in the array.

In order to do this quickly and painlessly, we are going to parse through this array twice… no iterations, just a couple of foreach loops and we’ll get our tree exactly how we want it.

In order to do this, we must first make sure our array indexes are the same as the IDs of the items we are sorting (because we are pulling this from a database, right?).

To do this in CakePHP we run it through the Set::combine function like so:
Set::combine($tree_data, '/Model/id', '/.');

If you are not using CakePHP, you can create a new array, and as you foreach through your original array, set elements in the new array accordingly:

$old_tree_data = $tree_data;
$tree_data = array( );
foreach ($old_tree_data as $node) {
	$tree_data[$node['Model']['id']] = $node;
}

Now that we have our array indexes set to our model ID, we can proceed.

The trick to this method is not to move the nodes around, because if we did that, we’d still have to keep track of what went where, and that’s exactly what we’re trying to avoid. Instead, we’re going to use references to keep track of our data as it gets moved around. That way we still have our original base array element that we can play with without having to know where it actually is in the tree.

Here is the code, and then we’ll go through it and explain.

foreach ($tree_data as $key => $node) {
	if ( ! $node['Model']['parent_id']) {
		continue;
	}

	if ( ! isset($tree_data[$node['Model']['parent_id']]['Child'])) {
		$tree_data[$node['Model']['parent_id']]['Child'] = array( );
	}

	$tree_data[$node['Model']['parent_id']]['Child'][] =& $tree_data[$key];
}

Now to explain… We parse through the array and for each element, we first test the element to see if it has a parent, if it does not, we just skip it, there’s no need to go further.

We then check and see if the parent element has an index called ‘Child’ and if it does not, we create one and set it as an array.

Then we do the magic. We set the next item in the parent node’s Child element to the reference of the current node. We don’t actually move the node. So now if you look at the array, you’ll see two entries for the current node, one inside the parent element, and one that was the original in the flat array.

WARNING: One thing to note here, is that we are not setting it to the reference of $node, but to the reference of $tree_data[$key]. The reason for this is because if the element is referenced to $node, the next time through the loop, all of the referenced elements will also be set to the new value of $node, and we certainly don’t want that.

The magical part of this, is that no matter where the references end up, the original is still there to be modified. So for instance if I have a branch path with IDs as follows: 12, 5, 13, 14… it doesn’t matter what that path is, I can still access the element with ID 14 by modifying $tree_data[14]. So if element 14 has child nodes, I can place them in the tree by modifying $tree_data[14]['Child'], and wherever that node is actually supposed to be, it will get modified there as well. That’s the beauty of references.

Now to clean up the array, we just parse through it once more, and clear out the original reference nodes (the ones that have parents):

foreach ($tree_data as $key => $node) {
	if ( ! empty($tree_data['Model']['parent_id']) {
		unset($tree_data[$key]);
	}
}

And that’s it! No messing around with paths… no iterative functions… just twice through an array (maybe three times), and it’s all sorted, compartmentalized, and pretty.

If you have other methods of getting your trees into a usable form, please let us know in the comments. We love seeing how other people do things.


06.01.2010   |   0comment

After some time off, the Sharpening the Blades series is back with two front-end/design articles.

Luke, Redesign v. Realign
I really liked this article. As designers when we are approached by a client we always start to redesign their project. Sometimes all they want is a realign though. This article defines what a redesign is and what a realign is. The way each is approached is different and when they are followed I think it will lead to more happy clients. The hard part is defining when each is needed. This article will help with that. Web designers give this a read.

Mike, Better Buttons with CSS3
With better browser support, CSS3 is finally starting to get some traction. While IE is still emerging from the dark ages, there’s no reason we can’t start using CSS3. Web Designer Wall recently published an article on creating web buttons with nothing more than CSS. Even though rounded corners, gradients, text shadows, and box shadows aren’t all supported, your buttons will look fantastic for browsers that do, and perfectly usable for the ones that don’t.



04.01.2010   |   0comment

This April Fools edition of Sharpening the Blades only has two serious articles and we’ll let you decide on the last one. Luke talks about the Future of Web Typography, Benjam talks about jQuery Methods and Mac, well, Mac is the playful one at the office so he chimes in with his April Fools joke for all you PHP gurus.

Luke, Future of Web Typography
For years typography on the web has been very limited when compared to what can be in the print world. Over the last few years though we have been given more and more tools to help us accomplish good typography on the web. As time goes on these tools will get better and will become more widely supported. There was an article on Smashing Magazine this week that talked about a lot of these tools that are available to web designers. I really enjoyed reading up, refreshing my memory of code I haven’t used in a while, and also learning some new ways of styling type. Read it over, the text on your website will be very happy you did.

Benjam, 20 Helpful jQuery Methods You Should Be Using
While developing a website, I use a lot of tools, both in the creation of the website files (my text editor of choice, file manager, etc.), and within the website itself (CakePHP, jQuery, CSS, etc.), and I’m always interested in finding features of those tools that I might not be very familiar with.  While I have a deep familiarity with the features I use regularly, and a passing familiarity with most of the features of these tools, it’s always good to get a refresher on what I could be using more.  Here is a post highlighting 20 jQuery methods/features (actually 33 methods in 20 groups) that should be in everybody’s familiarity tool box.

Mac, April Fools – PHP Style
This discusses a topic that we often only think about once or twice a year, but it is still worthy of our attention and deserves some practice to improve our skills. Also, while you are there, subscribe to the PHP Developers feed. The main guy, Chris Cornutt, does an excellent job of filtering the best PHP articles.


03.05.2010   |   1comment

This edition of Sharpening the Blades features an article from Mike about using jQuery, CSS and image sprites to create stylish forms, an article from Benjam about Passwords on the web and Mark chimes in with an article about the possibility of HTML5 in Internet Explorer 9.

Mike, Get your form on with Uniformuniform
We’ve all been there. You finish an amazing design using some sweet custom form elements that perfectly match the theme of your design. Then after a few frustrating attempts, you realize that some form elements just can’t be styled. Or if they can, not consistently. So you throw on a border, maybe a background image, and hope for the best as dreams of your custom UI vanish into nothingness. But fear not! Using the clever jQuery script Uniform and some CSS sprites, your form designs can once more be glorious! Works beautifully in all major browsers (degrades gracefully in IE6).

Benjam, The Problem with Passwordspasswords
Being in the Web Development industry for a while now, and having had a few third-party scripts that were on my site hacked, I have become more and more interested in web security.  Passwords are on the front lines to that.  Being a user of Web technologies, I’m also interested in usability and choice, and when it comes to showing or hiding passwords (what? you can do that?) I’m in the boat of give the user the choice.  This article nicely explains a few examples that offer people the choice to show or hide their passwords, both of which are very useful.

Mark, Microsoft to Double Down on HTML5 in Internet Explorer 9internetexplorer
Doubling down seems like the wrong approach to me. If I were the CEO at Microsoft I would instead of thinking of trying to put their foot down harder, they should instead learn to bend in the winds of the market and work on compliance with the other browsers. Though I hate to say it even forced upgrades like Firefox does would be good, to keep people current and reduce the amount of cross browsers compatibility problems Microsoft gives developers. I don’t think Microsoft realizes that by making developers lives bad by trying to be different they are actually building up a mass market of developers who hate them because it is so difficult to make cross compatibility easy and affordable.


Benjam,on the topic of  JavaScript, PHP, Tools, Usability
02.25.2010   |   5comment

Why is coding so personal?
I’ve been noticing that often times, when getting or giving feedback on code, or browsing my favorite programming forum, or just reading posts about programming, that people often get very emotional about their code. I was wondering why this is, and because I am not a psychologist, I’ll just give you my thoughts.

Coding to me is like creating art, and there’s a great quote that backs me up on this:

Programming is an art form that fights back. —Unknown

Because code is like art, I get very attached to my code, as well as my style of coding. My code is like my baby, my something from nothing that wouldn’t be there if it weren’t for me. It’s just a bunch of characters on the screen that, from somewhere in the blue smoke, creates a function, or a game, or a website. I have received criticism on my code (as everyone has), as well as given criticism on other’s code (as everyone has), and those times when I’ve received criticism on my code, depending on how it was delivered, or what was said, it was almost like a personal attack on me. And I’ve noticed a few other coders react the same way to criticisms on their code. It’s like the person who called your code ugly or inelegant was saying that your child was ugly (and those of you who have kids know… that’s a huge no-no, punishable by any means available).

It may be because I think that my coding style is the best, it’s what I’m used to, and it’s the format I use because it’s the easiest for me to get at the information I need as fast as possible. I know this because I’ve tried other styles (sometimes flipping back and forth in the same day), and looking at someone else’s code that uses a different style from me, is often times hard to peruse easily. It’s what I like, and sometimes I have to hold myself back from reformatting code I come across into my own style.

So maybe we should stop thinking of code and coding styles as being “right” or “wrong”, and think of them more like the tool that they are, a means to an end. And the way you react to someone else’s means should be a little more like a suggestion for a different method of painting. Not a matter of fact, but just another tool for the tool box.

To continue the art analogy, it’s like everybody is given all the art supplies in the world, and told to make/paint/draw/create a box. Everyone will come up with a different way of doing it, some will be huge and bright red; others will be small and drawn in pencil; others still might be made of clay or brick. No matter what, it’s the way you chose to do it, and it’s no better or worse than the person’s next to you. You might think so because yours was faster, fancier, more elegant, or more “boxy”; but they might think the opposite. In the end, you still have a box, and so do they.


02.19.2010   |   0comment

This weeks edition features an article about customizing WordPress for beginners, designers who can’t code their own designs and the best way to handle content management systems for sites that matter.

Chad, The Beginner’s Guide to Tricking Out Your WordPress Blogtrickingoutwordpress
I liked this post/entry about WP because it was built and geared for the beginner. Once you installed it now what. I find these type of articles interesting because sometimes they are just so simple that I don’t even think of them. And it helps me to explain or think of other things that I feel our clients may want or need.

Mike, Web Designer’s Who Can’t Codedesignerswhocantcode
Twitter exploded in a debate this week when Elliot Jay Stocks boldly tweeted:

“Honestly, I’m shocked that in 2010 I’m still coming across ‘web designers’ who can’t code their own designs. No excuse.”

The world is full of talented designers trained in a wide array of media, but just like other mediums, the web offers its own constraints and limitations. Knowing how to code definitely gives you an edge, even if you don’t code the site yourself. Image resolution, measurements, typography, and browser discrepancies all play a role in what is possible, and help determine the collective best practices of the web. So does a good architect need to know how to dry wall? Maybe not. What about a fundamental understanding of construction and engineering? Absolutely. How much does a good web designer need to know about their craft in order to build a successful website? What do you think?

Mac, Content Management for Sites that Mattercontentmanagementforsitesthatmatter
I liked this article because it gets right at the core of the cost/benefit trade-off that many people don’t think enough about when building their web site. Either there’s a significant value to the work you’re doing on your site, which justifies spending some money on it and getting it done right, or there isn’t a significant value to your site, so why bother? I don’t 100% agree with them about the WYSIWIG comments, but I’ve never tried to tell a client to assume it would look identical in TinyMCE and on the public site. We’ve generally had to train them to be very careful to keep it simple. Use bold if you want, make some lists, paragraphs, links, and stuff like that, but don’t try and do anything funky or you’ll end up disappointed. Another annoying thing about TinyMCE is that even when you tweak the HTML manually in their HTML view, it often wants to “automatically fix” some of the things you did. I was trying to leave a <br /> or two between a couple of separate lists if I remember right, and it kept either taking it completely out, or turning into a paragraph, constantly leaving too much or too little whitespace, even though the HTML I manually entered would display exactly how I intended.


Benjam,on the topic of  Usability, WordPress
01.12.2010   |   5comment

A few of our projects here at Code Greene required the use of WordPress, and those projects had situations that I have since encountered in a site I built in WordPress for someone in my family. That situation was trying to redirect to a parent or child page when a certain page was clicked on.

I know that may seem a bit confusing, but let me give an example. Say I have an “About” page, and that “About” page has three child pages; “Who I Am”, “What I Do”, and “Why I Do It”. Now let’s also say that my “About” page doesn’t have any actual content, it’s just a container for the other three pages, and I just want to redirect my visitors to the “About | Who I Am” page without ever hitting the “About” page. Well, here’s how I do that.

First we need a page template that we can use for the “About” page that will do all the magic for us:

In a new file in your theme folder called redirect_down.php (you can really call it anything you want, this is what I used), put the following:


<?php

/*
Template Name: Redirect Down
*/

// grab the direct children pages of this page
// (both child_of and parent are needed)
$sub_pages = get_pages(array('child_of' => $post->ID, 'parent' => $post->ID, 'sort_column' => 'menu_order', 'number' => 1));

$URI = get_permalink($sub_pages[0]->ID);

// redirect the user down one level in the tree
header('Location: '.$URI);

How this works is it finds the first child of the page you are on, grabs the URI for it, and redirects you to that page.

Now when I create my “About” page (the one with no content), I set my page template to “Redirect Down” in the template drop down, and voilà, when a visitor clicks on the “About” link, they automatically get redirected to the “About | Who I Am” page, no questions asked. If I had pages under the “Who I Am” page, and it was just a container for those, I could also set my template for the “Who I Am” page to “Redirect Down”, and when my visitor clicked the “About” link, it would redirect to the “Who I Am” page, which would then redirect to the first child page.

To complete the collection… in one of the projects I worked on recently, we had a situation where if a child page link was clicked, we needed to redirect up the tree to the parent page. This is basically the same thing, just the other direction, but also a bit easier to code. Here is how it is achieved:

In a new file in your theme folder called redirect_up.php (again, you can call it anything you want, this is just what I used), put the following:


<?php

/*
Template Name: Redirect Up
*/

// redirect the user up one level in the tree
$URI = rtrim($_SERVER['REQUEST_URI'], ' /');

$URI = substr($URI, 0, strrpos($URI, '/') + 1);

if ( ! in_array($URI, array('', '/'))) {
	header('Location: '.$URI);
}

The way this works, is it grabs the URI given, and simply removes the last directory from the URI. (You could also find the parent ID from the $post data and use that to find the permalink, much like the previous template, but this works for what I needed it to do.) If you have your permalinks set up properly, this should work beautifully. And again, with this one, you can set it on as many pages as you want, redirecting all the way up the tree if you wish.

Hope this helps someone. Let me know if it helped you in the comments below.


Benjam,on the topic of  Usability, WordPress
05.07.2009   |   24comment

EDIT: This post has been deprecated by the recently released WordPress 2.9. Please update your WordPress installation to get this functionality in your blog.

If you don’t wish to update your blog software, then please continue reading.


I was writing a post on my personal blog recently and wanted to show a gallery of pictures, but I also wanted to show one of those pictures near the top of the post, but not in the gallery, and if you’ve ever tried to do this with [gallery], you know it can’t be done.

Well, now it can, and I’ll show you how.

continue reading Filter images from WordPress [gallery]”


Master Sensei,on the topic of  Usability
03.01.2009   |   13comment

When I first started dabbling with HTML, it was from within the Notepad program on Windows 98. The font used was the one and only fixedsys, which happens to be the oldest font on Windows, dating all the way back to version 1.0.

fixedsys

Digital typography has come a long way in the last decade, and a wide array of monospaced beauties are now available for our coding pleasure. But what’s the best font choice when it comes to code? What about size? What about color? I think a lot of these decisions come down to personal preference, but one thing’s for sure, when you’re staring at a screen for hours on end, readability is paramount.

continue reading What’s the best coding font?”