0

i'm working with Agile Toolkit

i got a Model_Product

class Model_Product extends Model_Table {
public $table="product";
function init(){
    parent::init();

    $this->addField('name')->mandatory(true);
    $this->addField('price')->mandatory(true)->type('money');
    $this->addField('user_id')->refModel('Model_User')
        ->defaultValue($this->api->auth->get('id'));    
    //$this->hasOne('User',null,'email'); => send me an error message
}
}

and Model_User

class Model_User extends Model_Table {
public $table="user";

function init(){
    parent::init();

    $this->addField('first_name')->mandatory('Prénom nécesssaire');
    $this->addField('last_name')->mandatory('Nom nécesssaire');
    $this->addField('email')->mandatory('entrez un email valide');
    $this->addField('nationality')->mandatory('nécessaire')->enum(array('FR','EN','US'));
    $this->addField('birthday')->defaultValue(date('Y-m-d'))->type('date');
    $this->addField('is_admin')->type('boolean');       
    $this->hasMany('Product','user_id');
}

I want to list on a User page all the products from one User

$q=$this->api->db->dsql();
$q->table('product')->where('product.user_id',$this->api->auth->model['id']);
$tab->add('GRID')->setModel($q);

Some way, I get it wrong because I get an error no mater how I try to filter my Model.

Adrien
  • 3
  • 2

1 Answers1

0

If you're not using newest ATK4 version from Github then you should grab it and stay up-to-date.


You should do like this:

1) In Model_Product create hasOne reference and not refModel (it's deprecated).

// adding 'user_id' parameter is not needed, it'll be calculated anyway
// but many developers add it anyway to clear thing up a bit.
$this->hasOne('User','user_id')->defaultValue($this->api->auth->get('id'));

2) Model_User is OK. Just some side-notes about it:

  • I don't think you should make birthday = today() by default. It's quite unbelievable that child at his first day in this world will use computer :)
  • is_admin should be mandatory + defaultValue(false) - by default user is not admin.

3) How to list all all products from current user.

// model of current user
$model = $this->add('Model_User')
              ->load($this->api->auth->get('id'));
// add grid
$page->add('Grid')
     // reference Product model with condition already set
     ->setModel($model->ref('Product'));

and that's it.


Maybe even better and safer way is to define new model class for logged in user:

class Model_Myself extends Model_User {
    function init(){
        parent::init();
        $this->addCondition('id', $this->api->auth->get('id'));
        $this->loadAny(); // I'm not sure do we have to explicitly load it here
    }
}

and then create grid like this

// model of products of current user
$prod_model = $this->add('Model_Myself')->ref('Product');
// add grid
$page->add('Grid')->setModel($prod_model);
DarkSide
  • 3,670
  • 1
  • 26
  • 34