Reputation: 441
I am trying to save sets of data, through these models.
Model 1: Service
Generates a series of service dates.
Model 2: Response
For each service entry, user is required to add a set number of responses.
So, I'd like to save multiple service entries for multiple response. The code is fairly self explanatory, but I can add more information if required. I can't find an easy solution to do this, though I feel it's fairly straight forward.
if (isset($_POST['Service'], $_POST['Response']))
{
$model->attributes = $_POST['Service'];
$valid = $model->validate();
// date manipulation
$start = new DateTime($model->date_booked);
$start->format('Y-m-d');
$end = new DateTime($model->end_date);
$end->format('Y-m-d');
$interval = DateInterval::createFromDateString($model->interval);
$range = new DatePeriod($start, $interval, $end);
if ($valid)
{
foreach ($range as $key => $value)
{
$schedule = new Service;
$schedule->attributes = $_POST['Service'];
$schedule->date_booked = $value->format('Y-m-d');
// If I were to save here, the following, Response Model
// will not be validated!
// $schedule->save();
foreach ($_POST['Response'] as $j => $k)
{
$response[$j] = new Response;
$response[$j]->attributes = $_POST['Response'][$j];
// If I were to save the Service Models here,
// evidently, entries are doubled up!
// $service->save();
$response[$j]->service_id = $service->id;
$valid = $response[$j]->validate() && $valid;
// $response[$j]->save();
}
}
}
}
Thank you!
Upvotes: 0
Views: 1209
Reputation: 441
I had to just run through, yet another foreach loop, to get this working. Yes, I do feel like I am iterating the loops, so if someone have another elegant solution, by all means share them to me. :-)
For now, this is done.
if (isset($_POST['Service'], $_POST['Response']))
{
// Assign and validate Service mcrypt_module_is_block_algorithm
$model->attributes = $_POST['Service'];
$valid = $model->validate();
// date manipulation
$start = new DateTime($model->date_booked);
$start->format('Y-m-d');
$end = new DateTime($model->end_date);
$end->format('Y-m-d');
$interval = DateInterval::createFromDateString($model->interval);
$range = new DatePeriod($start, $interval, $end);
// Assign and Validate Response Populated questions
foreach ($_POST['Response'] as $j => $k)
{
$response[$j] = new Response('populate'); // populate scenario
$response[$j]->attributes = $_POST['Response'][$j];
$valid = $response[$j]->validate() && $valid;
}
if ($valid)
{
foreach ($range as $key => $value)
{
$schedule = new Service; // static model
$schedule->attributes = $_POST['Service'];
$schedule->date_booked = $value->format('Y-m-d');
$schedule->save();
foreach ($_POST['Response'] as $x => $y)
{
$response[$x] = new Response('populate'); // populate scenario
$response[$x]->attributes = $_POST['Response'][$x];
$response[$x]->service_id = $schedule->id;
$response[$x]->save();
}
}
}
}
Upvotes: 1