I have 2 models that handle sliders and slides for my website. Blow is a small part of the used code. This is inside a wordpress backend, using the phalcon micro framework.
// Existing or new image ?
$id =$app->request->getPost( 'id', 'int' );
if( !is_numeric( $id ) && $id <= 0 ) $slider =new Sliders();
else $slider =Sliders::findFirst( $id );
$slider->cover =Images::findFirst( $app->request->getPost( 'cover', 'int' ));
$slider->setName( $app->request->getPost( 'name', 'string' ));
$slider->setDescription( $app->request->getPost( 'description' ));
$slides =[];
foreach( $app->request->getPost( 'slides' ) as $slide )
{
$dummy =new Slides();
$dummy->image =Images::findFirst( $slide['image'] );
$dummy->setLink( $slide['link'] );
$dummy->setActive( $slide['active'] );
$dummy->setCaption( $slide['caption'] );
$dummy->setExternal( $slide['external'] );
$slides[] =$dummy;
}
// Remove all old slides
$dummy =Slides::find([
'conditions' => 'slider_id = ?1',
'bind' => [
'1' => $slider->getId()
]
]);
$dummy->delete();
// Add the new slides
$slider->slides =$slides;
// Create or update region
if( $slider->save())
The above code is used to save a slider and its slides. Although I had a strange thing happening when using something else to delete the former slides. The code below sees to be the solution.
// Remove all old slides
$dummy =Slides::find([
'conditions' => 'slider_id = ?1',
'bind' => [
'1' => $slider->getId()
]
]);
$dummy->delete();
But I don't get it why the code below isn't working as expected. When I use the code below instead of the fin above. All the old slides get removed, but the new slides don't get added. I know the relations on the two modes are correct.
$slider->slides->delete();