Files

95 lines
2.2 KiB
C++
Raw Permalink Normal View History

2015-11-10 20:16:30 +01:00
#ifndef AUTOFORM_H
#define AUTOFORM_H
#include <QWidget>
#include <QDebug>
2016-02-13 21:41:05 +01:00
#include <QMessageBox>
2015-11-10 20:16:30 +01:00
#include "service.h"
2016-02-13 21:41:05 +01:00
#include "iservice.h"
#include "iplugin.h"
2016-02-24 22:46:36 +01:00
#include "formbinder.h"
2015-11-10 20:16:30 +01:00
#include "combodata.h"
2015-11-17 22:24:00 +01:00
2015-11-10 20:16:30 +01:00
template <class T>
2016-02-24 22:46:36 +01:00
class AutoForm : public FormBinder<T>
2015-11-10 20:16:30 +01:00
{
public:
explicit AutoForm(QWidget *parent = nullptr) {
this->setParent(parent);
2016-02-13 21:41:05 +01:00
m_serviceConnected = false;
m_saved = false;
2015-11-10 20:16:30 +01:00
}
virtual ~AutoForm() = default;
2015-11-17 22:24:00 +01:00
void setNewRec(bool isNew) {
2016-02-24 22:46:36 +01:00
this->m_newRec = isNew;
2015-11-10 20:16:30 +01:00
}
public slots:
2015-11-10 22:39:58 +01:00
bool saveRecord() {
2016-02-24 22:46:36 +01:00
if (!this->bindToData())
2015-11-10 22:39:58 +01:00
{
return false;
}
2016-02-13 21:41:05 +01:00
if (!m_serviceConnected)
{
this->connect(service(), &IService::dbError, [this](const QString& msg) {
2016-04-06 20:38:01 +02:00
QMessageBox::critical(this, this->tr("Database error"), msg.toStdString().c_str());
2016-02-13 21:41:05 +01:00
m_saved = false;
2016-03-11 14:13:40 +01:00
});
this->connect(service(), &IService::permissionDenied, [this](const QString& permission) {
2016-04-06 20:38:01 +02:00
if (permission != PERM_DELETE) {
QMessageBox::critical(this, this->tr("Permission denied"), permission.toStdString().c_str());
m_saved = false;
}
2016-02-13 21:41:05 +01:00
});
2016-02-24 22:46:36 +01:00
this->connect(service(), &IService::dataChanged, [this]() {
2016-02-13 21:41:05 +01:00
m_saved = true;
});
m_serviceConnected = true;
}
2016-02-24 22:46:36 +01:00
if (this->m_newRec) {
service()->save(this->entity());
2016-02-13 21:41:05 +01:00
if (m_saved)
{
2016-02-24 22:46:36 +01:00
emit this->recordAdded();
2016-02-13 21:41:05 +01:00
}
2015-11-10 20:16:30 +01:00
} else {
2016-02-24 22:46:36 +01:00
service()->update(this->entity());
2016-02-13 21:41:05 +01:00
if (m_saved)
{
2016-02-24 22:46:36 +01:00
emit this->recordUpdated();
2016-02-13 21:41:05 +01:00
}
2015-11-10 20:16:30 +01:00
}
2015-11-10 22:39:58 +01:00
2016-02-13 21:41:05 +01:00
return m_saved;
2015-11-10 20:16:30 +01:00
}
2016-02-13 21:41:05 +01:00
private:
Service<T> *service() {
2016-02-24 22:46:36 +01:00
IPlugin *plugin = Context::instance().plugin(this->pluginId());
if (plugin == nullptr) {
2016-02-13 21:41:05 +01:00
Q_ASSERT(false);
return nullptr;
2016-02-13 21:41:05 +01:00
}
Service<T> *service = plugin->service<T>();
if (service == nullptr) {
2016-02-13 21:41:05 +01:00
Q_ASSERT(false);
return nullptr;
2016-02-13 21:41:05 +01:00
}
return service;
}
bool m_serviceConnected;
bool m_saved;
2015-11-10 20:16:30 +01:00
};
#endif // AUTOFORM_H