Yii2 Select2 multiselect dependent fields - ajax

How can I do: I have 2 multi-select fields Select2, the first field for Branches, second for Workers.
When I choose branches, in second field I need to show Workers, who work in this branches.

View file
<label><?= $model->getAttributeLabel('branch') ?></label>
<?php echo Select2::widget([
'name' => 'branch',
'id' => 'branches',
'theme' =>Select2::THEME_BOOTSTRAP,
'value' => '',
'data' => $branchList,
'options' => [
'placeholder' => Yii::t('app', 'Choose branch'),
'multiple' => true,
],
'pluginOptions' => [
'tags' => true,
'allowClear' => true,
],]);?>
<label><?= $model->getAttributeLabel('Workers') ?></label>
<?php echo Select2::widget([
'name' => 'worker',
'id' => 'workers',
'theme' =>Select2::THEME_BOOTSTRAP,
'value' => '',
'data' => [],
'options' => [
'placeholder' => Yii::t('app', 'Choose workers'),
'multiple' => true,
],
'pluginOptions' => [
'tags' => true,
'allowClear' => true,
],]);
?>
JS
$("#branches").change(function(){
change();
});
function change() {
var selectValue = $("#branches").val();
$("#workers").empty();
$.post( "'.Yii::$app->urlManager->createUrl('constructor/lists?id=').'"+selectValue,
function(data){
$("#workers").html(data);
}
);
};
ConstructorController
public function actionLists($id)
{
if ($id != null) {
$ids = explode(",", $id);
foreach ($ids as $id_branch) {
$workers = Report::getWorkers($id_branch);
if (count($workers) > 0) {
foreach ($workers as $worker) {
echo "<option value='" . $worker . "'>" . $worker . "</option>";
}
} else {
echo "'<option>-</option>'";
}
}
}
}

Related

Notice: Undefined index

I have this error message when I submit form.
Notice: Undefined index: title in
C:\xampp\htdocs\ameyaw\module\BusinessGhana\src\Service\AutosManager.php
on line 38
Notice: Undefined index: description in
C:\xampp\htdocs\ameyaw\module\BusinessGhana\src\Service\AutosManager.php
on line 39
Notice: Undefined index: featured in
C:\xampp\htdocs\ameyaw\module\BusinessGhana\src\Service\AutosManager.php
on line 58
Message:
An exception occurred while executing 'INSERT INTO auto (title,
description, featured, date_created) VALUES (?, ?, ?, ?)' with params
[null, null, null, "2017-06-15 05:04:44"]:
SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'title'
cannot be null
this is my form and fieldset
use Zend\Form\Fieldset;
use Doctrine\Common\Persistence\ObjectManager;
use DoctrineModule\Persistence\ObjectManagerAwareInterface;
use BusinessGhana\Entity\Autos;
class AddFieldset extends Fieldset
{
protected $objectManager;
public function init()
{
$this->add([
'type' => 'text',
'name' => 'title',
'attributes' => [
'id' => 'autoTitle'
],
'options' => [
'label' => 'Title',
'display_empty_item' => true,
'empty_item_label' => 'Maximum of 60 characters',
],
]);
$this->add([
'type' => 'textarea',
'name' => 'description',
'attributes' => [
'id' => 'autoDescription'
],
'options' => [
'label' => 'Description',
'display_empty_item' => true,
'empty_item_label' => 'description',
],
]);
$this->add([
'type' => 'radio',
'name' => 'featured',
'attributes' => [
'id' => 'autoFeatured'
],
'options' => array(
'label' => 'Featured',
'value_options' => array(
array('value' => '0',
'label' => 'No',
'selected' => true,
'label_attributes' => array(
'class' => 'col-sm-2 btn btn-default',
),
),
array(
'value' => '1',
'label' => 'Yes',
'label_attributes' => array(
'class' => 'col-sm-2 btn btn-danger',
),
),
),
'column-size' => 'sm-12',
'label_attributes' => array(
'class' => 'col-sm-2',
),
),
]);
}
}
use Zend\Form\Form;
//use Zend\InputFilter\InputFilter;
class AddForm extends Form
{
public function init()
{
$this->add([
'name' => 'dependentForm',
'type' => AddFieldset::class,
]);
$this->add([
'type' => 'submit',
'name' => 'submit',
'attributes' => [
'value' => 'Submit',
],
]);
}
}
This is my controller action
public function addAction()
{
// Create the form.
$form = new PostForm();
if ($this->getRequest()->isPost()) {
// Get POST data.
$data = $this->params()->fromPost();
// Fill form with data.
$form->setData($data);
if ($form->isValid()) {
// Get validated form data.
$data = $form->getData();
$this->AutosManager->addNewAutos($data);
return $this->redirect()->toRoute('retrieve');
}
}
return new ViewModel([
'form' => $form
]);
}
I know hydration can solve this problem but I don't know how to use it yet.
thanks for any help.
this is my autosManager
class AutosManager
{
/**
* Entity manager.
* #var Doctrine\ORM\EntityManager;
*/
private $entityManager;
/**
* Constructor.
*/
public function __construct($entityManager)
{
$this->entityManager = $entityManager;
}
public function addNewAutos($data)
{
$autos = new Autos();
$autos->setTitle($data['title']);
$autos->setDescription($data['description']);
$autos->setFeatured($data['featured']);
$currentDate = date('Y-m-d H:i:s');
$autos->setDateCreated($currentDate);
$this->entityManager->persist($autos);
$this->entityManager->flush();
}
}
i can retrieve data from database.
This is where i render my forms:
$form = $this->form;
$fieldset = $form->get('dependentForm');
$title = $fieldset->get('title');
$title->setAttribute('class', 'form-control');
$title->setAttribute('placeholder', 'Maximum of 60 characters');
$title->setAttribute('id', 'autoTitle');
$description = $fieldset->get('description');
$description->setAttribute('class', 'form-control');
$description->setAttribute('placeholder', 'Description here...');
$description->setAttribute('id', 'autoDescription');
$featured = $fieldset->get('featured');
$featured->setAttribute('id', 'autoRadio');
$form->get('submit')->setAttributes(['class'=>'btn btn-primary']);
$form->prepare();
echo $this->form()->openTag($form);
?>
<fieldset>
<div class="form-group">
<?= $this->formLabel($title) ?>
<?= $this->formElement($title) ?>
<?= $this->formElementErrors()->render($title,['class'=>'help-block'])?>
</div>
<div class="form-group">
<?= $this->formLabel($description) ?>
<?= $this->formElement($description) ?>
<?=$this->formElementErrors()->render($description,
['class'=>'help-block'])?>
</div>
<div class="form-group">
<?= $this->formLabel($featured) ?>
<?= $this->formElement($featured) ?>
<?= $this->formElementErrors()->render($featured,
['class' =>'help-block']) ?>
</div>
</div></div><div class="row">
<div class="col-md-4">
</fieldset>
<?= $this->formElement($form->get('submit')); ?>
In your function addNewAutos($data) : your $data variable don't have title, description and featured fields. So php consider these as null, and your $this->entityManager->flush() will try to write null values in database, but you have a constraint that at least title must not be null.
So check your $data array contains the title, description and featured fields before to initiate your Auto object...

CakePHP 3 : Retrieving data from database using Ajax

I am working on a CakePHP 3 project which is having a Apply Coupon form.
I want to apply the coupon using Ajax.
The view of coupon form is
<?= $this->Form->create(null, [
'url' => ['controller' => 'Coupons', 'action' => 'checkCoupon'],
'name' => 'checkCoupon'
]) ?>
<?= $this->Form->input('coupon_code', [
'type' => 'text',
'placeholder' => 'Apply Coupon Code',
'label' => false
]) ?>
<?= $this->Form->submit('Apply Coupon') ?>
and the checkCoupon action in CouponsController is
public function checkCoupon()
{
$this->request->onlyAllow('ajax'); // No direct access via browser URL
if ($this->request->is('post')) {
$couponCode = $this->request->data['coupon_code'];
$couponCheck = $this->Coupons->find('all', [
'conditions' => [
'coupon_code' => $couponCode
]
]);
if ($couponCheck->count() === 1) {
$coupon = $couponCheck->first();
$valid_till = $coupon->valid_till;
$dt = new Time($valid_till);
$date = $dt->format('Y-m-d');
if ($date >= date('Y-m-d')) {
echo 'Coupon is Valid. Discount of '.$coupon->value.'has been applied';
} else {
echo 'Coupon is Expired';
}
} else {
echo 'This is not a valid coupon code';
}
}
}
I want the $coupon->value and $coupon->id to be retrieved and added to the checkout link as
<?= $this->Html->link(__('Confirm Checkout'), ['controller' => 'ServiceRequests', 'action' => 'confirmCheckout', $service->id, $primaryAddressId, $serviceArea->id, $coupon->id], ['class' => 'btn btn-block btn-success']) ?>
The Apply Coupon form is in checkout action of RequestsController
Also the form is working well. I have checked it by removing the onlyAllow('ajax') line and printing values in check_coupon.ctp view.
How could I do it using Ajax ?
Edit 2 : checkout.ctp
<div class="form-info coupon">
<?= $this->Form->create(null, [
'url' => ['controller' => 'Coupons', 'action' => 'ajax_checkCoupon'],
'name' => 'checkCoupon',
'id' => 'checkCoupon'
]) ?>
<?= $this->Form->input('coupon_code', [
'type' => 'text',
'placeholder' => 'Apply Coupon Code',
'label' => false
]) ?>
<label class="hvr-sweep-to-right">
<?= $this->Form->submit('Apply Coupon', ['id' => 'applyCoupon']) ?>
</label>
<label id="couponUpdate"></label>
<label id="loading" style="display:none;">Loading...</label>
<?php
$data = $this->Html->script('#checkCoupon')->serializeForm(['isForm' => true, 'inline' => true]);
$this->Html->script('#checkCoupon')->event(
'submit',
$this->Html->script(
[
'controller' => 'Coupons',
'action' => 'ajax_checkCoupon'
],
[
'update' => '#couponUpdate',
'data' => $data,
'async' => true,
'dataExpression' => true,
'before' => "$('#loading').fadeIn();$('#applyCoupon').attr('disabled','disabled');",
'complete' => "$('#loading').fadeOut();$('#applyCoupon').removeAttr('disabled');"
]
)
);
?>
</div>
Error : Call to a member function serializeForm() on string on line 18 in checkout.ctp

CakePHP - How to dynamically change the fields in my form after selecting from drop-down list

I am having a trouble on getting the value of the selected drop-down list(package_id) to populate the next fields particularly the Departure Time and Price which is in the Package Model.
Here is my code in View/Reservations/package.ctp:
<?php echo $this->Form->create('Reservation'); ?>
<table cellspacing="10">
<?php
echo $this->Html->tableCells(array(
array(
'Date: ',
$this->Form->input('date', array('label' => false, 'type' => 'text', 'class' => 'datepicker'))
),
array(
'Package Name:',
$this->Form->input('package_id', array('label' => false, 'options' => $name, 'id' => 'PackageID', 'empty' => '-- Select Package --'))
),
array(
'Departure Time:',
$this->Form->input('departure_time', array('label' => false, 'type' => 'label', 'id' => 'test'))
),
array(
'Price:',
$this->Form->input('price', array('label' => false, 'id' => 'test'))
),
array(
'Number of Person:',
$this->Form->input('number_of_people', array('label' => false))
),
array(
'Total Price:',
$this->Form->input('price', array('label' => false))
),
array(
'',
$this->Form->Submit('Book Now', array('class' => 'button'))
),
));
?>
</table>
and Here is my code in public function package():
$options = $this->Packages->find('list'); //or whatever conditions you want
$this->set('name', $options);
I was trying to use JS helper but I can't get it right here is my code:
$this->Js->get('#PackageID');
$this->Js->event('change',
$this->Js->request(array(
'controller'=>'Reservation',
'action'=>'getPackage'
), array(
'update'=> '#test',
'async' => true,
'method' => 'post',
'dataExpression' => true,
'data'=> $this->Js->serializeForm(array(
'isForm' => true,
'inline' => true))
)
)
);
Feel free to ask questions for clarification. Thank You in advance :)
Try this :
in the view .ctp , add this js function :
<script language="JavaScript">
jQuery(document).ready(function() {
$("#PackageID").chosen().bind('change', function() {
$.post('/project_name/controller_name/listDeparetementByPackage/'+$(this).val(), function(data) {
$("#test").empty().append(data);
$("#test").trigger("liszt:updated");
}, 'html');
});
});
</script>
and in your controller , here is the function to get the departements by pacakge id :
function listDeparetementByPackage($package = null ) {
$this->layout = 'ajax';
$this->beforeRender();
$this->autoRender = false;
$data = $this->Package->Departement->find('list', array('fields' => array('Departement.id', 'Departement.libelle'),
'conditions' => array('Departement.package_id' => $package),
'recursive' => 0 ));
if(count($data)>0){
foreach($data as $key => $val) {
echo "<option value=$key>$val</option>";
}
}else{
echo "<option></option>"; // if the result is empty , show a select empty
}
}
Hope it helps .

ajax function in drupal 6 not working

I need to filter the territory field upon the value of the region field im using ajax function like it's mentioned in the below code but it's not working. THE AJAX CALL on the fonction is not getting into the function 'territory_filter_callback' anyway would know where is the error?
function form_search_menu() {
$items['form/search'] = array(
'title' => t('Search'),
'page callback' => 'drupal_get_form',
'page arguments' => array('_search'),
'access callback' => TRUE,
'description' => t('search'),
);
return $items;
}
function _search(&$form_state) {
drupal_add_js(drupal_get_path('module', 'form_search') .'/script.js');
$form['description'] = array(
'#type' => 'item',
'#title' => t('Search page'),
);
//FILL THE LIST OF REGIONS
$conn = oci_connect('webuser', 'website', '172.16.1.1');
//regions
$stid = oci_parse($conn, "SELECt code,descr1 FROM table1.region");
oci_execute($stid);
$cidades = array(); while (($row = oci_fetch_array($stid, OCI_ASSOC))) {
$cidades[$row['CODE']]= $row['DESCR1'];
} $cidades ['']='Select';
//city
$stid1 = oci_parse($conn, "SELECT code,descr1 from table1.city ORDER BY DESCR1"); oci_execute($stid1); $types = array(); while (($row = oci_fetch_array($stid1, OCI_ASSOC))) {
$types [$row['CODE']]= $row['DESCR1'];
} $types['']='Select';
//territory
$stid2 = oci_parse($conn, "SELECT code,descr1 FROM table1.territory"); oci_execute($stid2);
$territory = array();
while (($row = oci_fetch_array($stid2, OCI_ASSOC))) {
$territory [$row['CODE']]= $row['DESCR1'];
}
$territory ['']='Select';
oci_free_statement($stid);
oci_close($conn);
$form['name'] = array(
'#type' => 'fieldset',
//'#title' => t('Name'),
// Make the fieldset collapsible.
'#collapsible' => false, // Added
'#collapsed' => FALSE, // Added
);
$form['name']['Region'] = array(
'#type' => 'select',
'#title' => t('Region'),
'#options' => $cidades,
'#required' => FALSE, '#default_value' => isset($form_state['values']['name']['Region']) ? $form_state ['values']['name']['Region'] : '',
'#ajax' => array(
'event' => 'change',
'callback' => 'territory_filter_callback',
'wrapper' => 'dropdown_second_replace'
),
// Added
);
$form['name']['Territory'] = array(
'#type' => 'select',
'#title' => t('Territory'), '#prefix' => '<div id="dropdown_second_replace">', '#suffix' => '</div>',
'#options' => $territory,
'#required' => FALSE, '#default_value' => isset($form_state['values']['name']['Territory']) ? $form_state['values']['name']['Territory'] : '',
// Added );
$form['name']['City'] = array(
'#type' => 'select',
'#title' => t('City'),
'#options' => $types,
'#required' => FALSE,
// Added
);
$form['link'] = array(
'#type' => 'markup',
'#value' => '<a href="#" onclick="navigate()" ><input type="button" value="Search" style="background-color:#2A64A9;color:#FFFFFF;width:80px; height:25px; border:1;CURSOR:POINTER;float:right;border-color:#FFFFFF;" ></a>', //
return $form;
}
function territory_filter_callback(&$form,&$form_state)
{
$territory_options=array();
if(isset($form['name']['Region']['#default_value']['0'])
{ $Region=$form['name']['Region']['#default_value']['0'];
}
else
{ $Region=0;
}
$territory_options=selected_territory($Region);
$form['name']['Region']['#ajax']=
array('event' => 'change',
'wrapper' => 'territory_wrapper',
'callback' => 'filter_territory_callback',
'method' =>replace,
);
$form ['name']['territory']['prefix']='<div id="territory_wrapper">';
$form ['name']['territory']['prefix']='</div>';
$form ['territory']['#options']=$territory_options;
}
function filter_territory_callback($form,$form_state)
{
$Region=$form['name']['Region']['#value'];
$form['name']['territory']['#options']=selected_territory($Region);
return $form['territory'];
}
drupal 6 not support '#ajax'...'#ajax' is working with drupal 7...in drupal 6 you can use '#ahah'
http://drupal.org/node/331941
good luck

Validation Errors not showing

I am trying to validate a user when they register to my application. Nothing is getting set to validationErrors, which is strange can anyone help me out?
Here is my MembersController
<?php
class MembersController extends AppController {
var $name = 'Members';
var $components = array('RequestHandler','Uploader.Uploader');
function beforeFilter() {
parent::beforeFilter();
$this->layout = 'area';
$this->Auth->allow('register');
$this->Auth->loginRedirect = array('controller' => 'members', 'action' => 'dashboard');
$this->Uploader->uploadDir = 'files/avatars/';
$this->Uploader->maxFileSize = '2M';
}
function login() {}
function logout() {
$this->redirect($this->Auth->logout());
}
function register() {
if ($this->data) {
if ($this->data['Member']['psword'] == $this->Auth->password($this->data['Member']['psword_confirm'])) {
$this->Member->create();
if ($this->Member->save($this->data)) {
$this->Auth->login($this->data);
$this->redirect(array('action' => 'dashboard'));
} else {
$this->Session->setFlash(__('Account could not be created', true));
$this->redirect(array('action' => 'login'));
pr($this->Member->invalidFields());
}
}
}
}
}
?>
Member Model
<?php
class Member extends AppModel {
var $name = 'Member';
var $actsAs = array('Searchable');
var $validate = array(
'first_name' => array(
'rule' => 'alphaNumeric',
'required' => true,
'allowEmpty' => false,
'message' => 'Please enter your first name'
),
'last_name' => array(
'rule' => 'alphaNumeric',
'required' => true,
'allowEmpty' => false,
'message' => "Please enter your last name"
),
'email_address' => array(
'loginRule-1' => array(
'rule' => 'email',
'message' => 'please enter a valid email address',
'last' => true
),
'loginRule-2' => array(
'rule' => 'isUnique',
'message' => 'It looks like that email has been used before'
)
),
'psword' => array(
'rule' => array('minLength',8),
'required' => true,
'allowEmpty' => false,
'message' => 'Please enter a password with a minimum lenght of 8 characters.'
)
);
var $hasOne = array('Avatar');
var $hasMany = array(
'Favourite' => array(
'className' => 'Favourite',
'foreignKey' => 'member_id',
'dependent' => false
),
'Friend' => array(
'className' => 'Friend',
'foreignKey' => 'member_id',
'dependent' => false
),
'Guestbook' => array(
'className' => 'Guestbook',
'foreignKey' => 'member_id',
'dependent' => false
),
'Accommodation'
);
var $hasAndBelongsToMany = array('Interest' => array(
'fields' => array('id','interest')
)
);
function beforeSave($options = array()) {
parent::beforeSave();
if (isset($this->data[$this->alias]['interests']) && !empty($this->data[$this->alias]['interests'])) {
$tagIds = $this->Interest->saveMemberInterests($this->data[$this->alias]['interests']);
unset($this->data[$this->alias]['interests']);
$this->data[$this->Interest->alias][$this->Interest->alias] = $tagIds;
}
$this->data['Member']['first_name'] = Inflector::humanize($this->data['Member']['first_name']);
$this->data['Member']['last_name'] = Inflector::humanize($this->data['Member']['last_name']);
return true;
}
}
?>
login.ctp
<div id="login-form" class="round">
<h2>Sign In</h2>
<?php echo $form->create('Member', array('action' => 'login')); ?>
<?php echo $form->input('email_address',array('class' => 'login-text',
'label' => array('class' => 'login-label')
));?>
<?php echo $form->input('psword' ,array('class' => 'login-text',
'label' => array('class' => 'login-label','text' => 'Password')
))?>
<?php echo $form->end('Sign In');?>
</div>
<div id="signup-form" class="round">
<h2>Don't have an account yet?</h2>
<?php echo $form->create('Member', array('action' => 'register')); ?>
<?php echo $form->input('first_name',array('class' => 'login-text',
'label' => array('class' => 'login-label')
));?>
<?php echo $form->input('last_name',array('class' => 'login-text',
'label' => array('class' => 'login-label')
));?>
<?php echo $form->input('email_address',array('class' => 'login-text',
'label' => array('class' => 'login-label')
));?>
<?php echo $form->input('psword' ,array('class' => 'login-text',
'label' => array('class' => 'login-label','text' => 'Password')
))?>
<?php echo $form->input('psword_confirm' ,array('class' => 'login-text',
'label' => array('class' => 'login-label','text' => 'Confirm'),
'div' => array('style' => ''),
'type' => 'password'
))?>
<?php echo $form->end('Sign In');?>
</div>
I believe your problem is here:
$this->redirect(array('action' => 'login'));
pr($this->Member->invalidFields());
The validation errors are designed to show on the form, underneath the appropriate field. However, instead of continuing and trying to display the form, you are redirecting the user to a different page.
If you remove the two lines above, it should show the validation errors beneath their fields on the form when the validation fails.

Resources