#ifndef GRIDFORM_H #define GRIDFORM_H #include #include "autoform.h" #include "autotablemodel.h" #include "context.h" #include "iplugin.h" #include "igridform.h" template class GridForm : public IGridForm { public: explicit GridForm(QWidget *parent = 0) : IGridForm(parent) { m_form = NULL; m_tableModel = NULL; m_formHandler = new DefaultFormHandler(); } virtual ~GridForm() { delete m_formHandler; } void setForm(AutoForm *form) { Q_ASSERT(m_form == NULL); m_form = form; //m_form->setParent(this); connect(m_form, SIGNAL(recordAdded()), this, SLOT(saveNew())); connect(m_form, SIGNAL(recordUpdated()), this, SLOT(saveUpdate())); } void setTableModel(AutoTableModel *tableModel) { Q_ASSERT(m_tableModel == NULL); m_tableModel = tableModel; } void setFormHandler(IFormHandler *handler) { delete m_formHandler; m_formHandler = handler; } public slots: void fillData() { if (m_tableModel == NULL) { Q_ASSERT(false); return; } m_tableModel->setData(service()->all()); tableView()->setModel(m_tableModel); } protected slots: void saveNew() { service()->save(m_form->entity()); m_tableModel->addRow(m_form->entity()); emit dataChanged(); } void saveUpdate() { service()->update(m_form->entity()); emit dataChanged(); } private: AutoForm *m_form; AutoTableModel *m_tableModel; IFormHandler *m_formHandler; Service *service() { IPlugin *plugin = Context::instance().plugin(pluginId()); if (plugin == NULL) { Q_ASSERT(false); return NULL; } Service *service = plugin->service(); if (service == NULL) { Q_ASSERT(false); return NULL; } return service; } // IGridForm interface protected: void handleNewRecord() override { if (m_form == NULL) { Q_ASSERT(false); return; } m_form->setEntity(QSharedPointer(new T())); m_form->setNewRec(true); m_formHandler->showForm(m_form); } void handleEditRecord() override { if (m_form == NULL || m_tableModel == NULL || tableView()->currentIndex().row() < 0) { Q_ASSERT(false); return; } m_form->setEntity(m_tableModel->itemFromIndex(tableView()->currentIndex())); m_form->setNewRec(false); m_formHandler->showForm(m_form); } }; #endif // GRIDFORM_H