XF 2.1 'unique' => true for multiply primary key

CMTV

Well-known member
My entity has a complex primary key that consists of two columns: criterion_id and param_id.

Right now, when trying to create an entity which duplicates primary key, it shows an error:

189041

For single column primary keys we can simply use 'unique' => true.

What is the preferred way to show a fancy error message?
 
Well, this might help:

If you have a unique constraint that spans multiple columns that are not your primary key then just check for uniqueness in _preSave().
That would probably work:
Code:
    protected function _preSave()
    {
        $exists = $this->finder('EWR\Rio:Spelling')
            ->where([
                'service_id' => $this->service_id,
                'spelling' => $this->spelling,
            ])->fetchOne();
      
        if ($exists && $exists != $this)
        {
            $this->error(\XF::phrase('EWRrio_spelling_already_exists'));
        }
    }

So, the right way is to manually trying to find duplicate in _preSave()? Even in case that these columns are primary key?
 
How did you set up your primary key? I've never used a composite key on entities that are created manually I think, but the mvc entity looks like it has code to handle the uniqueness of composite keys.
 
If you have a multi-column primary/unique key, you need to check uniqueness in pre-save. The unique constraint is column specific so it won't work.
 
Here is the solution:
PHP:
protected function _preSave()
{
    $duplicate = $this->finder(C::ADDON_PREFIX('Param'))
        ->whereId([$this->criterion_id, $this->param_id])->fetchOne();

    if ($duplicate && $this->isInsert())
    {
        $this->error(\XF::phrase(C::PHRASE_PREFIX('param_id_must_be_unique_for_criterion')));
    }
}
 
Last edited:
Top Bottom