Zend FR

Consultez la FAQ sur le ZF avant de poster une question

Vous n'êtes pas identifié.

#1 27-02-2009 17:54:02

eilijah
Membre
Date d'inscription: 17-02-2009
Messages: 20

[résolu]un souci avec update()

Salut a tous,

voila mon souci, je veux faire une simple update de ma base en passant pas un formulaire, j'ai écris un code qui marchait hier mais j'ai fait des modifs hier soir, résultat çà ne fonctionne plus. Mon gros souci est que je n'ai aucune erreur ?!
Pourtant mon environnement n'a pas changé.  Plus précisément, lorsque je soumet le formulaire il semble bien le traiter et me renvoit "formulaire valide" (voir le code, normalement tout s'est bien passé), mais la base n'est pourtant pas modifiée. Il ne semble y avoir aucun problème avec l'acquisition de la table et le tableau de donnée transmit parait ok hmm
bref j'y suis depuis ce matin et j'y comprend rien.

J'ai essayé d'épurer le code au maximum pour le post, j'espere que vous pourrez m'eclairer ! (ps: l'action new-course marche tres bien, seul l'edit-course ne marche pas).

la table :

Code:

-- phpMyAdmin SQL Dump
-- version 3.1.1
-- http://www.phpmyadmin.net
--
-- Serveur: localhost
-- Généré le : Ven 27 Février 2009 à 17:49
-- Version du serveur: 5.1.30
-- Version de PHP: 5.2.8

SET SQL_MODE="NO_AUTO_VALUE_ON_ZERO";

--
-- Base de données: `courses_platform`
--

-- --------------------------------------------------------

--
-- Structure de la table `courses`
--

CREATE TABLE IF NOT EXISTS `courses` (
  `c_id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `c_title_raw` varchar(80) NOT NULL,
  `c_title_formatted` varchar(80) DEFAULT NULL,
  `c_description` varchar(255) NOT NULL,
  `c_creator_id` int(11) unsigned DEFAULT NULL,
  `c_creation_date` datetime DEFAULT NULL,
  `c_editor_id` int(11) unsigned DEFAULT NULL,
  `c_edit_date` datetime DEFAULT NULL,
  `c_edit_comment` varchar(255) DEFAULT NULL,
  PRIMARY KEY (`c_id`),
  UNIQUE KEY `c_title_raw` (`c_title_raw`,`c_title_formatted`,`c_description`),
  UNIQUE KEY `c_title_formatted` (`c_title_formatted`),
  KEY `c_creator_id` (`c_creator_id`),
  KEY `c_editor_id` (`c_editor_id`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=10 ;

--
-- Contraintes pour les tables exportées
--

--
-- Contraintes pour la table `courses`
--
ALTER TABLE `courses`
  ADD CONSTRAINT `courses_ibfk_5` FOREIGN KEY (`c_creator_id`) REFERENCES `users` (`u_id`) ON DELETE NO ACTION ON UPDATE CASCADE,
  ADD CONSTRAINT `courses_ibfk_6` FOREIGN KEY (`c_editor_id`) REFERENCES `users` (`u_id`) ON DELETE NO ACTION ON UPDATE CASCADE;

Code:

<?php

/**
 * CoursesController
 * 
 * application/default/controllers/CourseController.php
 */

// indexAction() : get the array of courses
// listlessonsAction() : get the array of lessons
// viewlessonAction() : get the right lesson
// _getModel() : build and get a Model_Table to allow the requests above


require_once 'Zend/Controller/Action.php';

class CoursesController extends Zend_Controller_Action 
{
    protected $_model;
    
    /**
     * indexAction()
     * list the courses
     *
     * @return void
     */
    public function indexAction() 
    {
    ...
    }
    
    ...
    
    /**
     * newCourseAction() 
     * create a course
     *
     * @return void
     */
    public function newCourseAction() 
    {
        $this->_applyForm('Course', 'new-course');
    }
    
    ...
    
    /**
     * editCourseAction() 
     * edit a course
     *
     * @return void
     */
    public function editCourseAction() 
    {
        $courseId = $this->_request->getParam('c_id');
        $model = $this->_getModel();
        $courses = $model->fetchEntries('Courses', 'c_id', $courseId);
        
        print_r($courses);
        
        $registry = Zend_Registry::getInstance(); 
        $registry->set('courses', $courses);
        $url = $this->view->url(array(  'controller' => 'courses',
                                        'action' => 'edit-course',
                                        'c_id' => $courseId,
                                ),
                                'default', true);
        $apply = $this->_applyForm('Course', $url, 'c_id', $courseId);
        /*if($apply){
            $archivesCourse['ac_course_id']    = $courses['0']['c_id'];
            $archivesCourse['ac_title']        = $courses['0']['c_title_raw'];
            $archivesCourse['ac_description']  = $courses['0']['c_description'];
            $archivesCourse['ac_editor_id']    = $courses['0']['c_editor_id'];
            $archivesCourse['ac_edit_date']    = $courses['0']['c_edit_date'];
            $archivesCourse['ac_edit_comment'] = $courses['0']['c_edit_comment'];
            $model->save($archivesCourse, 'ArchivesCourses');
        }*/
        unset($registry['courses']);
    }
    
    /**
     * _getModel() 
     * get a new Table instance
     *
     * @return void
     */
    protected function _getModel()
    {
        if (null === $this->_model) {
            require_once APPLICATION_PATH . '\models\Table.php';
            $this->_model = new Model_Table();
        }
        return $this->_model;
    }
    
    /**
     * function _applyForm()
     * create and get back the appropriate Form_ object
     * if isPost, insert or, if $row and $rowvalue are provided, update datas
     *
     * @param  string $table_name_with_cap
     * @param  string $actionTarget
     * @param  mixed  $row
     * @param  mixed  $rowValue     
     * @return bool $updating
     */
    protected function _applyForm($form_name_with_cap, $actionTarget, $row = '', $rowValue = '')
    {
        $request = $this->getRequest();
        $form = 'Form_' . $form_name_with_cap;
        $form = new $form(array(
                                'action' => $actionTarget,
                                'method' => 'post'));
        $updating = false;
        if ($this->getRequest()->isPost()) {
            if ($form->isValid($request->getPost())) {
                if($row != '' && count($row) == count($rowValue)){
                    $model = $this->_getModel();
                    $formValues = $form->getValues();
                    $model->upToDate($formValues, $form_name_with_cap . 's', $row, $rowValue);
                    //debug
                    echo '$formValues : ';
                    print_r($formValues);
                    echo '$form_name_with_cap : ' . $form_name_with_cap;
                    echo 'formulaire valide';
                    $updating = true;
                }
                else if(count($row) != count($rowValue)){
                    throw new Exception('Cannot update entries, not the same amount of rows and values');
                }
                else if ($row == ''){
                    $model = $this->_getModel();
                    $formValues = $form->getValues();
                    $model->save($formValues, $form_name_with_cap.'s');
                    //debug
                    //echo '$formValues : ';
                    //print_r($formValues);
                    //echo '$table_name_with_cap1 : ' . $table_name_with_cap;
                    echo 'formulaire valide2';
                }
            }
            else{
                echo 'formulaire non valide';
                //debug
                print_r($form->getErrors());
                print_r($form->getMessages());
            }
        }
        else {
            echo 'formulaire non posté';
        }
        $this->view->form = $form;
        return $updating; 
    }
}
?>

Code:

<?php

/**
 * Model_Table
 * 
 * @author
 * @version 0.01
 * 
 * application/default/models/Table.php
 */

// Standard methods for all the tables


/**
 * half of the business logic (other side is under the DbTable folder)
 */
 
class Model_Table
{
    /** Model_Table_Support */
    protected $_table;

    /**
     * get a named table object
     * 
     * @param  string $table_name_with_cap
     * @return Model_Guestbook_Table
     */
    public function getTable($table_name_with_cap)
    {
        unset($this->_table);
        require_once APPLICATION_PATH . '/models/DbTable/'.$table_name_with_cap.'.php';
        $modelDbTableName = 'Model_DbTable_'.$table_name_with_cap;
        $this->_table = new $modelDbTableName;
        return $this->_table;
    }
    
    /**
     * Save a new entry
     * 
     * $data is an array in where u have the same key names
     * than in the table columns
     * If u want fill the "content" column in the table 
     * you should have a $data['content'].
     * Its working well with _getAppropriateForm() method
     * from the supportController class.
     * 
     * @param  array $data 
     * @param  string $table_name_with_cap
     * @return int|string
     */
    public function save(array $data, $table_name_with_cap)
    {
        //debug
        /*
        echo '$data avant : ';
        print_r($data);
        */
        
        $table  = $this->getTable($table_name_with_cap);
        $fields = $table->info(Zend_Db_Table_Abstract::COLS);
        
        //debug
        /*
        echo '$fields avant : ';
        print_r($fields);
        */
        
        // unset the element of $data which have no column in the table.
        foreach ($data as $field => $value) {
            if (!in_array($field, $fields)) {
                unset($data[$field]);
            }
        }
        
        //debug
        /*
        echo '$table_name_with_cap : ' . $table_name_with_cap;
        echo '$data apres : ';
        print_r($data);
        */
        
        //insert() method from Model_Support include the creation date 
        //then insert $data in the table
        return $table->insert($data);
    }
    
    /**
     * Update an entry
     * 
     * $data is an array in where u have the same key names
     * than in the table columns
     * If u want fill the "content" column in the table 
     * you should have a $data['content'].
     * 
     * @param  array $data 
     * @param  string $table_name_with_cap
     * @param  mixed $row 
     * @param  mixed $rowValue 
     * @return int|string
     */
    public function upToDate(array $data, $table_name_with_cap, $row, $rowValue)
    {
        //debug
        echo '$data avant : ';
        print_r($data);
        
        $table  = $this->getTable($table_name_with_cap);
        $fields = $table->info(Zend_Db_Table_Abstract::COLS);
        
        //debug
        echo '$fields avant : ';
        print_r($fields);
        
        // unset the element of $data which have no column in the table.
        foreach ($data as $field => $value) {
            if (!in_array($field, $fields)) {
                unset($data[$field]);
            }
        }
        
        // set the 'WHERE' for the update
        $where = '';
        if (is_array($row)){
           $where = $row . ' = ' . $rowValue;
           for($i=1; $i<count($row);$i++){
                $where .= ' AND ' . $row . ' = ' . $rowValue;    
           }
        }
        else {
            $where = $row . ' = ' . $rowValue;
        }
        $where = $table->getAdapter()->quote($where);
        
        //debug
        echo '$table_name_with_cap : ' . $table_name_with_cap;
        echo '$data apres : ';
        print_r($data);
        echo '$where : ';
        print_r($where);
        
        return $table->update($data, $where);
    }

    ...
}

Code:

<?php

/**
 * Model_DbTable_Courses
 * 
 * @author
 * @version 0.01
 * 
 * application/default/models/DbTable/Courses.php
 */

// Particular methods for the table courses
// insert() : insert the immediate date in co_creation_date 
//     and insert the datas in the courses table
// update() : update data for the targeted entry


class Model_DbTable_Courses extends Zend_Db_Table_Abstract{
    
    // table name
    protected $_name = "courses";

    /**
     * insert()
     * Insert new row
     *
     * Ensure that a timestamp is set for the created field.
     * 
     * @param  array $data 
     * @return int
     */
    public function insert(array $data)
    {
        $data['c_creation_date'] = date('Y-m-d H:i:s');
        $data['c_edit_date'] = $data['c_creation_date'];
        return parent::insert($data);
    }

    /**
     * update()
     * Do not allow updating of entries
     * 
     * @param  array $data 
     * @param  mixed $where 
     * @return void
     * @throws Exception
     * 
     * public function update(array $data, $where)
    */
    public function update(array $data, $where)
    {
        $data['c_edit_date'] = date('Y-m-d H:i:s');
        return parent::update($data, $where);
    }
    
}

Code:

<?php
// application/default/forms/Course.php

/**
 * This is the support form.  It is in its own directory in the application 
 * structure because it represents a "composite asset" in your application.  By 
 * "composite", it is meant that the form encompasses several aspects of the 
 * application: it handles part of the display logic (view), it also handles 
 * validation and filtering (controller and model).  
 */
class Form_Course extends Zend_Form
{
    /**
     * init()
     * initialization routine
     *
     * @see    http://framework.zend.com/manual/en/zend.form.html
     * @return void
     */ 
    public function init()
    {
        // if it's an edit we get the last course datas
        $registry = Zend_Registry::getInstance(); 
        if ($registry->isRegistered('courses')){
            $courses = $registry->get('courses');
            $this->addElement('textarea', 'c_edit_comment', array(
                'label'      => 'Modifications apportées par l\'édition :',
                'required'   => false,
                'filters'    => array('StringTrim'),
                'order'         => 2,
            ));
        }
        else{
            $courses['0']['c_title_raw'] = '';
            $courses['0']['c_description'] = '';
            $registry->set('courses', $courses);
        }
        
        // set the method for the display form to POST
        $this->setMethod('post');

        $this->addElement('text', 'c_title_raw', array(
            'label'      => 'Titre du cours :',
            'required'   => true,
            'filters'    => array('StringTrim'),
            'value'      => $courses['0']['c_title_raw'],
        ));

        $this->addElement('textarea', 'c_description', array(
            'label'      => 'Description du cours :',
            'required'   => true,
            'filters'    => array('StringTrim'),
            'value'      => $courses['0']['c_description'],
        ));

        $this->addElement('captcha', 'captcha', array(
            'label'      => 'Entrez les lettres suivantes svp :',
            'required'   => true,
            'captcha'    => array('captcha' => 'Figlet', 'wordLen' => 5, 'timeout' => 300)
        ));

        // add the submit button
        $this->addElement('submit', 'submit', array(
            'label'    => 'Enregistrer',
        ));
    }
}

Code:

<?php
/**
 * new-course.phtml
 * 
 * @author
 * @version 0.01
 * 
 * application/default/views/scripts/courses/new-course.phtml
 */

// Creation of a new course

$this->headTitle('Nouveau cours');
//$this->headScript('');
$this->headStyle('./styles/style.css');
?>

<p><a href="<?= $this->url(
    array(
        'controller' => 'courses',
    ), 
    'default', 
    true) ?>">Liste des cours</a></p>
<p><a href="<?= $this->url(
    array(
        'controller' => 'courses',
        'action'     => 'new-lesson'
    ), 
    'default', 
    true) ?>">Créer une leçon</a></p>
    
<p>Nouveau cours :</p>

<?= $this->form ?>

Code:

<?php
/**
 * edit-course.phtml
 * 
 * @author
 * @version 0.01
 * 
 * application/default/views/scripts/courses/edit-course.phtml
 */

// Edition of an existing course

$this->headTitle('Modification de cours');
//$this->headScript('');
$this->headStyle('./styles/style.css');
?>

<p><a href="<?= $this->url(
    array(
        'controller' => 'courses',
    ), 
    'default', 
    true) ?>">Liste des cours</a></p>
<p><a href="<?= $this->url(
    array(
        'controller' => 'courses',
        'action'     => 'new-lesson'
    ), 
    'default', 
    true) ?>">Créer une leçon</a></p>
    
<p>Editer le cours :</p>

<?= $this->form ?>

Code:

<?php

/**
 * index.phtml
 * 
 * @author
 * @version 0.01
 * 
 * application/default/views/scripts/courses/index.phtml
 */

// List the available courses

$this->headTitle('Home');
?>
<br />
<p>Cours disponibles: </p>
<br />

<!-- exemple pour le test, remplace le code original un peu long -->

<p>
    <a href="<?= $this->url(array(    'controller'     => 'courses',
                                    'action'           => 'edit-course',
                                    'c_id'     => 3,), 
                            'default', 
                            true) ?>">
        edit the 3rd course
    </a>
</p>

<p><a href="<?= $this->url(
    array(
        'controller' => 'courses',
        'action'     => 'new-course'
    ), 
    'default', 
    true) ?>">Créer un cours</a></p>

exemple d'un retour :

Code:

<?xml version="1.0" encoding="UTF-8" ?><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>

    <head>
        ...
    </head>
    
    <body>
        
        <a href="/ZendStudio/plateformeDeCours/public/login">login</a>               
           <div id="nav"></div>
           <div id="content">
<p><a href="/ZendStudio/plateformeDeCours/public/courses">Liste des cours</a></p>
<p><a href="/ZendStudio/plateformeDeCours/public/courses/new-lesson">Créer une leçon</a></p>
    
<p>Editer le cours :</p>

<form> <!--formulaire--> </form>Array
(
    [0] => Array
        (
            [c_id] => 3
            [c_title_raw] => Moyen-age
            [c_title_formatted] => 
            [c_description] => période du moyen-age
            [c_creator_id] => 
            [c_creation_date] => 2009-02-25 03:51:18
            [c_editor_id] => 
            [c_edit_date] => 2009-02-26 19:02:06
            [c_edit_comment] => 
        )

)
$data avant : Array
(
    [c_edit_comment] => 
    [c_title_raw] => Renaissance
    [c_description] => période du Renaissance
    [captcha] => Array
        (
            [id] => 898338cc80740ce7f360153733ece59e
            [input] => ZIQIK
        )

    [submit] => Enregistrer
)
$fields avant : Array
(
    [0] => c_id
    [1] => c_title_raw
    [2] => c_title_formatted
    [3] => c_description
    [4] => c_creator_id
    [5] => c_creation_date
    [6] => c_editor_id
    [7] => c_edit_date
    [8] => c_edit_comment
)
$table_name_with_cap : Courses$data apres : Array
(
    [c_edit_comment] => 
    [c_title_raw] => Renaissance
    [c_description] => période du Renaissance
)
$where : 'c_id = 3'$formValues : Array
(
    [c_edit_comment] => 
    [c_title_raw] => Renaissance
    [c_description] => période du Renaissance
    [captcha] => Array
        (
            [id] => 898338cc80740ce7f360153733ece59e
            [input] => ZIQIK
        )

    [submit] => Enregistrer
)
$form_name_with_cap : Courseformulaire valide</div>

            </body>

</html>

j'espere que vous pourrez m'aider !

Dernière modification par eilijah (03-03-2009 21:27:19)

Hors ligne

 

#2 02-03-2009 21:32:31

eilijah
Membre
Date d'inscription: 17-02-2009
Messages: 20

Re: [résolu]un souci avec update()

Je suis toujours bloqué avec cette histoire, personne n'a une idée svp?
Au pire je reprend tout demain hmm

Hors ligne

 

#3 02-03-2009 22:27:24

3uclide
Membre
Date d'inscription: 09-08-2008
Messages: 194

Re: [résolu]un souci avec update()

Je ne sais pas si c'est ça, mais dans ton contrôleur tu as commenté cette partie

Code:

  /*if($apply){
            $archivesCourse['ac_course_id']    = $courses['0']['c_id'];
            $archivesCourse['ac_title']        = $courses['0']['c_title_raw'];
            $archivesCourse['ac_description']  = $courses['0']['c_description'];
            $archivesCourse['ac_editor_id']    = $courses['0']['c_editor_id'];
            $archivesCourse['ac_edit_date']    = $courses['0']['c_edit_date'];
            $archivesCourse['ac_edit_comment'] = $courses['0']['c_edit_comment'];
            $model->save($archivesCourse, 'ArchivesCourses');
        }*/

Hors ligne

 

#4 02-03-2009 22:36:01

-=blu3+3y3s=-
Membre
Lieu: Toulouse
Date d'inscription: 01-04-2008
Messages: 47

Re: [résolu]un souci avec update()

Salut,
tu as mis en commentaire un partie de ton code dans CoursesController::editCourseAction(). Ne serait-ce pas ça, ton problème?

Hors ligne

 

#5 03-03-2009 02:06:39

eilijah
Membre
Date d'inscription: 17-02-2009
Messages: 20

Re: [résolu]un souci avec update()

@ 3uclide > non en fait pour update un cours j'update la table course et je sauve l'ancienne version dans archive_course, cependant l'update ne marche pas , le save lui marche tres bien, j'ai donc juste commenté le save pour pouvoir y voir plus clair.

@-=blu3+3y3s=- >  Tous les commentaires sont censé etre la il n'y a pas d'erreur a ce niveau là, malheureusement.

bonne nuit a tous smile

Dernière modification par eilijah (03-03-2009 02:06:57)

Hors ligne

 

#6 03-03-2009 21:28:30

eilijah
Membre
Date d'inscription: 17-02-2009
Messages: 20

Re: [résolu]un souci avec update()

Le probleme venait de la fonction :

Code:

public function upToDate(array $data, $table_name_with_cap, $row, $rowValue)
    {
        //debug
        echo '$data avant : ';
        print_r($data);
        
        $table  = $this->getTable($table_name_with_cap);
        $fields = $table->info(Zend_Db_Table_Abstract::COLS);
        
        //debug
        echo '$fields avant : ';
        print_r($fields);
        
        // unset the element of $data which have no column in the table.
        foreach ($data as $field => $value) {
            if (!in_array($field, $fields)) {
                unset($data[$field]);
            }
        }
        
        // set the 'WHERE' for the update
        $where = '';
        if (is_array($row)){
           $where = $row . ' = ' . $rowValue;
           for($i=1; $i<count($row);$i++){
                $where .= ' AND ' . $row . ' = ' . $rowValue;    
           }
        }
        else {
            $where = $row . ' = ' . $rowValue;
        }
        $where = $table->getAdapter()->quote($where);
        
        //debug
        echo '$table_name_with_cap : ' . $table_name_with_cap;
        echo '$data apres : ';
        print_r($data);
        echo '$where : ';
        print_r($where);
        
        return $table->update($data, $where);
    }

L'argument where pour update() doit etre de la forme

c_id = '4'

Or ce que j'avais ecris renvoyait

'c_id = 4'

Je trouve bizar qu'il y ait aucune erreure renvoyée cependant.

Je note egalement que dans mon cas je ne peux mettre 
$where = $table->getAdapter()->quote($where);
sinon j'obtiens

'c_id =\'4\''

qui ne marche pas mieux que dans mon premier cas

au final la methode ressemble donc a :

Code:

    public function upToDate(array $data, $table_name_with_cap, $row, $rowValue)
    {
        // get the right table
        $table  = $this->getTable($table_name_with_cap);
        
        // unset the elements of $data which have no column in the table.
        $fields = $table->info(Zend_Db_Table_Abstract::COLS);
        foreach ($data as $field => $value) {
            if (!in_array($field, $fields)) {
                unset($data[$field]);
            }
        }
        
        // set the 'WHERE' for the update request
        $where = '';
        if (is_array($row)){
           $where = $row . " = '" . $rowValue . "'";
           for($i=1; $i<count($row); $i++){
                $where .= " AND " . $row . " = '" . $rowValue . "'";    
           }
        }
        else {
            $where = $row . " = '" . $rowValue . "'";
        }

        return $table->update($data, $where);
    }

Dernière modification par eilijah (03-03-2009 21:42:45)

Hors ligne

 

Pied de page des forums

Propulsé par PunBB
© Copyright 2002–2005 Rickard Andersson
Traduction par punbb.fr

Graphisme réalisé par l'agence Rodolphe Eveilleau
Développement par Kitpages