I am sure I am going about this the wrong way, but I need to unset an array key from one of my choices in a sfWidgetFormChoice. The only way to get that variable to the Form is from the action. Here's what I have:
Action:
$id = $request->getParameter('id');
$deleteForm = new UserDeleteForm();
$choices = array();
$choices = $deleteForm->getWidgetSchema('user')->getAttribute('choices');
unset($choices[$id]); //I obviously don't want the user to be able to transfer to the user being deleted
$this->deleteForm = $deleteForm;
Form:
$users = Doctrine_Core::getTable('sfGuardUser')->getAllCorpUsers()->execute();
$names = array();
foreach($users as $userValue){
$names[$userValue->getId()] = $userValue->getProfile()->getFullName();
};
// unset($names[$id]); //this works, but I can't figure out how to get $id here.
$this->widgetSchema['user'] = new sfWidgetFormChoice(array(
'choices' => $names
));
$this->validatorSchema['user'] = new sfValidatorChoice(array(
'required' => true,
'choices' => $names
));
Understanding forms and actions:
Usually we will setup a form with fields, print it in a html page and fill the form with data. Pressing the submit form button will send all the data to a method defined in your form action html attribute.
The method will receive and get a $request , with a lot of parameters and also the form with the data. Those values will be processed in the action.
Lets look how it exactly works in symfony:
Define and Setup a symfony form, like the one you have shown above.
Print the form and in the action parameter point to the submit method
which will receive the request:
<form action="currentModuleName/update"
Symfony will automatically send the request to the action.class.php
of your module, and will look for and send the data to the function
executeUpdate
public function executeUpdate(sfWebRequest $request){ //...
$this->form = new TestForm($doctrine_record_found);
$this->processForm($request, $this->form); }
After some checks, symfony will process the form and set a result
template.
processForm(sfWebRequest $request, sfForm $form)
{ ... } $this->setTemplate('edit');
In the processForm of your module action.class.php, you should process all the received values (request) also with the form:
protected function processForm(sfWebRequest $request, sfForm $form)
{
$form->bind($request->getParameter($form->getName()), $request->getFiles($form->getName()));
if ($form->isValid())
{
$formValues = $this->form->getValues();
$Id = $formValues['yourWidgetName'];
}
}
You may check the following link for an example like yours, about how to process a sfWidgetFormChoice.
And now answering to the real question, in order to select the deleted users, add the following code in your action:
//process the form, bind and validate it, then get the values.
$formValues = form->getValues();
$choicesId = $formValues['choices'];
Pass variable from action to the form:
Excuse me if I have not understand your question at all but in case you need to pass some parameters from your action to the form, send the initialization variables in an array to the form constructor:
Pass a variable to a Symfony Form
In your case, get the list of users, delete the user you dont want and send the non deleted users to the form constructor.
You will need to redeclare/overwrite your form again in the configure() function so that you could change the initialization of the form. Copy and paste the same code into the configure() function and comment the line: //parent::setup();
class TbTestForm extends BaseTbTestForm
{
public function configure()
{
//.. copy here the code from BaseTbTestForm
//parent::setup();
$vusers = $this->getOption('array_nondeleted_users');
//now set the widget values with the updated user array.
}
}
Related
I am currently trying to add a Clone action to my EmployeeCrudController.
The action should redirect to the Action::NEW view and have some prefilled values.
However I can't figure out how to prefill this form.
Here is where how I define my action within the EmployeeCrudController:
public function configureActions(Actions $actions): Actions
{
$cloneAction = Action::new('Clone', '')
->setIcon('fas fa-clone')
->linkToCrudAction('cloneAction');
return $actions->add(Crud::PAGE_INDEX, $cloneAction);
}
And this is how my cloneAction looks like, which currently redirects to the Action::NEW as expected but without prefilled values:
public function cloneAction(AdminContext $context): RedirectResponse
{
$id = $context->getRequest()->query->get('entityId');
$entity = $this->getDoctrine()->getRepository(Employee::class)->find($id);
$clone = new Employee();
$entity->copyProperties($clone);
$clone->setFirstname('');
$clone->setLastname('');
$clone->setEmail('');
$routeBuilder = $this->get(CrudUrlGenerator::class);
$url = $routeBuilder->build([
'Employee_lastname' => 'test',
'Employee[teamMembershipts][]' => $clone->getTeamMemberships(),
])
->setController(EmployeeCrudController::class)
->setAction(Action::NEW)
->generateUrl()
;
return $this->redirect($url);
}
You can set the value of a field in easyAdmin using the option data.
$builder->add('Employee_lastname', null, ['data' => $clone->getTeamMemberships()]);
If your field has multiple options, you can use the choices and choices_value.
I've Yii2 form containing form fields depending on action of page. Ex. Few fields appears when then action is create and few appears when action is update. I want to add required validation based on this scenario.
Ex.
<?= $form->field($model, 'unique_identifier')->textInput(['maxlength' => 45]) ?>
I am showing this field only when action => 'update'.
Now I want to add required validation for this and I tried this:
[['unique_identifier'], 'required', 'on' => 'update'],
But above validation not working. If I remove on=>update then its validating on both create and update scenario.
Any help would be appreciated.
ActiveRecord does not set scenario automaticaly when you update or create items. You must override update() method in your model and set scenario that you need. E.g. in your case
public function update($runValidation = true, $attributeNames = null)
{
$this->scenario = 'update';
return parent::update($runValidation, $attributeNames);
}
Also you can set scenario in your actionUpdate
public function actionUpdate($id)
{
$model = $this->findModel($id);
$model->scenario = 'update';
//load data from request, save model etc.
}
I need a help..
I have a unique form with multiples fieldsets, and i need separate some fieldsets in tabs..
So, i tried in the view (form is my variable with the whole form):
$form = $this->form;
$customFieldset = $form->get('customFieldset');
$form->remove('customFieldset');
It works, my fieldset form is in $customFieldset.. but, i can't render this!
When a try:
echo $this->form($customFieldset);
//OR
echo $this->formInput($customFieldset);
//OR
$this->formCollection($customFieldset);
None of that works..
I'm doing right? How i can do it?
Thank very much.
To achieve the result you want (using the form across several tabs, it is better to construct the form differently, based on the tab's number. For example, your form constructor method would look like below:
<?php
namespace Application\Form;
use Zend\Form\Form;
// A form model
class YourForm extends Form
{
// Constructor.
public function __construct($tabNum)
{
// Define form name
parent::__construct('contact-form');
// Set POST method for this form
$this->setAttribute('method', 'post');
// Create the form fields here ...
if($tabNum==1) {
// Add fields for the first tab
} else if($tabNum==2) {
// Add fields for the second tab
}
}
}
In the example above, you pass the $tabNum parameter to form model's constructor, and the constructor method creates a different set of fields based on its value.
In your controller's action, you use the form model as below:
<?php
namespace Application\Controller;
use Application\Form\ContactForm;
// ...
class IndexController extends AbstractActionController {
// This action displays the form
public function someAction() {
// Get tab number from POST
$tabNum = $this->params()->fromPost('tab_num', 1);
// Create the form
$form = new YourForm($tabNum);
// Check if user has submitted the form
if($this->getRequest()->isPost()) {
// Fill in the form with POST data
$data = $this->params()->fromPost();
$form->setData($data);
// Validate form
if($form->isValid()) {
// Get filtered and validated data
$data = $form->getData();
// ... Do something with the validated data ...
// If all tabs were shown, redirect the user to Thank You page
if($tabNum==2) {
// Redirect to "Thank You" page
return $this->redirect()->toRoute('application/default',
array('controller'=>'index', 'action'=>'thankYou'));
}
}
}
// Pass form variable to view
return new ViewModel(array(
'form' => $form,
'tabNum' => $tabNum
));
}
}
In your view template, you use the following code:
<form action="">
<hidden name="tab_num" value="<?php echo $this->tabNum++; ?>" />
<!-- add other form fields here -->
</form>
Can we edit the possible options for a choice field after the field has been created?
Let's say, the possible options for the choice field(a drop down box for categories) comes from my database. My controller would look like this:
public function addAction(Request $request){
//get the form
$categories = $this->service->getDataFromDatabase();
$form = $this->formFactory->create(new CategoryType(), $categories);
$form->handleRequest($request);
if ($form->isValid()) {
// perform some action, such as saving the task to the database, redirect
}
return $this->templating->renderResponse('TestAdminBundle:Categories:add.html.twig',
array('form' => $form->createView())
);
}
This works. $categories is populated as a dropdown box so the user can select a category. What I don't like about this code is that it has to hit the "getDataFromDatabase" service again when the user hits submit and the form validates the input. This feels unnecessary to me; ideally it should only need to hit the service when validation fails and the form has to be regenerated for the user. I'm hoping to make the controller look something like this:
public function addAction(Request $request){
//get the form
$form = $this->formFactory->create(new CategoryType());
$form->handleRequest($request);
if ($form->isValid()) {
// perform some action, such as saving the task to the database, redirect
}
$categories = $this->service->getDataFromDatabase();
$form->setData($categories); //this tells the choice field to use $categories to populate the options
return $this->templating->renderResponse('TestAdminBundle:Categories:add.html.twig',
array('form' => $form->createView())
);
}
You need to use EventSubscriber, check the docs, here: http://symfony.com/doc/current/cookbook/form/dynamic_form_modification.html#cookbook-form-events-underlying-data
I have a form with some text fields and I have a preview button that needs to submit the form to the same controller. And then in the controller, I need to extract the values and populate a form with these values for the template to see. What is the best way to achieve this? I'm a newbe so please be clear.
Sample controller:
public function myControllerName(sfWebRequest $request)
{
$this->form = new myFormClass();
}
Use <?php echo $form->renderFormTag( url_for('#yourRoutingName'), array('method' => 'POST') ); ?> in your template and change #yourRoutingName to the one pointing to your controller.
Now change your controller to be something like this:
public function myControllerName(sfWebRequest $request)
{
$this->form = new myFormClass();
if ($request->isMethod(sfRequest::POST)
{
$this->form->bind( $request->getParameter( $this->form->getName() ) );
// Check if the form is valid.
if ($this->form->isValid())
{
$this->form->save();
// More logic here.
}
}
}
The $this->form->bind( $request->getParameter( $this->form->getName() ) ); part binds posted data to your form where $this->form->isValid() returns a boolean whether the form is valid or not.
Have you tried this ?
$this->redirect($request->getReferer()); //action
if not, then please try and check if its work for you.
Thanks.