Dynamic Country - city select on form - perl

newbie alert,
I am really enjoying perl Catalyst, however, i have googled and cant find a solution for Country - City dynamic selection. when i select a country from the dropdown, i would like the cities to change to that coutries cities only. How can i achieve this in Perl, Catalyst using HTML::FormHandler.
PS
The data is coming from mysql db with a one to many relatioship
has_field 'city_id' => (
label => 'City',
type => 'Select',
empty_select => 'Choose city',
required => 1,
required_message => 'Please enter city.',
);
has_field 'country_code' => (
label => 'Country',
type => 'Select',
empty_select => 'Choose country',
required => 1,
required_message => 'Please enter your country.',
);
has_field 'submit' => (
type => 'Submit',
value => 'Save',
element_class => ['btn']
);
sub options_country_code {
my $self = shift;
return unless $self->schema;
my #countries = $self->schema->resultset('Country')->all;
my #options = map { { value => $_->country_code, label => $_->country_name } } #countries;
unshift #options, { value => 0, label => 'Choose Country' };
return #options;
}
__PACKAGE__->meta->make_immutable;
1;

I found exactly what I was looking for, thank you for the effort, I appreciate it very much.
The solution I needed is here
I am using this code as my base:
<html>
<head>
<script type="text/javascript">
function setmenu2() {
var menu1 = document.getElementById('menu1');
var sel = menu1.options[menu1.selectedIndex].text;
var menu2 = document.getElementById('menu2');
if (sel == "Foo") {
menu2.innerHTML = "<option>Foo-1</option>"
+"<option>Foo-2</option>";
} else {
menu2.innerHTML = "<option>Bar-1</option>"
+"<option>Bar-2</option>"
+"<option>Bar-3</option>";
}
}
</script>
</head>
<body>
<select id="menu1" onchange="setmenu2()">
<option>please select...</option>
<option>Foo</option>
<option>Bar</option>
</select>
<select id="menu2">
<option>- ?? -</option>
</select>
</body>
</html>
So far this is what I have:
<script type="text/javascript">
function setcities() {
var country_select = document.getElementById('country_code');
var sel = country_select.options[country_select.selectedIndex].value;
var city_select = document.getElementById('city_id');
if (sel == "AFG") {
city_select.innerHTML = "<option value='1' id='city_id.1'>Kabul</option>"
+"<option value='2' id='city_id.2'> Qandahar</option>";
} else if (sel == "AGO"){
city_select.innerHTML = "<option value='56' id='city_id.1'>Luanda</option>"
+"<option value='57' id='city_id.2'>Huambo</option>"
+"<option value='58' id='city_id.3'>Lobito</option>";
} else {
city_select.innerHTML = "<option>nothing</option>";
}
}
</script>
<select id="country_code" onchange="setcities()">
<option value="" id="country_code.0">please select...</option>
<option value="AFG" id="country_code.1">Afghanistan</option>
<option value="AGO" id="country_code.2">Angola</option>
<option value="AIA" id="country_code.3">Anguilla</option>
</select>
<select id="city_id">
<option>- ?? -</option>
</select>

Related

How to set id for AJAX

I have following Jquery-Script, which works fine outside of yii2
<script>
$(function () {
$(".comment_button").click(function () {
var element = $(this);
var test = $("#_id_").val();
var dataString = '_id_=' + test;
if (test == '')
{
alert("No record, no action...!");
} else
{
$.ajax({
type: "POST",
url: '<?=\Yii::$app->urlManager->baseUrl?>/insert.php',
//url: 'insert.php',
data: dataString,
cache: false,
/*
success: function (html) {
$("#display").after(html);
document.getElementById('_id_').value = '';
*/
}
});
}
return false;
});
});
</script>
It works,'cause I have following html input box:
<textarea cols="30" rows="2" style="width:480px;font-size:14px; font-weight:bold" id="_id_" maxlength="145" ></textarea>
As u can see, jquery will take id= _ id _ in order to use AJAX.
I try to realize same thing with yii2, but I get following error:
bewerber_update?id=2:1925 Uncaught TypeError: Cannot set property 'value' of null
at Object.success (bewerber_update?id=2:1925)
at fire (jquery.js:3187)
at Object.fireWith [as resolveWith] (jquery.js:3317)
at done (jquery.js:8757)
at XMLHttpRequest.<anonymous> (jquery.js:9123)
This error will be thrown out,' cause I don't konw, how to set id correctly in yii2. I tried like this, but this is obviously the wrong way:
<?=
$form->field($model, 'beurteilung_fachlich')->widget(\dosamigos\ckeditor\CKEditor::className(), [
'id'=>'_id_',
'options' => ['rows' => 1],
'preset' => 'full'
])
?>
Any ideas, how to set id in a correct way?
You should pass id in options
<?= $form->field($model, 'beurteilung_fachlich')->widget(\dosamigos\ckeditor\CKEditor::className(), [
'options' => ['rows' => 1, 'id' => '_id_'],
'preset' => 'full'
]) ?>

How to get List for Contact Form 7

I have 2 contact forms created by Contact Form 7.
How to list all contact forms created through shortcode?
Please check images, tks.
Updated:
this is my code, this working!
$args = array('post_type' => 'wpcf7_contact_form', 'posts_per_page' => -1);
$rs = array();
if( $data = get_posts($args)){
foreach($data as $key){
$rs[$key->ID] = $key->post_title;
}
}else{
$rs['0'] = esc_html__('No Contact Form found', 'text-domanin');
}
Below is a dropdown list:
<select name="field-name" id="field-id">
<option value="">--Select--</option><?php
$dbValue = get_option('field-name'); //example!
$posts = get_posts(array(
'post_type' => 'wpcf7_contact_form',
'numberposts' => -1
));
foreach ( $posts as $p ) {
echo '<option value="'.$p->ID.'"'.selected($p->ID,$dbValue,false).'>'.$p->post_title.' ('.$p->ID.')</option>';
} ?>
</select>

Associating Adjacent Elements with Perl's Web::Scraper

The following is the example at hand :
#!/usr/bin/perl
use strict;
use Web::Scraper;
use Data::Dumper;
my $html = q[
<html>
<body>
<div class="mainContainer">
<div class="when">February 20, 2014</div>
<div class="name">Name 1</div>
<div class="desc">Desc 1</div>
<div class="when">February 21, 2014</div>
<div class="name">Name 2</div>
<div class="desc">Desc 2</div>
<div class="name">Name 3</div>
<div class="desc">Desc 3</div>
<div class="when">February 22, 2014</div>
<div class="name">Name 4</div>
<div class="desc">Desc 4</div>
</div>
</body>
</html>
];
my $scraper = scraper {
process ".when", "events[]" => scraper {
my $when = $_->content();
my $hash = {};
$hash->{$when}->{name} = "NAME";
$hash->{$when}->{desc} = "DESC";
return $hash;
};
};
my $result = $scraper->scrape($html);
print Dumper( $result );
What I am trying to do is associate the dates with the events details. As you can see, the divs are not nested so it is not as trivial (at least for me). Also each event is composed of the name and desc. I did not find a way to associate the adjacent elements in the desired structure using css selectors. I figured I would need a custom subroutine to return to do that associations of the elements. What I would like to retrieve is something similar to the following :
[
'February 20, 2014' => [
{
'name' => 'Name 1',
'desc' => 'Desc 1'
}
],
'February 21, 2014' => [
{
'name' => 'Name 2',
'desc' => 'Desc 2'
},
{
'name' => 'Name 3',
'desc' => 'Desc 3'
}
],
'February 22, 2014' => [
{
'name' => 'Name 4',
'desc' => 'Desc 4'
}
]
]
You might be better served by getting the data first, and then processing these after the scraper. So...:
my $scraper = scraper {
process ".when", "dates[]" => "TEXT";
process ".name", "names[]" => "TEXT";
process ".desc", "desc[]" => "TEXT";
};
my $result = $scraper->scrape($html);
# Here you would start processing these
my #dates = #{ $result->{dates} };
my #names = #{ $result->{names} };
my #info = #{ $result->{desc} };
my %events;
for ( my $i = 0; $i < scalar #dates; $i++ ) {
my $date = $dates[$i];
my $name = $names[$i];
my $info = $info[$i];
if ( exists $events{$date} ) {
push #{ $events{$date} }, { 'name' => $name, 'desc' => $info };
}
else {
$events{$date} = [{ 'name' => $name, 'desc' => $info}];
}
}
%events would have the data you need. This is all assuming you still need this, and each event date has a name and description after it. Also, I haven't tested this.

Form text diappears and comeing ab up again

How do I do that in symfony?
http://dorward.me.uk/tmp/label-work/example.html
When I click into the input field username. The text disappears. If I don't enter nothing and click somewhere else the text is comeing up again. How do I do that in symofny in lib/forms/.
Thanks for an advice!
Craphunter
This isnt symfony - its javascript ... just take a look at the source (uses jQuery)
HTML:
<div class="slim-control">
<label for="username"> Username </label>
<input name="username" id="username">
</div>
<div class="slim-control">
<label for="password"> Password </label>
<input name="password" id="password" type="password">
</div>
JavaScript:
(function () {
var nonEmpty = "non-empty";
var inputs = jQuery('.slim-control input');
var setLabelStyle = function setLabelStyle () {
var label = jQuery(this);
if (label.val().length) {
label.addClass(nonEmpty);
} else {
label.removeClass(nonEmpty);
}
};
inputs.focus(function () {
jQuery(this).addClass(nonEmpty);
});
inputs.blur(setLabelStyle);
inputs.each(setLabelStyle);
}());
So if you want to do this - you would need to add the javascript to the template (indexSuccess.php) for example - you would probably need to modify the ids / classes to meet your local needs
Updated
You could create the following form - this would match the above form (untested):
$this->form = new sfForm();
$this->form->setWidgets(array(
'username' => new sfWidgetFormInputText(),
'password' => new sfWidgetFormInputPassword()
));
Creating forms (indeed all of Symfony) is very well documented here -> http://www.symfony-project.org/gentle-introduction/1_4/en/10-Forms
'input' => new sfWidgetFormInputText(array(), array('size' => '100', 'maxlength' => '255', 'value' => 'Some text', 'onblur' =>"if(this.value == '') { this.value='Some text'}", 'onfocus' =>"if (this.value == 'Some text') {this.value=''}")),
This is much shorter! Be careful that "Some text" is identical!
If you need to pass more, take a look to SetWidgetsHtml in Symfony form: (slide down)
http://www.symfony-project.org/forms/1_4/en/01-Form-Creation

zend-form select optgroup, how to specify id

Hello i am using Zend Framework Form and have tried to get this example to work http://framework.zend.com/issues/browse/ZF-8252, but it fails xD
this is my code
$options = Array
(
[] => Qualsiasi Agente
[agenti_attivi] => Array
(
[4] => Giovanni Abc
[10] => Luigi Abc
[13] => Michela Abc
)
);
$agenti->addMultiOptions($options);
and the generated code is :
<select name="agente_id" id="agente_id" tabindex="6">
<option value="" label="Qualsiasi Agente" selected="selected">Qualsiasi Agente</option>
<optgroup id="agente_id-optgroup-Agenti attivi: " label="Agenti attivi: ">
<option value="4" label="Giovanni Abc">Giovanni Abc</option>
<option value="10" label="Luigi Capoarea">Luigi Abc</option>
<option value="13" label="Michela Abc">Michela Abc</option>
</optgroup>
</select>
where id="agente_id-optgroup-Agenti attivi: " is not xhtml valid Line 724, Column 44: value of attribute "id" must be a single token
i am using zend 1.11.10
thanks
Create a custom view helper FormSelect that extends the core FormSelect and then modify the code.
Include the path to your view helpers in the bootstrap file
protected function _initHelpers()
{
$this->bootstrap('view');
$view = $this->getResource('view');
$view->addHelperPath('My/View/Helper', 'My_View_Helper');
}
The custom view helper. It's a copy of Zend_View_Helper_FormSelect but with small modification.
class My_View_Helper_FormSelect extends Zend_View_Helper_FormSelect
{
public function formSelect($name, $value = null, $attribs = null,
$options = null, $listsep = "<br />\n")
{
$info = $this->_getInfo($name, $value, $attribs, $options, $listsep);
extract($info); // name, id, value, attribs, options, listsep, disable
// force $value to array so we can compare multiple values to multiple
// options; also ensure it's a string for comparison purposes.
$value = array_map('strval', (array) $value);
// check if element may have multiple values
$multiple = '';
if (substr($name, -2) == '[]') {
// multiple implied by the name
$multiple = ' multiple="multiple"';
}
if (isset($attribs['multiple'])) {
// Attribute set
if ($attribs['multiple']) {
// True attribute; set multiple attribute
$multiple = ' multiple="multiple"';
// Make sure name indicates multiple values are allowed
if (!empty($multiple) && (substr($name, -2) != '[]')) {
$name .= '[]';
}
} else {
// False attribute; ensure attribute not set
$multiple = '';
}
unset($attribs['multiple']);
}
// now start building the XHTML.
$disabled = '';
if (true === $disable) {
$disabled = ' disabled="disabled"';
}
// Build the surrounding select element first.
$xhtml = '<select'
. ' name="' . $this->view->escape($name) . '"'
. ' id="' . $this->view->escape($id) . '"'
. $multiple
. $disabled
. $this->_htmlAttribs($attribs)
. ">\n ";
// build the list of options
$list = array();
$translator = $this->getTranslator();
foreach ((array) $options as $opt_value => $opt_label) {
if (is_array($opt_label)) {
$opt_disable = '';
if (is_array($disable) && in_array($opt_value, $disable)) {
$opt_disable = ' disabled="disabled"';
}
if (null !== $translator) {
$opt_value = $translator->translate($opt_value);
}
$opt_id = ' id="' . $this->formatElementId($id . '-optgroup-' . $opt_value) . '"';
$list[] = '<optgroup'
. $opt_disable
. $opt_id
. ' label="' . $this->view->escape($opt_value) .'">';
foreach ($opt_label as $val => $lab) {
$list[] = $this->_build($val, $lab, $value, $disable);
}
$list[] = '</optgroup>';
} else {
$list[] = $this->_build($opt_value, $opt_label, $value, $disable);
}
}
// add the options to the xhtml and close the select
$xhtml .= implode("\n ", $list) . "\n</select>";
return $xhtml;
}
private function formatElementId($id)
{
// in here put whatever filter you want for the id value
$id = trim(strtr($id, array('[' => '-', ']' => '', ' ' => '', ':' => '')), '-');
$id = strtolower($id);
return $id;
}
}
Done. Create multi select element with a valid id.
<?php
$this->addElement('multiSelect', 'agente_id', array(
'label' => 'Label Name:',
'multiOptions' => array(
'' => 'Qualsiasi Agente',
'Agenti attivi: ' => array(
4 => 'Giovanni Verdi',
10 => 'Luigi Capoarea',
13 => 'Michela Passarin',
)
)
));
try this, it's works for me:
$select = new Zend_Form_Element_Select('select');
$options = Array(
'' => 'Qualsiasi Agente',
'agenti_attivi' => Array(
4 => 'Giovanni Verdi',
10 => 'Luigi Capoarea',
13 => 'Michela Passarin'
)
);
$this->addElements(array($xxxx,$select,$yyyy)); // $this : the form instance
and the result is:
<select id="select" name="select">
<option label="Qualsiasi Agente" value="">Qualsiasi Agente</option>
<optgroup label="agenti_attivi">
<option label="Giovanni Verdi" value="4">Giovanni Verdi</option>
<option label="Luigi Capoarea" value="10">Luigi Capoarea</option>
<option label="Michela Passarin" value="13">Michela Passarin</option>
</optgroup>
</select>
the problem is that the id attribute does not accept spaces and special special characters:
id="agente_id-optgroup-Agenti attivi: "
Zend is usually pretty good about rendering the proper html, given a doctype.
Try setting your doctype like this if you aren't already.
<?php
$viewRenderer = Zend_Controller_Action_HelperBroker::getStaticHelper('viewRenderer');
$viewRenderer->initView();
$viewRenderer->view->doctype('XHTML1_STRICT');
AND
<?php echo $this->doctype(); ?>
at the top of your layout
I don't have a install of ZF i can mess with easy, if this doesn't work ill setup a test environment.