cakephp 3: change class input error - forms

I build my form template according the documentation. It seemed everything was fine until I get fields errors. Now I have two problems:
How can I change the class name of the forms fields when they get error?
Solution:
$this->loadHelper('Form', [
'templates' => 'your_template_file',
'errorClass' => 'your-class',
]);
How can I set escape => false in the error-message from cakephp, when the field get error? Because I have icon within that div, such as
<div class="error-message"><i class="fa fa-times"></i> My error</div>
Well, I got part of th solution. To escape HTML I could put $this->Form->error('field', null, ['escape' => false]); in all fields, but it´s a hard manually task. I´d like to keep escape with default of all fields errors. I could edit the FormHelper.php class. However, I think that is not good idea.
My form template is:
'formStart' => '<form {{attrs}} class="form-horizontal" novalidate>',
'inputContainer' => '{{content}}',
'input' => '<input type="{{type}}" name="{{name}}" {{attrs}} class="form-control"/>',
'checkbox' => '<input type="checkbox" value="{{value}}" name="{{name}}" {{attrs}}/>',
'textareaContainerError' => '{{content}}',
'textarea' => '<textarea name="{{name}}" {{attrs}} class="form-control"></textarea>',
'select' => '<select name="{{name}}" {{attrs}} class="form-control">{{content}}</select>',
'button' => '<button {{attrs}} class="btn btn-primary">{{text}}</button>',
'nestingLabel' => '{{input}}',
'formGroup' => '{{input}}',

to the second part of the question: you can extend FormHelper like in code below, so that escape will be set to false by default
// extended FormHelper, this goes in src/View/Helper
namespace App\View\Helper;
use Cake\View\Helper;
class MyFormHelper extends Helper\FormHelper
{
public function error($field, $text = null, array $options = [])
{
if (!isset($options['escape'])) {
$options['escape'] = false;
}
return parent::error($field, $text, $options);
}
}
next create alias for this helper in AppController.php
public $helpers = [
'Form' => ['className' => 'MyForm']
];
this also allows you to add more customization of your own and at any time, you can go back to default implementation of FormHelper, just remove that alias from AppController.php.

For those who wants an 'easy solution' to escape error message on some fields, you cant simply set escape options to false :
<?= $this->Form->input('email', [
"label" => "Email",
"error" => [
"escape" => false
]
]) ?>

Related

Laravel form validation wrong when using checkbox to hide/show fields causes

I have a form in Laravel 6 that uses a checkbox to hide/show additional fields. So the fields are hidden, but when the user checks the box ('attorney') and the fields appear, they are required. Otherwise, when they are hidden (checkbox unchecked) they are not required.
The following are the validation rules for the form:
public function rules()
{
return [
'name' => 'required',
'email' => 'required|email|unique:users,email',
'password' => 'required',
'role' => 'required',
'role.*' => 'exists:roles,id',
'attorney' => 'nullable',
'bar_number' => 'nullable|required_if:attorney,1',
'law_firm_email' => 'nullable|required_if:attorney,1',
'law_firm_address' => 'nullable|required_if:attorney,1',
'law_firm_name' => 'nullable|required_if:attorney,1',
];
}
This hide/unhide works fine for users who check the box, and the form works for those that submit that extra info, but for those that don't check the box (those extra fields remain hidden) the form fails with the error "The bar number must be a string" (bar number is first field in list). The hidden fields are still being validated even though the checkbox is unchecked (the condition required_if should be false). I have tried 'checked' and 'on' for the checkbox value, same result.
This is the checkbox in the view:
<div class="col-md-6"></br>
<input id="attorney" type="checkbox" name="attorney" value="{{ old('attorney') }}"> Check if registering a law firm
#if ($errors->has('attorney'))
<span class="help-block">
<strong>{{ $errors->first('attorney') }}</strong>
</span>
#endif
</div>
This is the JavaScript that hides/shoes the DIV with the additional fields:
<script>
$(document).ready(function() {
$('input[name="attorney"]').change(function() {
if(this.checked) {
$('#bar_number_div').fadeIn('fast');
} else {
$('#bar_number_div').fadeOut('fast');
}
});
});
</script>
The JavaScript works fine as expected. The validation config is my issue.
There are no errors in the console.
I thought the required_if condition in the validation rules should work as expected, i.e., when the checkbox "attorney" is unchecked the required validation rule is not applied.
You can try with on in required_if
public function rules() {
return [
'name' => 'required',
'email' => 'required|email|unique:users,email',
'password' => 'required',
'role' => 'required',
'role.*' => 'exists:roles,id',
'attorney' => 'nullable',
'bar_number' => 'nullable|required_if:attorney,on',
'bar_number' => 'nullable|required_if:attorney,on',
'law_firm_email' => 'nullable|required_if:attorney,on',
'law_firm_address' => 'nullable|required_if:attorney,on',
'law_firm_name' => 'nullable|required_if:attorney,on',
];
}
Remove value from input checkbox
<input id="attorney" type="checkbox" name="attorney">

How to display the componentProperties options by the selected option in the dropdown?

I'm sure this is very simple but it's proving just a bit beyond me at the moment.
I have made a plugin that I would like to use for displaying galleries which is working fine. However, trying to add the options of the galleries that I have created in my component is proving to be difficult.
When I add the component to a page, I have now got the option to choose all the galleries that I created but displaying the gallery based upon which one I selected is what I have been unsuccessful in doing.
Any help would be greatly appreciated!
I'm sure this is very simple but it's proving just a bit beyond me at the moment.
I have made a plugin that I would like to use for displaying galleries which is working fine. However, trying to add the options of the galleries that I have created in my component is proving to be difficult.
When I add the component to a page, I have now got the option to choose all the galleries that I created but displaying the gallery based upon which one I selected is what I have been unsuccessful in doing.
Any help would be greatly appreciated!
Components/Gallery.php:
use Cms\Classes\ComponentBase;
use MartinSmith\Gallerys\Models\Gallery as GalleryModel;
class gallerys extends ComponentBase
{
public $gallery;
public function componentDetails(){
return [
'name' => 'Frontend Gallery',
'description' => 'A gallery for you webpage'
];
}
public function defineProperties() {
$lists = $this->getLists();
return [
'galleryName' => [
'title' => 'Gallery',
'type' => 'dropdown',
'placeholder' => 'Select Gallery',
'options' => $lists
]
];
}
public function getLists() {
$agreements = GalleryModel::all()->pluck('name', 'id');
return $agreements->toArray();
}
public function getList() {
$agreement = GalleryModel::where('id', $this->property('galleryName'))->get();
return $agreement->first();
}
}
Components/gallery/default.htm:
{% set gallerys = __SELF__.gallery %}
{% for gallery in gallerys %}
<div class="container-fluid px-0">
<div class="gallery">
<div class="row">
{% for image in gallery.fullImage %}
<div class="col-md-4 px-0 home-galleryImg">
<a href="{{ image.path }}">
<div class="gallery-imgOverlay">
<p>{{ image.title }}</p>
<h5>{{ image.description }}</h5>
</div>
<img class="img-fluid" src="{{ image.thumb(650,auto) }}" alt="{{ thumbnail.description }}">
</a>
</div>
{% endfor %}
</div>
</div>
</div>
{% endfor %}
See screenshot
I solved this for myself by creating a function that returns the "name" and indexed by the 'id' using the laravel pluck method. pluck('name', 'id') The first argument selects the column to use as the value and the second argument selects the column to use as a key. Note* the toArray() method I don't think the options field can take collections.
public function getLists() {
$agreements = Agreements::all()->pluck('agrnum', 'id');
return $agreements->toArray();
}
//returns
array:3 [▼
2 => "DLE-2"
4 => "DLE-1"
5 => "DLE-3"
]
Now in my properties area I call the function $list = $this->getList();
public function defineProperties() {
$lists = $this->getLists();
return [
'getList' => [
'title' => 'List',
'type' => 'dropdown',
'placeholder' => 'Select List',
'options' => $lists
]
];
}
After that you can proceed to do a Lists::where('id', $this->property('getList')); or something of that sort in a function to show the selected list or in your case gallery.
My results:
The CMS Page Backend from component
public function defineProperties() {
$lists = $this->getLists();
return [
'getList' => [
'title' => 'List',
'type' => 'dropdown',
'placeholder' => 'Select List',
'options' => $lists
]
];
}
public function getLists() {
$agreements = Agreements::all()->pluck('agrnum', 'id');
return $agreements->toArray();
}
public function getList() {
$agreement = Agreements::where('id', $this->property('getList'))->get();
return $agreement->first();
}
The Webpage from default.htm in the component template folder
{{ d(__SELF__.getList) }}
Also if I do {{ d(__SELF__.property('getList')) }} it shows me the value is "5".

Undefined variable in Laravel view

I have tried to get a solution for this for hours and I really do not understand why it's not working.
routes.php
Route::get("/user/Session::get('theuser')/charname", array(
'as' => 'profile-character',
'uses' => 'ProfileController#dropDownList'
));
ProfileController.php
public function dropDownList() {
$list = Character::lists('char_name', 'char_dynasty');
return View::make('layout.profile')->with('character_options',$list);
}
profile.blade.php
<div class="selected_char">
<form action="{{ URL::route('profile-character') }}" method="get">
{{ Form::select('character', $character_options , Input::old('character')) }}
</form>
</div>
This code throws me the error that the $character_options is undefined. I have read dozens of examples doing the same thing like me and working for them. Maybe this is Laravel 3?
This is something that should not work on Laravel:
Route::get("/user/Session::get('theuser')/charname", array(
'as' => 'profile-character',
'uses' => 'ProfileController#dropDownList'
));
You cannot have a call like Session::get() in your route, not as far as I know at least. Your route will work because it's a string valid for route, but that Session::get() will never really be used in the process.
If you literally hit the url:
http://localhost/user/Session::get('theuser')/charname
What you can have is something like:
Route::get("/user/{user}/charname", array(
'as' => 'profile-character',
'uses' => 'ProfileController#dropDownList'
));
And do
public function dropDownList($user) {
$list = Character::lists('char_name', 'char_dynasty');
return View::make('layout.profile')->with('character_options',$list);
}

zend framework - group elements of a form within a subforms [duplicate]

I would like to be able to add a hidden form field using array notation to my form. I can do this with HTML like this:
<input type="hidden" name="contacts[]" value="123" />
<input type="hidden" name="contacts[]" value="456" />
When the form gets submitted, the $_POST array will contain the hidden element values grouped as an array:
array(
'contacts' => array(
0 => '123'
1 => '456'
)
)
I can add a hidden element to my form, and specify array notation like this:
$form->addElement('hidden', 'contacts', array('isArray' => true));
Now if I populate that element with an array, I expect that it should store the values as an array, and render the elements as the HTML shown above:
$form->populate($_POST);
However, this does not work. There may be a bug in the version of Zend Framework that I am using. Am I doing this right? What should I do differently? How can I achieve the outcome above? I am willing to create a custom form element if I have to. Just let me know what I need to do.
You have to use subforms to get the result you seek. The documentation was quite a ride but you can find it here
Using what I found there I constructed the following formL
<?php
class Form_Test extends Zend_Form {
public function init() {
$this->setMethod('post');
$this->setIsArray(true);
$this->setSubFormDecorators(array(
'FormElements',
'Fieldset'
));
$subForm = new Zend_Form(array('disableLoadDefaultDecorators' => true));
$subForm->setDecorators(array(
'FormElements',
));
$subForm->addElement('hidden', 'contacts', array(
'isArray' => true,
'value' => '237',
'decorators' => Array(
'ViewHelper',
),
));
$subForm2 = new Zend_Form(array('disableLoadDefaultDecorators' => true));
$subForm2->setDecorators(array(
'FormElements',
));
$subForm2->addElement('hidden', 'contacts', array(
'isArray' => true,
'value' => '456', 'decorators' => Array(
'ViewHelper',
),
));
$this->addSubForm($subForm, 'subform');
$this->addSubForm($subForm2, 'subform2');
$submit = new Zend_Form_Element_Submit('submit');
$submit->setValue('Submit');
$this->addElement('submit', 'submit');
}
}
Wich outputs this html:
<form enctype="application/x-www-form-urlencoded" method="post" action=""><dl class="zend_form">
<input type="hidden" name="contacts[]" value="237" id="contacts">
<input type="hidden" name="contacts[]" value="456" id="contacts">
<dt id="submit-label"> </dt><dd id="submit-element">
<input type="submit" name="submit" id="submit" value="submit"></dd></dl></form>
And when submited the post looks like:
array(2) {
["contacts"] => array(2) {
[0] => string(3) "237"
[1] => string(3) "456"
}
["submit"] => string(6) "submit"
}
So thats how you can create the kind of forms you seek. Hope this helps! if you have a question post a comment!
Its quite hackish if you ask me. You basically create subforms but disable there form decorators so just the element gets output. Since the identical contacts[] elements are in different form object zend does'nt overwrite them and it works. But yeah..
Edit: changed it a bit to remove labels and garbage arount the hidden inputs.
To use array notation, you need to specify that the element "belongs to" a parent array:
$form->addElement('hidden', 'contact123', array('belongsTo' => 'contacts', 'value' => '123'));
$form->addElement('hidden', 'contact456', array('belongsTo' => 'contacts', 'value' => '456'));
This indeed seems to be a bug in Zend Framework - the value attribute for an element is properly set to array, but it's ignored when the element renders - it just uses$this->view->escape($value) to output element's html.
I've solved this by implementing a custom helper for such elements:
class My_View_Helper_HiddenArray extends Zend_View_Helper_FormHidden
{
public function hiddenArray($name, $value = null, array $attribs = null)
{
if (is_array($value)) {
$elementXHTML = '';
// do not give element an id due to the possibility of multiple values
if (isset($attribs) && is_array($attribs) && array_key_exists('id', $attribs)) {
unset($attribs['id']);
}
foreach ($value as $item) {
$elementXHTML .= $this->_hidden($name, $item, $attribs);
}
return $elementXHTML;
} else {
return $this->formHidden($name, $value, $attribs);
}
}
}
Which, when used the next way:
$contacts = $form->createElement('hidden', 'contacts')
->setIsArray(true)
->setDecorators(array(
array('ViewHelper', array('helper' => 'HiddenArray')),
));
$form->addElement($contacts);
generates the needed output.
The reason to extend Zend_View_Helper_FormHidden here is just to be able to call the default behaviour if no array value is set ( return parent::formHidden($name, $value, $attribs) ).
Hope this helps someone :)
For the newer versions of ZF you should use https://framework.zend.com/manual/2.1/en/modules/zend.form.elements.html#multicheckbox

Zend Framework: Working with Form elements in array notation

I would like to be able to add a hidden form field using array notation to my form. I can do this with HTML like this:
<input type="hidden" name="contacts[]" value="123" />
<input type="hidden" name="contacts[]" value="456" />
When the form gets submitted, the $_POST array will contain the hidden element values grouped as an array:
array(
'contacts' => array(
0 => '123'
1 => '456'
)
)
I can add a hidden element to my form, and specify array notation like this:
$form->addElement('hidden', 'contacts', array('isArray' => true));
Now if I populate that element with an array, I expect that it should store the values as an array, and render the elements as the HTML shown above:
$form->populate($_POST);
However, this does not work. There may be a bug in the version of Zend Framework that I am using. Am I doing this right? What should I do differently? How can I achieve the outcome above? I am willing to create a custom form element if I have to. Just let me know what I need to do.
You have to use subforms to get the result you seek. The documentation was quite a ride but you can find it here
Using what I found there I constructed the following formL
<?php
class Form_Test extends Zend_Form {
public function init() {
$this->setMethod('post');
$this->setIsArray(true);
$this->setSubFormDecorators(array(
'FormElements',
'Fieldset'
));
$subForm = new Zend_Form(array('disableLoadDefaultDecorators' => true));
$subForm->setDecorators(array(
'FormElements',
));
$subForm->addElement('hidden', 'contacts', array(
'isArray' => true,
'value' => '237',
'decorators' => Array(
'ViewHelper',
),
));
$subForm2 = new Zend_Form(array('disableLoadDefaultDecorators' => true));
$subForm2->setDecorators(array(
'FormElements',
));
$subForm2->addElement('hidden', 'contacts', array(
'isArray' => true,
'value' => '456', 'decorators' => Array(
'ViewHelper',
),
));
$this->addSubForm($subForm, 'subform');
$this->addSubForm($subForm2, 'subform2');
$submit = new Zend_Form_Element_Submit('submit');
$submit->setValue('Submit');
$this->addElement('submit', 'submit');
}
}
Wich outputs this html:
<form enctype="application/x-www-form-urlencoded" method="post" action=""><dl class="zend_form">
<input type="hidden" name="contacts[]" value="237" id="contacts">
<input type="hidden" name="contacts[]" value="456" id="contacts">
<dt id="submit-label"> </dt><dd id="submit-element">
<input type="submit" name="submit" id="submit" value="submit"></dd></dl></form>
And when submited the post looks like:
array(2) {
["contacts"] => array(2) {
[0] => string(3) "237"
[1] => string(3) "456"
}
["submit"] => string(6) "submit"
}
So thats how you can create the kind of forms you seek. Hope this helps! if you have a question post a comment!
Its quite hackish if you ask me. You basically create subforms but disable there form decorators so just the element gets output. Since the identical contacts[] elements are in different form object zend does'nt overwrite them and it works. But yeah..
Edit: changed it a bit to remove labels and garbage arount the hidden inputs.
To use array notation, you need to specify that the element "belongs to" a parent array:
$form->addElement('hidden', 'contact123', array('belongsTo' => 'contacts', 'value' => '123'));
$form->addElement('hidden', 'contact456', array('belongsTo' => 'contacts', 'value' => '456'));
This indeed seems to be a bug in Zend Framework - the value attribute for an element is properly set to array, but it's ignored when the element renders - it just uses$this->view->escape($value) to output element's html.
I've solved this by implementing a custom helper for such elements:
class My_View_Helper_HiddenArray extends Zend_View_Helper_FormHidden
{
public function hiddenArray($name, $value = null, array $attribs = null)
{
if (is_array($value)) {
$elementXHTML = '';
// do not give element an id due to the possibility of multiple values
if (isset($attribs) && is_array($attribs) && array_key_exists('id', $attribs)) {
unset($attribs['id']);
}
foreach ($value as $item) {
$elementXHTML .= $this->_hidden($name, $item, $attribs);
}
return $elementXHTML;
} else {
return $this->formHidden($name, $value, $attribs);
}
}
}
Which, when used the next way:
$contacts = $form->createElement('hidden', 'contacts')
->setIsArray(true)
->setDecorators(array(
array('ViewHelper', array('helper' => 'HiddenArray')),
));
$form->addElement($contacts);
generates the needed output.
The reason to extend Zend_View_Helper_FormHidden here is just to be able to call the default behaviour if no array value is set ( return parent::formHidden($name, $value, $attribs) ).
Hope this helps someone :)
For the newer versions of ZF you should use https://framework.zend.com/manual/2.1/en/modules/zend.form.elements.html#multicheckbox