Google analytics code

Wednesday, September 17, 2014

Sencha Touch: Android Halo Light Theme

One of the things I love about Sencha Touch is the built in themes. Android has 4.x has two themes: Halo Dark, Halo Light.  There is only one Android theme for Sencha Touch and it's dark. I've been bugging them for awhile to include a light theme and their response was "You do it".

I googled for a long time and couldn't find a theme someone else did. I gave in and decided to make my own theme after finding this one. It's beautiful. I read his breakdown and he created a theme by copying the winPho theme and made changes until he was happy. I did something similar. I copied the Android theme and started digging in.

That's when I found it. There is a Sass variable in /[Sencha SDK folder]/resources/themes/stylesheets/sencha-touch/mountainview/var/_Class.scss called $dark-theme. If you set this variable to false in your local sass file for android it becomes a light theme.

I wish this was explained better. It's only through source code diving can we find the true answers.

Zend Framework 2: Using mysql functions in SQL classes

The built in ZF2 classes for sql queries have been wonderful to use. I like that it takes care of escaping data and saves you from messy string all over your codebase. I ran into a problem when trying to do something "complex".

Here is an example of the SQL I was trying to write.
INSERT into `table` SET `col1` = FROM_UNIXTIME(?)

When I tried running this the mysql method was quoted
`FROM_UNIXTIME(?)`
I started digging around and found an extra class required if you want to use functions in the escaped data spot. It's called an expression. Here is how they're used in the insert class.

$insert->into($tableName)
       ->values([`col` => new \Zend\Db\Sql\Expression("FROM_UNIXTIME(?)","?", [\Zend\Db\Sql\Expression::TYPE_VALUE])]);

Now the function won't be quoted and the value can be safely escaped when execute is run.


Here's some documentation on how expressions are used in a where clause.

Monday, July 28, 2014

Angular: Form element not attaching to $scope

I'm well into a redesign using AngularJS as my front-end framework. After a small learning period I'm in love. It's a fantastic way to tie your UI to your backend. That said there is still some work to be done.

I'm breaking my project into modules that are included with the ng-include tag. This helps shrink the code on the page into manageable chunks. It nice when you're using a very verbose framework like Bootstrap.

All of my forms are wired up using Angular's form validation. Once again this is fantastic. Being able to watch the inputs in real time and display helpful errors is great. I ran into an issue trying to reuse a form after I've removed it from the users view.

<form name="createUser">
    <input name="name" ng-model="formObj.name" />
    <input name="email" ng-model="formObj.email" />
</form>

I should be able to access the form in my angular in this fashion.

// This will reset any validation errors on the form
$scope.createUser.$setPristine();

This wasn't working for me and I spent a lot of time trying to figure out why. Here is how my code looked.

<div ng-controller=“controllerName”>
    <div ng-include=“ ‘path-to-the-template’ ”></div>
</div>

<!—- Inside path-to-the-template -—>
<form name="createUser">
    <input name="name" ng-model="formObj.name" />
    <input name="email" ng-model="formObj.email" />
</form>

One thing to consider is when Angular is starting up the controller code the form isn't attached yet. When you click the button that submits the form it will be attached by that time. I was still unable to access the form element.

Update

I submitted this as a bug to the git repo and got a response very quickly. That team is really on top of things. Turns out when you use ng-include it creates a new scope var. This is how the setup should look.

<!—- The vars should live in the controller. I placed them here for the example. -—>
<div ng-controller=“controllerName” ng-init="form={}; model={}" >
    <div ng-include=“ ‘path-to-the-template’ ”></div>
</div>

<!—- Inside path-to-the-template -—>
<form name="form.createUser">
    <input name="name" ng-model="model.name" />
    <input name="email" ng-model="model.email" />
</form>

Now the include can reference the variables from the parent scope. The form and it's input should now be accessible.

Friday, June 27, 2014

Zend Framework 2.x Learn ZF2 by Example: Protecting our Pages - Authentication type

I'm starting to implement authentication on my web app and I ran into a problem with the example in the book.

The example on page 146 uses MD5 as a encryption scheme.

$adapter = new DbAdapter($db,
                         'users',
                         'login',
                         'password',
                         'MD5(password)');

The adapter builds a simple SQL query that will check the table, match the user name and password then let you know if it's valid. The problem lies in the 5th parameter. When I tried to match an account I know works it kept saying the account wasn't valid. After digging into the documentation I found the 5th parameter wasn't configured right. It should be 'MD5(?)'.

$adapter = new DbAdapter($db,
                         'users',
                         'login',
                         'password',
                         'MD5(?)');

After the change the auth adapter works perfectly. Hope this helps save you some time.

Thursday, June 5, 2014

Sencha Touch Themes: Using built-in themes for iOS and Android

One of the things I like about Sencha Touch is the built in device themes. I like being able to make a web app look native.

I found many resources that talked about the themes but none gave very good instructions on how to make them work. I finally found a video that walked you through some of the process involved in making themes work. It left out some important stuff that I found through lots of trial and even more error.

I'll show you how to apply a theme to the default sencha project. You can apply these steps to your own project.

  1. Create an example app.
    • sencha -sdk [path to sdk] generate app [AppName] [path]
  2. You'll need to create scss files for the different platforms you want to support.
    • cupertino.scss (iOS 7 styling)
    • cupertino-classic.scss (iOS 6 styling) 
    • mountainview.scss (Android)
  3. Each of these files will include two imports lines that define our theme styles.

    @import 'sencha-touch/[platform name]';
    @import 'sencha-touch/[platform name]/all';

    [platform name] is the name of the style you're including. cupertino.scss will use "cupertino" and mountainview.scss will use "mountainview". All the platform names are available here under tip 2.
  4. Next you'll need to run "compass compile" or "compass watch" in the resources/sass folder. 
  5. Now we have to update app.json to include the new css files that were generated by compass. Look for the css option and add each platform as an object to the css array.
    {
        "path": "resources/css/cupertino.css",
        "platform": ["ios"],
        "update": "delta"
    }

    Make sure to update the platform value with the appropriate value. The options are available here under available platforms.

    IMPORTANT NOTE: Make sure to add the "platform": ['desktop'] to the app.css entry. If you don't app.css will be included in every theme and it will break the display. 

  6. Lastly you'll need to run sencha app build to bring everything together. You can test the different templates by appending ?platform=[platform name] to your uri.
    eg: senchaapp.io/?platform=ios
I've added the example project to github so you can pull that down as an example.

Tuesday, April 22, 2014

Zend Framework 2 & MAMP : Memory Issues

I ran into a problem working through the tutorial for Learn ZF2 for form validation. I reached the section where the form data would be inserted into a database and that wasn't possible using the command line PHP server. I decided to switch to MAMP because it has more stuff baked in.

I quickly ran into an issue that was tough to track down. After added the database code the form no longer submitted. After ripping out lots of code and not finding an answer I called it a night. The next day I figured out the problem was with MAMP not my code. If I disabled the file validation on the form everything worked fine.

This was the error I ran into
Fatal error: Allowed memory size of 33554432 bytes exhausted (tried to allocate 32 bytes) in /Volumes/zend_framework/learnzf2/vendor/zendframework/zendframework/library/Zend/Stdlib/ErrorHandler.php on line 113

Not the most straight forward bug. Turns out the issue is the command line PHP server has a larger memory_limit size. It's 128M while MAMP is set to 32M. It overflowed after processing the file. After upping memory_limit to 128M and restarting the server everything worked fine.

The memory_limit var is stored in php.ini. It can be reached by using
File => Edit template => php => php 5.4
Find memory_limit and change it to 128M.

Wednesday, April 9, 2014

Zend Framework 2.x Learn ZF2 by Example : Unable to render template

Getting to the MVC portion of the book and ran into an error. On page 59 it shows you how to manually include a template to aid debugging. I ran into this error when trying to see my changes.


Fatal error: Uncaught exception 'Zend\View\Exception\RuntimeException' with message 'Zend\View\Renderer\PhpRenderer::render: Unable to render template "debug/layout/sidebar"; resolver could not resolve to a file' in /Volumes/zend_framework/learnzf2/vendor/zendframework/zendframework/library/Zend/View/Renderer/PhpRenderer.php:498 Stack trace: #0 /Volumes/zend_framework/learnzf2/vendor/zendframework/zendframework/library/Zend/View/View.php(205): Zend\View\Renderer\PhpRenderer->render(Object(Zend\View\Model\ViewModel)) #1 /Volumes/zend_framework/learnzf2/vendor/zendframework/zendframework/library/Zend/Mvc/View/Http/DefaultRenderingStrategy.php(102): Zend\View\View->render(Object(Zend\View\Model\ViewModel)) #2 [internal function]: Zend\Mvc\View\Http\DefaultRenderingStrategy->render(Object(Zend\Mvc\MvcEvent)) #3 /Volumes/zend_framework/learnzf2/vendor/zendframework/zendframework/library/Zend/EventManager/EventManager.php(468): call_user_func(Array, Object(Zend\Mvc\MvcEvent)) #4 /Volumes/zend_framework/learnzf2/vendor/zendframe in /Volumes/zend_framework/learnzf2/vendor/zendframework/zendframework/library/Zend/View/Renderer/PhpRenderer.php on line 498

Page 58 talks about the way templates are included. The middle of the page shows a config option called 'template_path_stack'. This is the path the PhpRender uses to find manually included templates. There is a similar line in the Application module.config.php. I thought this would be imported into the master config but that didn't happen. You have to add this.

Tuesday, April 8, 2014

Zend Framework 2.x Learn ZF2 by Example : Error creating Debug module

I'm rewriting part of my website with Zend Framework 2 because I want to use something more mature and flexible than something I wrote years ago. I picked up the book Learn ZF2 by Example because it was rated well. The intro gets your feet wet and eases you in. I got stuck when trying to reproduce the steps to create a new module using ZFTool.

On page 28 under Automatic Module Creation they want you to download a tool that will help with creating new modules. I'm not sure if the instructions are old but it not work. Running the command will give you the following error

Fatal error: Uncaught exception 'Zend\ModuleManager\Exception\RuntimeException' with message 'Module (ZFTool) could not be initialized.' in /Volumes/zend_framework/learnzf2/vendor/zendframework/zendframework/library/Zend/ModuleManager/ModuleManager.php:189
Stack trace:
#0 /Volumes/zend_framework/learnzf2/vendor/zendframework/zendframework/library/Zend/ModuleManager/ModuleManager.php(163): Zend\ModuleManager\ModuleManager->loadModuleByName(Object(Zend\ModuleManager\ModuleEvent))
#1 /Volumes/zend_framework/learnzf2/vendor/zendframework/zendframework/library/Zend/ModuleManager/ModuleManager.php(90): Zend\ModuleManager\ModuleManager->loadModule('ZFTool')
#2 [internal function]: Zend\ModuleManager\ModuleManager->onLoadModules(Object(Zend\ModuleManager\ModuleEvent))
#3 /Volumes/zend_framework/learnzf2/vendor/zendframework/zendframework/library/Zend/EventManager/EventManager.php(468): call_user_func(Array, Object(Zend\ModuleManager\ModuleEvent))
#4 /Volumes/zend_framework/learnzf2/vendor/zendframework/zendframework/library/Zend/ in /Volumes/zend_framework/learnzf2/vendor/zendframework/zendframework/library/Zend/ModuleManager/ModuleManager.php on line 189

Your path will vary, but the error is the same. Searching google didn't give me a good answer. The ZFTool page has instructions on how to install the it using composer. When the install finished I ran the command php vendor/bin/zf.php create module Debug and the new module was created.

I hope this saves you some time.

Monday, February 24, 2014

Sencha Touch: Reorder a list with drag and drop handles using SortableList

Part of a project I'm working on requires the ability to reorder a list. I was pretty sure sencha touch could handle this, but couldn't figure out how to do it. I searched google for a solid week. I had one lead that turned bad after digging into it further. I basically gave up and moved onto the next issue when I ran across the solution buried in their documentation: SortableList

The second problem arose from the poor documentation on this feature. Outside of the class docs there is nothing explaining how to use it. The upside is at least it's easy to view the source.

I ran across this forum post that talked about a bug in the code. This was the only code I found that gave an example of how the code works.

There are a few things required to use this plugin.

Step 1: Include the plugin

// Make sure the plugin in include when the app builds
requires: ['Ext.plugin.SortableList'],

config:{
        // Include the plugin in your config. Don't forget the period on the class name
        plugins: [{xclass: 'Ext.plugin.SortableList', handleSelector: '.gripper'}],

        
        // These are required to fix a bug that exists in the plugin
        infinite: true,
        variableHeights: true,
        ...
}

Step 2: Configure the drag handle

config: {
        // Set the class to the name you passed in for the handleSelector
        itemTpl: '<span class="gripper"></span>[html goes here]'
        ...
        }

The tag used for the list-sortablehandle is the object that will start the reorder process. This can be styled using whatever you like.

Step 3: Listen for the finishing event

config: {
        listeners:[
            event: 'dragsort',
            // to is the new position in the list
            // from is where the item used to be
            fn: function(listObject, row, to, from)
        ]
        ...
}

It was smooth sailing after this point.

Thursday, January 23, 2014

Javascript: Problems, trouble, issues parsing JSON data / Unexpected token

I ran into an issue trying to parse a JSON string that made very little sense. Normally when you have a token in the JSON response that doesn't work the error will include that character. This time it gave me nothing.

// This is all you have to do
JSON.parse(jsonObject);

After 4 hours and much googling I had no answer. I though for some reason the server response had the wrong type of quotes on it, but turned out to be something very left field.

I used JSON.stringify() on the server response and saw something really weird on the end of the string that wasn't showing up by looking at the response.

// What is this?!
'"timeCreated\":1390518047098}\u0000\u0000\'

The \u0000 character was choking the parser and wasn't showing up as a bad token. This is the unicode character for null. Not sure why it was on the response but it was causing the problem. Running this cleaned up the problem.

// Take out the garbage
[server response] = [server response].replace(/\u0000/g, "")

As a safety measure it's good to have a method you can use to clean your JSON strings before trying to parse them.

Friday, January 10, 2014

Javascript: Quick Date timestamp

I wanted to find a quick way to compare two dates. The easiest way is to use their unix timestamp. If the date exists as an object you can use .getTime() to retrieve the number of milliseconds that have passed since epoch time.

You can retrieve that number even faster with the following bit of code

+new Date

I found the tip here and wanted to surface it.