Referring to my older question, I have the entryId working on an existing entry. However I've noticed a new entry doesn't have an entryId set (makes sense).
I have some custom information in text fields that needs to be saved after onSaveEntry is fired (which I have working). I have a custom model, record, controller and service setup. In my controller I retrieve these custom text fields including the entryId field from Craft. But because a new entry doesn't have an entryId set yet, my controller/service is not working as it should.
When the entry is saved and the page redirects to wherever, I also lose all the information in the text fields. So that's why I want to save my custom information directly after the entry is saved.
My question is, how do I handle this when I don't have the entry id. I don't want the user saving the entry first (to basically generate the entry id), then fill in the custom text fields and then save again (which works). But I think this is very devious.
This is my controller:
public function actionSaveRecord() {
$this->requirePostRequest();
if ($id = craft()->request->getPost('recordId')) {
$model = craft()->plugin->getRecordById($id);
} else {
$model = craft()->plugin->newRecord($id);
}
$model->entryId = craft()->request->getPost('entryId');
$model->customField = craft()->request->getPost('customField ');
if ($model->validate()) {
craft()->plugin->saveRecord($model);
}
}
This is the service:
public function saveRecord(PluginModel &$model)
{
if ($id = $model->getAttribute('id')) {
$pluginRecord = PluginRecord::model()->findById($id);
if (!$pluginRecord) {
throw new Exception(Craft::t('Can\'t find record with ID "{id}"', array('id' => $id)));
}
} else {
$pluginRecord = new PluginRecord();
}
if ($model->validate()) {
$attributes = array(
'entryId' => $model->entryId,
'customField' => $model->customField,
);
foreach ($attributes as $k => $v) {
$pluginRecord ->setAttribute($k, $v);
}
if ($pluginRecord ->save()) {
// update id on model (for new records)
$model->setAttribute('id', $pluginRecord->getAttribute('id'));
return true;
} else {
$model->addErrors($pluginRecord->getErrors());
return false;
}
}
}
The rest of the plugin can be found here for reference: https://github.com/iNalgiev/webtexttool1