Nuanes
Nuanes

Reputation: 67

Telephone formatting

I am new to Rails and I am trying to figure out how to use the example at http://apidock.com/rails/ActionView/Helpers/NumberHelper/number_to_phone to format a phone number in my code below. Trying to figure out how and where I call number_to_phone(number, options = {}) public

<div class="form-group">
      <label class="control-label col-sm-5" for="phone">Phone Number:</label>
      <div class="col-sm-7">
        <%= f.text_field :phone, class: 'form-control', autofocus: true, placeholder: 'xxx-xxx-xxxx' %>
     </div>
   </div>

Upvotes: 3

Views: 10885

Answers (4)

dr.
dr.

Reputation: 1449

You would use it in show.html.erb

<%= number_to_phone(@contact.phone) %>

Upvotes: 0

Cristiano Mendon&#231;a
Cristiano Mendon&#231;a

Reputation: 1282

First of all you must know that number_to_phone method doesn't return an HTML input field. It returns a String. Thus what can be formatted with that method is telephones already saved.

Following code will show a saved telephone formatted inside an input text field.

<%= f.text_field :phone, class: 'form-control', autofocus: true, placeholder: 'xxx-xxx-xxxx', value: number_to_phone(@my_variable.telephone, area_code: true, extension: 555) %>

If you're looking for some way of masking an input field dynamically (as user types in text), you'll want to use a jQuery library such as maskedInput

Upvotes: 1

Tilo
Tilo

Reputation: 33732

You should hand in the phone number, or an object that contains the phone number through an instance variable @your_variable from your controller to your view. Let's assume that the instance you are handing in, has an attribute phone_number.

In the view file, you should do something like this:

 <%= form_for @person do |f| %>
   <%= f.telephone_field(:phone, :value => @your_variable.phone_number ) %> 

   <%= f.submit %>
 <% end %>

If you want to have an HTML input field, you should use the appropriate form helpers in your view, e.g.: telephone_field

See: http://api.rubyonrails.org/classes/ActionView/Helpers/FormHelper.html

Upvotes: 4

esthervillars
esthervillars

Reputation: 16

You use number_to_phone(number, options = {}) in a rails helper or view

Here is an example of a helper used to format the phone How do you use number_to_phone in Rails 3?

Upvotes: 0

Related Questions