Tag Archives: forms

Select List (ng-select) – AngularJS

Hey everyone,

Just a quick post on how to do up a select list in AngularJS. This one took a bit of time to work out, particularly the display/value pairing.

HTML:

<div ng-controller="MyCtrl">
    <p>
        Status: <br />
        <select name="Status" ng-model="lesson.Status" required ng-options="status.value as status.display for status in status_options"></select>   
    </p>
</div>

JavaScript:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
var myApp = angular.module('myApp', []);
 
function MyCtrl($scope) {
    $scope.status_options = [
            { display: 'Enabled', value: 'enabled' },
            { display: 'Disabled', value: 'disabled' },
            { display: 'Deleted', value: 'deleted' }
        ];
 
    $scope.lesson = {
        BusinessId: 0,
        Description: null,
        Duration: 0,
        Price: 0,
        ProductId: 0,
        Quantity: 0,
        Start: "/Date(-62135596800000)/",
        Status: 'enabled', //Change to null in order to remove default
        Title: null,
        Type: null
    };
}

If you’re just following along, I’ve added a quick JSFiddle: http://jsfiddle.net/rtR6e/5/

You’ll notice that in the markup, the value is actually an index. This is pretty misleading, but Angular will actually assign the appropriate value to the model (“enabled”, “disabled”, etc).

Another thing that you can do fairly easily, is to remove the default value. Simply make the status null. You can test both these by outputting the JSON or using http://jsfiddle.net/rtR6e/5/.

Check out the following StackOverflow post for more info: http://stackoverflow.com/a/13808743/522859
Or the documentation: http://docs.angularjs.org/api/ng.directive:select

Excon::Errors::SocketError Broken pipe (Errno::EPIPE) – Ruby on Rails

Hey everyone,

I was having a bit of trouble with CarrierWave on Amazon S3 today. When attempting to upload files that were larger than ~150kb I received one of the following errors (depending on config):

getaddrinfo: Name or service not known carrierwave
Excon::Errors::SocketError in PhotosController#create
Broken pipe (Errno::EPIPE)

 

Despite the vague error, the solution was fairly simple. The region configured in my initialiser was different to the one my bucket was created in.

In order to find out which region you need, logon to your AWS console and browse to an uploaded image. Check the endpoint URL (properties > static website hosting) and simply copy the region. For examples:

Endpoint: testbucket123321.s3-website-us-west-2.amazonaws.com
Region: us-west-2

A couple of final tips if this doesn’t work for you:

  • You need the region codes, not the name. For instance, “Oregon” won’t work
  • Don’t forget to restart your app after making changes to the initialiser
  •  

    Blank Row in Select_Tag – Ruby on Rails

    Hey everyone,

    Just a quick post on how to include a blank row or prompt value when using a select_tag in rails:

    1
    2
    3
    4
    5
    6
    
     
    #Prompt
    <select_tag "Animals", animals_as_options, :prompt => "Please select an animal" />
     
    #Blank option
    <select_tag "Animals", animals_as_options, :include_blank => true />

    Let me know if you have any issues.

    Fields Missing from jQuery Post – Serialize Data

    Hey everyone,

    I was using jquery’s serialize method to post completed form data only to find that a number of my fields were missing.

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    
     
                    //Display loader and disable forms
    		disable_form_fields(true);
     
                    //Post via ajax
    		$.ajax({
    			type: 'POST',
    			url: 'uploads/add',
    			data: $(form).serialize(),
    			success: function(data, text_status, oHTTP){
    				handle_form_response(data, text_status, oHTTP, $(form).data('file_id'))
    			},
    			error: function(){
     
    				//Hide loader etc
    				set_form_loading(false);
     
    				//Unspecified error
    				alert('An error has occurred.');
    			},
    			dataType: 'json'			
    		});

    Thanks to this stackoverflow post I realised that the data wasn’t being serialised because I’d disabled most of the fields beforehand. This was done in order to prevent the user from changing the values. To get around this I simply had to serialise the data BEFORE disabling anything.

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    
     
                    //Post via ajax
    		$.ajax({
    			type: 'POST',
    			url: 'uploads/add',
    			data: $(form).serialize(),
    			success: function(data, text_status, oHTTP){
    				handle_form_response(data, text_status, oHTTP, $(form).data('file_id'))
    			},
    			error: function(){
     
    				//Hide loader etc
    				set_form_loading(false);
     
    				//Unspecified error
    				alert('An error has occurred.');
    			},
    			dataType: 'json'			
    		});
     
                   //Display loader and disable forms - DO THIS AFTER SERIALISING
    		disable_form_fields(true);

    Let me know if you have any issues.

    Blocking Duplicate Payment – Paypal

    Hey everyone,

    Just a quick post on how to block duplicate payments with PayPal. All you have to do is pass an invoice parameter and then select the ‘block multiple payments per invoice ID’ option in PayPal. I’ve attached an extract from PayPal’s documentation below:

    1. Login at https://www.paypal.com
    2. Click the ‘Profile’ subtab
    3. Under ‘Selling Preferences’ click ‘Payment Receiving Preferences’
    4. Choose ‘Yes, block multiple payments per invoice ID’ if you wish to utilize this feature while passing the “invoice” variable
    5. Scroll to the bottom and click the ‘Save’ button

    To pass the invoice number for Website Payments Standard, you will need to add a line of code to your existing button code. You cannot add this code to a button originally created as encrypted. Example below:

    <input type=”hidden” name=”invoice” value=”001″>

    The documentation is available at the following link:
    https://ppmts.custhelp.com/app/answers/detail/a_id/165

    Uploadify – Limit to One Upload Only

    Hey everyone,

    Just a quick post detailing how to limit uploadify to a single file. Simply add the following settings to your uploadify initialisation:

    multi: false
    queueSizeLimit : 1
    uploadLimit : 1

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    
     
    $(document).ready(function() {
         $('#file_upload').uploadify({
            'swf' : '<?php echo $this->Html->url('/uploadify/uploadify.swf');?>',
    	'uploader' : '<?php echo $this->Html->url('/uploadify/uploadify.php');?>',
    	'cancelImg' : '<?php echo $this->Html->url('/webroot/uploadify/cancel.png');?>',
    	'folder' : '<?php echo $this->Html->url('/extraz/uploaded_by_all_users');?>',
    	'auto' : true,
    	'buttonText' : 'Browse',
    	'multi' : false,
    	'queueSizeLimit' : 1,
    	'uploadLimit' : 1,
    	'sizeLimit' : 1073741824,
    	'debug' : true,
    	'multi' : false,	        
    	'onUploadProgress' : upload_progress_handler,
    	'onUploadStart' : upload_start_handler,
    	'onUploadSuccess' : on_upload_success,
    	'onUploadError' : on_upload_error
         });
    });

    Once the upload limit is exceeded the onUploadError event is raised.

    Cheers

    POST http://192.168.1.3:3000 406 (Not Acceptable) – AJAX with Ruby on Rails

    Just a quick post on an error I ran into today when trying to create an AJAX image upload with Ruby on Rails. When submitting an AJAX form I received the following error:

    POST http://192.168.1.3:3000/uploads 406 (Not Acceptable)
    

    It turns out that there is a fairly simple (and admittedly obvious) solution. Ensure that your controller has an appropriate response for JavaScript files:

    i.e.
    Form:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    
    <%= form_for(@upload, :html =>{:multipart => true}, :remote => 'true') do |f| %>
      <% if @upload.errors.any? %>
        <div id="error_explanation">
          <h2><%= pluralize(@upload.errors.count, "error") %> prohibited this image from being saved:</h2>
          <% @upload.errors.keys.each do |field| %>
            <% @upload.errors[field].each do |msg| %>
              <% if field.to_s == "uploads.upload_content_type" %>
                <li><%= field.to_s + " " + msg %></li>
            <% end %>
          <% end %>
        </div>
      <% end %>
      <div>
        <p>
          <%= f.file_field :upload %>
        </p>
      </div>
      <div class="actions">
        <%= f.submit :class => 'button' %>
      </div>
      <%= f.hidden_field :product_id, :value => @upload.product_id %>
    <% end %>

    Form JavaScript:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    
    /* Wait for document to load */
    $(document).ready(function() {
        create_ajax_form('new_upload');
    })
     
    /* Create an ajax form */
    function create_ajax_form(form_id){
     
       //Handle ajax submission
       $j('#' + form_id).submit(function(){
     
           //Send for data
           $j.post($j(this).attr("action"), $j(this).serialize(), null, "script");
     
           //Return false
           return false;
       });
    }

    Controller Action:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    
    #Create an upload
      def create
     
        #Create vars
        @upload = Upload.new(params[:upload])
     
        #Create responses
        respond_to do |format|
          if @upload.save
     
            #Retrieve product
            @product = Product.find_by_id(@upload.product_id)
     
            #Create success responses
            format.html { redirect_to @product, :notice => 'Image Added Successfully!'}
            format.js
          else
     
            #Create error responses
            format.html { render :action => 'new'}
            format.js
          end
        end
      end

    JavaScript Response:

    1
    
    alert('test');

    Popover Function – Twitter Bootstrap

    Just a quick post on how easy it is to implement a popover with twitter bootsrap:

    JavaScript:

    //Create tooltips for login/signup forms
    function create_tooltips(){
     
        //Create vars
        var titles = ['test title']
        var contents = ['test content'];
        var fields = ['#user_email'];
     
        //Loop through each field and assign tooltip
        for(var i = 0; i < fields.length; i++){
     
            //Create vars
            var field = $(fields[i]);
            var title = titles[i];
            var content = contents[i];
     
            //Ensure field found
            if(field){
     
                //Create popover
                $(field).popover(
                    {
                        animation: true,
                        placement: 'right',
                        selector: false,
                        trigger: 'hover',
                        title: title,
                        content: content,
                        delay: 0
                    });
            }
        }
    }

    Form:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    
      <div class="span4">
        <%= form_for(resource, :as => resource_name, :url => registration_path(resource_name), :class => 'form-vertical') do |f| %>
        <fieldset class="well">
          <div class="control-group">
            <%= f.label :email, 'Email:' %>
            <div class="controls">
              <%= f.email_field :email %>
            </div>
          </div>
          <div class="control-group">
            <%= f.label :display_name, 'Display Name:' %>
            <div class="controls">
              <%= f.text_field :display_name %>
            </div>
          </div>
          <div class="control-group">
            <%= f.label :password, 'Password:' %>
            <div class="controls">
              <%= f.password_field :password %>
            </div>
          </div>
          <div class="control-group">
            <%= f.label :password_confirmation, 'Password Confirmation:'%>
            <div class="controls">
              <%= f.password_field :password_confirmation %>
            </div>
          </div>
          <div class="control-group">
            <%= f.submit "Sign up", :class => 'btn btn-success' %>
          </div>
        </fieldset>
        <% end %>
      </div>

    Result:

    Popover - Twitter Bootstrap

    Popover - Twitter Bootstrap

    That’s all there is to it, if you haven’t had a chance to check it out yet make sure you head on over to the official site - there are some pretty neat features.

    undefined method `merge’ for 5:Fixnum – Hidden Field

    Just a quick post on an error I ran into today while using hidden fields:

    undefined method `merge' for 5:Fixnum
     
    27:   <div class="actions">
    28:     <%= f.submit :class => 'button' %>
    29:   </div>
    30:   <%= f.hidden_field(:product_id, @upload.product_id) %>
    31: <% end %>
    32:

    Thankfully this is an easy fix, simply amend your code as follows:

    1
    2
    3
    4
    5
    
    <div class="actions">
        <%= f.submit :class => 'button' %>
    </div>
       <%= f.hidden_field :product_id, :value => @upload.product_id %>
    <% end %>

    And that’s all there is to it, let me know if there are any issues.

    Create Button which does not Submit – Ruby on Rails

    Just another quick post – how to create a button which does not submit a form when it’s clicked:

    <%= submit_tag 'My Button',  :type => 'button', :onclick => 'alert('Button not Submitted - Hopefully!!!!'), :class => "my_class" %>

    Let me know if you have any problems.