Laravel 5, Form::select - Dropdown select 'other' - forms

im working on a Laravel 5 Site and implemented a Form with a DropDown menu. All works fine but the user should be able to select the option "Other" and write his own Text.
I've googled and found some good ideas but i can't implement it.
here's what i got:
<div class="form-group">
{!! Form::label('special_status', 'Erasmus, Nebenhöhrer:') !!}
{!! Form::select('special_status',$status, null, ['id' => 'special_status', 'class' => 'form-control', 'dropdown-menu']) !!}
</div>
with the
$status = array (
'Erasmus' => 'Erasmus',
'NebenhörerIn'=> 'NebenhörerIn',
'Sonstiges' => 'Sonstiges',
);
An example how it should be:
http://jsfiddle.net/CxV9c/4/
And here's what i find on StOverf:
Laravel 4 - Assign OnChange to Form::select
Running Laravel 5.2.22 - Homestead
Includes:
bootstrap.min.css
jquery.min.js
bootstrap.min.js
Thx,
Pat

Actually, you can just put a script tag in your blade view, for example:
<script>
$(function(){
$("input[type=text]").hide();
$('#visit').on('change', function () {
var v = this.value == 4 ? 'show' : 'hide';
$.fn[v].call($("input[type=text]"));
});
});
</script>
Just put this snippet at the bottom of your blade view. Also, make sure you've added the jQuery library vefore this script runs. This is the simplest way but there are other ways to add one or more script tags in a blade view. A working example here.

Related

Symfony: Hide/Show form element dependent on dropdown selection with database entries

I hope my title is proper: I have a dropdown, that comes from a form as an EntityType and the values are from an entity class. Code:
->add('type', EntityType::class, array(
'class' => 'DocumentBundle:DocumentType',
'label' => 'label.type',
'property' => 'translationKey',
'required' => true,
'multiple' => false,
'expanded' => false,
'empty_value' => 'label.select_type',
'choice_translation_domain' => 'Documents'
))
->add('vka_number', 'text', array(
'label' => 'label.vka_number',
'required' => false,
'translation_domain' => 'Documents'))
the second one is a text field (vka_number) that I only want to be shown when a specific value from that dropdown is selected
in my twig template I render the elements:
<div class="row">
<div class="col-md-6" id="documentDropdown">
{{ form_row(form.type) }}
</div>
<div class="col-md-6" id="vka">
{{ form_row(form.vka_number) }}
</div>
</div>
I was thinking about a javascript function like that:
<script>
$(document).ready(function(){
$('#documentDropdown').on('change', function(){
if (this.value == 'Contract')
{
$('#vka').show();
}
else {
$('#vka').hide();
}
});
});
</script>
but it's not working and I think this is because it can't access the values from the dropdown since they are not hard coded but database entries.
'Contract' would be the entry (id=1) that "makes" the vka_number text field appear.
I copied the html code from your previous question Sonja, and you seem to be continuing to ask the same question. I used that code in this jsfiddle:
https://jsfiddle.net/alvinbunk/to9qodwx/
You can use jsfiddle to experiment with your jQuery code to figure out what is wrong. As you can see the code does work and does hide the vka id division. it really has nothing to do with the fact that values are from the database. Make sure you don't have duplicate ids in various elements in your html code. Use "view source" in your browser to see the rendered code.
By the way I spent at least 15 minutes on this answer, and also 15 - 30 minutes on the other one. be aware that people on StackOverflow are very busy, and it's good to ask your questions very clearly.
EDIT #2 - Based on comments
Use this jQuery code:
<script>
$(document).ready(function(){
$('#documentDropdown').on('change', function(){
if (this.value == '1')
{
$('#vka').show();
}
else {
$('#vka').hide();
}
});
});
</script>
That should work.
Here's my javascript function that eventually solved my problem.
$(document).ready(function () {
$('#type ').change(function() {
if ($('select[id$="_type"]>option:selected').text() == "Contract") {
$('#vka_number ').show();
}
else {
$('#vka_number').hide();
}
});
});

Phalcon use Phalcon\Tag OR Phalcon\Forms for creating forms

I searched up and down but couldn't find which one is better Phalcon\Tag OR Phalcon\Forms for creating forms.
Both classes have functionality to create form elements. But I found there are some handy tags in the Phalcon\Tag, for example Phalcon\Tag::emailField() or Phalcon\Tag::dateField(array())
Phalcon documentation says:
"Phalcon\Forms is a component that aid the developer in the creation
and maintenance of forms in web applications."
"Phalcon\Tag is designed to simplify building of HTML tags. It
provides a set of helpers to generate HTML in a dynamic way."
Can anybody help me with the pros and cons of using both the methods.
Thanks
In simple meaning Phalcon\Tag are used to design only html (users view). but for validation && adding rules to the form you need to use phalcon\forms i will show you an example of phalcon\forums below
NEW FORM CLASS:
use Phalcon\Forms\Form,
Phalcon\Forms\Element\Password,
Phalcon\Forms\Element\Email as Emailfield,
Phalcon\Forms\Element\Check,
Phalcon\Forms\Element\Hidden,
Phalcon\Validation\Validator\PresenceOf,
Phalcon\Validation\Validator\Identical,
Phalcon\Validation\Validator\Email;
class LoginForm extends Form
{
public function initialize()
{
$email = new Emailfield('email', array(
'placeholder' => 'Type your Email'
));
$email->setLabel('E-Mail');
$email->setFilters('email');
$email->addValidators(array(
new PresenceOf(array(
'message' => 'E-mail is required'
)),
new Email(array(
'message' => 'E-mail is not valid'
))
));
$this->add($email);
$password = new Password('password', array(
'placeholder' => 'Type your Password'
));
$password->setLabel('Password');
$password->setFilters(array('striptags', 'string'));
$password->addValidators(array(
new PresenceOf(array(
'message' => 'Password required'
))
));
$this->add($password);
//Remember
$long_login = new Check('long_login', array(
'value' => 'yes'
));
$long_login->setLabel('Keep me logged in');
$this->add($long_login);
// CSRF
$csrf = new Hidden('csrf');
$csrf->addValidator(new Identical(array(
'value' => $this->security->getSessionToken(),
'message' => 'CSRF validation failed'
)));
// $this->add($csrf);
}
}
In Controller:
$form = new LoginForm();
if (!empty($_POST)) {
if (!$form->isValid($_POST)) {
$errors = array();
foreach ($form->getMessages() as $message) {
$errors[] = $message;
}
if (!empty($errors))
$this->flash->error(join('<br/>', $errors));
} else {
//Login Continues
}
}
$this->view->setVar('form', $form);
To convert this form to html below is the code:
<div class="form-group">
{{ form.label('email',['class': 'control-label']) }}
{{ form.render('email', ['class': 'form-control input-md']) }}
</div>
<div class="form-group">
{{ form.label('password',['class': 'control-label']) }}
{{ form.render('password', ['class': 'form-control input-md']) }}
</div>
<div class="checkbox">
{{ form.render('long_login') }}
{{ form.label('long_login') }}
</div>
Really great example in general but I'm struggling with the flash message. After a quick google search I was more confused after reading the documentation. Some say that $this->flash->output() should be placed to the view to see the flash messages. Though this causes errors and I believe it's something from the past. Can somebody tell me what flash method should I place to view to see the flash messages or Where I'm going wrong?
EDIT: Well I managed to get \Phalcon\Flash\Session to work and I believe it's event more suitable for me than Direct. For that you need to register flash service in Dependency Injector in config/services.php. I also replaces classes with bootstrap classes.
$di->set('flash', function() {
return new Phalcon\Flash\Session(array(
'error'=>'text-danger',
'warning'=>'text-warning',
'notice'=>'text-info',
'success'=>'text-success'
));
});
It depends on which you are working.
If we say, you need to insert lots of data with lots of validations and it may change during progress then its far better to use "Phalcon\Forms"
As they are very dynamic.
Means you can change text-box with select box very easily without touching template.
You can add validations without worrying about template and other stuff.
And for-most reusable you can reuse form if you need.
so if there is less data then you are free to use anyone of that but more suggestible is "Phalcon\Forms" its very dynamic and structural.

How to send a POST image url variable through a form in Laravel 4

I am trying to upload an image url through a form in Laravel 4.
Without a framework, I would use something like this:
<div id="myResults" value="<php echo h($_POST['img'])"></div>
where the image url is sent to the id "myResults" by a javascript file.
In the javascript:
document.getElementById("myResults").innerHTML = "<img src='" + FPFile.url + "' width='200px' height='200px'>";
I would use the h($_POST['img'])" value to get the url and then store it in the database upon the submit click of the form.
My question is how can I do this same function in Laravel 4? Using the form:
{{ Form::open(array('route' => 'artists.store')) }}
{{Form::submit('Submit', null, array(
'class' => 'button',
));}}
Thank you for your help.
{{ Form::file('myImage') }}
Seriously, it's that easy! See: http://laravel.com/docs/html
Then, to retrieve the file: $file = Input::file('myImage');
See: http://laravel.com/docs/requests#files
I'm not really understanding your question.
But equivalent of
<div id="myResults" value="<php echo h($_POST['img'])"></div>
in Blade is...
<div id="myResults" value="{{{ Input::get("img") }}}"></div>
Is that what you were asking?

ZF: Form array field - how to display values in the view correctly

Let's say I have a Zend_Form form that has a few text fields, e.g:
$form = new Zend_Form();
$form->addElement('text', 'name', array(
'required' => true,
'isArray' => true,
'filters' => array( /* ... */ ),
'validators' => array( /* ... */ ),
));
$form->addElement('text', 'surname', array(
'required' => true,
'isArray' => true,
'filters' => array( /* ... */ ),
'validators' => array( /* ... */ ),
));
After rendering it I have following HTML markup (simplified):
<div id="people">
<div class="person">
<input type="text" name="name[]" />
<input type="text" name="surname[]" />
</div>
</div>
Now I want to have the ability to add as many people as I want. I create a "+" button that in Javascript appends next div.person to the container. Before I submit the form, I have for example 5 names and 5 surnames, posted to the server as arrays. Everything is fine unless somebody puts the value in the field that does not validate. Then the whole form validation fails and when I want to display the form again (with errors) I see the PHP Warning:
htmlspecialchars() expects parameter 1 to be string, array given
Which is more or less described in ticket: http://framework.zend.com/issues/browse/ZF-8112
However, I came up with a not-very-elegant solution. What I wanted to achieve:
have all fields and values rendered again in the view
have error messages only next to the fields that contained bad values
Here is my solution (view script):
<div id="people">
<?php
$names = $form->name->getValue(); // will have an array here if the form were submitted
$surnames= $form->surname->getValue();
// only if the form were submitted we need to validate fields' values
// and display errors next to them; otherwise when user enter the page
// and render the form for the first time - he would see Required validator
// errors
$needsValidation = is_array($names) || is_array($surnames);
// print empty fields when the form is displayed the first time
if(!is_array($names))$names= array('');
if(!is_array($surnames))$surnames= array('');
// display all fields!
foreach($names as $index => $name):
$surname = $surnames[$index];
// validate value if needed
if($needsValidation){
$form->name->isValid($name);
$form->surname->isValid($surname);
}
?>
<div class="person">
<?=$form->name->setValue($name); // display field with error if did not pass the validation ?>
<?=$form->surname->setValue($surname);?>
</div>
<?php endforeach; ?>
</div>
The code work, but I want to know if there is an appropriate, more comfortable way to do this? I often hit this problem when there is a need for a more dynamic - multivalue forms and have not find better solution for a long time.
Having no better idea, I have created a view helper that handles the logic presented above. It can be found here.
If the helper is available in the view, it can be used in the following way (with the form from the question):
<?=
$this->formArrayElements(
array($form->name, $form->surname),
'partials/name_surname.phtml'
);
?>
The contents of the application/views/partials/name_surname.phtml partial view are:
<div class="person">
<?= $this->name ?>
<?= $this->surname ?>
</div>
The fields are rendered according to the posted form and validation messages are shown only next to the values that failed validation.
The helper's code is far from perfect (I just rewrote the idea from the question) but is easy to use and can be considered as good starting point.

CakePHP: allowing database update with button click

I have a product search page with the form below. The search result is displayed on the same page with search bar at the top.
echo $this->Form->create('Searches', array('action'=>'products', 'type' => 'get', 'name' => 'textbox1'));
echo $form->input($varName1, array('label' => false));
echo $form->end('Locate');
I also have a little box next to the search result that allows (it doesn't work yet) the user to flag using checkboxes a product and accordingly update its database (table products and using model Product) with a button click. Note that I have a Searches controller for this search page.
<form method="link" action="/myapp/product/test_update_db>
<label><input type="checkbox" name="flag1" <?php echo $preCheckBox1; ?>>Flag 1</input></label>
<label><input type="checkbox" name="flag2" <?php echo $preCheckBox2; ?>>Flag 2</input></label>
<input type="submit" value="Update">
</form>
I'm having difficulty with this approach figuring out how to perform this check-box-and-DB-update routine. I'm getting to the link I'd like to go (/myapp/product/test_update_db), but I don't know how to take variables flag1 and flag2, along with row ID of this result ($results['Product']['id'])) to the new page.
Could someone guide me on how to perform this neatly? Is this general approach correct? If not, what route should I be taking? I'd prefer not to use javascript at this time, if possible.
EDIT: I think I can make this work if I use the URL for passing data.. but I'd still like to know how this could be done "under the hood" or in MVC. I feel like I'm hacking at the CakePHP platform.
UPDATE: So, I ended up using the URL parameters for retrieving information pieces like flag1 and flag2. I'm still looking for an alternative method.
To see where your is-checkbox-checked data is located, do the following in your controller:
// Cake 2.0+
debug($this->request->data);
// previous versions
debug($this->data);
If you want to pass data to your search controller from the current page, you can always add the data to your form:
$this->input
(
'Product.id',
array
(
'type' => 'hidden',
'value' => $yourProductId
)
);
I ended up using information embedded in the URL for getting submission data. Something like below..
In Products controller, when the form with flag1 and flag2 are submitted:
public function test_update_db() {
// Get variables from URL, if any, and save accordingly
$result = $this->Product->updateProduct($this->params['url'], 'url');
if ($result) {
$this->Session->setFlash('Successfully updated!', 'default', array('class' => 'success'));
$this->redirect($this->referer());
}
else {
$this->Session->setFlash('Update was unsuccessful!', 'default', array('class' => 'error'));
$this->redirect($this->referer());
}
}
This works for doing what I needed to do. I feel like there's a more proper way to do this though.
if ($result) {
$this->Session->setFlash('Successfully updated!', 'default', array('class' => 'success'));
$this->redirect($this->referer());
}