Wtx ~ Wt Extension Library
WtxLib
Make a ComboBox model with a blank item

Sometimes you want to populate a combo box from another table. This is all well and good when you want to pick from a list of items populated from a table, but what if you want to also be able to select "no" item, or otherwise deselect any current selections? When populating a combo box from a model, the combo box will only allow a selection from the list. Therefore, it is necessary to create a model that has an extra blank item.

This is very easy to do with a direct SQL statement.

97 std::shared_ptr<Wt::WAbstractItemModel> Mrp::Company::getComboBoxModel( int sid, int tid, const std::string & where, Wtx::Dbo::Session & session )
98 {
99 auto retVal = std::make_shared< Wtx::Dbo::QueryModel< std::tuple<int,std::string> > >();
100
107 Wt::Dbo::Transaction t(session);
108
109 // auto w = where;
110 // if( tid != -1 )
111 // w = Wt::WString("WHERE id={1}").arg(tid).toUTF8();
112
113 auto sql =
114 Wt::WString
115 (
116 "SELECT id,\"keyField\" || ' ~ ' || \"cfyField\" AS key FROM \"crmCompany\""
117 " {1}"
118 " UNION "
119 "SELECT -1 as id, '' as key"
120 " ORDER BY key"
121 )
122 .arg( where )
123 .toUTF8()
124 ;
125
126
127 auto query =
128 session.query< std::tuple<int,std::string> >( sql )
129 ;
130
131 retVal-> setQuery( query );
132 retVal-> addColumn("id");
133 retVal-> addColumn("key");
134
135 return retVal;
136 }