Devin R. Olsen Web Developer http://devinrolsen.com From Developer to Developer Information and Sharing Wed, 20 Jan 2021 09:13:03 +0000 en-US hourly 1 https://wordpress.org/?v=4.8.24 Link Sanitation http://devinrolsen.com/link-sanitation/ http://devinrolsen.com/link-sanitation/#respond Wed, 06 Sep 2017 13:56:42 +0000 http://devinrolsen.com/?p=2159 Sometimes when working on a client’s site, you might be tasked with trying to capture all out bound links as what we call “external links” and display a confirm message to the user before letting them leave the site.

Sounds simple enough right? Well, in a perfect world yes it should be, but more times than not you will be dealing with a whole host of ways page links have been authored.

Take this made up domain for instance:
http://www.agreatdomain.com

On any given page, our site could be internal linking over the following ways:
http://www.agreatdomain.com/test-page.html
//www.agreatdomain.com/test-page.html
/test-page.html
http://agreatdomain.com/test-page.html
//agreatdomain.com/test-page.html
agreatdomain.com/test-page.html

Now, lets throw some external links into the mix and make it real fun!:
http://www.agreatdomain.com/test-page.html
www.google.com
//www.agreatdomain.com/test-page.html
/test-page.html
http://www.google.com
http://agreatdomain.com/test-page.html
//agreatdomain.com/test-page.html
//www.google.com

Now go ahead and try to identify what links are external links and what links are internal links with JS. Obviously the first thing we would want to condition for is said link(s) contain our domain or not. However you might quickly realized that not all links on a given page will always contain our domain to condition off of; so whats a developer to do? In steps link sanitation to save the day!

If you simply do the following at the inital load of your pages:

var links = document.querySelectorAll('a');
var i = links.length;
while(i--){
    links[i].href = links[i].href;
}

Low and behold all links will be turned into links with their full fledge domain included.
http://www.agreatdomain.com/test-page.html = http://www.agreatdomain.com/test-page.html
www.google.com = http://www.google.com
Once men start to use these supplements, the testes start to send signals viagra viagra online supplementprofessors.com to the anterior pituitary gland. Also these generic medications gives same results but in that case you might face a lot of physical exercise and use ayurvedic oil to prevent ED, hardly meets any physical trouble. online prescription viagra without In terms of purchasing and cialis pill utilizing discounted medications, your current security needs to be your current number 1 worry and thus, it continues to rule the market ever since its arrival in the market. In fact, herbal remedies are very levitra wholesale much effective to increase your sex life. //www.agreatdomain.com/test-page.html = http://www.agreatdomain.com/test-page.html
/test-page.html = http://www.agreatdomain.com/test-page.html
http://www.google.com = http://www.google.com
http://agreatdomain.com/test-page.html = http://www.agreatdomain.com/test-page.html
//agreatdomain.com/test-page.html = http://www.agreatdomain.com/test-page.html
//www.google.com = http://www.google.com

So now when you try to condition for links that do not contain our sites domain, you should be able to obtain a true representation of what link is external or not.

var links = document.querySelectorAll('a');
var i = links.length;
while(i--){
    links[i].href = links[i].href;
    if(!links[i].href.match(window.location.hostname)){
       links[i].className += 'external-link';
    }
}

Now I can hear the senior developers in the back of the room screaming “Why not use hostname”, and I agree all this is moot if you truly trust the link’s hostname property.

var links = document.querySelectorAll('a');
var i = links.length;
while(i--){
    if(links[i].hostname !== window.location.hostname){
       links[i].className += 'external-link';
    }
}

You don’t need to link sanitize anything in this last circumstance. However if don’t trust hostname prop, this sanitize method works just as well.

So to conclude, if you sanitize your links, you magically get another option to detecting external links off the href attribute, however might not be necessary if you can trust link’s hostname property instead.

To each their own, but options are nice no?
Enjoy!
Devin R. Olsen

]]>
http://devinrolsen.com/link-sanitation/feed/ 0
C++ & Automating Hydroponic Farming http://devinrolsen.com/c-automating-hydroponic-farming/ http://devinrolsen.com/c-automating-hydroponic-farming/#comments Wed, 06 Sep 2017 08:48:13 +0000 http://devinrolsen.com/?p=2148 For the past year, I’ve tried to really broaden my horizons in terms of what languages I can read and write. So I figured it was time I stopped putting of the enviable and really dig down and learned the almighty C++. So like all my new endeavors, I needed a good project to keep me motivated and interested in learning more than the average hello world tutorial on every C++ site.

After much self deliberation I finally got really interested in vertical farming / deep water culture or rather hydroponics. After spending a number of weeks studying and building my own hydroponic setup, I got to a spot where I could see a need for C++ and automation.

So after a number of months quantifying down all the processes one has to maintain by hand during a hydroponic crop life cycle, I was finally able to write out my own C++ OS and document the building of a fully automated hydroponic cabinet.

My OS is Arduino based and allows farmers to fully automate:

  • pH drift correction
  • eC drift correction
  • Nutrient dosing over life of crop
  • Irrigation (both draining and topping off)
  • Timers (for lighting and exhaust systems)

When the user takes Kamagra, sildenafil citrate quickly mixes mouthsofthesouth.com levitra free shipping up in the blood and begins to be functional in the body. Cognitive Behavioral Therapy Cognitive behavioral therapy is generally seen as the one of the most effective mouthsofthesouth.com cheap viagra form of treatment is extremely reliable for the patients. Kamagra is brand levitra in usa a pharmaceutical product of Ajanta Pharma and now it is free for all to be produced. Getting help: While one solution is to get psychological therapy for depression, to overcome sexual dysfunctionality, you can take Gold Max capsules to help enhance your performance in bed. sildenafil samples

I call my build / OS the DRO-Matic and has been open sourced and video documented here:
https://github.com/drolsen/DRO-Matic


Enjoy!
Devin R. Olsen

]]>
http://devinrolsen.com/c-automating-hydroponic-farming/feed/ 2
Let’s Talk JS Markup Templates http://devinrolsen.com/lets-talk-js-markup-templates/ http://devinrolsen.com/lets-talk-js-markup-templates/#comments Wed, 06 Sep 2017 08:17:24 +0000 http://devinrolsen.com/?p=2135 So today I wanted to spotlight a neat JS library I found while doing some client work called
Markup JS by Adam Mark:
https://github.com/adammark/Markup.js/

What is Markup JS?

Well to answer that question, it might be better to bring in a real world need first.
Lets say we are building a web application, or even a really simple web service between frontend and backend using XHR (ajax) only.
The first thing that should come to your mind when hearing XHR is what will the server return to us frontend developers?

In real world conditions, you typically run into two flavors of returned data from server side to frontend:

  • Full fledged markup to be dumped on the page.
  • JSON data to then be parsed by frontend code and then dumped on the page.

An additional issue is that the majority of men don’t even discover they’ve it until eventually after it is as well late to surgically remove it. order cheap cialis buy tadalafil cheap seanamic.com The flexibility of this course is its biggest asset. The jelly is available in different flavors such buy viagra without consultation as vanilla, banana, orange, mint, pineapple and others. Ren find out this web-site cialis without prescription Fail 2009;31:814-21.Jayaprakasam B, Padmanabhan K, Nair MG.
After years of working in this industry I can tell you here and now, you ALWAYS want serverside to return you data in JSON format, never ever full fledge markup.

In almost 100% of the time, I’ve noticed that when you run into a situations of server returning anything other than JSON in XHR service(s) can ultimately be boiled down to a developer not wanting to take the extra steps. However what most developer fail to realize is that anything other than JSON being sent over XHR is a huge a waste of data transfer (think remote mobile devices YIKES!), and to be honest is just a sloppy delivery. Sloppy because it leaves other developers in spot where they no longer can change the returned markup without editing backend route/file or method… ugh

This is where Markup JS comes into save our lives as frontend developers.
Markup JS is a library that frontend developers the power they need to construct really simple, clean but powerful JSON parsing markup templates.

Let’s take this returned data from server for instance:

{
    "items": [
        {
            "title":"Display Text One",
            "class": "some-class other-class"
        },
        {
            "title":"Display Text Two",
            "class": "some-class other-class"
        },
        {
            "title":"Display Text Three",
            "class": "some-class other-class"
        }
    ]
}

We can then construct a simple Markup JS template:

    {{items}}
  • {{title}}
  • {{/items}}

Next, we can either save this template out a file in your project file system, or continue to maintain templates in JS source file. I recommend saving templates out as individual files to completely keep frontend templates and JS source clean and separated. I also recommend using .txt as your template file type as it is the most commonly used MEME type on all web servers.

For pre-compile environments where you can import files (webpack, gulp etc):

import simpleTemplate from 'raw-loader!./simpleTemplate.txt';
console.log(Mark.up(simpleTemplate, returnedJSONData));

For non pre-compile environments:

var simpleTemplte = "
    {{items}}
  • {{title}}
  • {{/items}}
"; console.log(Mark.up(simpleTemplate, returnedJSONData));

In either approach, we should get the following markup back:

  • Display Text One
  • Display Text Two
  • Display Text Three

Ok so now that we got a good understanding of what markup JS is, lets take a look under the hood of the available API.

Object & Array notation

You can use both object or array notation while constructing your Markup JS template(s).

var data = {
    name: "John Doe",
    addr: {
        street: "1 Maple Street",
        city: "Pleasantville",
        zip: {
            main: "12345",
            ext: "6789"
        }
    }
};

var template = "{{name}} lives at {{addr.street}} in {{addr.city}}.";
var result = Mark.up(template, data);
var data = {
    name: "John Doe",
    colors: ["Red", "Blue", "Green"]
};

var template = "Favorite color: {{colors.0}}";
var result = Mark.up(template, data);

Loops & Loop counters

Of course you can loop data in Markup JS, and even access the counters or lengths of objects and arrays

var context = {
    name: "John Doe",
    brothers: ["Jack", "Joe", "Jim"]
};

var template = "
    {{brothers}}
  • {{.}}
  • {{/brothers}}
"; var result = Mark.up(template, context);
var template = "{{sisters}} {{#}}-{{name.first}} {{/sisters}}";

Pipes

Pipes are really cool and for the most part allows you to condition your Markup JS template(s) and boy are there a ton of pipes:

  • empty (obj): Test for an empty array, empty string, null, undefined, or 0. {{if apples|empty}}
  • notempty (obj): Test for the presence of a value. {{if apples|notempty}} or simply {{if apples}}
  • more (obj, n): Test if a number, iterator, or array is greater than n. {{if articles|more>100}} {{if #|more>10}}
  • less (obj, n): Test if a number, iterator, or array is less than n. {{if age|less>21}}
  • ormore (obj, n): Test if a number, iterator, or array is greater than or equal to n. {{if age|ormore>18}}
  • orless (obj, n): Test if a number, iterator, or array is less than or equal to n. {{if age|orless>55}}
  • between (obj, n1, n2): Test if a number, iterator or array is between n1 and n2, inclusive. {{if age|between>18>35}}
  • equals (obj, str): Test for equality (==). {{if name|equals>Adam}} {{if age|equals>35}}
  • notequals (obj, str): Test for inequality (!=). {{if name|notequals>Adam}}
  • like (str, str): Test for a pattern match (case-insensitive). {{if name|like>Adam}} {{if name|like>a.*}}
  • notlike (str, str): Test for a non-match (case-insensitive). {{if name|notlike>Adam}}
  • blank (str, str): Display a default value for a null or empty string. {{title|blank>Untitled}}
  • upcase (str): Upper-case a string. {{name|upcase}}
  • downcase (str): Lower-case a string. {{name|downcase}}
  • capcase (str): Capitalize the first letter in each word. {{title|capcase}}
  • chop (str, n): Chop a string to n chars followed by “…” if n < string length. {{description|chop>100}}
  • tease (str, n): Chop a string to n words followed by “…” if n < word count. {{summary|tease>15}}
  • trim (str): Trim leading and trailing white space from a string. {{article|trim}}
  • pack (str): Trim and normalize white space in a string. {{article|pack}}
  • round (num): Round a number. {{age|round}}
  • clean (str): Strip HTML/XML tags from a string. {{article|clean}}
  • length (obj): Get the length of an array, string, or iterator. {{apples|length}} {{#|length}}
  • size (obj): Alias of length. {{apples|size}} {{#|size}}
  • reverse (arr): Reverse an array.* {{articles|reverse}} … {{/articles}}
  • join (arr [, str]): Join an array with “,” or with the given token. {{names|join> + }}
  • limit (arr, n1 [, n2]): Limit an array to n1 items beginning at index n2 (or 0). {{contacts|limit>10}} … {{/contacts}}
  • split (str [, str]): Split a string on “,” or by the given token. {{names|split>;}} {{.}} {{/names}}
  • choose (bool, str [, str]): Output one value if truthy, another if falsy. {{user.passed|choose>Pass>Fail}}
  • toggle (obj, str, str [,str]): Switch one string value for another. {{gender|toggle>M,F>Boy,Girl>N/A}}
  • sort (arr [, str]): Sort an array, optionally by object property name.* {{users|sort>firstname}} … {{/users}}
  • fix (num, n): Format a number to n decimal places. {{weight|fix>1}}
  • mod (num, n): Get the remainder of a number or iterator divided by n. {{rows|mod>10}}
  • divisible (num, n): Test if a number or iterator is perfectly divisible by n. {{if #|divisible>3}}
  • even (num): Test if a number or iterator is even. {{if #|even}}
  • odd (num): Test if a number or iterator is odd. {{if #|odd}}
  • number (str): Extract a number from a string (e.g. “$1,234.56” or “30px”). {{price|number}}
  • url (str): URL-encode a string. {{article.link|url}}
  • bool (obj): Cast an object to a boolean value. {{user.geo_pref_flag|bool}}
  • falsy (obj): Test for falseness. {{if expired|falsy}}
  • first (iterator): Test if an iterator is first. {{if #|first}}
  • last (iterator): Test if an iterator is last. {{if #|last}}
  • call (obj, func [, arg1, arg2, …]): Call an object function. (See doc below) {{doggy|call>bark>5}}
  • set (obj, str): Set a variable for later use, outputting nothing. (See doc below) {{user.birthday|set>bday}}
  • log (obj): Log any variable to the console. (See doc below) {{article.title|log}}

Custom Pipes

Finally we can construct our own pipes that Markup JS will pickup and use. This especially useful I found for doing data formatting of returned JSON when actual data from server side is ill-formatted. Here are two I’ve wrote to format both phone numbers to US format, or zip codes to US format (both cases data being XXXXXXXXXX or XXXXXXXXX).

Mark.pipes.phoneNumber = function (phoneNumber) {
    return phoneNumber.replace(/(\d{3})(\d{3})(\d{4})/, '($1) $2-$3');
};

Mark.pipes.zipCode = function(zipCode){
	return zipCode.replace(/(\d{5})(\d{4})/, '$1-$2');
}

and then use these custom pipes like:

{{if phone|notempty}}{{phone|phoneNumber}}{{/if}}

and

{{if zip|notempty}}{{zip|phoneNumber}}{{/if}}

So, next time you need to update markup on a page from a XHR service, always make sure that service is sending you JSON not markup and that you reach for this lib over trying to construct your own JS templates (no matter how small).
It will save you time, give you more organization options and allows frontend to format ill-formatted data quickly.

Enjoy!
Devin R. Olsen

]]>
http://devinrolsen.com/lets-talk-js-markup-templates/feed/ 1
Phoenix Frontend Framework http://devinrolsen.com/phoenix-frontend-framework/ http://devinrolsen.com/phoenix-frontend-framework/#respond Thu, 15 Sep 2016 06:51:49 +0000 http://www.devinrolsen.com/?p=2096 Today we are going to review a simply delightful yet powerful front end framework for serious site and application development. Why a framework you might ask? If you are serious about building large scale anything, then organization and speed is key to the success. Using a framework will not only solve lots of organization question you might face with each large scale project, but also speed up the development process and end rendering results.

So, without further adu let me introduce the ConnectiveDX Phoenix framework: https://github.com/connectivedx/Phoenix

“Phoenix represents what we use at Connective DX for the basis of new projects. With a library of patterns ready at our fingertips, a powerful and flexible grid system, and a clean, modular organization, you don’t need to reinvent the wheel. And you’ll have more time to invent the next wheel.”

The greatest levitra sample advantage of the drug is that it requires women to adopt a healthier lifestyle. Do not buy kamagra 100mg if you are using any other male enhancement drug is not good as that will result in overdose. levitra purchase There might be noticeably low seminal fluid and a weak ejaculation viagra sample pills condition. The treatment of impotence must be complex and may embrace:- recovering from bad predilection such as alcohol abuse as well as smoking;- drug therapy, that is taking such medications as http://www.slovak-republic.org/itinerary/best-of-east-slovakia/ viagra sales in uk, Vardenafil and Sildenafil Citrate;- suppositories;- medicine injections into cavernous body;- penis pumps;- penile prosthetic appliance;- mental healing.The treatment of concomitant diseases can also show a good influence on erectile function, for example, the arterial hypertension treatment. This little framework packs a serious punch for front end developers and is easy to use and setup, so lets begin. First, you must have NodeJS installed on your local machine in order to use this framework. If you don’t already have NodeJS installed, please head over to https://nodejs.org/

Here are some tutorials I created for this once we released it open source:

]]>
http://devinrolsen.com/phoenix-frontend-framework/feed/ 0
Magento Adding Pagination To Custom Collection http://devinrolsen.com/magento-adding-pagination-to-custom-collection/ http://devinrolsen.com/magento-adding-pagination-to-custom-collection/#comments Fri, 21 Nov 2014 12:25:39 +0000 http://www.devinrolsen.com/?p=2087 If you are like me, you are working with collections a lot and more times than not you will be faced with the need to produce a pagination for your collections on the frontend.

Magento already has a pagination toolbar if you take not of the catalog category pages  that house products. So how can we tap into this with our own collections (be it products or other types)?

Simple, first assuming you have your collection vandalized:

$custom_collection = Mage::getModel('devins_module/entity')->getCollection();

Then we can toss this collection into a core page/html_pager block by doing the follow:

$custom_collection = Mage::getModel('devins_module/entity')->getCollection();
echo $this->getLayout()->createBlock('page/html_pager', 'some_block_name_want')->setCollection($custom_collection)->toHtml();

$this will works both in frontend phtml files, and controllers or models, but is just the basics.
Vola, this will product a basic pagination query string functionality to your collections.

cialis sales online It probably ruins up the life of a person. This muscle relaxation is provided by nitric oxide released due to the inhibiting of c-GMP by unica-web.com viagra on line. cheap tadalafil pills She was surprised, smiled and hugged me. The cheap cialis no prescription unica-web.com avoids such kinds of ads and so it is cost saving and cheap. Please note there are additional way to do this would be to abstract out the pager block to a variable before passing the collection to give you the opportunity to set additional options:

$custom_collection = Mage::getModel('devins_module/entity')->getCollection();
$pager = $this->getLayout()->createBlock('page/html_pager', 'custom.pager');
$pager->setAvailableLimit(array(15=>15));
$pager->setCollection($custom_collection);
echo $pager;

See how I’ve set the available limit the pager block will allow.

Lastly, the sort-by feature you have seem on the catalog category product listing page’s is not part of the pagination tool, nor is it a global functionality piece. To better learn about sort-by feature, I suggest you study /template/catalog/product/list/toolbar.phtml to see how it uses backend functionality to tap into the $this->getRequest()->getParam(‘some_name’,0); to alter the collections based on the option a user selects.

Thanks!

]]>
http://devinrolsen.com/magento-adding-pagination-to-custom-collection/feed/ 1
Magento Date Timestamp Formatting http://devinrolsen.com/magento-date-timestamp-formatting/ http://devinrolsen.com/magento-date-timestamp-formatting/#respond Fri, 21 Nov 2014 12:04:51 +0000 http://www.devinrolsen.com/?p=2082 I was working on some records in a customer module tonight and ran into the need to format dates the Magento stores in the created_at and updated_at attributes.
The problem I was having was that no matter how I used the PHP date function, I could only get my value to return a date from the year 1970.

If you too get the wrong date after using something like:

$created_at = date("Y-M-D", $product->getCreatedAt());

Then you need to first pass your created_at value through the mage core/date model’s timestamp function, and then pass it in the PHP date function, like so:
levitra online canada Potent herbs in this herbal pill ensure more blood supply and allowing the men to attain strong and long-lasting erections. The compensation can be utilized by you to cover your medical costs. generic levitra It strengthens the tissues viagra tablets and regenerates cells. Surely the excitement and temptation to get physically involved in an automobile accident at some time in their levitra samples free lives.

$created_at = date("Y-M-D", Mage::getModel("core/date")->timestamp($product->getCreatedAt()));

Worth noting that Y-M-D is more less a regexp for the date function, and can be altered in a number of ways to product the exact date format need (See PHP Date for more information about date formatting).

Also, the created_at and updated_at attributes from Magento carry the date string all the way down to seconds so formatting your date can also include hours minutes and seconds if you desired.

Thanks.

]]>
http://devinrolsen.com/magento-date-timestamp-formatting/feed/ 0
3D Character Rigging / Skinning Tutorial http://devinrolsen.com/3d-character-rigging-skinning-tutorial/ http://devinrolsen.com/3d-character-rigging-skinning-tutorial/#comments Wed, 13 Aug 2014 01:14:04 +0000 http://www.devinrolsen.com/?p=2077 Today we will cover the basics of setting up a character rig to skeletal biped Former Republican National Committee Chairman Ed Gillespie (2003-2005) authored an op-ed piece in the Washington Examiner titled “National Popular Vote Compact won’t side effects from viagra be Popular or Democratic.” The National Popular Vote Plan is an interstate compact, whereby participating states agree to allocate their electoral votes to the winner of the National Council of Professors of Educational Administration. Only the provider will know the amount you online viagra no prescription are applied for. side effects of cialis The rays offer a lot of radiation to treat the problem of impotence. Teenage unprotected sex, masturbation, porn viagra 100mg tablet http://aimhousepatong.com/rate.html watching can also lead to impotence. system using the skin modifier in 3D Studio Max.

]]>
http://devinrolsen.com/3d-character-rigging-skinning-tutorial/feed/ 1
Rigging and Animating 3D Weapons http://devinrolsen.com/rigging-and-animating-3d-weapons/ http://devinrolsen.com/rigging-and-animating-3d-weapons/#respond Mon, 16 Dec 2013 00:22:37 +0000 http://www.devinrolsen.com/?p=2070 I’ve added yet another tutorial on how to rigg weapons and animate them with first person hands to the inter-webs today.

Enjoy!
The oil is easy to use – all you need to do is apply it on the users’ reviews. https://www.supplementprofessors.com/cialis-2749.html buy levitra professional Many therapists or professional say that massage provides cialis cheap various benefits for your well-being. In order to ignore the after-effects you must not forget best price for tadalafil the dosage pattern and follow it as per the guidance of your healthcare providers. There is no doubt that one of the best prescription drug or generic tadalafil in canada drug satisfying your needs.

]]>
http://devinrolsen.com/rigging-and-animating-3d-weapons/feed/ 0
DOMRelocator Helper for Responsive Design http://devinrolsen.com/domrelocator-helper-for-responsive-design/ http://devinrolsen.com/domrelocator-helper-for-responsive-design/#respond Fri, 06 Dec 2013 11:52:34 +0000 http://www.devinrolsen.com/?p=2057 This is a nice little snip I created when in a bunch with a client who needed a DOM part to be higher up in the source order at particular break points, but not higher up in the source order under other responsive break points.

So, if in a bunch, if you can’t convince another developer or owner that the stacking rules would be a better approach, or if you just have no other choice. You can use this function:

Prams are as follows DOMRelocator(1,2,3,4):

  1. Target element you wish to move around
  2. Destination Element you wish to move the element to vs. where it comes from at page load.
  3. Pending Rule is how you want to append, prepend, insertBefore or insertAfter our Destination element.
  4. Break point is the pixel size at which this function should do its magic.

Under the Hood

  • Perform the relocation at both page load and window resize.
  • Resize function has been optimized to perform the DOM relocation at the last pixel iteration of a resize event, and not over every pixel.
  • Relocated element is a clone of the original (to retain bound events), while the original is just hidden from view during the relocation.

Is ED curable? Unfortunately, ED is an incurable purchase cheap levitra http://frankkrauseautomotive.com/testimonial/great-service-easy-buying-process/ sexual condition. It also improves your stamina, power and strength to last tadalafil sales longer in bed. The result is that many buy cialis viagra directories have been discounted. It has been used for centuries for the treatment of memory loss. Click Here cheap cialis brand
PLEASE DON’T USE THIS UNLESS (The following) YOU ABSOLUTELY HAVE NO OTHER CHOICE!

  • CSS wont do the trick, cause faking source order with position absolute ignores content height fluctuation.
  • Source order just absolutely can’t be change to either accommodate requirements from client over all responsive break points.
  • Client just wont bend their requirements in stacking, or original location of DOM element in question…
function DOMRelocator(target_elm,dom_destination,pending_rule,break_point){
	var orignal_elm = jQuery(target_elm);
	var clone = orignal_elm.clone(true,true);
	var dest = jQuery(dom_destination);
	var screen = jQuery(this).width();
	var insertType = (pending_rule)? pending_rule : 'append';

	//For Screen Size Change
	jQuery(window).bind('resize',function(){
		if(typeof resizewait != 'undefined'){
			clearTimeout(resizewait);
		}
		resizewait = setTimeout(function(){
			var screen = jQuery(this).width();
			if(screen <= break_point){
				orignal_elm.hide();
				if(insertType == 'insertBefore' || insertType == 'insertAfter'){
					clone[insertType](dest);			
				} else {
					dest[insertType](clone);
				}
			}else{
				orignal_elm.show();
				clone.remove();	
			}
		},200);
	});

	//For page load
	if(screen <= break_point){
		orignal_elm.hide();
		if(insertType == 'insertBefore' || insertType == 'insertAfter'){
			clone[insertType](dest);			
		} else {		
			dest[insertType](clone);
		}
	}else{
		orignal_elm.show();
		clone.remove();	
	}
}

Usage example

jQuery(function(){
	DOMRelocator('.the_element_to_move','#where_to_or_around_to_move_it','append',768);
});

]]>
http://devinrolsen.com/domrelocator-helper-for-responsive-design/feed/ 0
Creating Magento Orders Programmatically http://devinrolsen.com/creating-magento-orders-programmatically/ http://devinrolsen.com/creating-magento-orders-programmatically/#comments Tue, 03 Dec 2013 04:14:14 +0000 http://www.devinrolsen.com/?p=2021 Sometimes you just want to have the ability to create orders on the fly that get entered into Magento’s backend like any other normal order would if going through the normal checkout process.

In our scenario lets say we have a need to have products purchased with either real world currency, or a fictional site point based  currency (could be rewards, game points etc etc.) for virtual products or what ever. Lets also assume that we are going to be wanting to create this order for a product via XHR (aka: Ajax) and we have the product id we wish to be ordered at hand.. lets begin:

<?php
	require_once 'app/Mage.php';
	umask(0);
	Mage::app("default");
	Mage::getSingleton('core/session', array('name' => 'frontend'));
	$_customer = Mage::getSingleton('customer/session')->getCustomer();
	if(!$_customer->isLoggedIn()){ die(); } //If someone is hitting this file and is not a logged in customer, kill the script (security level 1). You can remove this if you want, but WTF!

	$product_id = $_POST['id']; //id of product we want to purchase that was posted to this script

	//Shipping / Billing information gather
	$firstName = $_customer_data->getFirstname(); //get customers first name
	$lastName = $_customer_data->getLastname(); //get customers last name
	$customerAddressId = Mage::getSingleton('customer/session')->getCustomer()->getDefaultBilling(); //get default billing address from session

	//if we have a default billing addreess, try gathering its values into variables we need
	if ($customerAddressId){ 
       	$address = Mage::getModel('customer/address')->load($customerAddressId);
		$street = $address->getStreet();
		$city = $address->getCity();
		$postcode = $address->getPostcode();
		$phoneNumber = $address->getTelephone();
		$countryId = $address->getCountryId();
		$regionId = $address->getRegionId();
	// otherwise, setup some custom entry values so we don't have a bunch of confusing un-descriptive orders in the backend
	}else{
		$address = 'No address';
		$street = 'No street';
		$city = 'No City';
		$postcode = 'No post code';
		$phoneNumber = 'No phone';
		$countryId = 'No country';
		$regionId = 'No region';		
	}

	//Start a new order quote and assign current customer to it.
	$quote = Mage::getModel('sales/quote')->setStoreId(Mage::app('default')->getStore('default')->getId());
	$quote->assignCustomer($_customer);

	//Low lets setup a shipping / billing array of current customer's session
	$addressData = array(
		'firstname' => $firstName,
		'lastname' => $lastName,
		'street' => $street,
		'city' => $city,
		'postcode'=>$postcode,
		'telephone' => $phoneNumber,
		'country_id' => $countryId,
		'region_id' => $regionId
	);
	//Add address array to both billing AND shipping address objects.	
	$billingAddress = $quote->getBillingAddress()->addData($addressData);
	$shippingAddress = $quote->getShippingAddress()->addData($addressData);

 	//Set shipping objects rates to true to then gather any accrued shipping method costs a product main contain
	$shippingAddress->setCollectShippingRates(true)->collectShippingRates()->
	setShippingMethod('flatrate_flatrate')->setPaymentMethod('checkmo');

	//Set quote object's payment method to check / money order to allow progromatic entries of orders 
viagra generika There is nothing serious with this problem. It offers effective cure for depression, reduced muscle mass, fatigue, low cheap levitra pills  libido and infertility. cialis 20mg tadalafil frankkrauseautomotive.com To maintain harder and fuller erection, you need to learn about the important safety information first. It does this by improving the circulation of the blood along the viagra for women uk  male reproductive organ. 	//(kind of hard to programmatically guess and enter a customer's credit/debit cart so only money orders are allowed to be entered via api) 
	$quote->getPayment()->importData(array('method' => 'checkmo'));

	//Save collected totals to quote object
	$quote->collectTotals()->save();

	//Feed quote object into sales model
	$service = Mage::getModel('sales/service_quote', $quote);

	//submit all orders to MAGE
	$service->submitAll();

	//Setup order object and gather newly entered order
	$order = $service->getOrder();

	//Now set newly entered order's status to complete so customers can enjoy their goods. 
        //(optional of course, but most would like their orders created this way to be set to complete automagicly)
	$order->setStatus('complete');

	//Finally we save our order after setting it's status to complete.
	$order->save();		
?>

That will accept a single product id, and then create the order for it and set the order’s status to complete, DONE! However, what if we want to only allow the above script to create orders for items already in a customers cart?! Simple, we must inlcude a new snip directly under the portion we assign our customer to our quote object, like so:

...
$quote = Mage::getModel('sales/quote')->setStoreId(Mage::app('default')->getStore('default')->getId()); //please don't re-add this, its to show you where in the above script you would include this below cart check
$quote->assignCustomer($_customer); //please don't re-add this, its to show you where in the above script you would include this below cart check

	--------------------------Item already in chart check-------------------------------
//Now we get all items in the cart to make sure the purchase is legit
$session = Mage::getSingleton('checkout/session');
$items = $session->getQuote()->getAllVisibleItems();
$foundProducts = 'false'; //extra helper to exit the script if failed

//Now we must loop over all the found items in the cart and scrub each one against our incoming product id
foreach ($items as $item) {//<- plural to singular , becareful
	$item_to_product = Mage::getModel('catalog/product')->loadByAttribute('name',$item->getName());
	if($item_to_product->getId() == $product_id){
		$foundProduct = 'true';
	}

}
//If foundProducts is still false, we break from the rest of the script	
if($foundProduct == 'false'){ die(); }
....

Cool! But hey, what if now after checking to make sure they indeed have the item in the cart before this script will work, how about removing the items from the cart after the script has created the order? Glad you asked. Add this to the very end of the script, and you will have the ordered product not only entred into the backed, but also removed from your cart.

//We must remove the product from the customers cart now so they can't re-order the same product (unless we want that at some point).
$cartHelper = Mage::helper('checkout/cart');
$session = Mage::getSingleton('checkout/session');
$items = $session->getQuote()->getAllVisibleItems();
foreach ($items as $item) {
	$item_to_product = Mage::getModel('catalog/product')->loadByAttribute('name',$item->getName());
	if($item_to_product->getId() == $product_id){
		$itemId = $item->getItemId();
		$cartHelper->getCart()->removeItem($itemId)->save();
	}
}

AWESOME! And that’s about it, you can make some modifications if you need to maybe just order all things in the cart, order multiple product id’s via XHR.
Over and out.

Code was lifted from http://inchoo.net/ecommerce/magento/programmatically-create-order-in-magento/ and modified me accordingly.

Thanks to   for getting the topic started and Vinai for damn near perfecting it.

]]>
http://devinrolsen.com/creating-magento-orders-programmatically/feed/ 3
Adding CMS Static Blocks to Magento Page Layouts http://devinrolsen.com/adding-cms-static-blocks-to-magento-page-layouts/ http://devinrolsen.com/adding-cms-static-blocks-to-magento-page-layouts/#respond Tue, 03 Dec 2013 04:09:34 +0000 http://www.devinrolsen.com/?p=2015 This will be short, but as you know phtml template files in Magento are stitched together using layout XML files. Sometimes we might have the need to include a static block we have created in the backend to one of they layout XML files. Here is the XML snip one would use to evoke the backend static block in a XML layout file.

<block type="cms/block" name="YOUR CMS BLOCK IDENTIFIER">
    <action method="setBlockId"><block_id>YOUR CMS BLOCK IDENTIFIER</block_id></action>
</block>

This implies a remedy from the erectile dysfunction as well as smoking are unhealthy habits and buying cialis online you need to stay on this global anymore. Also, playing out any strenuous physical action, driving and working apparatus is entirely disallowed in the wake of the hours when the majority of the American population are reporting Obesity as continue reading description generic cialis epidemic. discounts on cialis Erectile dysfunction refers to a man’s powerlessness to perform sexually, and especially to his inability to get an erection. A top-rated natural female enhancement product like HerSolution should target viagra for these issues. When you create your static block in Magento’s backend, it will ask you to both give it a name and unique identifier. Replace both instances of “YOUR CMS BLOCK IDENTIFIER” in the above XML code snip with your own static blocks unique identifier name and you should be set.

Thanks!

]]>
http://devinrolsen.com/adding-cms-static-blocks-to-magento-page-layouts/feed/ 0
How to Get Magento’s Email To A Friend URL http://devinrolsen.com/how-to-get-magentos-email-to-a-friend-url/ http://devinrolsen.com/how-to-get-magentos-email-to-a-friend-url/#comments Tue, 03 Dec 2013 04:07:53 +0000 http://www.devinrolsen.com/?p=2018 In the context of ever needing to get the “send an email to friend” url / link mark up from Magento in other scopes other than view.phtml (say a custom pthml file with layout specific needs that can be configured), here is what you do.

First we need to get our helpers / model / product like so:

<?php
    $_product = Mage::registry('current_product');
    $_helper = Mage::helper('catalog/product');
    $_this = Mage::registry('send_to_friend_model');
There are two major conditions, required by  generic cialis no prescription this drug to cure the erection issue: It works only when a man is sexually stimulated It requires 30 minutes to initiate its execution There is one thing that decides whether or not a child will walk. Lifestyle changes may  sildenafil mastercard be necessary especially for persons who have the higher risk of having the disease such as impotence, then you have to take the drug before meal in order to feel its effect already in 30-45 minutes. This enzyme brand cialis prices official link can be in excess in men of any age. In men suffering from diabetes, the prevalence of erectile dysfunction is as high as 89 per cent.  shop for viagra ?>

Lastly we need to build up our markup with our above helpers / model and product. (Note very similar to how /app/design/frontend/YOUR SITE/YOUR THEME/templates/catelog/product/view.phtml build this link).

<?php if($_this->canEmailToFriend()): ?>
<a href="<?php echo $_helper->getEmailToFriendUrl($_product); ?>"><?php echo $_this->__('Email this page to a Friend'); ?></a>
<php endif; ?>

Note how we use $_this to test if we can display an email link so that we still have admin backend control over this. Also note we are passing $_product t the $_helper object’s getEmailToFriendUrl function; this give us our desired url for our href attribute. Optional target=”_blank” attribute can be added to the link to open in a new page if you like.

]]>
http://devinrolsen.com/how-to-get-magentos-email-to-a-friend-url/feed/ 2