Laravel Eloquent gotcha using With and Find

The Eloquent ORM in Laravel makes it easy to pull in related models using the ::with() method.  It’s very useful and can solve the N+1 Query problem that can occur when accessing related models in a loop from the parents records.

<?php
$data = MyParentModel->with('ChildModel');

You’d commonly want to use this when accessing a particular parent model using the ::find() or ::findOrFail() method. The trap can be that with() must be called before findOrFail().

If you chain methods and call findOrFail() first it will be ignored and your result set will include all parent rows!

<?php
$data = MyParentModel->with('ChildModel')->findOrFail($parent_id);

Gravity Form Checkbox Values

This post is an extension of Gravity Forms – Collecting Select Box Value.
In this demo we are capturing the values from a group of checkboxes.

Demo with Checkboxes

    Select the items to add to your order
  • ...we'll grab the checkbox values here

/**
* Wrap our JS for capturing values
*/
var checkboxHandler = {
 
 	//Change these IDs to match your form
 	checkboxFieldId: 'input_5_3',  //checkbox container ID
	outputFieldId:   'input_5_2',    //hidden field to capture values
	
	checkboxField: null,
	outputField: null,
	
    /*
	Listen to Checkboxes
	---------------------- */
    init: function() {
    
		this.outputField = document.getElementById(this.outputFieldId);
		
		if( typeof this.outputField === 'undefined' || !this.outputField ) {
			console.error('Missing output field ' + this.outputFieldId);
			return;
		}
		
        this.checkboxField = document.getElementById(this.checkboxFieldId);
        if(typeof this.checkboxField === 'undefined' || !this.checkboxField) {
			console.error('Missing checkbox field ' + this.checkboxFieldId);
            return;
        }
         
        jQuery(this.checkboxField).on(
			'change',
			'input[type=checkbox]',
			{
				checkbox: this.checkboxField,
				output:   this.outputField
			},
			this.setValues
		);
    },
    
	
    /*
	Set text (or hidden) field to list of checkbox values
    ----------------------------------- */
    setValues: function(ev) {
	
		var fields = ev.data;
        var valueString = '';
		
		jQuery(fields.checkbox).find('input:checked').each( function(i){
			valueString += this.value + ', ';
		});
		
		fields.output.value = valueString.replace(/, $/, '');
    }
};

jQuery().ready( checkboxHandler.init() );

If you are using a child theme or custom theme you can add this code to its JavaScript file.
Otherwise use WordPress’ wp_register_script and wp_enqueue_script functions to load a new file.
The value of the hidden/text box can then be included in your Gravity Forms notification.

Gravity Forms – Collecting Select Box Value

Gravity Forms for WordPress has a select box field type, which by default uses the same data for both value and label. The field can easily be configured to have separate value and label attributes, however only the label will be sent in the form notification. In many cases this is fine, but sometimes you need the <option> value data to be sent as well as the display label.

Alternative Option: Capturing Checkbox Values

Capture the Value Attribute in a Hidden Field

One solution is to use JavaScript to capture the <select> field’s value, and copy it to a hidden form field which can be included in the email notification.

We’ll use a bit of custom JavaScript to listen to the <select> change event and update our hidden form field. This example code uses specific field ids that Gravity Forms generates. You could also write more general JS and selectors to match more scenarios if your site has multiple forms.

The Form Setup

At minimum we’ll need a select input (drop down) and a hidden field. For this demo our hidden field is actually plain text so we can see what’s happening.

Demo Product Form

  • Choose a product...
  • ...we'll grab the select option value here

Here’s the JavaScript. This example matches the IDs in the demo form. You’ll need to change those selectors to suit your form.

/**
* Wrap our JS for capturing values
*/
var selectHandler = {

	// Setup & Event listener
	// ----------------------
	init: function() {
		
		var select = jQuery('#input_3_1')[0]; //change id to match your form
		if(typeof select === 'undefined' || !select) {
			return;
		}
		
		//Set Initial Value (before change)
		selectHandler.setEmail.apply( {value: select.value} );
		
		jQuery(select).on('change', this.setEmail);
	},
	
	// Set text (or hidden) field to option value
	// (change selector to match your form)
	// ------------------------------------
	setEmail: function(ev) {
		 jQuery('#input_3_2')[0].value = this.value;
	}
};
jQuery().ready( selectHandler.init() );

If you are using a child theme or custom theme you can add this code to its JavaScript file.
Otherwise use WordPress’ wp_register_script and wp_enqueue_script functions to load a new file.
The value of the hidden/text box can then be included in your Gravity Forms notification.

WordPress Debugging

Bronson Quick spoke at the WordCamp Sunshine Coast today on debugging for WordPress. He covered techniques for fixing a white-screen of death as well as getting detailed information to sort out squirrelly bugs and performance issues.

Firstly WordPress has a few rad constants you can switch on to get better information about where things are breaking.

define( 'WP_DEBUG', true );     //I was blind, now I can see (my PHP errors)
define( 'WP_DEBUG_LOG', true ); //for production, write logs to wp-content
define( 'SCRIPT_DEBUG', true ); //use non-minified versions of core CSS/JS
define( 'SAVEQUERIES', true );  //log queries, look for suspicious ones. Not for production

Local Development

Develop in an environment close to the production hosting environment your site will be deployed to. The best way to do this is with virtual machines and tools like Vagrant.

Chassis is a WordPress focused VM for Vagrant. It’s configured with Nginx, MySQL, PHP 5.4 – 5.6 and has a bunch of handy extensions available to set up things like Xdebug, Debug Bar and Query Monitor quickly. The disposable nature of VMs means you can create one for each project.

Creating a Chassis VM

git clone git@github.com:Chassis/Chassis.git myproject
cd myproject
vagrant up

Chassis Extensions

Debug Bar gives you a lot of insight into what WordPress is doing to generate a page.

cd myproject/extensions
git clone https://github.com/Chassis/Debugging.git
vagrant provision

This will install a collection of Debug Bar plugins into WordPress en mass. What a time saver.

Query Monitor is an alternative tool for monitoring database activity in WordPress. It does more than monitoring SQL and can even show script dependencies, en queued styles and highlight errors.

So…

  • Develop in an environment similar to where you’ll deploy. Let Chassis set that up for you.
  • Use Xdebug, Debug Bar and Query Monitor as necessary to get insight into what your code is doing