Dynamically change CRUD's model

Hi,

I have a CRUD into a Modal that is showed when the submit button of a Form is pressed. I would like to change the model of the crud to add a condition, which is to show only the entries of the DB related to the email asked in the Form.

What I have until now is the Modal showing when the email typed is in the DB but is showing all the entries. I just want the entries related to the email I just typed in the Form.

$modal = \atk4\ui\Modal::addTo($app);
$crud = \atk4\ui\CRUD::addTo($modal);
$model = new Sales($app->db);
$crud->setModel($model);
\atk4\ui\Button::addTo($modal, ['Hide'])->on('click', $modal->hide());

$form = \atk4\ui\Form::addTo($app);
$form->addField('user_email', null,  ['required'=>true, 'type'=>'email']);
$form->onSubmit(function ($form) use ($modal, $model, $app, $crud) {
	$email = $form->model['user_email'];
    if (DBUsers::userExists($email)) {
	    return $modal->show();
    } else {
	    print("This user doesn't exist");
    }
});

Any ideas? Thank you guys!

Hello, you can try adding a condition, just before doing $modal->show(); i.e. $curd->model->addCondition(), but I would suggest to show the modal’s content as a callbas, so that it reloads when it is shown

Thanks for the reply, zak!

I’m rather new to the web development specially in Agile Ui. I have more questions:

  1. How I show the modal as a callback?
  2. How to remove the condition when I call $modal->hide()?

Thanks again!

PS: I tried adding the line right before $modal->show() and it doesn’t work. Am I doing something wrong?

I’m not sure if I’m doing this properly, but this code ended up working for me:

$modal = \atk4\ui\Modal::addTo($app, ['title' => 'User purchases']);

$modal->set(function ($modal) use ($app) {
    $user_email = @$_GET['user_email'];

    $crud = \atk4\ui\CRUD::addTo($modal);

    $salesModel = new Sales($app->db);
    $crud->setModel($salesModel);
    $crud->model->addCondition('user_email', '=', $user_email);
});

$form = \atk4\ui\Form::addTo($app);
$form->addField('user_email', null, ['required'=>true, 'type'=>'email']);
$form->onSubmit(function ($form) use ($modal, $crud, $app) {
    $email = $form->model['user_email'];
    return $modal->show(['user_email' => $email]);
});

Feel free to add any comments or corrections to my approach. It was made using other people’s code and trial and error.

Cheers

This is exactly what I meant. You seem to have figured it out on your own :slight_smile:

1 Like