Aggiornare due tabelle

Ciao a tutti,

da una view vorrei aggiornare due tabelle.

Nella vista che fa l’update della tabella events, ho messo un input file per uploadare una o più immagini nella tabella events_images, legare quindi una o più immagini ad un evento (aggiungendo più immagini conlo stesso event_id).

Io ho creato i model ed i crud delle due tabelle.

poi le tabelle sono queste:

tabella events

Campo Tipo

event_id int(11)

title tinytext

content text Sì

schedule text

start_date date

end_date date

place varchar(100)

tabella events_images

Campo Tipo

file_id int(11)

name varchar(64)

description text

real_name varchar(128)

event_id int(11)

e la view _form.php di update della tabella "events" è questa:




<div class="form">

<?php 

    $form = $this->beginWidget('CActiveForm', array(

        'id' => 'events-form',

        'enableAjaxValidation' => false,

        

        /*'htmlOptions' => array(

            'enctype' => 'multipart/form-data'

        )*/

            ));




?>


	<p class="note">Fields with <span class="required">*</span> are required.</p>

	<?php echo $form->errorSummary($model); ?>

           <div class="row">

                <?php echo $form->labelEx($model,'title'); ?>

                <?php // echo $form->textArea($model,'title',array('rows'=>6, 'cols'=>50)); ?>

                <?php

                    

                        $this->widget('application.extensions.tinymce.ETinyMce', array(

                            'name' => 'html',

                            'editorTemplate' => 'full',

                            'model' => $model,

                            'attribute' => 'title',

                              'options' => array(

                                'theme' => 'advanced',

                                'skin' => 'o2k7',

                                'theme_advanced_buttons1' => 'preview,bold,italic,underline,fontselect,fontsizeselect,link,justifyfull,justifyleft,justifycenter,justifyright,pasteword,pastetext,table,image,|,bullist,numlist,|,undo,redo,|,code,fullscreen',

                                'theme_advanced_buttons2' => '',

                                'theme_advanced_buttons3' => '',

                            ),

                            'value' => $model->title,

                        ));

                                               

                    ?>

                <?php echo $form->error($model,'title'); ?>

            </div>


      	

        <div class="row">  

         <?php echo $form->labelEx($model, 'content'); ?>

         <?php

            $this->widget('application.extensions.tinymce.ETinyMce', array(

                //'name' => 'html',

                'editorTemplate' => 'full',

                'model' => $model,

                'attribute' => 'content',

                'options' => array(

                    'theme' => 'advanced',

                    'skin' => 'o2k7',

                    'theme_advanced_buttons1' => 'preview,bold,italic,underline,fontselect,fontsizeselect,link,justifyfull,justifyleft,justifycenter,justifyright,pasteword,pastetext,table,image,|,bullist,numlist,|,undo,redo,|,code,fullscreen',

                    'theme_advanced_buttons2' => '',

                    'theme_advanced_buttons3' => '',

                ),

                'value' => $model->content,

            ));

        ?>

       <?php echo $form->error($model, 'content'); ?>

        </div>

     

<!--

	<div class="row">

		<?php echo $form->labelEx($model,'schedule'); ?>

		<?php echo $form->textArea($model,'schedule',array('rows'=>6, 'cols'=>50)); ?>

		<?php echo $form->error($model,'schedule'); ?>

-->

	<div class="row">

		<?php echo $form->labelEx($model,'start_date'); ?>

		<?php //echo $form->textField($model,'start_date'); ?>

	        <?php $this->widget('zii.widgets.jui.CJuiDatePicker', array(

                                'model'=>$model, 

                                'value'=>'',

                                'attribute' => 'start_date',

                                'language' => 'it',

                                'options'=>array(  

                                    'dateFormat'=>'dd-mm-yy',

                                    'changeMonth' => 'true',

                                    'changeYear' => 'true',

                                    'showButtonPanel' => 'true',

                                    'constrainInput' => 'false',

                                    'showAnim' =>'slideDown'

                                ),

                                

                                /*'htmlOptions'=>array(

                                        'class'=>'start_date'

                                ),*/

          ));

?>

            <?php echo $form->error($model,'start_date'); ?>

	</div>

        

        <?php echo $form->labelEx(EventsImages::model(), 'real_name'); ?>

        <?php echo $form->fileField(EventsImages::model(), 'real_name', array('size' => 60, 'maxlength' => 250)); ?>

        <?php echo $form->error(EventsImages::model(),'real_name'); ?>

	<div class="row buttons">

            <?php echo CHtml::submitButton($model->isNewRecord ? 'Create' : 'Save'); ?>

	</div>

<?php $this->endWidget(); ?>


</div>

<!-- form -->



questo invece una delle tante prove del mio metodo update di EventsController.php




    public function actionUpdate($id) {

        $model = $this->loadModel($id);

        // Uncomment the following line if AJAX validation is needed

        // $this->performAjaxValidation($model);


        if (isset($_POST['Events'])) {

            $model->attributes = $_POST['Events'];

            // parte che interessa l'upload

            $modelEventsImages = new EventsImages;

            $modelEventsImages->attributes = $_POST['EventsImages'];          

            echo "<pre>";  

            echo "<br><br>\$models->attributes:<br>";

            var_dump($model->attributes);

            echo "<br><br>\$modelEventsImages->attributes:<br>";

            var_dump($modelEventsImages->attributes);

                //die();

                // Aggiungo anche in update l'upload dell'immagine  

               if (isset($_FILES["Events"])) {

                $ext = end(explode(".", $_FILES["Events"]["name"]["real_name"]));

                $immagine = md5(mktime() . $_FILES["EventsImages"]["name"]["real_name"]) . '.' . $ext;

                //$modelEventsImages = new EventsImages;

                $modelEventsImages->real_name = CUploadedFile::getInstance($modelEventsImages, 'real_name');

                $modelEventsImages->real_name->saveAs(Yii::app()->basePath . "/../images/" . $immagine);

                $image = Yii::app()->image->load(Yii::app()->basePath . "/../images/" . $immagine);

                $image->resize(179, 179);

                $image->save();

                $modelEventsImages->real_name = $immagine;

                //$modelEventsImages->save();

                /*if ($modelEventsImages->save())

                    $this->redirect(array('view', 'id' => $model->id));

               */

            }

            

            if ($model->save())

                $this->redirect(array('view', 'id' => $model->event_id));

        }


        $this->render('update', array(

            'model' => $model,

        ));

    }




mi sono un po inceppato… perchè se stampo

var_dump($model->attributes);

var_dump($modelEventsImages->attributes);

ricevo sia i dati della form originale sia l’immagine., ma non riesco a capire come continuare…

qualsiasi suggerimento e ben accetto!

grazie mille

GIuseppe

La prima cosa che noto, è che non vedo nessun codice che salvi l’immagine nel db:


$modelEventsImages->save();

Per il resto? Nel file system è tutto ok?

Ciao Simone,

ho modificato il metodo in questo modo, ora mi fa l’upload ma non mi salva nel database.

Ho aggiunto alla fine




if($model->save() && $modelEventsImages->save())



cosi se ha salvato entrambi mi va sulla view.




public function actionUpdate($id) {

        $model = $this->loadModel($id);

        // Uncomment the following line if AJAX validation is needed

        // $this->performAjaxValidation($model);


        if (isset($_POST['Events'])) {

            $model->attributes = $_POST['Events'];

            // parte che interessa l'upload

            $modelEventsImages = new EventsImages;

            $modelEventsImages->attributes = $_POST['EventsImages'];          

            // Aggiungo anche in update l'upload dell'immagine  

            if (isset($_FILES["EventsImages"])) {

                $ext = end(explode(".", $_FILES["EventsImages"]["name"]["real_name"]));

                $immagine = md5(mktime() . $_FILES["EventsImages"]["name"]["real_name"]) . '.' . $ext;

                $modelEventsImages->real_name = CUploadedFile::getInstance($modelEventsImages, 'real_name');

                $modelEventsImages->real_name->saveAs(Yii::app()->basePath . "/../images/" . $immagine);

                $image = Yii::app()->image->load(Yii::app()->basePath . "/../images/" . $immagine);

                $image->resize(179, 179);

                $image->save();

                $modelEventsImages->real_name = $immagine;

                

             }

            

            if ($model->save() && $modelEventsImages->save())

                $this->redirect(array('view', 'id' => $model->event_id));

        }


        $this->render('update', array(

            'model' => $model,

        ));

    }




Allego un immagine con l’errore che mi restituisce…

Ho paura comunque che mi manca proprio la parte relativa al database.

Cioè facendo questo $modelEventsImages->save() cosa richiamo? devo modificare il model della tabella EventsImages o va bene così…? (io creato per la tabella EventsImages sia model che crud da gii)

ciao e grazie ancora

GIuseppe

Devi installare l’estensione image.

che pivello… che sono :) la installo e ci riprovo…

Allora… spero abbiate ancora un po di pazienza…

ho spostato tutta l’applicazione su ubuntu… magari gle piaceva di più…

ora dopo avere installato l’extension image mi da quest’errore.

C’è la faro prima o poi… :)

ciao e grazie

Giuseppe

Esiste questo file? protected/extensions/image/CImageComponent.php? Sembra che lo cerchi ma non lo trovi. Probabilmente bisogna mettere ancora mano al file di configurazione. In particolare nell’import.

Se apri protected/config/main.php trovi il file di configurazione. Se cerchi all’inizio import, noterai che vengono caricati tutti i controller e tutti i model. Io, che mi diverto a tenere in una cartella separata i behavior. Salvo tutti i behavior nella cartella protected/behavior ma poi mi devo ricordare di indicare questa cartella dentro il parametro import del mio file di configurazione.

E’ possibile che tu debba fare lo stesso per l’estensione image.

Allora… In effetti caro sensorario era l’estensione.

Ho rifatto l’installazione da capo e sta volta è andata…

poi qui nell’esempio ho anche commentato la parte relativa al resize.

Posto comunque la soluzione nella speranza che possa servire a qualcuno.

Il metodo in questione mi aggiorna sia la tabella "events" sia la tabella "events_images".




   public function actionUpdate($id) {

        $model = $this->loadModel($id);

        // Uncomment the following line if AJAX validation is needed

        // $this->performAjaxValidation($model);

         

        if (isset($_POST['Events'])){

            $model->attributes = $_POST['Events'];

                //parte che interessa l'upload

                $modelEventsImages = new EventsImages;

                $modelEventsImages->attributes = $_POST['EventsImages'];

            //Aggiungo anche in update l'upload dell'immagine  

            if (isset($_FILES["EventsImages"])) {

                $ext = end(explode(".", $_FILES["EventsImages"]["name"]["real_name"]));

                $immagine = md5(mktime() . $_FILES["EventsImages"]["name"]["real_name"]) . '.' . $ext;

                $modelEventsImages->real_name = CUploadedFile::getInstance($modelEventsImages, 'real_name');

                $modelEventsImages->real_name->saveAs(Yii::app()->basePath . "/../images/events/originals/" . $immagine);

               

                //salvo nel database

                $modelEventsImages->event_id = $id;

                $modelEventsImages->name="Name";

                $modelEventsImages->description="Description";

                $modelEventsImages->real_name="/images/events/originals/" . $immagine;

                

                /*

                resize thumbs

                $image = Yii::app()->image->load(Yii::app()->basePath . "/../images/" . $immagine);

                $image->resize(179, 179);

                $image->save();

                */

            }


            if ($model->save() && $modelEventsImages->save())

                $this->redirect(array('view', 'id' => $model->event_id));

        }


        $this->render('update', array(

            'model' => $model,

        ));

    }




l’unica domanda che vorrei fare e se è giusto scrivere in successione:





 $modelEventsImages->real_name = CUploadedFile::getInstance($modelEventsImages, 'real_name');

 $modelEventsImages->real_name->saveAs(Yii::app()->basePath . "/../images/events/originals/" . $immagine);

 //salvo nel database

 $modelEventsImages->event_id = $id;

 $modelEventsImages->name="Name";

 $modelEventsImages->description="Description";

 $modelEventsImages->real_name="/images/events/originals/" . $immagine;

                




grazie sensorario della tua pazienza.

buona serata

Giuseppe