We have moved our forum to GitHub Discussions. For questions about Phalcon v3/v4/v5 you can visit here and for Phalcon v6 here.

Set form field default value to a query result

I'm trying to figure out how to set a default value to a qeury result with setDefault() for a Date field in a form object. Because I want to set the date to the latest user bookdate. Do I need to add a query to the model or can it be done inside the form object?

    $bookdate = new Date(
            "book_date",
            [
                "class" => "form-control",
                //"value" => date('Y-m-d')
            ]
        );
        $bookdate->setLabel("Date");
        $bookdate->setDefault('2020-01-01'); /* here */
        $this->add($bookdate);

        // the query would be like this with user_id being variable
        // SELECT MAX(book_date) FROM urenboeker.time_registration WHERE user_id = 1;

Well answred. You can check out my site WEBDISK

You should take a look at Phalcon\Forms\Form if you extend this class you can set values passing the model objet as data to set
https://docs.phalcon.io/4.0/fr-fr/forms#initialization



13.8k
edited Jul '20

Thanks a lot for your reply! It made me search again and I found multiple solutions.

  1. Add function to create a query to the model
use \Phalcon\Mvc\Model\Resultset\Simple as Resultset;

public static function findByRawSql($conditions, $params = null)
{
        // Raw SQL statement
        $sql = 'SELECT MAX(book_date) AS last_booked_date FROM time_registration WHERE '.$conditions;

        // Base model
        $timeRegistration = new TimeRegistration();

        // Execute the query
        $result = new Resultset(
            null,
            $timeRegistration,
            $timeRegistration->getReadConnection()->query($sql, $params)
        );

        // format result as array
        return $result->toArray();
}

2 . Pass variables to the form via the controller

// Controller
$this->view->setVar('form', new TimeRegistrationForm(null, ['edit' => false, 'user_id' => $this->session->get('auth-identity')['id']]));
  1. Get the result in the form OR just pass the result in the controller via above step (2)
// Form
public function initialize($entity = null, $options = [])
{
        $userLastBookDate = TimeRegistration::findByRawSql(
            'user_id = ?',
            [
                $options['user_id']
            ]
        );

}