#ifndef AUTOFORM_H #define AUTOFORM_H #include #include #include #include #include #include #include "service.h" #include "ivalidator.h" template class AutoForm : public QWidget { public: explicit AutoForm(QWidget *parent = 0) : QWidget(parent) { m_newRec = false; } virtual ~AutoForm() { foreach (IValidator *val, m_validators) { delete val; m_validators.clear(); } } void setEntity(QSharedPointer entity) { m_entity = entity; bindToUi(); } void registerBinding(QWidget *widget) { if (!m_bindWidgets.contains(widget)) { m_bindWidgets.append(widget); } } void registerValidator(IValidator *validator) { m_validators.append(validator); } private: QSharedPointer m_entity; QList m_bindWidgets; QList m_validators; bool m_newRec; void bindToUi() { foreach (QWidget *widget, m_bindWidgets) { const char* prop = widget->metaObject()->userProperty().name(); widget->setProperty(prop, ((QObject*)m_entity.data())->property(widget->objectName().toStdString().c_str())); } } bool bindToData() { foreach (IValidator *val, m_validators) { if (!val->validate()) { emit validationError(val->errMessage()); return false; } } foreach (QWidget *widget, m_bindWidgets) { const char* prop = widget->metaObject()->userProperty().name(); ((QObject*)m_entity.data())->setProperty(widget->objectName().toStdString().c_str(), widget->property(prop)); } return true; } signals: void recordAdded(QSharedPointer entity); void recordUpdated(QSharedPointer entity); void validationError(QString errMessage); public slots: bool saveRecord() { if (!bindToData()) { return false; } Service service; service.save(m_entity); if (m_newRec) { emit recordAdded(m_entity); } else { emit recordUpdated(m_entity); } return true; } }; #endif // AUTOFORM_H