Twig comes with its own Debug extension to allow users to output “var_dump()” — the function that spits out the raw values behind a PHP variable, array or object — inside a Twig template.  This functions is helpful in the dev environment while trying to debug code.

 

Step 1:  Add the following to the /app/config/config_dev.yml (don’t add this to config_prod.yml):

twig: 
    debug: 1
services:
    debug.twig.extension:
        class: Twig_Extensions_Extension_Debug
        tags: [{ name: 'twig.extension' }]

Step 2:  Inside any Twig template, you can “var_dump” variables using the Twig Debug Extension:

{% debug varName %} 

– Aaron Belchamber


Let’s say you are creating a form in Symfony that has some dynamic fields that you need to allow the user to add and remove a subset of options and fields from within the form.  Enabling dynamic forms in Symfony is a bit confusing to those just getting their feet wet.  Here’s a hint:  You have to use data prototypes and a little bit of Javascript.  I prefer JQuery, but it doesn’t matter as long as the behavior ends up with the same result of “cloning” the prototype HTML into the proper place on the form with a serialized incrementation of its field name values.

Symfony relies on Javascript for dynamic forms?!  Say it isn’t so, Fabien!

Well, every framework and those home rolled models all employ the same basic tactic where parts of a form that may “grow” need to first be hidden from the user and serialized as the user adds new fields.  Think of a blogger adding multiple “tags” to a post, or someone needing to leave multiple notes in someone’s medical record.

The fact is that dynamic forms rely on the client side to allow users to add and remove new elements to and from a form so it’s a good initial test to see if they have the capability by initializing a hidden element and taking the “prototype” data out of the “data-prototype” tag that Symfony generates and unescape the embedded HTML and putting it into it’s new visible location within the dynamic form.  By the way, another good practice would be to design the form with “graceful degradation” so those who are blocking Javascript or don’t have it on their browser for some strange reason can still use the forms basically as initially intended, but that choice is up to you — and the people paying the bills.  After all, time is money.

For all those who’ve Googled and been on Stack Overflow and Binged your way onto this god-forsaken page in the middle of the great cyber void, if you need to access prototype information in order to render out certain tags the prototype html generates inside a hidden element with a “data-prototype” tag and you can’t rely on JavaScript and plain CSS to format the label and fields or maybe you just need more control over formatting, this is the general pattern to access such elements inside Twig.  Just replace “blogPost” with the name of the form and “tagName” with the name of the form field.


<div id="clone-tag-form">
<div class="formatting-tag-couldnt-do-before">

{{ form_label(form.blogPost.vars.prototype.tagName)   }}

</div>
{{ form_widget(form.blogPost.vars.prototype.tagName) }}
</div>

Keep in mind that this gives you more granular control over the part of a form that will be cloned so it’s up to you to take the HTML inside “clone-tag-form” and use a placeholder in the field name values such as “__NAME__” and replace these with serialized, incremented numbers so when processed the data won’t confuse the form handler and data won’t get lost.  It’s an all or nothing proposition.  Others suggest making a prototype template and binding the results from the prototype output to the template like so, but it just gets a little more complicated:

Idea adapted from Stack Overflow:

The idea is simply to render the collection items through a Twig template, so you can customize the prototype that will be placed in your

data-prototype="..."

tag as if it was a normal form.

In yourMainForm.html.twig:

<span class="tag">&lt;div</span><span class="atn">id</span><span class="pun">=</span><span class="atv">"collectionCont"</span><span class="atn">data-prototype</span><span class="pun">=</span><span class="atv">"
         {% filter escape %}
             {{ include('MyBundle:MyViewsDir:prototype.html.twig', { 'form': form.myForm.vars.prototype }) }}
         {% endfilter %}}"</span><span class="tag">&gt;</span><span class="tag">&lt;/div&gt;</span>

And in MyBundle:MyViewsDir:prototype.html.twig:

<span class="tag">&lt;div&gt;</span><span class="com">&lt;!-- customize as needed --&gt;</span><span class="pln">
    {{ form_label(form.field1) }}
    {{ form_widget(form.field1) }}
    {{ form_label(form.field2) }}
    {{ form_widget(form.field2) }}
</span><span class="tag">&lt;/div&gt;</span>

Symfony2 and Twig work great together.  Symfony is an advanced PHP framework that is growing in popularity.  If you are a company that relies on rapid application development and need a stable and secure development and production environment, Symfony is one of the top choices to consider.  More on Symfony another time, we’re talking Twig today.

What is Twig and why should I learn it?

Twig is straight forward and has a pretty quick learning curve.  Twig is a templating system that is intuitive and really does help reduce the amount of code while keeping your views neat and more importantly, functionally separate from your business logic, which is always what good “V”s — the “V” in “mVc” — is supposed to do.  Twig isn’t a language, it’s a set of rules and constructs based on simple programming patterns that introduce only 3 new tags:  {% do something %}, {{ show something }}, {# comment on something #}.  These tags help you create editable blocks based on a base template.  If you use Dreamweaver templates or some other template system, adapting to Twig and the concept of extending and overriding base templates will be nothing new.  It’s powerful because it’s simple to follow the cascading logic that so much of the web works from.

Basics behind Twig templating

The concept behind templates and cascading style sheets are all the same.  For simplification, let’s say you have a base template that can have anything in it, including the base HTML code for a basic page in your website.  We’ll represent that as a simple-to-follow pattern where each number represents a different important part of the webpage, like the header, metatags in the header, top menu, sidebar, footer, etc.  However you want to logically group your pages into manageable blocks, so let’s say your template is based on a simple construct:  “1 – 2 – 3 – 4 – 5 – 6 – 7 – 8 – 9”.  When you create a new template based on this base template, you only tell the system what’s different and show the rest as is.  So in simplified terms if your new template has a command that says “5=A”, the new output from a template will look like this:  “1 – 2 – 3 – 4 – A – 6 – 7 – 8 – 9”.  Basically, instead of writing out all the code for each page over-and-over, you practice the DRY (Do Not Repeat Yourself) principle and use a template to override the parent, or base template.

In your new child template, you can use powerful commands to change a lot from the base with little code.  In your child template, you can say things like “change all dashes to tildes” — and one command can change your template to the new pattern “1 ~ 2 ~ 3 ~ 4 ~ A ~ 6 ~ 7 ~ 8 ~ 9”.  You get the point, templates are all about making the output of your views easier to reuse and maintain.  Not to mention they’re not nearly as scary to non-coders who have to poke around and update little things in your website, you know they can’t alter global variable values or do other things that could alter the business logic of your web application(s).

Twig provides rules and structure that consolidate mainly view functions based on the most common PHP capabilities, like iterators — a way to “loop” through values and show a list on screen quickly and easily.  A way to sort or filter your output without sending a new query and waiting for a response from your database.  It can reduce requests and server loads by being more efficient with your website’s resources.  Twig also works best with PHP Storm IDE since it has great live validation and helpers.  PHP Storm is a potent combination for serious PHP web developers using Symfony, Twig, and LESS as well.


On one of my virtual servers, I suddenly encountered this error:

Failed to open a session for the virtual machine CentOS.

General failure – DON’T USE THIS!!!. (VERR_GENERAL_FAILURE).

Result Code:E_FAIL (0x80004005)
Component:Console
Interface:IConsole {8ab7c520-2442-4b66-8d74-4ff1e195d2b6}

 

This Oracle VM VirtualBox error resolved.  The problem went away when I went to the VM server’s settings and deactivated the USB port on the virtual machine.  This was the case for both the “Ubuntu 64” and the “CentOS6 64” virtual machine.  Just in case anyone else encounters this issue.

Apparently, I had plugged in an external USB drive to my host machine and this possibly triggered a conflict.  I hope this helps save someone some time!  Whatever the reason, if you Google this error and happen to come to this same error, this is what resolved the problem for me.


Here are a few more useful WordPress shortcodes.  Simply copy the code and paste it into your active theme’s “function.php”.

You can call on shortcodes with the square brackets inside your post or pages:

Insert a Google ad snippet, horizonal 720 x 90 pixels:

[insert_script path='/library/vendors/google/ads/horiz-720x90.php']

Show computer’s IP address:

[[show_ip]] — produces:  [show_ip]


/* Allows insertion of external PHP scripts easily into pages, posts & widgets.
*
* "vars" is query string that will be parsed by script in a variety of ways,
* Most useful is parse_str()  where ?x=1&y=3 will parse into script as $x=1, $y=3
*/
function insert_script($atts){

extract(shortcode_atts(array("path" => '',"vars"=>''), $atts));
ob_start();
include($_SERVER['DOCUMENT_ROOT'].$path);
return ob_get_clean();
}

add_shortcode('insert_script', 'insert_script');

// Shows current Date and Time
function todays_date_time($atts){
return date("Y-m-d H:i:s");
}
add_shortcode('todays_date_time','todays_date_time');

// Shows computer's current IP address
function show_ip(){
return $_SERVER['REMOTE_ADDR'];
}
add_shortcode('show_ip','show_ip');