Replies: 2 comments 2 replies
-
What is getting |
Beta Was this translation helpful? Give feedback.
1 reply
-
If it really is the case that the I've never used this functionality, but what if you moved your field setup out of class MyForm extends Form{
public function initialize(?Model $model, array $options = [])
{
$this->setMethod('post');
}
public function initializeFields(['user_id'=>DEFAULT_USER_ID])
{
$this->add((new Select('user_id', [DEFAULT_USER_ID]))
->setLabel('Assigned User')
->setAttribute('data-width', '100%')
);
}
} $model = new Members();
$record = $model->findFirstById($id);
$form = new MemberForm($record);
$form->initializeFields(['user_id',$this->request->getPost('user_id')]);// This'll just be NULL if nothing POSTed
if($this->request->isPost()) {
$form->bind($this->request->getPost(), $record);
if (!$form->isValid()) {
throw new \Exception('Invalid data');
}
$record->update();
}
$this->view->form = $form; |
Beta Was this translation helpful? Give feedback.
1 reply
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
-
I use form classes extensively throughout my Phalcon 4 projects.
Recently, I have been working on using Select2 JS with dynamic population of options (via an API endpoint). The problem I have is that when I bind the form data to the model, the new value of the select element does not get saved.
My thought is that because my form element has an empty array of select options (
$users
below), when the form gets validated and bound to my model instance, the new dynamic value (from my API endpoint) gets ignored because it was not one of the original options defined for my Select element in the form class. The value in the model record after validation remains unchanged, appearing to revert to the original value.My form:
Here is my volt view:
When the form is submitted, my code to bind the POST data to my model looks pretty much like this:
Does anyone know if the value of a
Select
element has to be defined in the form class, or whether it can be dynamically set and saved as above?As a quick test, I made
user_id
aHidden
element instead, and manually added HTML code for my Select2 dropdown (<select name="user_id" id="user_id2"></select>
) in my view afteruser_id
got rendered, and the dynamic value does get saved correctly.Beta Was this translation helpful? Give feedback.
All reactions