0

In short: I have form that has 2 text fields for values :title and :title_de. I need to automatically pass value :lang on submit as either "eng" or "de" depending on if field for :title was left empty or not. How to do it?

EDIT: controller code for create:

def create
  @article = Article.new(article_params)

  if @article.save
    redirect_to @article
  else
    render 'new'
  end
end

3 Answers 3

1

UPDATE

Solution to assign lang in controller:

def create
  @article = Article.new(article_params)

  @article.lang = params[:title].blank? ? "de" : "eng"

  if @article.save
    redirect_to @article
  else
    render 'new'
  end
end

Or, if you prefer, you could use javascript/jquery to get the value of :title and then assign the correct value to :lang before submitting your form.

Snippet:

$('#my-button').on('click', function() {
  event.preventDefault();
  var title = $('#title').val();

  if(title == "") {
    $('#lang').val("de");
  } else {
    $('#lang').val("eng");
  }
  
  // change to $('#my-form').submit();
  alert($('#lang').val());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<form id="my-form">
  title: <input type="text"name="title" id="title"/><br>
  title_de: <input type="text" name="title_de" id="title_de"/><br>
  <input type="hidden" id="lang" name="lang" />
  <input type="submit" id="my-button" />
</form>

Sign up to request clarification or add additional context in comments.

3 Comments

The controller solution seems to put "de" in lang regardless of title being empty or not.
fixed it by changing line to: @article.lang = @article.title.blank? ? 'rus' : 'eng'
If you created your form with rails helper methods all form values will be grouped together (most likely under the model/object name), so instead of using params[:title].blank? you could use something like params[:article][:title].blank?. But i like your fix better than calling params.
0

When a form field is left empty it returns nil. You can check for nil and set the language in your controller:

if params[:title] == "nil"
# set the language
else 
# title is not nil, do something else
end

You could do it in the view as well using javascript but if the user has javascript disabled you have a problem.

1 Comment

Not sure how to implement this into my controller. Edited main post and added what I'm using there.
0

Using javascript you can do like

In your view add hidden_file_tag
<%= hidden_filed_tag :langauge, id: "langauge" %>

and in javascript
$('#title').on("change",function(){
  if($(this).val() == ""){
    $("#langauge").val('eng')
  }else{
    $("#langauge").val('de')
  }
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.