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

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.
class Costumer(Form):
  name = FieldList(TextField('Costumer Name'), validators = [Required()])
@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():
  #validate after set form attributes
  if form.validate_on_submit():
    #get post data
    names = {}
    for i in range(total):
      name[i] =[i].data
  # populate obj  
  if form.is_submitted():
  # render to newcostumer.html template
  return render_template('newcostumer.html', form = form, total = total)
# render form on newcostumer.html with jinja2
{% for i in range(total) %}
  {{[i](id='cost'~i, class='costumer-class')}}
{% endfor %}
{% for error in form.errors %}
{% endfor %}
This entry was posted in