You can get an existing record from the database using
fetchOne()
, but you also need to be able to
create new records to save later. You can do so using the
fetchNew()
method, optionally passing an
array of data to pre-populate its properties.
<?php
// a new blog record with default values
$new_blog = $model->blogs->fetchNew();
// a new blog record with specified values
$new_blog = $model->blogs->fetchNew(array(
'title' => 'New Title Text',
'body' => '(insert body here)',
));
Warning | |
---|---|
There is a |
Whether it is a new record or an existing one, you can modify the
properties of the record by addressing its properties individually,
or by using the load()
method to load an array
of data to the record in one pass.
<?php
/**
* @var Solar_Sql_Model_Record $item The result of fetchNew() or fetchOne(),
* or a record from a collection.
*/
// modify the properties individually:
$item->title = 'Another Title';
$item->body = 'Different body text';
// or modify them via load().
$data = array(
'status' => 'draft',
'title' => 'Another Title',
'body' => 'Different body text',
);
$item->load($data);
// only load certain properties. useful for loading only
// specific values from a data source, e.g. $_POST.
$whitelist = array('title', 'body');
$item->load($data, $whitelist);
Once you have modified the record, you can call the
save()
method to insert or update it to the
database. (The record object knows if it is new, it needs to be
inserted; otherwise it will update itself using its primary key
value.)
Note | |
---|---|
The record will save only the data that has changed; that is, only the "dirty" elements. |
Because the model has defined certain filters for the record,
the save()
call will fail if any of the
validations fail, so you need to check if the save()
succeeded to see what went wrong.
<?php
/**
* @var Solar_Sql_Model_Record $item The result of fetchNew() or fetchOne(),
* or a record from a collection, and thereafter modified.
*/
// attempt to save the record.
$success = $item->save();
// did it work?
if (! $success) {
// no, something was not valid
$invalid = $item->getInvalid();
foreach ($invalid as $property => $message) {
echo htmlspecialchars($property) . ' is not valid: '
. htmlspecialchars($message) . '<br />';
}
// or you can get the internal exception
// that caused the save to fail.
echo $item->getSaveException();
} else {
// yes, it worked
echo 'Saved!';
}
You can combineload()
and
save()
into a single save()
call, optionally with a whitelist.
<?php
/**
* @var Solar_Sql_Model_Record $item The result of fetchNew() or fetchOne(),
* or a record from a collection.
*/
// incoming data
$data = array(
'status' => 'draft',
'title' => 'Another Title',
'body' => 'Different body text',
);
// only load these properties
$whitelist = array('title', 'body');
// load and save the record in one call
$success = $item->save($data, $whitelist);
// did it work?
if (! $success) {
// ...
} else {
// yes, it worked
echo 'Saved!';
}