2013-08-21 101 views
0

我以前在互联网上看到类似这样的表单 - 基本上我想让用户动态添加字段到WTForms中的SelectField下拉表单。例如,也许下拉菜单中的第一个字段是允许用户向表单添加自定义字段的链接。我将如何去执行WTForms中的这样的事情?谢谢!WTForms添加额外的类别到SelectField

回答

0

迈克尔您好我知道这3月中下旬,但最近我与AngularJS和引导情态动词的帮助下类似的东西,所以我想我会把这件事为完整起见:

这是一个非常简化版本我没有包括任何错误检查或验证,您当然希望为您的生产环境做这些。

在我的模板中,以下是选择字段的样子。而不是第一个选项是让人创建的东西,我只是在选择字段旁添加了一个链接,允许一个人添加一个新的类别。链接本身以模式打开一个表单。

以下是选择栏:

<div class="form-group"> 
     {{ form.maincategory.label(class="col-sm-2 control-label") }} 
     <div class="col-sm-5"> 
     {{ form.maincategory(**{'ng-model':'maincategory', 
           'ng-options':'c.id as c.displayname for c in allmaincategories', 
           'class':'form-control'}) }} 
     #over here is the link that opens the form in a modal window 
     </div><a data-toggle="modal" href="#newcategory">Add a new category</a> 
    </div> 

当链路上的用户单击添加新类别下面的模态窗口加载:

<!-- Add new category Modal --> 
<div class="modal fade" id="newcategory" tabindex="-1" role="dialog" 
    aria-labelledby="myModalLabel" aria-hidden="true"> 
    <div class="modal-dialog"> 
    <div class="modal-content"> 
     <div class="modal-header"> 
     <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button> 
     <h4 class="modal-title" id="myModalLabel">Create new main category</h4> 
     </div> 
     <div class="modal-body"> 
     <form method="post" ng-submit="createCategory()"> 
      <div class="form-group"> 
       {{ categoryform.displayname.label(class="col-sm-8 control-label") }} 
       <div> 
        {{ categoryform.displayname(**{'ng-model':'maincat.displayname','class':'form-control'}) }} 
       </div> 
      </div> 
      <div class="modal-footer"> 
       <button type="button" class="btn btn-default" data-dismiss="modal">Close</button> 
       <input type="submit" class="btn btn-primary" value="Save changes" /> 
      </div> 
     </form> 
     </div> 
    </div> 
    </div> 
</div> 

的WTFORM形式类呈现上述形式在模态窗口中如下:

class DirectoryMainCategoryForm(Form): 
    displayname = TextField('Category name as it appears', validators=[DataRequired(message=(u'This category name is how it appears in the menu'))]) 

#the following is the form main form where the select appears 
class MainEntry(Form): 
    maincategory = QuerySelectField('Main category', validators = DataRequired(message=(u'Please select a category for this place'))], get_label='category', 
    allow_blank=False, query_factory=Maincategory.query.all,blank_text =('-- Select a main category --')) 


#And of course the javascript magic that glues it all together: 
function DirectoryController($scope, $http){ 
    #Adds a new category to the select menu 
    $scope.createCategory = function() { 
     var categorydata = angular.toJson($scope.maincat); 
     $http.post('/create/new/category', categorydata).success(function(data) { 
      $scope.allmaincategories = data.category; 
     }); 
    } 
} 
相关问题