Submit array from Fluid-Template to Controller with f:form viewhelper - typo3

I am currently writing an Extbase Extension with a backend module. I have assigned an array to the template of my backend module. Now I am trying to submit that array back to my crontroller action "pageGenerator" with inputs of the form in the template.
Here is the code from my controller and template:
Controller:
public function listAction()
{
$array = [
'1' => '',
'2' => '',
'3' => ''
];
$this->view->assign('array', $array);
$this->view->setTemplatePathAndFilename('EXT:bm_test/Resources/Private/Templates/template.html');
}
public function pageGeneratorAction(array $array=null){}
Fluid-Template:
<div align="center">
<f:form method="post" controller="DomainModel" action="pageGenerator"
name="array" object="{array}" >
<input type="text" name="array[1]">
<input type="text" name="array[2]">
<input type="text" name="array[3]">
<f:form.submit value="Submit" />
</f:form>
</div>
The problem is that the array is null no matter what I type into the textfields.When i remove the "=null" from the pageGenerator action i get the following Error:
Too few arguments to function Bmt\BmTest\Controller\DomainModelController::pageGeneratorAction(), 0 passed and exactly 1 expected
So it seems like that the array isn't submitted.
Does anyone know what am I doing wrong here? Thanks in advance for your help.

have you tried to insert the assign variable after setTemplatePathAndFilename ?
Becouse in typo3 if the template haven't the same name of the Action you need first inizialize them and after return the view with assigned variable
example
$this->view->setTemplatePathAndFilename('EXT:bm_test/Resources/Private/Templates/template.html');
$this->view->assign('array', $array);
return $this->view->render();

Related

NgbTypeahead inside the form

I have NgbTypeahead component which uses a list of objects like
export class Example {
name: string;
value: number;
}
as source. It searches by name(value is used as placeholder in another input). I put it inside the form, set the formControlName:
<form [formGroup]="myForm" novalidate (ngSubmit)="save(myForm.value, myForm.valid)">
<input formControlName="name" name="exampleName" type="text" [ngbTypeahead]="search"
[resultFormatter]="formatMatches"
[inputFormatter]="formatMatches"
/>
<!--..some code-->
<br><button type="submit">Submit</button>
</form>
But when I submit it, the selected object of type Example is passed, but if instead I need the value of input, what should I do?
EDITED
Removed ngModel.
The code of formatMatches function:
formatMatches = (value: any) => value.name || '';

How to delete an entity from a template with a list of entities (CRUD)?

Explanation:
I have generated the CRUD of an entity, getting the following default actions:
indexAction(): lists all entities.
showAction($id): finds (by ID) and displays an entity.
deleteAction($id): deletes an entity.
another actions.
So, I have seen I can only delete an entity within the actions that use the param $id (e.g.: showAction($id) ) but I want to delete an entity inside the indexAction template because I save a step to users.
The deleteAction needs a request, an ID and use the POST method.
I was trying to code something like:
<a href="{{ path('entity_delete', { 'id': entity.id }) }}" class="btn">
<img src="{{ asset('bundles/acme/images/delete.png') }}" ... />
</a>
When I execute the action, I get the following error:
No route found for "GET /acme/something/4/delete": Method Not Allowed
(Allow: POST, DELETE)
This response is clear and it's what I expected, so I tried to do something similar but using a form. Something like this:
<form id="formDelete" action="{{ path('entity_delete', { 'id': entity.id }) }}" method="post">
<input type="hidden" name="_method" value="DELETE" />
{{ form_widget(delete_form) }}
<a href="{{ url('entity_delete') }}" class="btn" onclick="document.getElementById('formDelete').submit();">
<img src="{{ asset('bundles/acme/images/delete.png') }}" ... />
</a>
</form>
But the line {{ form_widget(delete_form) }} is a problem because the indexAction() hasn't got any parameter and it needs this code:
$deleteForm = $this->createDeleteForm($id);
return $this->render('AcmeBundle:Demo:index.html.twig', array(
'entities' => $entities,
'delete_form' => $deleteForm->createView(),
));
As you can see, the $id param is mandatory for the method createDeleteForm($id) but I can't get it from indexAction().
Question:
What is the best way to solve this issue?
if you only want to have as much delete buttons as items in your index here's how to easily do it.
In the indexAction, add the following loop and don't forget to pass the parameter to the view.
public function indexAction()
{
$em = $this->getDoctrine()->getManager();
$entities = $em->getRepository('FooBundle:Link')->findAll();
$deleteForms = array();
foreach ($entities as $entity) {
$deleteForms[$entity->getId()] = $this->createDeleteForm($entity->getId())->createView();
}
return array(
'entities' => $entities,
'deleteForms' => $deleteForms,
);
}
Basicaly I just loop over all my entities and create the corresponding delete form using the built-in method generated by the crud, storing each form in an array and passing it to the view.
Then in the view, just add the form already available in the edit.html.twig generated view and edit the form_widget's parameter:
<form action="{{ path('foo_delete', { 'id': entity.id }) }}" method="post">
<input type="hidden" name="_method" value="DELETE" />
{{ form_widget(deleteForms[entity.id]) }}
<button type="submit" class="btn btn-small">
<i class="icon-trash"></i>
{{ 'links.admin.form.delete' | trans({}, 'FooBundle') }}
</button>
</form>

Trigger validation of all fields in Angular Form submit

I'm using this method: http://plnkr.co/edit/A6gvyoXbBd2kfToPmiiA?p=preview to only validate fields on blur. This works fine, but I would also like to validate them (and thus show the errors for those fields if any) when the user clicks the 'submit' button (not a real submit but a data-ng-click call to a function)
Is there some way to trigger validation on all the fields again when clicking that button?
What worked for me was using the $setSubmitted function, which first shows up in the angular docs in version 1.3.20.
In the click event where I wanted to trigger the validation, I did the following:
vm.triggerSubmit = function() {
vm.homeForm.$setSubmitted();
...
}
That was all it took for me. According to the docs it "Sets the form to its submitted state." It's mentioned here.
I know, it's a tad bit too late to answer, but all you need to do is, force all forms dirty. Take a look at the following snippet:
angular.forEach($scope.myForm.$error.required, function(field) {
field.$setDirty();
});
and then you can check if your form is valid using:
if($scope.myForm.$valid) {
//Do something
}
and finally, I guess, you would want to change your route if everything looks good:
$location.path('/somePath');
Edit: form won't register itself on the scope until submit event is trigger. Just use ng-submit directive to call a function, and wrap the above in that function, and it should work.
In case someone comes back to this later... None of the above worked for me. So I dug down into the guts of angular form validation and found the function they call to execute validators on a given field. This property is conveniently called $validate.
If you have a named form myForm, you can programmatically call myForm.my_field.$validate() to execute field validation. For example:
<div ng-form name="myForm">
<input required name="my_field" type="text" ng-blur="myForm.my_field.$validate()">
</div>
Note that calling $validate has implications for your model. From the angular docs for ngModelCtrl.$validate:
Runs each of the registered validators (first synchronous validators and then asynchronous validators). If the validity changes to invalid, the model will be set to undefined, unless ngModelOptions.allowInvalid is true. If the validity changes to valid, it will set the model to the last available valid $modelValue, i.e. either the last parsed value or the last value set from the scope.
So if you're planning on doing something with the invalid model value (like popping a message telling them so), then you need to make sure allowInvalid is set to true for your model.
You can use Angular-Validator to do what you want. It's stupid simple to use.
It will:
Only validate the fields on $dirty or on submit
Prevent the form from being submitted if it is invalid
Show custom error message after the field is $dirty or the form is submitted
See the demo
Example
<form angular-validator
angular-validator-submit="myFunction(myBeautifulForm)"
name="myBeautifulForm">
<!-- form fields here -->
<button type="submit">Submit</button>
</form>
If the field does not pass the validator then the user will not be able to submit the form.
Check out angular-validator use cases and examples for more information.
Disclaimer: I am the author of Angular-Validator
Well, the angular way would be to let it handle validation, - since it does at every model change - and only show the result to the user, when you want.
In this case you decide when to show the errors, you just have to set a flag:
http://plnkr.co/edit/0NNCpQKhbLTYMZaxMQ9l?p=preview
As far as I know there is a issue filed to angular to let us have more advanced form control. Since it is not solved i would use this instead of reinventing all the existing validation methods.
edit: But if you insist on your way, here is your modified fiddle with validation before submit. http://plnkr.co/edit/Xfr7X6JXPhY9lFL3hnOw?p=preview
The controller broadcast an event when the button is clicked, and the directive does the validation magic.
One approach is to force all attributes to be dirty. You can do that in each controller, but it gets very messy. It would be better to have a general solution.
The easiest way I could think of was to use a directive
it will handle the form submit attribute
it iterates through all form fields and marks pristine fields dirty
it checks if the form is valid before calling the submit function
Here is the directive
myModule.directive('submit', function() {
return {
restrict: 'A',
link: function(scope, formElement, attrs) {
var form;
form = scope[attrs.name];
return formElement.bind('submit', function() {
angular.forEach(form, function(field, name) {
if (typeof name === 'string' && !name.match('^[\$]')) {
if (field.$pristine) {
return field.$setViewValue(field.$value);
}
}
});
if (form.$valid) {
return scope.$apply(attrs.submit);
}
});
}
};
});
And update your form html, for example:
<form ng-submit='justDoIt()'>
becomes:
<form name='myForm' novalidate submit='justDoIt()'>
See a full example here: http://plunker.co/edit/QVbisEK2WEbORTAWL7Gu?p=preview
Here is my global function for showing the form error messages.
function show_validation_erros(form_error_object) {
angular.forEach(form_error_object, function (objArrayFields, errorName) {
angular.forEach(objArrayFields, function (objArrayField, key) {
objArrayField.$setDirty();
});
});
};
And in my any controllers,
if ($scope.form_add_sale.$invalid) {
$scope.global.show_validation_erros($scope.form_add_sale.$error);
}
Based on Thilak's answer I was able to come up with this solution...
Since my form fields only show validation messages if a field is invalid, and has been touched by the user I was able to use this code triggered by a button to show my invalid fields:
// Show/trigger any validation errors for this step
angular.forEach(vm.rfiForm.stepTwo.$error, function(error) {
angular.forEach(error, function(field) {
field.$setTouched();
});
});
// Prevent user from going to next step if current step is invalid
if (!vm.rfiForm.stepTwo.$valid) {
isValid = false;
}
<!-- form field -->
<div class="form-group" ng-class="{ 'has-error': rfi.rfiForm.stepTwo.Parent_Suffix__c.$touched && rfi.rfiForm.stepTwo.Parent_Suffix__c.$invalid }">
<!-- field label -->
<label class="control-label">Suffix</label>
<!-- end field label -->
<!-- field input -->
<select name="Parent_Suffix__c" class="form-control"
ng-options="item.value as item.label for item in rfi.contact.Parent_Suffixes"
ng-model="rfi.contact.Parent_Suffix__c" />
<!-- end field input -->
<!-- field help -->
<span class="help-block" ng-messages="rfi.rfiForm.stepTwo.Parent_Suffix__c.$error" ng-show="rfi.rfiForm.stepTwo.Parent_Suffix__c.$touched">
<span ng-message="required">this field is required</span>
</span>
<!-- end field help -->
</div>
<!-- end form field -->
Note: I know this is a hack, but it was useful for Angular 1.2 and earlier that didn't provide a simple mechanism.
The validation kicks in on the change event, so some things like changing the values programmatically won't trigger it. But triggering the change event will trigger the validation. For example, with jQuery:
$('#formField1, #formField2').trigger('change');
I like the this approach in handling validation on button click.
There is no need to invoke anything from controller,
it's all handled with a directive.
on github
You can try this:
// The controller
$scope.submitForm = function(form){
//Force the field validation
angular.forEach(form, function(obj){
if(angular.isObject(obj) && angular.isDefined(obj.$setDirty))
{
obj.$setDirty();
}
})
if (form.$valid){
$scope.myResource.$save(function(data){
//....
});
}
}
<!-- FORM -->
<form name="myForm" role="form" novalidate="novalidate">
<!-- FORM GROUP to field 1 -->
<div class="form-group" ng-class="{ 'has-error' : myForm.field1.$invalid && myForm.field1.$dirty }">
<label for="field1">My field 1</label>
<span class="nullable">
<select name="field1" ng-model="myresource.field1" ng-options="list.id as list.name for list in listofall"
class="form-control input-sm" required>
<option value="">Select One</option>
</select>
</span>
<div ng-if="myForm.field1.$dirty" ng-messages="myForm.field1.$error" ng-messages-include="mymessages"></div>
</div>
<!-- FORM GROUP to field 2 -->
<div class="form-group" ng-class="{ 'has-error' : myForm.field2.$invalid && myForm.field2.$dirty }">
<label class="control-label labelsmall" for="field2">field2</label>
<input name="field2" min="1" placeholder="" ng-model="myresource.field2" type="number"
class="form-control input-sm" required>
<div ng-if="myForm.field2.$dirty" ng-messages="myForm.field2.$error" ng-messages-include="mymessages"></div>
</div>
</form>
<!-- ... -->
<button type="submit" ng-click="submitForm(myForm)">Send</button>
I done something following to make it work.
<form name="form" name="plantRegistrationForm">
<div ng-class="{ 'has-error': (form.$submitted || form.headerName.$touched) && form.headerName.$invalid }">
<div class="col-md-3">
<div class="label-color">HEADER NAME
<span class="red"><strong>*</strong></span></div>
</div>
<div class="col-md-9">
<input type="text" name="headerName" id="headerName"
ng-model="header.headerName"
maxlength="100"
class="form-control" required>
<div ng-show="form.$submitted || form.headerName.$touched">
<span ng-show="form.headerName.$invalid"
class="label-color validation-message">Header Name is required</span>
</div>
</div>
</div>
<button ng-click="addHeader(form, header)"
type="button"
class="btn btn-default pull-right">Add Header
</button>
</form>
In your controller you can do;
addHeader(form, header){
let self = this;
form.$submitted = true;
...
}
You need some css as well;
.label-color {
color: $gray-color;
}
.has-error {
.label-color {
color: rgb(221, 25, 29);
}
.select2-choice.ui-select-match.select2-default {
border-color: #e84e40;
}
}
.validation-message {
font-size: 0.875em;
}
.max-width {
width: 100%;
min-width: 100%;
}
To validate all fields of my form when I want, I do a validation on each field of $$controls like this :
angular.forEach($scope.myform.$$controls, function (field) {
field.$validate();
});

Dynamically adding form elements with jQuery and Zend_Form

I have a form in which people shall be able to add the same portion of elements with a plus-button, so that something like this is produced:
<div id="person-1" class="person">
<input type="text" name="name-1" id="name-1" />
<input type="text" name="age-1" id="age-1" />
</div>
<!-- as of here, it's JS created -->
<div id="person-2" class="person">
<input type="text" name="name-2" id="name-2" />
<input type="text" name="age-2" id="age-2" />
</div>
<div id="person-3" class="person">
<input type="text" name="name-3" id="name-3" />
<input type="text" name="age-3" id="age-3" />
</div>
I already managed to write jquery-code that allows me to add the same elements once again with a new id (name-1, age-1, name-2, age-2, name-3, age-3, …).
Of course, Zend_Form does not know about name-2 and name-3, so it just drops them when the form contains an error and is displayed again. Neither can I access the value of name-2 with $form->getValue('name-2'). I have to go over raw $this->getRequest()->getPost().
Is there a better method I can use to combine Zend_Form and javascript-based added form elements (of same type like an hardcoded element).
Caveat: In the real problem, it’s select and not input. Found out this could make a difference (with ->setIsArray(true)), but using select would blow up the example code.
What you could do is create a subform container inside your main form and add an X amount of subforms to that container.
For example:
class My_Form extends Zend_Form
{
private $_numPersons = 1;
public function setNumPersons($numPersons)
{
$this->_numPersons = (int) $numPersons;
}
public function init()
{
$container = new Zend_Form_SubForm();
$this->addSubForm($container, 'persons');
for($index = 0; $index < $this->_numPersons; $index++) {
$personForm = new My_PersonForm();
$container->addSubForm($personForm, $index+1);
}
}
}
When rendered, the input fields will have names like persons[1][name]. Note the $index+1, Zend_Form does not allow a form to be named '0'.
Ofcourse, you should only use this method if the amount of person subforms is limited.
Another strategy would be to override the isValid method and use a single My_PersonForm form to validate all the person data.
Sidenote; the above code will only work when you define the numPersons as part of the options set, when creating the form instance. E.g.;
$form = new My_Form(array('numPersons' => 10));

Can I use my normal (html) form in Zend Framework?

Can I use my normal (html) form in Zend Framework ? How can I do that & How can I call action in IndexController file?
of course you can ... just use
<form action="/index/action" methode="POST">
to access post arguments use
$this->getRequest()->getParam('argument')
thats no problem, put your form code inside the view script for the associated action. Maybe:
formAction()
{
// check if post request
if ($this->getRequest()->isPost()) {
// read global $_POST array
$data = $this->getRequest()->getPost();
}
}
the associated view ist than form.phtml
Yes, definitely.. You just have to remove the isValid call in your controller since it won't be performing any validation and also remove the post request check if it will not contain any form. It's like creating a common view with simple links in it.
Yes, I have a module called 'contact', and an action addcontactAction() in the ContactController.php.
So I can use :
/view/scripts/contacts/addcontact.phtml
<form action="" method="post" name="frm_addcontact" />
<input name="cn_fname" type="text" class="textbox" id="cn_fname"/>
<input type="submit" class="button" id="save" value="Save" />
</form>
when this form is submitted, it calls addcontactAction() in the controller.
$cn_fname = $_REQUEST['cn_fname'];
Just to know this is not a good practice to implement, but to solve such problem do the following:
in the view file when you define the form
<form action = "<?php echo $this->url(array('action'=>'ACTIONAME')); ?>" ...>
................
</form>
in the corresponding action name
if($this->_request->isPost()){
foreach ($_POST as $var => $value) {
echo "$var = $value<br>";
}