Archive for March 2014

PHP: Adding Custom Closure Parameter

PHP supported closure(anonymous function) since PHP 5.3. Sometimes extra parameter is needed to pass to those closure. PHP provide use keyword to do this job. Here is an example with array_filter():
$array = array(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
$param = 5; // custom parameter
 
$r = array_filter($array, function($i) use ($param) { return $i < $param; });
// checking result
print_r($r);

Flask: WTForm How To Create Dynamic Fields

I had a problem with Flask-WTForm when I need to create dynamic fields. Trying to search how to solve this problem by googling for several hours. Finally I got the idea and solved this problem. This is how I can create dynamic fields with WTForm in flask.
Form:
class Costumer(Form):
  name = FieldList(TextField('Costumer Name'), validators = [Required()])
View:
@app.route('/newcostumer/', methods = ['POST'])
def newcostumer(total): // total is user generated value
  # set field attributes as nessesary like choices etc
  for i in range(total):
    if not form.is_submitted():
        form.name.append_entry()
        
  #validate after set form attributes
  if form.validate_on_submit():
    #get post data
    names = {}
    for i in range(total):
      name[i] = form.name[i].data
      
  # populate obj  
  if form.is_submitted():
        form.populate_obj(request.form)
  # render to newcostumer.html template
  return render_template('newcostumer.html', form = form, total = total)
Template:
# render form on newcostumer.html with jinja2
{% for i in range(total) %}
  {{form.name[i](id='cost'~i, class='costumer-class')}}
{% endfor %}
 
{% for error in form.errors %}
  [{{error}}]
{% endfor %}
This entry was posted in