Problème d'ajout à la BDD si règle de validation : checkUnique

Par Manal Aba, il y a 11 ans


Salut, je suis nouvelle sur ce Forum.
Je suis en train de développer une appli cake-php de gestion d'événements.
Dans la partie ''Ajouter Ticket'' j'ai ajouté une règle de validation pour que le nom du ticket sois unique pour un événement. Sauf que une fois ajoutée, si je rentre un nom de ticket autre que ceux qui existent déjà les valeurs ne s'ajoutent pas à ma BDD.
TABLE ticket_types : (id,event_id,name,quantity,max_tickets_user,created,modified,status,start,end)
===>L'ajout d'un ticket sans appliquer la règle de validation marche très bien.
*******Voici mon Modèle*******

<?php
class TicketType extends AppModel {
        //var $name = 'TicketType';
    public $actsAs = array('Containable');
        public $belongsTo = 'Event';
        public $hasMany = array(
            'Ticket',
            'Discount',
            'FreeTicket' => array('dependent' => true),
            'PaidTicket' => array('dependent' => true)
            ) ;

    //règle de validation personnalisée
        public function checkUnique($check) {
            $count = $this->find('count', array('conditions' => array('TicketType.event_id' => $this->data'TicketType']'event_id'], 'TicketType.name' => $this->data'TicketType']'name'])));
            if($count)
                return false;
            return true;
        }
    public $validate = array(
        'name' =>
                    array(
                        "rule" => "checkUnique",
                       "message" => "A ticket with that name already exists for this event"
            ) 
    );

    public function beforeFind($query) {
        parent::beforeFind($query);
        $tickets = $this->find('all', array('callbacks' => false));
        if ($tickets) {
            foreach ($tickets as $key => $ticket) {
                $this->id = $ticket'TicketType']'id'];
                if ($this->exists()) {
                    $this->updateStatus();
                } else {
                    throw new NotFoundException();
                }
            }
        }                       
    }

    public function addTicketType($data) {
        $this->create();
        if($this->save($data'TicketType'], false)){ // test sur la création du ticket (isUnique)
        if (in_array($data'type'], array('F', 'P'))) {
            if ($data'type'] == 'F') {
                $this->FreeTicket = ClassRegistry::init('FreeTicket');
                $this->FreeTicket->create();
                return $this->FreeTicket->save(array('ticket_type_id' => $this->id, 'has_form' => $data'FreeTicket']'has_form']));
            } elseif ($data'type'] == 'P') {
                $this->Fee = ClassRegistry::init('Fee');
                $fee = $this->Fee->findById($data'PaidTicket']'fee_id']);
                $total_buyer = $data'PaidTicket']'price'];
                if ($fee'Fee']'type'] == 'pass') {
                    $total_buyer = $data'PaidTicket']'price'] + (($data'PaidTicket']'price'] * $fee'Fee']'value']) + 10);
                }               
                $this->PaidTicket = ClassRegistry::init('PaidTicket');
                $this->PaidTicket->create();
                return $this->PaidTicket->save(array('ticket_type_id' => $this->id, 'fee_id' => $data'PaidTicket']'fee_id'], 'price' => $data'PaidTicket']'price'], 'total_buyer' => $total_buyer));
            }
            return false;
        }
    }
    }
    public function removeTicketType() {
        if ($this->exists()) {
            return $this->delete();
        }
        return false;
    }
    public function reserveTicketTypeQuantity($requestType, $qty = 1) {
        if (in_array($requestType, array('block', 'unblock'))) {
            if ($requestType == 'block') {              
                if ($this->checkDates()) {
                    $data = $this->read();
                    if (($data'TicketType']'quantity'] > 0) && ($data'TicketType']'quantity'] >= $qty)) {
                        $this->saveField('quantity', $data'TicketType']'quantity'] - $qty);
                        $data'TicketType']'quantity'] = $qty; //decrement available quantity in DB
                        return $data;
                    }
                }
            }
            if ($requestType == 'unblock') {
                $ticket_qty = $this->read(array('quantity'));
                $ticket_qty'TicketType']'quantity'] += $qty; 
                return $this->saveField('quantity', $ticket_qty'TicketType']'quantity']);
            }
        }
        return false;
    }
    public function checkQuantity($userId, $qty = 0) {
        $this->Ticket = ClassRegistry::init('Ticket');
        $max = $this->read()'TicketType']'max_tickets_user'];
        $userNb = $this->Ticket->numberTicketsAcquiredByUser($userId, $this->id);
        $remain = $max - $userNb;
        if ($qty == 0) {
            return ($remain) > 0 ? $remain : 0;
        }
        if (($userNb + $qty > $max) || ($qty > $max)) {
            return false;
        }
        return $remain - $qty;
    }
    public function checkDates() {
        $t = time();        
        $this->data = $this->read(array('start', 'end'));
        return ((time() >= strtotime($this->data'TicketType']'start'], $t)) 
            && (time() <= strtotime($this->data'TicketType']'end'], $t)));          
    }

    public function updateStatus() {
        if ($this->data = $this->find('first', array('conditions' => array('TicketType.id' => $this->id), 'callbacks' => false))) {
            $t = time();
            if ($t > strtotime($this->data'TicketType']'end'], $t)) {
                return $this->saveField('status', 'ended', array('callbacks' => false));
            } elseif ($t < strtotime($this->data'TicketType']'start'], $t)) {
                return $this->saveField('status', 'upComing', array('callbacks' => false));
            } else {
                if ($this->data'TicketType']'quantity'] > 0) {
                    return $this->saveField('status', 'onSale', array('callbacks' => false));
                } else {
                    return $this->saveField('status', 'soldOut', array('callbacks' => false));
                }
            }
        }       
        return false;       
    }
}
?>

*****Dans le contrôleur****

public function add($eventId) {
        if ($this->request->data) {
            $this->request->data'TicketType']'event_id'] = $eventId;
            if (!$this->TicketType->save($this->request->data)) {
                $this->Session->setFlash(__('Erreur lors de la création du ticket'), 'default', array('class' => 'alert alert-danger'));
            }       
            return $this->redirect(array('action' => 'index', $eventId));
        }
    }

==MERCI

10 réponses

Manal Aba, il y a 11 ans

Oui je sais mais dans ma table ticket_types je peux avoir des tickets de même nom mais pour des événements différents

Glaived, il y a 11 ans

Mes ton code php dans une balise code ] /code ] (sans espaces) pour que ce soit lisible, merci ^^

Manal Aba, il y a 11 ans

Voilà c'est fait. Merci Glaived (oups j'ai validé ta réponse je sais plus comment annuler je crois que cette fonctionnalité n'existe pas encore sur le Forum :/ )

Manal Aba, il y a 11 ans

Il reste que le message de validation ne s'affiche pas sur mon formulaire d'ajout :/ any idea ?

Manal Aba, il y a 11 ans

Le problème d'ajout réside toujours :/ si le nom n'existe pas dans la BDD il est enregistré en NULL ! Personne ne peut aider?

Kareylo, il y a 11 ans

Peux-tu nous donner le debug de ton $this-request->data ?

Manal Aba, il y a 11 ans
\app\Controller\TicketTypesController.php (line 189)
array(
    'type' => 'F',
    'TicketType' => array(
        'event_id' => '',
        'name' => 'nom test ',
        'description' => 'test debug this request data',
        'start' => array(
            'month' => '08',
            'day' => '11',
            'year' => '2014',
            'hour' => '11',
            'min' => '25'
        ),
        'end' => array(
            'month' => '09',
            'day' => '11',
            'year' => '2014',
            'hour' => '11',
            'min' => '25'
        ),
        'quantity' => '300',
        'max_tickets_user' => '1',
        'visibility' => 'visible'
    ),
    'PaidTicket' => array(
        'fee_id' => '1',
        'price' => ''
    ),
    'FreeTicket' => array(
        'has_form' => '0'
    )
)
Kareylo, il y a 11 ans

Pour l'erreur que ça n'enregistre pas dans ta BDD, c'est parce que tu ne fais pas de $this->TicketType->create($this->request->data). Essaies d'en faire un, ça devrait résoudre ce problème.

Manal Aba, il y a 11 ans

j'ai déjà le create() dans ma fonction addTicket dans mon Model TicketType. L'ajout sans la règle marche très bien ce n'est qu'après avoir ajouté la règle que j'ai ce problème

public function addTicketType($data) {
        $this->create();
        if($this->save($data'TicketType'])){ //#CODE MANAL: ajouté le if(save())
        if (in_array($data'type'], array('F', 'P'))) {
            if ($data'type'] == 'F') {
                $this->FreeTicket = ClassRegistry::init('FreeTicket');
                $this->FreeTicket->create();
                return $this->FreeTicket->save(array('ticket_type_id' => $this->id, 'has_form' => $data'FreeTicket']'has_form']));
            } elseif ($data'type'] == 'P') {
                $this->Fee = ClassRegistry::init('Fee');
                $fee = $this->Fee->findById($data'PaidTicket']'fee_id']);
                $total_buyer = $data'PaidTicket']'price'];
                if ($fee'Fee']'type'] == 'pass') {
                    $total_buyer = $data'PaidTicket']'price'] + (($data'PaidTicket']'price'] * $fee'Fee']'value']) + 10);
                }               
                $this->PaidTicket = ClassRegistry::init('PaidTicket');
                $this->PaidTicket->create();
                return $this->PaidTicket->save(array('ticket_type_id' => $this->id, 'fee_id' => $data'PaidTicket']'fee_id'], 'price' => $data'PaidTicket']'price'], 'total_buyer' => $total_buyer));
            }
            return false;
        }
    }
    }